Skip to content

Commit 0421b7a

Browse files
committed
add telegram bot tutorial
1 parent 2b449c0 commit 0421b7a

File tree

4 files changed

+109
-0
lines changed

4 files changed

+109
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
126126
- [How to Translate Text in Python](https://www.thepythoncode.com/article/translate-text-in-python). ([code](general/using-google-translate-api))
127127
- [How to Make a URL Shortener in Python](https://www.thepythoncode.com/article/make-url-shortener-in-python). ([code](general/url-shortener))
128128
- [How to Get Google Page Ranking in Python](https://www.thepythoncode.com/article/get-google-page-ranking-by-keyword-in-python). ([code](general/getting-google-page-ranking))
129+
- [How to Make a Telegram Bot in Python](https://www.thepythoncode.com/article/make-a-telegram-bot-in-python). ([code](general/telegram-bot))
129130

130131
- ### [Database](https://www.thepythoncode.com/topic/using-databases-in-python)
131132
- [How to Use MySQL Database in Python](https://www.thepythoncode.com/article/using-mysql-database-in-python). ([code](database/mysql-connector))

general/telegram-bot/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# [How to Make a Telegram Bot in Python](https://www.thepythoncode.com/article/make-a-telegram-bot-in-python)
2+
To run this:
3+
- `pip3 install -r requirements.txt`
4+
- Get an API key contacting @FatherBot in Telegram
5+
- Run `telegram_bot.py`

general/telegram-bot/requirements.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
python-telegram-bot

general/telegram-bot/telegram_bot.py

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import telegram
2+
import telegram.ext
3+
import re
4+
from random import randint
5+
import logging
6+
logging.basicConfig(level=logging.INFO,
7+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
8+
9+
# The API Key we received for our bot
10+
API_KEY = "1463892065:AAF-9uhbX2D9zrRQXMjgdisFBpY_l7lGCOs"
11+
# API_KEY = "<INSERT_API_KEY_HERE>"
12+
# Create an updater object with our API Key
13+
updater = telegram.ext.Updater(API_KEY)
14+
# Retrieve the dispatcher, which will be used to add handlers
15+
dispatcher = updater.dispatcher
16+
# Our states, as integers
17+
WELCOME = 0
18+
QUESTION = 1
19+
CANCEL = 2
20+
CORRECT = 3
21+
22+
# The entry function
23+
def start(update_obj, context):
24+
# send the question, and show the keyboard markup (suggested answers)
25+
update_obj.message.reply_text("Hello there, do you want to answer a question? (Yes/No)",
26+
reply_markup=telegram.ReplyKeyboardMarkup([['Yes', 'No']], one_time_keyboard=True)
27+
)
28+
# go to the WELCOME state
29+
return WELCOME
30+
31+
# helper function, generates new numbers and sends the question
32+
def randomize_numbers(update_obj, context):
33+
# store the numbers in the context
34+
context.user_data['rand_x'], context.user_data['rand_y'] = randint(0,1000), randint(0, 1000)
35+
# send the question
36+
update_obj.message.reply_text(f"Calculate {context.user_data['rand_x']}+{context.user_data['rand_y']}")
37+
38+
# in the WELCOME state, check if the user wants to answer a question
39+
def welcome(update_obj, context):
40+
if update_obj.message.text.lower() in ['yes', 'y']:
41+
# send question, and go to the QUESTION state
42+
randomize_numbers(update_obj, context)
43+
return QUESTION
44+
else:
45+
# go to the CANCEL state
46+
return CANCEL
47+
48+
# in the QUESTION state
49+
def question(update_obj, context):
50+
# expected solution
51+
solution = int(context.user_data['rand_x']) + int(context.user_data['rand_y'])
52+
# check if the solution was correct
53+
if solution == int(update_obj.message.text):
54+
# correct answer, ask the user if he found tutorial helpful, and go to the CORRECT state
55+
update_obj.message.reply_text("Correct answer!")
56+
update_obj.message.reply_text("Was this tutorial helpful to you?")
57+
return CORRECT
58+
else:
59+
# wrong answer, reply, send a new question, and loop on the QUESTION state
60+
update_obj.message.reply_text("Wrong answer :'(")
61+
# send another random numbers calculation
62+
randomize_numbers(update_obj, context)
63+
return QUESTION
64+
65+
# in the CORRECT state
66+
def correct(update_obj, context):
67+
if update_obj.message.text.lower() in ['yes', 'y']:
68+
update_obj.message.reply_text("Glad it was useful! ^^")
69+
else:
70+
update_obj.message.reply_text("You must be a programming wizard already!")
71+
# get the user's first name
72+
first_name = update_obj.message.from_user['first_name']
73+
update_obj.message.reply_text(f"See you {first_name}!, bye")
74+
return telegram.ext.ConversationHandler.END
75+
76+
def cancel(update_obj, context):
77+
# get the user's first name
78+
first_name = update_obj.message.from_user['first_name']
79+
update_obj.message.reply_text(
80+
f"Okay, no question for you then, take care, {first_name}!", reply_markup=telegram.ReplyKeyboardRemove()
81+
)
82+
return telegram.ext.ConversationHandler.END
83+
84+
# a regular expression that matches yes or no
85+
yes_no_regex = re.compile(r'^(yes|no|y|n)$', re.IGNORECASE)
86+
# Create our ConversationHandler, with only one state
87+
handler = telegram.ext.ConversationHandler(
88+
entry_points=[telegram.ext.CommandHandler('start', start)],
89+
states={
90+
WELCOME: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), welcome)],
91+
QUESTION: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(r'^\d+$'), question)],
92+
CANCEL: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), cancel)],
93+
CORRECT: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), correct)],
94+
},
95+
fallbacks=[telegram.ext.CommandHandler('cancel', cancel)],
96+
)
97+
# add the handler to the dispatcher
98+
dispatcher.add_handler(handler)
99+
# start polling for updates from Telegram
100+
updater.start_polling()
101+
# block until a signal (like one sent by CTRL+C) is sent
102+
updater.idle()

0 commit comments

Comments
 (0)