pyTelegramBot¶
Installation¶
Synchronous and Asynchronous Bot.¶
The API provide two type of bots a synchronous and Asynchronous both with small difference on the implementation
Synchronous bot example¶
Asynchronous bot example¶
The steps to create the bot will be:¶
- Search for BotFather 👴🏽.
- BotFather will provide some instructions. From those instructions, I need to use /newbot.
- I give a name to the bot
no_my_first
. - I give a username to the bot with the postfix bot,
no_my_first_bot
. - After assigning the username BotFather will provide the Bot API key.
The response of the Bot father will be something like this:
Up, running, and listening.¶
The package pyTelegramBotAPI encapsulates the telegram API, with this package I can send messages and documents and several ways to parse or listen to incoming messages.
- Create an instance of the TeleBot() using the API key.
- Define Message handler.
- Keep the bot running.
Create an instance of the TeleBot() using the API key.¶
First, I need to install the module.
Define Message handler.¶
To create a message handler, I will use the decorator @bot.message_handler()
.
The function decorated with this handler can have any name.
The only requirement is a single parameter, the message itself.
Handler with commands¶
This handler will handle or react to messages that include a command. Commands are words prefixed with / the list of commands handled by a handler is defined in the decorator as a list after the parameter commands this without /.
Handler with function¶
This handler will handle the message if the result of a function is true.
Here is an example of a function that will return always true, so the handler will echo each message that is not a command.
⚠️ Handler with a Function that expects a keyword¶
I can create a different function without a decorator that will track the presence of a specific word.
Keep the bot running¶
To keep the bot running I need to add one command to the source file bot.infinity_polling()
.
Advance Bot replies.¶
The documentation provides extensive information about the telegram API, but what I’m interested in are the types and something callReply markup, this will allow me to provide different types of responses like audio, videos, and keyboard options.
Each function send_xyz
contains an argument reply_markup
.
This argument receives an instance of ReplyKeyboardMarkup
, ReplyKeyboardRemove
or ForceReply
.
Here is an example of what I what to do.
The Bot will reply with a custom keyword
- Create an instance of
ReplyKeyboardMarkup
. The instance will have 2 rowsrow_width=2
. - Create the Buttons
types.KeyboardButton(“option”)
. - Add to the markup object.
- Add the keyboard to the message.