Menu

Rate-limit free vs paid users in a python-telegram-bot bot (one gatekeeper handler)
📰

Rate-limit free vs paid users in a python-telegram-bot bot (one gatekeeper handler)

DEV Community: redis·Steve Jefferson·2 days ago
#7sRPWGf0
#devtoredis#devto#dev#window#user
Reading 0:00
15s threshold

Most Telegram bots that charge money end up with two kinds of users: free users who get a taste, and paid users who get more. The simplest way to draw that line is a rate limit: free users get, say, 5 requests an hour, paid users get 100.

This post shows how to do it cleanly in python-telegram-bot (v21/v22) with one "gatekeeper" handler that runs before everything else, so you don't sprinkle limit checks through every command.

The idea: a handler that runs first

In python-telegram-bot, handlers live in numbered groups. Groups are processed in ascending order, and within a group only the first matching handler runs. If any handler raises ApplicationHandlerStop , no further handlers run for that update, even in other groups.

So we register a TypeHandler(Update, ...) in group -1 . It sees every update before your normal handlers in group 0 . If the user is over their limit, it replies once and raises ApplicationHandlerStop .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.