Skip to content

Commit

Permalink
Merge pull request #32 from PaulMarisOUMary/fixes
Browse files Browse the repository at this point in the history
Fixes
  • Loading branch information
PaulMarisOUMary authored Mar 21, 2022
2 parents 6b4ed6f + 37df029 commit 47a239c
Show file tree
Hide file tree
Showing 16 changed files with 156 additions and 90 deletions.
24 changes: 16 additions & 8 deletions cogs/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@

class Admin(commands.Cog, name="admin"):
"""Admin commands, you probably don't have the permission to use them."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = '⚙️'
label = "Admin"
description = "Show the list of admin commands."
Expand All @@ -28,7 +28,8 @@ async def reload_views(self) -> list[str]:
if os.path.basename(os.path.dirname(module.__file__)) == "views":
reload(module)
infants.append(module.__name__)
except: pass
except:
pass

return infants

Expand Down Expand Up @@ -56,9 +57,11 @@ async def reload_all(self, ctx):
await ctx.send(f"{e.__class__.__name__}: {e}")
else:
succes_text = f"💪 All cogs reloaded ! | ☠️ __`{len(victims)} task(s) killed`__ : "
for victim in victims: succes_text += f"`{victim.replace('cogs.', '')}` "
for victim in victims:
succes_text += f"`{victim.replace('cogs.', '')}` "
succes_text += f"| 🔄 __`{len(infants)} view(s) reloaded`__ : "
for infant in infants: succes_text += f"`{infant.replace('views.', '')}` "
for infant in infants:
succes_text += f"`{infant.replace('views.', '')}` "
await ctx.send(succes_text)

@commands.command(name="reload", aliases=["rel"], require_var_positional=True)
Expand All @@ -84,7 +87,8 @@ async def reload_latest(self, ctx):
if actual[1] == ".py":
file_path = os.path.join(cogs_directory, file)
latest_edit = os.path.getmtime(file_path)
if latest_edit > latest_cog[1]: latest_cog = (actual[0], latest_edit)
if latest_edit > latest_cog[1]:
latest_cog = (actual[0], latest_edit)

try:
victims = await self.reload_cogs([f"cogs.{latest_cog[0]}"])
Expand All @@ -103,7 +107,8 @@ async def reload_view(self, ctx):
await ctx.send(f"{e.__class__.__name__}: {e}")
else:
succes_text = f"👌 All views reloaded ! | 🔄 __`{len(infants)} view(s) reloaded`__ : "
for infant in infants: succes_text += f"`{infant.replace('views.', '')}` "
for infant in infants:
succes_text += f"`{infant.replace('views.', '')}` "
await ctx.send(succes_text)

@commands.command(name="killloop", aliases=["kill"], require_var_positional=True)
Expand All @@ -114,10 +119,12 @@ async def kill_loop(self, ctx, cog):
if "return_loop_task" in dir(cogs):
cogs.return_loop_task().cancel()
await ctx.send("Task successfully killed")
else : await ctx.send("Task not found..")
else:
await ctx.send("Task not found..")

@commands.command(name="deletechannel", aliases=["delc"], require_var_positional=True)
@commands.is_owner()
@commands.guild_only()
async def delete_channel(self, ctx, channel_name):
"""Delete the provided channel."""
channel = discord.utils.get(ctx.guild.channels, name=channel_name)
Expand All @@ -128,6 +135,7 @@ async def delete_channel(self, ctx, channel_name):

@commands.command(name="changeprefix", aliases=["cp"], require_var_positional=True)
@commands.has_guild_permissions(administrator=True)
@commands.guild_only()
async def change_guild_prefix(self, ctx, new_prefix):
"""Change the guild prefix."""
try:
Expand Down
5 changes: 3 additions & 2 deletions cogs/basic.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import time
from tkinter import NONE

from discord.ext import commands

class Basic(commands.Cog, name="basic"):
"""Basic commands, like ping."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = '📙'
label = "Basic"
description = "Basic commands, like ping."
Expand Down
13 changes: 8 additions & 5 deletions cogs/birthday.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@

class Birthday(commands.Cog, name="birthday"):
"""I'll wish you soon a happy birthday !"""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot

self.birthday_data = self.bot.database_data["birthday"]

