aiogram/examples/throtling_example.py

43 lines
1.2 KiB
Python
Raw Normal View History

"""
Example for throttling manager.
You can use that for flood controlling.
"""
import asyncio
import logging
from aiogram import Bot, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import Dispatcher
from aiogram.utils.exceptions import Throttled
from aiogram.utils.executor import start_polling
API_TOKEN = 'BOT TOKEN HERE'
logging.basicConfig(level=logging.INFO)
2019-07-15 14:00:38 +07:00
bot = Bot(token=API_TOKEN)
2018-02-21 19:09:44 +03:00
# Throttling manager does not work without Leaky Bucket.
# Then need to use storages. For example use simple in-memory storage.
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
try:
2018-02-21 19:09:44 +03:00
# Execute throttling manager with rate-limit equal to 2 seconds for key "start"
await dp.throttle('start', rate=2)
except Throttled:
2018-02-21 19:09:44 +03:00
# If request is throttled, the `Throttled` exception will be raised
await message.reply('Too many requests!')
else:
2018-02-21 19:09:44 +03:00
# Otherwise do something
await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")
if __name__ == '__main__':
2019-07-15 14:00:38 +07:00
start_polling(dp, skip_updates=True)