Broadcasting to all users

Broadcasting to all users

Hinrich Mahler (@Bibo-Joshi)

When maintaining a bot, it is a common use case to inform all users about e.g. updates of the bot or down-times for maintenance. This short article tries to sum up a few tips on how to achieve such a functionality with the python-telegram-bot library.

Alternative: Information Channel

Before we dive into the details, let's quickly describe an easy alternative solution: Instead of sending the messages directly through your bot, you can instead set up a channel to publish the announcements. You can link your users to the channel in a welcome message.

If that doesn't work for you, here we go:

Getting the user IDs

To send a message to all users, you of course need the IDs of all the users.

Unfortunately, the API does not offer a method to get the IDs of all users that use your bot. Therefore you should keep track of your users IDs yourself. Storing them in bot_data is a convenient way to do that.

If you didn't keep track of your users from the beginning, you may have a chance to get the IDs anyway, if you're using persistence. Please have a look at this issue on GitHub in that case.

Sending the messages

Even if you have all the IDs, you can't know if a user has blocked your bot in the meantime. Therefore you should make sure to wrap your send request in a try-except clause checking for telegram.error.Unauthorized errors.

Flood limits

Telegram imposes some limits that restrict you to send ~30 Messages per second. If you have a huge user base and try to notify them all at once, you will get flooding errors. To prevent that, try spreading the messages over a long timerange. A simple way to achieve that is to leverage the JobQueue. If your bot is popular enough for you to care about flood limits anyway, you should instead have a look at the MessageQueue.

Report Page