Skip to content

Christmas Module

nbaak edited this page Jan 1, 2024 · 5 revisions

Christmas Module

The Christmas Module is a funny experiment to learn more about the Discord.py API.

The Module should count down the days to next Christmas in a Channel.

Channel

At first I thought it might be a nice idea if the bot creates and manages it's own channel. This idea is maybe just a little annoying for all the human users, so I decided it is better if we tell the bot where it should post the Christmas Countdown.

Now we have an Administrator Slash-Command /setchristmaschannel:

/setchristmaschannel <channel:Optional>

The Bot will manage the channels in a Dictionary {guild_id: channel_id}. Every time the daily Trigger runs it checks all the entries in this Dictionary and sends Messages if there are some.

Tasks

To Count down, I use the tasks component of discord.ext.

import datetime
from discord.ext import commands, tasks

utc = datetime.timezone.utc

# If no tzinfo is given then UTC is assumed.
time = datetime.time(hour=8, minute=30, tzinfo=utc)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.my_task.start()

    def cog_unload(self):
        self.my_task.cancel()

    @tasks.loop(time=time)
    async def my_task(self):
        print("My task is running!")

Leap Year Problem

Not all Years are 365 days long, so we have to detect if the year, where next christmas is in, is a leap year. If it is a leap year, we set year length to 366 days, else it is 365.

next_christmas_year = ChristmasCountdown.next_christmas_year()
...
# Progress Bar
progress_bar = ProgressBar(366 if Calendar.is_leap_year(next_christmas_year) else 365, 50)
Clone this wiki locally