async def bc(self, ctx): """ Command that shows your Bitcoin bank. :param ctx: Discord Context """ price = self.getPrice() bc = float(currency.getOrAddUser(ctx.author.id)[8]) currentTime = timeFormatters.dateTimeNow() currentTimeFormatted = currentTime.strftime('%m/%d/%Y om %H:%M:%S') # Create the embed embed = discord.Embed(colour=discord.Colour.gold()) embed.set_author( name="Bitcoin Bank van {}".format(ctx.author.display_name)) embed.add_field(name="Aantal Bitcoins:", value="{:,}".format(round(bc, 8)), inline=False) embed.add_field(name="Huidige waarde:", value="{:,} Didier Dink{}".format( round(bc * price, 8), checks.pluralS(bc * price)), inline=False) embed.set_footer(text="Huidige Bitcoin prijs: €{:,} ({})".format( price, str(currentTimeFormatted))) # Add the Bitcoin icon to the embed file = discord.File("files/images/bitcoin.png", filename="icon.png") embed.set_thumbnail(url="attachment://icon.png") await ctx.send(embed=embed, file=file)
async def checkBirthdays(self): """ Task that wishes people a happy birthday """ # Don't do it multiple times a day if bot dc's, ... with open("files/lastTasks.json", "r") as fp: lastTasks = json.load(fp) if int(self.getCurrentHour()) == 6 and int(time.time()) - int( lastTasks["birthdays"]) > 10000: dt = timeFormatters.dateTimeNow() res = birthdays.get_users_on_date(dt.day, dt.month) COC = self.client.get_guild(int(constants.CallOfCode)) people = [COC.get_member(int(user[0])) for user in res] general = COC.get_channel(int(constants.CoCGeneral)) lastTasks["birthdays"] = round(time.time()) with open("files/lastTasks.json", "w") as fp: json.dump(lastTasks, fp) if not people: return if len(people) == 1: return await general.send("Gelukkige verjaardag {}!".format( people[0].mention)) return await general.send("Gelukkige verjaardag {} en {}!".format( ", ".join(user.mention for user in people[:-1]), people[-1].mention))
async def today(self, ctx): """ Command that lists all birthdays of the day. :param ctx: Discord Context """ # Create a datetime object for today dt = timeFormatters.dateTimeNow() await ctx.send(self.getBirthdayOnDate(dt))
async def week(self, ctx): """ Command that lists all birthdays for the coming week. :param ctx: Discord Context """ # Dict of all birthdays this week this_week = {} # Create a datetime object starting yesterday so the first line # of the loop can add a day every time, # as premature returning would prevent this from happening # & get the day stuck dt = timeFormatters.dateTimeNow() - datetime.timedelta(days=1) # Create an embed embed = discord.Embed(colour=discord.Colour.blue()) embed.set_author(name="Verjaardagen deze week") # Add all people of the coming week for dayCounter in range(7): dt += datetime.timedelta(days=1) res = birthdays.get_users_on_date(dt.day, dt.month) # No birthdays on this day if not res: continue # Add everyone from this day into the dict this_week[str(dayCounter)] = { "day": dt.day, "month": dt.month, "users": [] } for user in res: this_week[str(dayCounter)]["users"].append(user[0]) # No one found if not this_week: embed.description = "Deze week is er niemand jarig." return await ctx.send(embed=embed) COC = self.client.get_guild(int(constants.CallOfCode)) # For every day, add the list of users into the embed for day, value in this_week.items(): dayDatetime, timeString = self.dmToDatetime( int(value["day"]), int(value["month"])) weekday = timeFormatters.intToWeekday(dayDatetime.weekday()) embed.add_field(name="{} {}".format(weekday, timeString), value=", ".join( COC.get_member(user).mention for user in value["users"]), inline=False) await ctx.send(embed=embed)
async def price(self, ctx): """ Command that shows the current Bitcoin price. :param ctx: Discord Context """ price = self.getPrice() currentTime = timeFormatters.dateTimeNow() currentTimeFormatted = currentTime.strftime('%m/%d/%Y om %H:%M:%S') await ctx.send("Huidige Bitcoin prijs: **€{:,}** ({}).".format( price, str(currentTimeFormatted)))
def findDate(targetWeekday): """ Function that finds the datetime object that corresponds to the next occurence of [targetWeekday]. :param targetWeekday: The weekday to find """ now = timeFormatters.dateTimeNow() while now.weekday() != targetWeekday: now = now + datetime.timedelta(days=1) return now
async def tomorrow(self, ctx): """ Command that lists all birthdays of tomorrow. :param ctx: Discord Context """ # Create a datetime object for tomorrow dt = timeFormatters.dateTimeNow() + datetime.timedelta(days=1) await ctx.send( self.getBirthdayOnDate(dt).replace("Vandaag", "Morgen").replace( "vandaag", "morgen"))
async def set(self, ctx, date=None, member: discord.Member = None): """ Command to add your birthday into the database. :param ctx: Discord Context :param date: the date of your birthday :param member: another member whose birthday has to be added/changed """ # No date passed if date is None: return await ctx.send("Geef een datum op.") # Invalid format used if date.count("/") != 2: return await ctx.send("Ongeldig formaat (gebruik DD/MM/YYYY).") # Check if anything is wrong with the date try: day = int(date.split("/")[0]) month = int(date.split("/")[1]) year = int(date.split("/")[2]) # This is not used, but creating an invalid datetime object throws a ValueError # so it prevents invalid dates like 69/420/360 dt = datetime.datetime(year=year, month=month, day=day) # Assume no one in the Discord is more than 5 years younger, or 10 years older # (which are also virtually impossible, but just to be sure) if year >= timeFormatters.dateTimeNow().year - 15 or year < 1990: raise ValueError except ValueError: return await ctx.send("Dit is geen geldige datum.") # A member was tagged, check if I did it if member is not None: if str(ctx.author.id) != str(constants.myId): return await ctx.send( "Je kan andere mensen hun verjaardag niet instellen, {}.". format(ctx.author.display_name)) else: birthdays.add_user(member.id, day, month, year) return await ctx.message.add_reaction("✅") # Birthday is already added if birthdays.get_user( ctx.author.id) and str(ctx.author.id) != constants.myId: return await ctx.send("Je verjaardag zit al in de database.") # Add into the db birthdays.add_user(ctx.author.id, day, month, year) return await ctx.send("Je verjaardag is toegevoegd aan de database.")
async def government(self, ctx): now = timeFormatters.dateTimeNow() newGov = datetime.datetime.fromtimestamp( 1601539200, tz=pytz.timezone("Europe/Brussels")) delta = now - newGov zin = "Na **494** dagen is er weer een regering, **47** dagen te vroeg om het record te breken. Very sad times.\nMAAR hoelang denk je dat de nieuwe regering het gaat volhouden? Place your bets! Momenteel zitten we aan **{}** dag{}.".format( delta.days, "en" if delta.days != 1 else "") # now = int(time.time()) # valVorige = 1545350400 # verkiezingen = 1558828800 # valDiff = now - valVorige # verkiezingenDiff = now - verkiezingen # zin = ( # "We zitten al **%d** dagen zonder regering, en proberen al **%d** dagen een nieuwe te vormen.\nHet " # "huidige wereldrecord is " # "**541** dagen, dus nog **%d** dagen tot we het gebroken hebben." % # (valDiff // 86400, verkiezingenDiff // 86400, 541 - int(verkiezingenDiff // 86400))) await ctx.send(zin)
def dmToDatetime(self, day, month): """ Converts a day + month to a datetime instance. :param day: the day in the date :param month: the month in the date :return: a datetime instance representing the next time this date occurs, and a formatted string for this date """ now = timeFormatters.dateTimeNow() year = now.year # Add an extra year to the date in case it has already passed if month < now.month or (month == now.month and day < now.day): year += 1 # Create a datetime object for this birthday timeString = "{}/{}/{}".format( stringFormatters.leadingZero(str(day)), stringFormatters.leadingZero(str(month)), year) dayDatetime = datetime.datetime.strptime(timeString, "%d/%m/%Y") return dayDatetime, timeString
def getCurrentWeekday(self): return timeFormatters.dateTimeNow().weekday()
def getCurrentHour(self): return timeFormatters.dateTimeNow().hour
def findDate(self, targetWeekday): now = timeFormatters.dateTimeNow() while now.weekday() != targetWeekday: now = now + datetime.timedelta(days=1) return now