self.daily_birthday.start()

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = '🎁'
label = "Birthday"
description = "Maybe I'll wish you soon a happy birthday !"
Expand All @@ -42,7 +42,8 @@ async def daily_birthday(self):
"https://sayingimages.com/wp-content/uploads/funny-birthday-and-believe-me-memes.jpg",
"https://i.kym-cdn.com/photos/images/newsfeed/001/988/649/1e8.jpg",
"https://winkgo.com/wp-content/uploads/2018/08/101-Best-Happy-Birthday-Memes-01-720x720.jpg",
"https://www.the-best-wishes.com/wp-content/uploads/2022/01/success-kid-cute-birthday-meme-for-her.jpg"]
"https://www.the-best-wishes.com/wp-content/uploads/2022/01/success-kid-cute-birthday-meme-for-her.jpg"
]

embed = discord.Embed(title="🎉 Happy birthday !", description=message, colour=discord.Colour.dark_gold())
embed.set_image(url=images[random.randint(0, len(images)-1)])
Expand All @@ -60,7 +61,8 @@ async def birthday(self, ctx, date: str = None):
if date:
try:
dataDate = datetime.strptime(date, "%d/%m/%Y").date()
if dataDate.year > datetime.now().year - 15 or dataDate.year < datetime.now().year - 99: raise commands.CommandError("Please provide your real year of birth.")
if dataDate.year > datetime.now().year - 15 or dataDate.year < datetime.now().year - 99:
raise commands.CommandError("Please provide your real year of birth.")
# Insert
await self.bot.database.insert(self.birthday_data["table"], {"user_id": ctx.author.id, "user_birth": dataDate})
# Update
Expand All @@ -78,7 +80,8 @@ async def birthday(self, ctx, date: str = None):
@commands.cooldown(1, 5, commands.BucketType.user)
async def show_birthday(self, ctx, user: discord.Member = None):
"""Allows you to show the birthday of other users."""
if not user: user = ctx.author
if not user:
user = ctx.author
await self.show_birthday_message(ctx, user)

async def show_birthday_message(self, ctx, user:discord.Member) -> None:
Expand Down
12 changes: 7 additions & 5 deletions cogs/croissants.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

class Croissants(commands.Cog, name="croissants", command_attrs=dict(hidden=True)):
"""Don't leave your computer unlocked !"""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot

self.EMOJI = '🥐'
Expand All @@ -19,7 +19,7 @@ def __init__(self, bot):

self.croissants_data = self.bot.database_data["croissants"]

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = self.EMOJI
label = "Croissants"
description = "For when someone left their computer unlocked."
Expand Down Expand Up @@ -80,8 +80,10 @@ def __get_screenshot(self, author : discord.Member, content : str) -> discord.Fi
pfp_content = Image.open(BytesIO(requests.get(author.display_avatar.url).content))
images_sequence, duration_array = [], []
for frame in ImageSequence.Iterator(pfp_content):
try: duration_array.append(frame.info["duration"])
except: duration_array.append(0)
try:
duration_array.append(frame.info["duration"])
except:
duration_array.append(0)

img = Image.new("RGBA", size=(500, 100), color=bg_color)
resized_pfp = frame.resize(pfp_size)
Expand Down Expand Up @@ -111,7 +113,7 @@ def __get_screenshot(self, author : discord.Member, content : str) -> discord.Fi
def __is_on_cooldown(self, user) -> bool:
return user.id in self.cooldown and datetime.now().timestamp() - self.cooldown[user.id].timestamp() < self.bot.database_data["croissants"]["cooldown"]

def __rank_emoji(self, rank):
def __rank_emoji(self, rank) -> str:
if rank == 1:
return '🥇'
elif rank == 2:
Expand Down
4 changes: 2 additions & 2 deletions cogs/dad.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

class Dad(commands.Cog, name="dad", command_attrs=dict(hidden=True)):
"""Dad's jokes."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot
self.settings = bot.bot_data["dad"]
self.pattern = re.compile(r"""
Expand All @@ -15,7 +15,7 @@ def __init__(self, bot):
(?P<name>.+) # The name
""", re.VERBOSE + re.IGNORECASE)

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = '👨‍🦳'
label = "Dad's jokes"
description = "Ahah, it was a good one!"
Expand Down
7 changes: 5 additions & 2 deletions cogs/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class Errors(commands.Cog, name="errors"):
"""Errors handler."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot

