Skip to content

Commit

Permalink
add telegram bot tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
x4nth055 committed Nov 10, 2020
1 parent 2b449c0 commit 0421b7a
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ This is a repository of all the tutorials of [The Python Code](https://www.thepy
- [How to Translate Text in Python](https://www.thepythoncode.com/article/translate-text-in-python). ([code](general/using-google-translate-api))
- [How to Make a URL Shortener in Python](https://www.thepythoncode.com/article/make-url-shortener-in-python). ([code](general/url-shortener))
- [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))
- [How to Make a Telegram Bot in Python](https://www.thepythoncode.com/article/make-a-telegram-bot-in-python). ([code](general/telegram-bot))

- ### [Database](https://www.thepythoncode.com/topic/using-databases-in-python)
- [How to Use MySQL Database in Python](https://www.thepythoncode.com/article/using-mysql-database-in-python). ([code](database/mysql-connector))
Expand Down
5 changes: 5 additions & 0 deletions general/telegram-bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# [How to Make a Telegram Bot in Python](https://www.thepythoncode.com/article/make-a-telegram-bot-in-python)
To run this:
- `pip3 install -r requirements.txt`
- Get an API key contacting @FatherBot in Telegram
- Run `telegram_bot.py`
1 change: 1 addition & 0 deletions general/telegram-bot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-telegram-bot
102 changes: 102 additions & 0 deletions general/telegram-bot/telegram_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import telegram
import telegram.ext
import re
from random import randint
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# The API Key we received for our bot
API_KEY = "1463892065:AAF-9uhbX2D9zrRQXMjgdisFBpY_l7lGCOs"
# API_KEY = "<INSERT_API_KEY_HERE>"
# Create an updater object with our API Key
updater = telegram.ext.Updater(API_KEY)
# Retrieve the dispatcher, which will be used to add handlers
dispatcher = updater.dispatcher
# Our states, as integers
WELCOME = 0
QUESTION = 1
CANCEL = 2
CORRECT = 3

# The entry function
def start(update_obj, context):
# send the question, and show the keyboard markup (suggested answers)
update_obj.message.reply_text("Hello there, do you want to answer a question? (Yes/No)",
reply_markup=telegram.ReplyKeyboardMarkup([['Yes', 'No']], one_time_keyboard=True)
)
# go to the WELCOME state
return WELCOME

# helper function, generates new numbers and sends the question
def randomize_numbers(update_obj, context):
# store the numbers in the context
context.user_data['rand_x'], context.user_data['rand_y'] = randint(0,1000), randint(0, 1000)
# send the question
update_obj.message.reply_text(f"Calculate {context.user_data['rand_x']}+{context.user_data['rand_y']}")

# in the WELCOME state, check if the user wants to answer a question
def welcome(update_obj, context):
if update_obj.message.text.lower() in ['yes', 'y']:
# send question, and go to the QUESTION state
randomize_numbers(update_obj, context)
return QUESTION
else:
# go to the CANCEL state
return CANCEL

# in the QUESTION state
def question(update_obj, context):
# expected solution
solution = int(context.user_data['rand_x']) + int(context.user_data['rand_y'])
# check if the solution was correct
if solution == int(update_obj.message.text):
# correct answer, ask the user if he found tutorial helpful, and go to the CORRECT state
update_obj.message.reply_text("Correct answer!")
update_obj.message.reply_text("Was this tutorial helpful to you?")
return CORRECT
else:
# wrong answer, reply, send a new question, and loop on the QUESTION state
update_obj.message.reply_text("Wrong answer :'(")
# send another random numbers calculation
randomize_numbers(update_obj, context)
return QUESTION

# in the CORRECT state
def correct(update_obj, context):
if update_obj.message.text.lower() in ['yes', 'y']:
update_obj.message.reply_text("Glad it was useful! ^^")
else:
update_obj.message.reply_text("You must be a programming wizard already!")
# get the user's first name
first_name = update_obj.message.from_user['first_name']
update_obj.message.reply_text(f"See you {first_name}!, bye")
return telegram.ext.ConversationHandler.END

def cancel(update_obj, context):
# get the user's first name
first_name = update_obj.message.from_user['first_name']
update_obj.message.reply_text(
f"Okay, no question for you then, take care, {first_name}!", reply_markup=telegram.ReplyKeyboardRemove()
)
return telegram.ext.ConversationHandler.END

# a regular expression that matches yes or no
yes_no_regex = re.compile(r'^(yes|no|y|n)$', re.IGNORECASE)
# Create our ConversationHandler, with only one state
handler = telegram.ext.ConversationHandler(
entry_points=[telegram.ext.CommandHandler('start', start)],
states={
WELCOME: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), welcome)],
QUESTION: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(r'^\d+$'), question)],
CANCEL: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), cancel)],
CORRECT: [telegram.ext.MessageHandler(telegram.ext.Filters.regex(yes_no_regex), correct)],
},
fallbacks=[telegram.ext.CommandHandler('cancel', cancel)],
)
# add the handler to the dispatcher
dispatcher.add_handler(handler)
# start polling for updates from Telegram
updater.start_polling()
# block until a signal (like one sent by CTRL+C) is sent
updater.idle()

0 comments on commit 0421b7a

Please sign in to comment.