Created
November 23, 2018 15:19
-
-
Save udf/ee60c2d20e0cf78e7c9c78b9ace356f8 to your computer and use it in GitHub Desktop.
Decorator that lets you apply per chat rate limits to telethon handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import logging | |
import time | |
from collections import defaultdict | |
from telethon import TelegramClient | |
from telethon import events | |
logging.basicConfig(level=logging.INFO) | |
client = TelegramClient('user', 6, 'eb06d4abfb49dc3eeb1aeb98ae0f581e').start() | |
def handler_ratelimit(timeout): | |
def wrapper(function): | |
last_called = defaultdict(int) | |
async def wrapped(event, *args, **kwargs): | |
current_time = time.time() | |
if current_time - last_called[event.chat_id] < timeout: | |
return | |
last_called[event.chat_id] = current_time | |
return await function(event, *args, **kwargs) | |
return wrapped | |
return wrapper | |
@client.on(events.NewMessage(incoming=True, pattern='^hi$')) | |
@handler_ratelimit(60) | |
async def hi(event): | |
await event.reply('hi') | |
client.run_until_disconnected() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment