Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Standard Library
- import asyncio
- import calendar
- import logging
- import time
- import uuid
- from datetime import datetime, timedelta
- # Discord.py
- import discord
- # Red
- from redbot.core import commands, Config
- log = logging.getLogger("red.Timer")
- __author__ = "Jarquafelmu"
- __version__ = "0.0.1"
- class Timer(commands.Cog):
- """Workspace to develop timers"""
- guild_id = 493101259012702208
- channel_id = 493101259012702210
- default_guild_settings = {
- "current_timers": [],
- "ignored": False
- }
- default_global_settings = {
- "timer": {
- "id": False,
- "end": False,
- "reason": False
- }
- }
- def __init__(self, bot):
- self.bot = bot
- self.db = Config.get_conf(self, 5348562126, force_registration=True)
- self.db.register_guild(**self.default_guild_settings)
- self.db.register_global(**self.default_global_settings)
- #self.load_check = self.bot.create_task(self.one_off_timer_worker())
- #self.loop1 = self.bot.loop.create_task(self.timer_example_one)
- self.timer_queue = []
- self.timer_expiry_task = self.bot.loop.create_task(self.check_timer_expirations())
- def __unload(self):
- """Handles unloading this instance"""
- self.timer_expiry_task.cancel()
- #async def timer_example_one(self):
- # """
- # Post something every day at a particular time
- # """
- #
- # guild = self.bot.get_guild(guild_id)
- # destination = guild.get_channel(channel_id)
- #
- # while self.bot.get_cog('TimerExample') is not None:
- # if datetime.datetime.now().strftime("%H%M") == time:
- # await destination.send(f"It is {time}!")
- # await asyncio.sleep(20)
- @commands.command(alias=["new_chapter", "newChapter", "discussion_blackout", "discussionBlackout"])
- async def blackout(self, ctx, chapter_number: int):
- """
- Creates a blackout period where speaking about the latest chapter is not allowed until 24 hours past the post time.
- """
- if chapter_number is None:
- return await ctx.send('Must supply a chapter number. Use help with this command for more information.')
- guild = ctx.guild
- author = ctx.author
- time_delta = timedelta(minutes=3)
- blackout_lift_time = datetime.utcnow() + time_delta
- # create a new timer
- timer = {
- "end": blackout_lift_time.timestamp(),
- "reason": f'Chapter {chapter_number}'
- }
- # add the timer to the list of timers
- cur_timers = await self.db.guild(guild).current_timers()
- cur_timers.append(timer)
- await self.db.guild(guild).current_timers.set(cur_timers)
- await self.start_timers()
- fmt_end = blackout_lift_time.strftime("%m-%d-%Y %H:%M:%S")
- title = 'Discussion Ban'
- description = (
- f"Created discussion ban for {timer['reason']}."
- )
- embed = discord.Embed(description=description, title=title, color=0x50bdfe)
- embed.set_footer(text=f"Started by {ctx.author.name} | Ends {fmt_end} UTC")
- await ctx.channel.send(embed=embed)
- async def check_timer_expirations(self):
- """
- Checks the currently running timers and see if any of them are done.
- """
- channel = self.bot.get_channel(self.channel_id)
- while self == self.bot.get_cog("Timer"):
- await channel.send("Checking Timers")
- for guild in self.bot.guilds:
- async with self.db.guild(guild).current_timers() as timers:
- for uid in timers.copy():
- await channel.send(f"Checking Timer: {uid}")
- end_time = datetime.utcfromtimestamp(
- uid['end']
- )
- now = datetime.utcnow()
- await channel.send(f"Timer end time: {end_time}")
- await channel.send(f"Now(): {now}")
- if now > end_time: # time to finish the timer
- await channel.send(f"Timer {uid} si done")
- await self.timer_finished(uid)
- timers.remove(uid)
- await asyncio.sleep(60)
- async def start_timers(self):
- """
- Starts the timer process
- """
- self.timer_expiry_task.cancel()
- self.timer_expiry_task = self.bot.loop.create_task(self.check_timer_expirations())
- @commands.command()
- async def clear(self, ctx):
- """Clears timers"""
- await self.db.guild(ctx.guild).current_timers.set([])
- @commands.command(alias=['stop'])
- async def stop_timers(self):
- """Stops timers"""
- self.timer_expiry_task.cancel()
- async def timer_finished(self, timer):
- """
- Handles the tasks when a timer is finished
- """
- channel = self.bot.get_channel(self.channel_id)
- title = 'Discussion Ban'
- description = (
- f'The discussion ban for {timer.reason} is over!'
- )
- embed = discord.Embed(description=description, title=title, color=0x50bdfe)
- await channel.send(embed=embed)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement