Advertisement
Jarquafelmu

Untitled

Oct 17th, 2018
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.52 KB | None | 0 0
  1. #Standard Library
  2. import asyncio
  3. import calendar
  4. import logging
  5. import time
  6. import uuid
  7. from datetime import datetime, timedelta
  8.  
  9. # Discord.py
  10. import discord
  11.  
  12. # Red
  13. from redbot.core import commands, Config
  14.  
  15. log = logging.getLogger("red.Timer")
  16.  
  17. __author__ = "Jarquafelmu"
  18. __version__ = "0.0.1"
  19.  
  20.  
  21. class Timer(commands.Cog):
  22.     """Workspace to develop timers"""
  23.    
  24.     guild_id = 493101259012702208
  25.     channel_id = 493101259012702210
  26.        
  27.     default_guild_settings = {
  28.         "current_timers": [],
  29.         "ignored": False
  30.     }    
  31.    
  32.     default_global_settings = {
  33.         "timer": {
  34.             "id": False,
  35.             "end": False,
  36.             "reason": False
  37.         }
  38.     }
  39.    
  40.     def __init__(self, bot):
  41.         self.bot = bot
  42.         self.db = Config.get_conf(self, 5348562126, force_registration=True)
  43.         self.db.register_guild(**self.default_guild_settings)
  44.         self.db.register_global(**self.default_global_settings)
  45.         #self.load_check = self.bot.create_task(self.one_off_timer_worker())
  46.         #self.loop1 = self.bot.loop.create_task(self.timer_example_one)
  47.        
  48.         self.timer_queue = []
  49.         self.timer_expiry_task = self.bot.loop.create_task(self.check_timer_expirations())
  50.        
  51.     def __unload(self):
  52.         """Handles unloading this instance"""
  53.         self.timer_expiry_task.cancel()  
  54.        
  55.     #async def timer_example_one(self):
  56.     #    """
  57.     #    Post something every day at a particular time
  58.     #    """
  59.     #    
  60.     #    guild = self.bot.get_guild(guild_id)
  61.     #    destination = guild.get_channel(channel_id)
  62.     #    
  63.     #    while self.bot.get_cog('TimerExample') is not None:
  64.     #        if datetime.datetime.now().strftime("%H%M") == time:
  65.     #            await destination.send(f"It is {time}!")
  66.     #        await asyncio.sleep(20)
  67.    
  68.     @commands.command(alias=["new_chapter", "newChapter", "discussion_blackout", "discussionBlackout"])
  69.     async def blackout(self, ctx, chapter_number: int):
  70.         """
  71.        Creates a blackout period where speaking about the latest chapter is not allowed until 24 hours past the post time.
  72.        """
  73.         if chapter_number is None:
  74.             return await ctx.send('Must supply a chapter number. Use help with this command for more information.')
  75.        
  76.         guild = ctx.guild
  77.         author = ctx.author
  78.         time_delta = timedelta(minutes=3)
  79.         blackout_lift_time = datetime.utcnow() + time_delta
  80.        
  81.         # create a new timer
  82.         timer = {
  83.             "end": blackout_lift_time.timestamp(),
  84.             "reason": f'Chapter {chapter_number}'
  85.         }
  86.        
  87.         # add the timer to the list of timers
  88.         cur_timers = await self.db.guild(guild).current_timers()
  89.         cur_timers.append(timer)
  90.         await self.db.guild(guild).current_timers.set(cur_timers)
  91.         await self.start_timers()
  92.        
  93.         fmt_end = blackout_lift_time.strftime("%m-%d-%Y %H:%M:%S")
  94.        
  95.         title = 'Discussion Ban'
  96.         description = (
  97.             f"Created discussion ban for {timer['reason']}."
  98.         )
  99.         embed = discord.Embed(description=description, title=title, color=0x50bdfe)
  100.         embed.set_footer(text=f"Started by {ctx.author.name} | Ends {fmt_end} UTC")
  101.         await ctx.channel.send(embed=embed)
  102.        
  103.        
  104.        
  105.     async def check_timer_expirations(self):
  106.         """
  107.        Checks the currently running timers and see if any of them are done.
  108.        """
  109.         channel = self.bot.get_channel(self.channel_id)
  110.         while self == self.bot.get_cog("Timer"):
  111.             await channel.send("Checking Timers")
  112.             for guild in self.bot.guilds:
  113.                 async with self.db.guild(guild).current_timers() as timers:
  114.                     for uid in timers.copy():
  115.                         await channel.send(f"Checking Timer: {uid}")
  116.                         end_time = datetime.utcfromtimestamp(
  117.                             uid['end']
  118.                         )
  119.                         now = datetime.utcnow()
  120.                         await channel.send(f"Timer end time: {end_time}")
  121.                         await channel.send(f"Now(): {now}")
  122.                         if now > end_time:  # time to finish the timer
  123.                             await channel.send(f"Timer {uid} si done")                            
  124.                             await self.timer_finished(uid)
  125.                             timers.remove(uid)
  126.             await asyncio.sleep(60)
  127.            
  128.            
  129.     async def start_timers(self):
  130.         """
  131.        Starts the timer process
  132.        """
  133.         self.timer_expiry_task.cancel()
  134.         self.timer_expiry_task = self.bot.loop.create_task(self.check_timer_expirations())
  135.    
  136.     @commands.command()
  137.     async def clear(self, ctx):
  138.         """Clears timers"""
  139.         await self.db.guild(ctx.guild).current_timers.set([])
  140.        
  141.    
  142.     @commands.command(alias=['stop'])
  143.     async def stop_timers(self):
  144.         """Stops timers"""
  145.        
  146.         self.timer_expiry_task.cancel()
  147.        
  148.    
  149.     async def timer_finished(self, timer):
  150.         """
  151.        Handles the tasks when a timer is finished
  152.        """
  153.         channel = self.bot.get_channel(self.channel_id)
  154.        
  155.         title = 'Discussion Ban'
  156.         description = (
  157.             f'The discussion ban for {timer.reason} is over!'
  158.         )
  159.         embed = discord.Embed(description=description, title=title, color=0x50bdfe)
  160.         await channel.send(embed=embed)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement