async def push(msg, config: Config): bot = Bot(**config.dict( include={'connections_limit', 'proxy', 'proxy_auth', 'validate_token', 'parse_mode', 'timeout'}), token=config.token.get_secret_value()) coros = [] for chat_id in config.chat_ids: if isinstance(msg, str): coros.append(bot.send_message(chat_id, msg)) elif isinstance(msg, Photo): coros.append(bot.send_photo(chat_id, msg.photo, msg.caption)) await gather(*coros) await bot.close()
async def send_user(self, bot: Bot, chat_id: int) -> List[types.Message]: if isinstance(self.loop, AbstractEventLoop): task_queue: TaskQueue = TaskQueue(self.loop) for item in self.get_block_list(): task_queue.add( bot.send_message(chat_id, item, parse_mode=self.mode, disable_web_page_preview=True) ) return sorted(list(task_queue.get_result()), key=attrgetter('message_id')) message_list: List[types.Message] = [] for item in self.get_block_list(): message = await bot.send_message(chat_id, item, parse_mode=self.mode, disable_web_page_preview=True) message_list.append(message) return message_list
async def report(): bot = Bot(token=config("TELEGRAM_API_TOKEN")) report = compare_reports() # Consider only reviewed and words translated statistics for resource in report: report[resource] = { k: v for k, v in report[resource].items() if k in ["reviewed", "translated_words"] } if not report: logger.warning("Nothing to report!") return message = "📈 *EstastÃsticas da tradução*\nPerÃodo: 7 dias\n\n" for resource, stats in sorted(report.items()): if not stats: continue message += f"*{resource}*\n" for stat, value in stats.items(): stat_message = STATS_MESSAGES.get(stat) if not stat_message: continue message += stat_message.format(value) users = config("BROADCAST_REPORT_TO", cast=lambda v: [s.strip() for s in v.split(",")]) await asyncio.gather(*[ bot.send_message(user, message, parse_mode="Markdown") for user in users ])
else: await bot.send_message(user.id, error_logging_in) elif user.state == 'get_lessons_choose_day': user.state = 'none' lessons_day = int(date[1].timestamp()) ctime_day = time.ctime(lessons_day).split()[:3] read_day = WEEK[ctime_day[0]] + ', ' + ctime_day[2] + ' ' + MONTH[ctime_day[1]] await bot.edit_message_text(text="Получаю расписание...", chat_id=user.id, message_id=message_id, parse_mode="HTML") log_in_attempt = user.log_in() if log_in_attempt['logged_in']: s = log_in_attempt['session'] lessons = user.get_lessons(s, lessons_day) msg = f'<b>Расписание на {read_day}:</b>' await bot.edit_message_text(text=msg, chat_id=user.id, message_id=message_id, parse_mode="HTML") await send_lessons(user.id, s, lessons) else: await bot.send_message(user.id, error_logging_in) except: await bot.send_message('@eschool239boterrors', traceback.format_exc()) if __name__ == '__main__': while True: try: executor.start_polling(dp) except KeyboardInterrupt: break except: time.sleep(2) asyncio.run(bot.send_message('@eschool239boterrors', traceback.format_exc()))
@dp.message_handler(commands=['start']) async def send_welcome(message: types.Message): try: # Execute throttling manager with rate-limit equal to 2 seconds for key "start" await dp.throttle('start', rate=2) except Throttled: # If request is throttled, the `Throttled` exception will be raised await message.reply('Too many requests!') else: # Otherwise do something await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.") @dp.message_handler(commands=['hi']) @dp.throttled(lambda msg, loop, *args, **kwargs: loop.create_task( bot.send_message(msg.from_user.id, "Throttled")), rate=5) # loop is added to the function to run coroutines from it async def say_hi(message: types.Message): await message.answer("Hi") # the on_throttled object can be either a regular function or coroutine async def hello_throttled(*args, **kwargs): # args will be the same as in the original handler # kwargs will be updated with parameters given to .throttled (rate, key, user_id, chat_id) print(f"hello_throttled was called with args={args} and kwargs={kwargs}") message = args[ 0] # as message was the first argument in the original handler await message.answer("Throttled")
async def on_startup(dp): dp.database = await asyncpg.create_pool(user='******', database='admin_olx', host='185.161.209.19', password='******') def hide_name(name): return f"{name[:round(len(name) / 2)]}{'*' * round(len(name) - round(len(name) / 2))}" @dp.message_handler(commands='start') @dp.throttled(lambda msg, loop, *args, **kwargs: loop.create_task( bot.send_message(msg.from_user.id, "☠️ 🏴☠️ хули ты такой быстрый блять, молодой пират?")), rate=0.5) async def startcmd(message: types.Message): if message.chat.type != "private": return async with dp.database.acquire() as conn: rows = await conn.fetch( "SELECT username, ban FROM workers where userid = $1", str(message.from_user.id)) if not rows: await conn.execute( "INSERT INTO workers (userid,username) VALUES ($1, $2);", str(message.from_user.id), message.from_user.username)