small code smell cleanups

This commit is contained in:
LBlend committed 2024-03-27 22:16:59 +01:00
1 parent 30d6f8e538
commit 22c18ac7d5
9 files changed
+54 -57

No files matched your search

+2 -1
View File
@@ -22,6 +22,7 @@ class Aurora(commands.Cog):
self.notified = datetime(2000, 9, 11) # Used to prevent spamming aurora alerts
# self.aurora_alarm.start()
self.AURORA_CHANNEL = 747542544291987599
async def get_forecast(self) -> dict | None:
"""
@@ -76,7 +77,7 @@ class Aurora(commands.Cog):
self.bot.logger.info("aurora_alarm: Fetch forecast")
return
channel = self.bot.get_channel(747542544291987599)
channel = self.bot.get_channel(self.AURORA_CHANNEL)
if not channel:
self.bot.logger.warning("aurora_alarm: Failed to get aurora channel")
return
+12 -9
View File
@@ -68,15 +68,18 @@ class Birthday(commands.Cog):
birthdays = self.cursor.fetchall()
self.bot.logger.info(f"Found the following birthdays: {birthdays}") # TODO: Temporary. Remove
if birthdays:
guild = self.bot.get_guild(747542543750660178)
channel = guild.get_channel(747542544291987597)
for birthday in birthdays:
user = await guild.fetch_member(birthday[0])
if user:
await channel.send(f"Gratulerer med dagen {user.mention}! 🥳")
else:
self.bot.logger.warning(f"Could not find user with ID {birthday[0]}")
if not birthdays:
return
guild = self.bot.get_guild(self.bot.UIO_GAMING_GUILD_ID)
channel = guild.get_channel(747542544291987597)
for birthday in birthdays:
user = await guild.fetch_member(birthday[0])
if user:
await channel.send(f"Gratulerer med dagen {user.mention}! 🥳")
else:
self.bot.logger.warning(f"Could not find user with ID {birthday[0]}")
@birthday_check.before_loop
async def before_birthday_check(self):
+2 -2
View File
@@ -180,10 +180,10 @@ class Gullkorn(commands.Cog):
most_cited_string = self.construct_data_string(most_cited)
citations_posted_string = self.construct_data_string(citations_posted)
gullkorn_first_msg = "https://canary.discord.com/channels/747542543750660178/865970753748074576/1034587913285025912" # noqa: E501
GULLKORN_FIRST_MSG = "https://canary.discord.com/channels/747542543750660178/865970753748074576/1034587913285025912" # noqa: E501
embed = discord.Embed(title="Gullkornstatistikk for serveren")
embed.description = f"Antall gullkorn siden [denne meldingen]({gullkorn_first_msg}): *{summary[0]}*"
embed.description = f"Antall gullkorn siden [denne meldingen]({GULLKORN_FIRST_MSG}): *{summary[0]}*"
embed.add_field(name="Mest sitert", value=most_cited_string, inline=False)
embed.add_field(name="Postet mest", value=citations_posted_string, inline=False)
await interaction.response.send_message(embed=embed, ephemeral=False)
+1 -2
View File
@@ -149,7 +149,7 @@ class Info(commands.Cog):
# Features
features_string = ""
if interaction.guild.features is not []:
if interaction.guild.features != []:
features = {
"ANIMATED_BANNER": "Animer serverbanner",
"ANIMATED_ICON": "Animert serverikon",
@@ -548,7 +548,6 @@ class Info(commands.Cog):
paginator = misc_utils.Paginator(members_formatted)
view = discord_utils.Scroller(paginator, interaction.user)
# Send first page
embed = view.construct_embed(
discord.Embed(
color=interaction.guild.me.color, title="Eldste brukere på serveren basert på når de ble lagd"
+1 -2
View File
@@ -144,7 +144,7 @@ class Meme(commands.Cog):
font_size += 2
# Draw textbox and text
text_box = draw.multiline_textbbox(box_size, text=text, font=font, align="center", anchor="mm")
draw.multiline_textbbox(box_size, text=text, font=font, align="center", anchor="mm") # TODO: remove?
text_box = box.size[0] // 2, box.size[1] // 2
draw.multiline_text(text_box, text, font=font, fill=(0, 0, 0, 255), align="center", anchor="mm")
@@ -206,7 +206,6 @@ class Meme(commands.Cog):
os.remove(temp_file)
except (FileNotFoundError, PermissionError):
self.bot.logger.warn(f"Failed to remove temporary file {temp_file}")
pass
@staticmethod
def make_crab(top_text: str, bottom_text: str, user_id: int):
+10 -15
View File
@@ -10,16 +10,11 @@ class RepeatedMessages(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.general_channel = 747542544291987597
# @aiocron.crontab('37 13 * * *')
# async def leet():
# """Sends a message at leet gamer hours"""
# guild = self.bot.get_guild(747542543750660178)
# channel = guild.get_channel(747542544291987597)
# sticker = await guild.fetch_sticker(1046948904471633951)
# await asyncio.sleep(1)
# await channel.send(stickers=[sticker])
# Yes we have to have these inside the constructor
# Probably could've implemented the waiting functions myself
# but that sounds like work and I don't like to work
@aiocron.crontab("0 0 * * 5")
async def fredag():
@@ -27,8 +22,8 @@ class RepeatedMessages(commands.Cog):
Sends a message on Friday at 00:00
"""
guild = self.bot.get_guild(747542543750660178)
channel = guild.get_channel(747542544291987597)
guild = self.bot.get_guild(self.bot.UIO_GAMING_GUILD_ID)
channel = guild.get_channel(self.general_channel)
videos = [
"https://cdn.discordapp.com/attachments/750052141346979850/851216786259181578/video0.mp4",
@@ -54,8 +49,8 @@ class RepeatedMessages(commands.Cog):
Sends a message on Monday at 00:00
"""
guild = self.bot.get_guild(747542543750660178)
channel = guild.get_channel(747542544291987597)
guild = self.bot.get_guild(self.bot.UIO_GAMING_GUILD_ID)
channel = guild.get_channel(self.general_channel)
await channel.send(
"ENDELIG MANDAG!\n\n"
# + "https://cdn.discordapp.com/attachments/678396498089738250/862853827278929940/hvorfor_de_rike_br_spises.mp4" # noqa: E501
@@ -68,8 +63,8 @@ class RepeatedMessages(commands.Cog):
Sends a message on New Year's Day at 00:00
"""
guild = self.bot.get_guild(747542543750660178)
channel = guild.get_channel(747542544291987597)
guild = self.bot.get_guild(self.bot.UIO_GAMING_GUILD_ID)
channel = guild.get_channel(self.general_channel)
await channel.send(
"GODT NYTTÅR!\n\nNå, meld dere inn i UiO Gaming igjen <:ThisIsAThreat:874998234072903710>"
)
+13 -14
View File
@@ -221,8 +221,9 @@ class SocialCredit(commands.Cog):
ORDER BY credit_score DESC
"""
)
result = self.cursor.fetchall()
if not (result := self.cursor.fetchall()):
if not result:
return await interaction.send(
embed=embed_templates.error_warning("Ingen brukere er registrert i databasen")
)
@@ -324,10 +325,10 @@ class SocialCredit(commands.Cog):
message (discord.Message): The message object
"""
if message.channel.id == 865970753748074576:
if message.mentions:
for mention in message.mentions:
await self.social_punishment(mention.id, 10, "gullkorn")
# This only works in the UiO Gaming server as well
if message.channel.id == 865970753748074576 and message.mentions:
for mention in message.mentions:
await self.social_punishment(mention.id, 10, "gullkorn")
@commands.Cog.listener("on_reaction_add")
async def on_star_add(self, reaction: discord.Reaction, user: discord.User | discord.Member):
@@ -346,12 +347,11 @@ class SocialCredit(commands.Cog):
if reaction.emoji == "⭐":
if reaction.message.author == user:
await self.social_punishment(user.id, 100, "self-star")
else:
if len(reaction.message.reactions) >= 3:
await self.social_punishment(
user.id, (len(reaction.message.reactions) - 1) * 25, "remove already accumulated stars"
)
await self.social_reward(user.id, 25 * len(reaction.message.reactions), "add new stars")
elif reaction.count == 3:
await self.social_punishment(
user.id, (len(reaction.message.reactions) - 1) * 25, "remove already accumulated stars"
)
await self.social_reward(user.id, 25 * len(reaction.message.reactions), "add new stars")
@commands.Cog.listener("on_reaction_remove")
async def on_star_remove(self, reaction: discord.Reaction, user: discord.User | discord.Member):
@@ -362,9 +362,8 @@ class SocialCredit(commands.Cog):
if user.bot:
return
if reaction.emoji == "⭐":
if len(reaction.message.reactions) >= 3:
await self.social_punishment(user.id, 25, "remove star")
if reaction.emoji == "⭐" and reaction.count >= 3:
await self.social_punishment(user.id, 25, "remove star")
async def setup(bot: commands.Bot):
+1 -2
View File
@@ -26,6 +26,7 @@ class Streak(commands.Cog):
self.cursor = self.bot.db_connection.cursor()
self.init_db()
# Cache to avoid having to insert to the db for every message
self.streak_cache = {}
self.populate_cache()
@@ -195,7 +196,6 @@ class Streak(commands.Cog):
""",
(bruker.id,),
)
streak = self.cursor.fetchone()
if not streak:
@@ -250,7 +250,6 @@ class Streak(commands.Cog):
ORDER BY streak_start_time;
"""
)
streaks = self.cursor.fetchall()
if not streaks:
+12 -10
View File
@@ -20,8 +20,6 @@ from wordcloud import WordCloud as WCloud # Avoid naming conflicts with cog cla
from cogs.utils import embed_templates
# from wordcloud import ImageColorGenerator
class WordCloud(commands.Cog):
"""Generate a wordcloud based on the most frequent words posted"""
@@ -41,6 +39,8 @@ class WordCloud(commands.Cog):
# The user's defaultdict has a default value of 0
self.word_freq_cache = defaultdict(lambda: defaultdict(int))
# We cache the consenting users to avoid querying the database every 16:36
# It's frail but it works unless you have a skill issue
self.consenting_users = []
self.populate_consenting_users()
@@ -48,6 +48,7 @@ class WordCloud(commands.Cog):
self.insert_cache_loop.start()
self.MSG_NO_DATA = "Fant ingen data om deg" # SonarCloud recommended this LMAO. Makes sense but also not
def init_db(self):
"""
@@ -127,7 +128,6 @@ class WordCloud(commands.Cog):
word_freqs,
)
except psycopg2.Error as err:
self.bot.db_connection.rollback()
self.bot.logger.error(f"Failed to insert wordcloud cache into database - {err}")
self.word_freq_cache.clear()
@@ -330,11 +330,13 @@ class WordCloud(commands.Cog):
freq_list = {f"{word}": freq for word, freq in result}
embed = discord.Embed(description="Her er dataen jeg har lagret om deg")
# Create Json file
buffer = StringIO()
buffer.write(json.dumps(freq_list, indent=4))
buffer.seek(0)
file = discord.File(buffer, filename=f"uiog_word_freqs_{interaction.user.id}.json")
embed = discord.Embed(description="Her er dataen jeg har lagret om deg")
await interaction.response.send_message(embed=embed, file=file, ephemeral=True)
@app_commands.checks.bot_has_permissions(embed_links=True, attach_files=True)
@@ -373,6 +375,8 @@ class WordCloud(commands.Cog):
)
# Fetch tracking start time metadata
# This doesn't work most of the time so consider using the API call instead of cache call
# Or consider removing this feature entirely
self.cursor.execute(
"""
SELECT tracked_since_message_channel_id, tracked_since_message_id
@@ -402,13 +406,11 @@ class WordCloud(commands.Cog):
word_cloud_file = discord.File(word_cloud, filename=f"wordcloud_{interaction.user.id}.png")
embed = discord.Embed(title="☁️ Her er ordskyen din! ☁️")
embed.description = "Basert på de 4000 mest frekvente ordene dine siden "
if origin_found:
embed.description = (
f"Basert på de 4000 mest frekvente ordene dine siden {origin_msg_timestamp}\n"
+ f"[Se melding]({origin_msg.jump_url})"
)
embed.description += f"{origin_msg_timestamp}\n[Se melding]({origin_msg.jump_url})"
else:
embed.description = "Basert på de 4000 mest frekvente ordene dine siden `ukjent dato`"
embed.description += "`ukjent dato`"
embed.set_image(url=f"attachment://wordcloud_{interaction.user.id}.png")
await interaction.followup.send(embed=embed, file=word_cloud_file)
@@ -433,7 +435,7 @@ class WordCloud(commands.Cog):
# This shouldn't be hard coded but eh
board_member_role = interaction.guild.get_role(779849617651138601)
# Fetch last 1000 messages
# This is horrible but there's a lot of edge cases to handle so spare me pls
all_messages = ""
for channel in interaction.guild.text_channels:
if not channel.permissions_for(interaction.user).send_messages: