Search code examples
telegram-botaiogram

aiogram: How to group, format and send multiple dictionaries


You need to send separate messages schedule for different days. Here is an example input:

raspisanie = [{'week_day': 'Monday, 'name': 'Lesson 1', 'time': '8:30'}, {'week_day': 'Tuesday', name: 'Lesson 1', 'time': '8:30'}, {'week_day': 'Tuesday', name: 'Lesson 2', 'time': '10:30'}])

I can’t figure out how to send one SMS every day so that it looks like this:

First SMS: Monday Lesson 1 8:30 Second SMS: Tuesday Lesson 1 8:30 Lesson 2 10:30

Only the cycle inside message.answer comes to mind, but this is not possible. I will be glad for any help)


Solution

  • For better usage, it is better to save week_day as index. Monday = 0, Tuesday = 1, Wednesday = 2, ... , Sunday = 6. If you still want to keep it as a word, you can write a function to convert the name of the weekday to the index, it is not a big deal tho.

    import datetime
    import asyncio
    
    
    def get_schedule_for_today(schedule: list, current_day: int) -> list:
        schedule_for_today = []
    
        for lesson in schedule:
            if lesson['week_day'] == current_day:
                schedule_for_today.append(lesson)
    
        return schedule_for_today
    
    
    async def daily_worker():
        schedule = [{'week_day': 0, 'name': 'Lesson 1', 'time': '8:30'},
                    {'week_day': 1, 'name': 'Lesson 1', 'time': '8:30'},
                    {'week_day': 1, 'name': 'Lesson 2', 'time': '10:30'}]
    
        schedule_for_today = get_schedule_for_today(schedule, datetime.datetime.today().weekday())
        while True:
            current_hour_minute = datetime.datetime.now().strftime("%H:%M")
    
            if current_hour_minute == '00:00':
                schedule_for_today = get_schedule_for_today(schedule, datetime.datetime.today().weekday())
    
            for lesson in schedule_for_today:
                if lesson['time'] == current_hour_minute:
                    await bot.send_message(chat_id=100, text=f"{lesson['name']}")
    
            await asyncio.sleep(60)
    
    
    if __name__ == '__main__':
        # register new thread to 'executor'
        loop = asyncio.get_event_loop()
        loop.create_task(daily_worker())
    
        executor.start_polling(dp, loop = loop)