"""def help_custom(self):
Expand Down Expand Up @@ -31,7 +31,8 @@ async def get_command_error(self, ctx, error):
await message.edit(f"🕳️ Command is on cooldown, wait `{str(error).split(' ')[7]}` !")
elif isinstance(error, commands.errors.MissingRequiredArgument):
command, params = ctx.command, ""
for param in command.clean_params: params += " {"+str(param)+'}'
for param in command.clean_params:
params += " {"+str(param)+'}'
await message.edit(f"🕳️ Something is missing. `?{command}{params}`")
elif isinstance(error, commands.errors.MemberNotFound):
await message.edit(f"🕳️ Member `{str(error).split(' ')[1]}` not found ! Don't hesitate to ping the requested member.")
Expand All @@ -45,5 +46,7 @@ async def get_command_error(self, ctx, error):
except Exception as e:
print(f"! Cogs.errors get_command_error : {type(error).__name__} : {error}\n! Internal Error : {e}\n")



def setup(bot):
bot.add_cog(Errors(bot))
18 changes: 10 additions & 8 deletions cogs/fridaycake.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def mix_participants(participants : list, seed : int, n_group : int) -> list[lis

class FridayCake(commands.Cog, name="fridaycake", command_attrs=dict(hidden=False)):
"""FridayCake's event commands."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self.bot = bot
self.cakes = ['🎂', '🥮', '🥧', '🥯', '🧁', '🫓', '🧇', '🍞', '🍮', '🍰', '🥐']

Expand All @@ -52,19 +52,19 @@ def __init__(self, bot):

self.bot.loop.create_task(self.initFridaycake())

async def initFridaycake(self):
async def initFridaycake(self) -> None:
participants = await self.bot.database.select(self.fridaycake_data["table"], "user_id, user_name", "user_isin = 1", "user_name ASC")
participants = [[*row] for row in participants] #convert tuple of tuples to list of lists
self.participants = mix_participants(participants, self.seed, 2)
self.nparticipants = len(participants) #mandatory in fridaycake view

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = random.choice(self.cakes)
label = "FridayCake"
description = "Commands relative to the FridayCake event !"
return emoji, label, description

def all(self, ctx):
def all(self, ctx) -> discord.Embed:
author = ctx.message.author
embed = discord.Embed(title=f"{random.choice(self.cakes)} Fridaycake · All", description="`Show your personnal order of passage.`\n\u200b" ,colour=0xf7346b, url='https://github.com/PaulMarisOUMary/Algosup-Discord')
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/332696002144501760/800791318200188998/fridaycake.png")
Expand All @@ -76,7 +76,7 @@ def all(self, ctx):
embed.add_field(name=f"Friday {_date.strftime('%d %B, %Y')}", value=f"~~{string[0:-4]}~~" if date.today() >= _date else f"{string[0:-4]}", inline=False)
return embed

def next(self, ctx):
def next(self, ctx) -> discord.Embed:
author, pin = ctx.message.author, []
for participants, _date in zip(self.participants, get_dates(start, holidays, len(self.participants))):
if date.today() <= _date:
Expand All @@ -94,11 +94,12 @@ def next(self, ctx):
embed.add_field(name="👥 Participants :", value=participants, inline=False)
return embed

def when(self, author):
def when(self, author) -> discord.Embed:
pin = None
for participants, _date in zip(self.participants, get_dates(start, holidays, len(self.participants))):
for participant in participants:
if int(participant[0]) == author.id: pin = (participants, _date)
if int(participant[0]) == author.id:
pin = (participants, _date)
if not pin:
raise commands.CommandError("You are not registered for the FridayCake.")
else:
Expand Down Expand Up @@ -138,7 +139,8 @@ async def fridaycake(self, ctx):
view.stop()
await message.delete()
await ctx.message.add_reaction("<a:checkmark_a:842800730049871892>")
except: pass
except:
pass

@commands.command(name='next', aliases=['n', 'fn'])
async def next_cake(self, ctx):
Expand Down
9 changes: 5 additions & 4 deletions cogs/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ async def send_bot_help(self, mapping) -> None:
view.stop()
await message.delete()
await self.context.message.add_reaction("<a:checkmark_a:842800730049871892>")
except: pass
except:
pass

async def send_command_help(self, command):
cog = command.cog
Expand Down Expand Up @@ -68,7 +69,7 @@ async def send_group_help(self, group):

class Help(commands.Cog, name="help"):
"""Help commands."""
def __init__(self, bot):
def __init__(self, bot) -> None:
self._original_help_command = bot.help_command

attributes = {
Expand All @@ -80,10 +81,10 @@ def __init__(self, bot):
bot.help_command = HelpCommand(command_attrs=attributes)
bot.help_command.cog = self

def cog_unload(self):
def cog_unload(self) -> None:
self.bot.help_command = self._original_help_command

def help_custom(self):
def help_custom(self) -> tuple[str]:
emoji = '🆘'
label = "Help"
description = "Help utilities."
Expand Down
Loading

0 comments on commit 47a239c

Please sign in to comment.