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
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.
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:
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
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
Register Message Handler
Processes all text messages
When a user sends a text message, the 'handle_message' function will be executed
Register Error Handler
Handle error's during a telebot's opertation. If an error occurs, the 'error' function will be executed
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
Putting it all together
Your code should look something like this:
Last updated