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 user

  • parse_mode=ParseMode.MARKDOWN_V2 means your telebot will use Telegram's MarkdownV2 formatting for the message

  • user.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

  1. 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

  1. Register Command Handlers

  • When a user sends /start the 'start' function will be executed

  • When a user sends /help the 'help' function will be executed

  • When a user sends /quadratic the 'quadratic' function will be executed

  1. Register Message Handler

  • Processes all text messages

  • When a user sends a text message, the 'handle_message' function will be executed

  1. Register Error Handler

  • Handle error's during a telebot's opertation. If an error occurs, the 'error' function will be executed

  1. 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

  1. Putting it all together

Your code should look something like this:

Last updated