How to Handle Telegram Bot Updates
Updates are the main way your bot learns what happened in Telegram. If you need information later, design your bot to store it when the update arrives.
Handle the update types your bot needs
Think of updates as events that your bot program receives from Telegram servers. There can be an update about an incoming message, an update about a user joining a group, and so on.
We'll use this term throughout the book.
Telegram adds new update types when new bot features appear. Recent examples include business connections and business messages, guest bot messages, managed bot updates, checklist changes, suggested posts, and richer poll events.
If you use allowed_updates in webhooks or long polling, remember to include the new update types you need. Otherwise Telegram may silently skip updates that your bot would otherwise be able to handle.
Here's an example of handling updates for incoming photos:
@bot.private_message
async def handle_photo(message: Message):
if not message.photo:
return
file_path = await message.download_media()
return 'Got your photo! Saved to ' + file_pathSave everything you need later
Updates are almost the only way to get any information about chats, messages, and users.
Your program can't fetch the latest user's message or the list of chats where the bot belongs. Telegram only provides information about the current user or the current chat in updates—for example, when a user sends a message or the bot is added to a group.
If you need a list of bot users, received messages, or anything similar, you should save this data. (You'll likely need a database.)
If you lose this info, you won't be able to retrieve it again.
NOTE
You can fetch some information using Telegram API and not Bot API—for example, it's possible to get a message by its ID or the info about a user. These features are listed in the table.
Know when updates can be received again
Do not rely on receiving the same Bot API update again. If you received an update in Bot API, you won't be able to receive it again.
There's no such limitation in Telegram API. This is because Telegram API is primarily designed for apps, where a user can have multiple Telegram applications on different devices, each needing to receive new messages. The same principle applies to bots: when you run multiple bot programs using Telegram API, they all receive the new updates.
DEV TIP
Moreover, there's a Telegram API technique to fetch old updates. For instance, it may be useful to get a list of bot users if it wasn't saved or the database was lost. Docs.
