Работа с aiogram3 и aioschedule
Пишу бота на aiogram3. Мне нужно отправлять сообщение всем юзерам каждую неделю во вторник в определенное время. Но не один из приложенных ниже вариантов кода просто не помогает. Первый пример:
class Main:
def __init__(self):
# Initialize bot
self.bot = Bot(token=TOKEN)
self.dp = Dispatcher(bot=self.bot)
self.users_service: UsersService = UsersService()
def get_routers(self):
self.dp.include_router(users_router.router)
self.dp.include_router(support_router.router)
self.dp.include_router(random_coffee_router.router)
self.dp.include_router(events_router.router)
self.dp.include_router(residents_router.router)
self.dp.include_router(contacts_router.router)
self.dp.include_router(about_router.router)
self.dp.include_router(profile_router.router)
self.dp.include_router(admins_router.router)
def start(self):
self.get_routers()
self.dp.run_polling(self.bot)
async def random_coffee():
try:
print('random_coffee')
main: Main = Main()
users = main.users_service.get_users_for_cron()
random_num = random.randint(0, len(users) - 1)
for i in range(len(users)):
await main.bot.send_message(chat_id=users[i][1],
text=f"*[Random Coffee]*\n\n"
f"{users[random_num][5]}\n"
f"*Бизнес:* {users[random_num][7]}\n"
f"*Хобби:* {users[random_num][8]}\n"
f"*Запрос:* {users[random_num][9]}\n"
f"*Ресурсы:* {users[random_num][10]}\n"
f"*[https://t.me/{users[random_num][2]}]*\n\n"
f"#земляки", parse_mode='Markdown')
except Exception as e:
print(f'Error while random_coffee: {e}')
def cron_task():
job = random_coffee()
schedule.every().tuesday.at("22:25").do(job)
async def cron():
t1 = threading.Thread(target=cron_task)
t1.daemon = True
t1.start()
if __name__ == '__main__':
asyncio.create_task(cron())
main = Main()
main.start()
Второй пример:
class Main:
def __init__(self):
# Initialize bot
self.bot = Bot(token=TOKEN)
self.dp = Dispatcher(bot=self.bot)
self.users_service: UsersService = UsersService()
def get_routers(self):
self.dp.include_router(users_router.router)
self.dp.include_router(support_router.router)
self.dp.include_router(random_coffee_router.router)
self.dp.include_router(events_router.router)
self.dp.include_router(residents_router.router)
self.dp.include_router(contacts_router.router)
self.dp.include_router(about_router.router)
self.dp.include_router(profile_router.router)
self.dp.include_router(admins_router.router)
def start(self):
self.get_routers()
self.dp.run_polling(self.bot)
async def random_coffee():
try:
print('random_coffee')
main: Main = Main()
users = main.users_service.get_users_for_cron()
random_num = random.randint(0, len(users) - 1)
for i in range(len(users)):
await main.bot.send_message(chat_id=users[i][1],
text=f"*[Random Coffee]*\n\n"
f"{users[random_num][5]}\n"
f"*Бизнес:* {users[random_num][7]}\n"
f"*Хобби:* {users[random_num][8]}\n"
f"*Запрос:* {users[random_num][9]}\n"
f"*Ресурсы:* {users[random_num][10]}\n"
f"*[https://t.me/{users[random_num][2]}]*\n\n"
f"#земляки", parse_mode='Markdown')
except Exception as e:
print(f'Error while random_coffee: {e}')
async def cron():
job = await random_coffee()
aioschedule.every().tuesday.at("22:16").do(job)
while True:
await aioschedule.run_pending()
await asyncio.sleep(1)
async def cron_task():
await asyncio.create_task(cron())
task = cron_task()
if __name__ == '__main__':
asyncio.create_task(cron_task())
main = Main()
main.start()
При использовании двух вариантов бот просто падает, без отправки сообщения, и выдает вот такую ошибку:
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'cron' was never awaited
При таком подходе бот отправляет сообщение сразу после запуска, независимо от текущего времени (даже если оно больше или меньше нужного) и ложится вот с такой ошибкой: