if recipient is None

This commit is contained in:
2025-02-15 13:57:47 -05:00
parent 9d23438b13
commit 6463ace40c
9 changed files with 617 additions and 716 deletions

View File

@@ -9,6 +9,7 @@ import traceback
import time
import importlib
import logging
from typing import Optional
import discord
import regex
from regex import Pattern
@@ -30,7 +31,7 @@ class Util:
self.timers: dict = {} # discord uid : timestamp, used for rate limiting
self.karma_cooldown: int = 15 # 15 seconds between karma updates
async def get_karma(self, keyword: str) -> int|str:
async def get_karma(self, keyword: str) -> int:
"""
Get Karma for Keyword
Args:
@@ -50,15 +51,15 @@ class Util:
return resp.get('count')
except Exception as e:
traceback.print_exc()
return f"Failed-- {type(e).__name__}: {str(e)}"
return False
async def get_top(self, n: int = 10) -> dict:
async def get_top(self, n: int = 10) -> Optional[dict]:
"""
Get top (n=10) Karma
Args:
n (int): Number of top results to return, default 10
Returns:
dict
Optional[dict]
"""
try:
async with ClientSession() as session:
@@ -74,8 +75,9 @@ class Util:
return resp
except:
traceback.print_exc()
return None
async def get_top_embed(self, n:int = 10) -> discord.Embed:
async def get_top_embed(self, n:int = 10) -> Optional[discord.Embed]:
"""
Get Top Karma Embed
Args:
@@ -83,11 +85,13 @@ class Util:
Returns:
discord.Embed
"""
top: dict = await self.get_top(n)
top: Optional[dict] = await self.get_top(n)
if not top:
return None
top_formatted: str = ""
for x, item in enumerate(top):
top_formatted += f"{x+1}. **{discord.utils.escape_markdown(item[0])}**: *{item[1]}*\n"
top_formatted: str = top_formatted.strip()
top_formatted = top_formatted.strip()
embed: discord.Embed = discord.Embed(title=f"Top {n} Karma",
description=top_formatted,
colour=0xff00ff)
@@ -103,7 +107,7 @@ class Util:
flag (int)
"""
if not flag in [0, 1]:
return
return False
reqObj: dict = {
'granter': f"Discord: {display} ({_id})",
@@ -171,6 +175,8 @@ class Karma(commands.Cog):
try:
top_embed = await self.util.get_top_embed(n=25)
channel = self.bot.get_channel(self.karma_chanid)
if not isinstance(channel, discord.TextChannel):
return
message_to_edit = await channel.fetch_message(self.karma_msgid)
await message_to_edit.edit(embed=top_embed,
content="## This message will automatically update periodically.")
@@ -184,7 +190,10 @@ class Karma(commands.Cog):
Message hook, to monitor for ++/--
Also monitors for messages to #karma to autodelete, only Havoc may post in #karma!
"""
if not self.bot.user: # No valid client instance
return
if not isinstance(message.channel, discord.TextChannel):
return
if message.channel.id == self.karma_chanid and not message.author.id == self.bot.user.id:
"""Message to #karma not by Havoc, delete it"""
await message.delete(reason="Messages to #karma are not allowed")
@@ -192,12 +201,13 @@ class Karma(commands.Cog):
title="Message Deleted",
description=f"Your message to **#{message.channel.name}** has been automatically deleted.\n**Reason**: Messages to this channel by users is not allowed."
)
return await message.author.send(embed=removal_embed)
await message.author.send(embed=removal_embed)
if message.author.id == self.bot.user.id: # Bots own message
return
if not message.guild:
return
if not message.guild.id in [1145182936002482196, 1228740575235149855]: # Not a valid guild for cmd
return
@@ -209,15 +219,19 @@ class Karma(commands.Cog):
logging.debug("Mention: %s", mention)
mentioned_uid: int = int(mention[1])
friendly_flag: int = int(mention[2])
guild: discord.Guild = self.bot.get_guild(message.guild.id)
guild_member: discord.Member = guild.get_member(mentioned_uid)
guild: Optional[discord.Guild] = self.bot.get_guild(message.guild.id)
if not guild:
return
guild_member: Optional[discord.Member] = guild.get_member(mentioned_uid)
if not guild_member:
return
display: str = guild_member.display_name
message_content: str = message_content.replace(mention[0], display)
message_content = message_content.replace(mention[0], display)
logging.debug("New message: %s", message_content)
except:
traceback.print_exc()
message_content: str = discord.utils.escape_markdown(message_content)
message_content = discord.utils.escape_markdown(message_content)
karma_regex: list[str] = regex.findall(self.karma_regex, message_content.strip())
if not karma_regex: # Not a request to adjust karma
@@ -233,6 +247,8 @@ class Karma(commands.Cog):
logging.debug("Matched: %s", karma_regex)
for matched_keyword in karma_regex:
if not isinstance(matched_keyword, tuple):
continue
if len(matched_keyword) == 4:
(keyword, friendly_flag, _, __) = matched_keyword
else:
@@ -242,9 +258,9 @@ class Karma(commands.Cog):
flag: int = None
match friendly_flag:
case "++":
flag: int = 0
flag = 0
case "--":
flag: int = 1
flag = 1
case _:
logging.info("Unknown flag %s", flag)
continue
@@ -266,18 +282,24 @@ class Karma(commands.Cog):
"""With no arguments, top 10 karma is provided; a keyword can also be provided to lookup."""
try:
if not keyword:
top_10_embed: discord.Embed = await self.util.get_top_embed()
top_10_embed: Optional[discord.Embed] = await self.util.get_top_embed()
if not top_10_embed:
return
return await ctx.respond(embed=top_10_embed)
keyword: str = discord.utils.escape_markdown(keyword)
keyword = discord.utils.escape_markdown(keyword)
mentions: list[str] = regex.findall(self.mention_regex_no_flag, keyword)
for mention in mentions:
try:
mentioned_uid = int(mention[1])
guild = self.bot.get_guild(ctx.guild.id)
guild_member = guild.get_member(mentioned_uid)
guild: Optional[discord.Guild] = self.bot.get_guild(ctx.guild.id)
if not guild:
return
guild_member: Optional[discord.Member] = guild.get_member(mentioned_uid)
if not guild_member:
return
display = guild_member.display_name
keyword = keyword.replace(mention[0], display)
except:
@@ -286,8 +308,6 @@ class Karma(commands.Cog):
score: int = await self.util.get_karma(keyword)
description: str = f"**{keyword}** has a karma of *{score}*"
if isinstance(score, dict) and score.get('err'):
description: str = f"*{score.get('errorText')}*"
embed: discord.Embed = discord.Embed(title=f"Karma for {keyword}",
description=description)
return await ctx.respond(embed=embed)