Telebot Basics
Commands
Commands in Telegram are messages that start with a slash "/" followed by the command name
e.g. /start
or /help
We define a few commands.
These usually take in two arguments "update" and "context"
/start Command
Sends a message when the command /start is issued
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
user = update.effective_user
await update.message.reply_text(text=f'Hello {user.mention_markdown_v2()}\!'
f'\nEnter /help to see the list of '
f'commands for this bot\.',
parse_mode=ParseMode.MARKDOWN_V2)
Your Output will look something like this:
Hello 'Username'! #replaced by your username
Enter /help to see the list of commands for this bot.
Code Explanation
user = update.effective_user
extracts information about the userparse_mode=ParseMode.MARKDOWN_V2
means your telebot will use Telegram's MarkdownV2 formatting for the messageuser.mention_markdown_v2()
is a function that ensures the user is mentioned and displayed correctly
/error Command
The error function is an error handler for your Telegram Bot. It is designed to log and print information about errors during the bot's operation.
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
print(f'Update {update} caused error {context.error}')
Update {update} : Includes information about the update (user input) that was processed when the error occurred
caused error {context.error} : Information about the error that was raised
Now, let us move on to something more "custom" for our telebot. Like a quadratic formula!
Custom Commands
Creating a quadratic formula command
The Formula:
import math
async def quadratic(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# extract the message from the user input
# e.g. /quadratic 1 2 3
message = update.message.text
# assign each number input to a string
# e.g. a_string = 1, b_string = 2, c_string = 3
_, a_string, b_string, c_string = message.split()
# convert from a string to a float
a = float(a_string)
b = float(b_string)
c = float(c_string)
# Calculate the discriminant
disc = b**2 - 4*a*c
# Assume 2 real solutions and calculate the roots
# Can add conditional statements for imaginary solution etc.
root1 = (-b + math.sqrt(disc)) / 2*a
root2 = (-b - math.sqrt(disc)) / 2*a
# Create the reply text
reply = f"Your roots are {root1} and {root2}"
update.message.reply_text(reply)
Initialising and Command Handling
First, Initialise the Bot with your Token
We do this using the 'Application' class from the 'python-telegram-bot' library
The TOKEN is your unique bot token obtained from BotFather
if __name__ == '__main__':
app = Application.builder().token(TOKEN).build()
Register Command Handlers
When a user sends
/start
the 'start' function will be executedWhen a user sends
/help
the 'help' function will be executedWhen a user sends
/quadratic
the 'quadratic' function will be executed
app.add_handler(CommandHandler('start', start))
app.add_handler(CommandHandler('help', help))
app.add_handler(CommandHandler('quadratic', quadratic))
Register Message Handler
Processes all text messages
When a user sends a text message, the 'handle_message' function will be executed
app.add_handler(MessageHandler(filters.TEXT, handle_message))
Register Error Handler
Handle error's during a telebot's opertation. If an error occurs, the 'error' function will be executed
app.add_error_handler(error)
Now, Start Polling
Prints 'Polling...' to the console to indicate that the bot is starting
Polling is a method for the bot to continuously check for new updates from Telegram
print('Polling...')
asyncio.run(app.run_polling())
Putting it all together
Your code should look something like this:
if __name__ == '__main__':
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler('start', start))
app.add_handler(CommandHandler('help', help))
app.add_handler(CommandHandler('quadratic', quadratic))
app.add_handler(MessageHandler(filters.TEXT, handle_message))
app.add_error_handler(error)
print('Polling...')
asyncio.run(app.run_polling())
Last updated