Optimization review, ref #120

This commit is contained in:
Zeva Rose 2022-02-05 23:50:21 -07:00
parent 5917f252e1
commit adf770d624
9 changed files with 29 additions and 234 deletions

View file

@ -119,7 +119,3 @@ class MuteCog(Scale):
embed.set_thumbnail(url=user.display_avatar.url) embed.set_thumbnail(url=user.display_avatar.url)
embed.set_footer(text=f"{user.username}#{user.discriminator} | {user.id}") embed.set_footer(text=f"{user.username}#{user.discriminator} | {user.id}")
await ctx.send(embed=embed) await ctx.send(embed=embed)
embed.set_author(name=user.display_name, icon_url=user.display_avatar.url)
embed.set_thumbnail(url=user.display_avatar.url)
embed.set_footer(text=f"{user.username}#{user.discriminator} | {user.id}")
await ctx.send(embed=embed)

View file

@ -31,11 +31,11 @@ class PurgeCog(Scale):
await ctx.send("Amount must be >= 1", ephemeral=True) await ctx.send("Amount must be >= 1", ephemeral=True)
return return
await ctx.defer() await ctx.defer()
channel = ctx.channel
messages = [] messages = []
async for message in channel.history(limit=amount + 1): async for message in ctx.channel.history(limit=amount + 1):
messages.append(message) messages.append(message)
await channel.delete_messages(messages) await ctx.channel.delete_messages(messages, reason=f"Purge by {ctx.author.username}")
_ = Purge( _ = Purge(
channel=ctx.channel.id, channel=ctx.channel.id,
guild=ctx.guild.id, guild=ctx.guild.id,
@ -71,16 +71,19 @@ class PurgeCog(Scale):
elif delay > 300: elif delay > 300:
await ctx.send("Delay must be < 5 minutes", ephemeral=True) await ctx.send("Delay must be < 5 minutes", ephemeral=True)
return return
autopurge = Autopurge.objects(guild=ctx.guild.id, channel=channel.id).first() autopurge = Autopurge.objects(guild=ctx.guild.id, channel=channel.id).first()
if autopurge: if autopurge:
await ctx.send("Autopurge already exists.", ephemeral=True) await ctx.send("Autopurge already exists.", ephemeral=True)
return return
_ = Autopurge( _ = Autopurge(
guild=ctx.guild.id, guild=ctx.guild.id,
channel=channel.id, channel=channel.id,
admin=ctx.author.id, admin=ctx.author.id,
delay=delay, delay=delay,
).save() ).save()
await ctx.send(f"Autopurge set up on {channel.mention}, delay is {delay} seconds") await ctx.send(f"Autopurge set up on {channel.mention}, delay is {delay} seconds")
@slash_command( @slash_command(
@ -126,6 +129,8 @@ class PurgeCog(Scale):
if not autopurge: if not autopurge:
await ctx.send("Autopurge does not exist.", ephemeral=True) await ctx.send("Autopurge does not exist.", ephemeral=True)
return return
autopurge.delay = delay autopurge.delay = delay
autopurge.save() autopurge.save()
await ctx.send(f"Autopurge delay updated to {delay} seconds on {channel.mention}.") await ctx.send(f"Autopurge delay updated to {delay} seconds on {channel.mention}.")

View file

@ -1,7 +1,5 @@
"""J.A.R.V.I.S. RolepingCog.""" """J.A.R.V.I.S. RolepingCog."""
from datetime import datetime, timedelta from dis_snek import InteractionContext, Permissions, Scale
from dis_snek import InteractionContext, Permissions, Snake
from dis_snek.ext.paginators import Paginator from dis_snek.ext.paginators import Paginator
from dis_snek.models.discord.embed import EmbedField from dis_snek.models.discord.embed import EmbedField
from dis_snek.models.discord.role import Role from dis_snek.models.discord.role import Role
@ -14,17 +12,13 @@ from dis_snek.models.snek.application_commands import (
from dis_snek.models.snek.command import check from dis_snek.models.snek.command import check
from jarvis.db.models import Roleping from jarvis.db.models import Roleping
from jarvis.utils import build_embed from jarvis.utils import build_embed, find_all
from jarvis.utils.cachecog import CacheCog
from jarvis.utils.permissions import admin_or_permissions from jarvis.utils.permissions import admin_or_permissions
class RolepingCog(CacheCog): class RolepingCog(Scale):
"""J.A.R.V.I.S. RolepingCog.""" """J.A.R.V.I.S. RolepingCog."""
def __init__(self, bot: Snake):
super().__init__(bot)
@slash_command( @slash_command(
name="roleping", sub_cmd_name="add", sub_cmd_description="Add a role to roleping" name="roleping", sub_cmd_name="add", sub_cmd_description="Add a role to roleping"
) )
@ -35,6 +29,7 @@ class RolepingCog(CacheCog):
if roleping: if roleping:
await ctx.send(f"Role `{role.name}` already in roleping.", ephemeral=True) await ctx.send(f"Role `{role.name}` already in roleping.", ephemeral=True)
return return
_ = Roleping( _ = Roleping(
role=role.id, role=role.id,
guild=ctx.guild.id, guild=ctx.guild.id,
@ -60,14 +55,6 @@ class RolepingCog(CacheCog):
@slash_command(name="roleping", sub_cmd_name="list", description="Lick all blocklisted roles") @slash_command(name="roleping", sub_cmd_name="list", description="Lick all blocklisted roles")
async def _roleping_list(self, ctx: InteractionContext) -> None: async def _roleping_list(self, ctx: InteractionContext) -> None:
exists = self.check_cache(ctx)
if exists:
await ctx.defer(ephemeral=True)
await ctx.send(
f"Please use existing interaction: {exists['paginator']._message.jump_url}",
ephemeral=True,
)
return
rolepings = Roleping.objects(guild=ctx.guild.id) rolepings = Roleping.objects(guild=ctx.guild.id)
if not rolepings: if not rolepings:
@ -77,8 +64,8 @@ class RolepingCog(CacheCog):
embeds = [] embeds = []
for roleping in rolepings: for roleping in rolepings:
role = await ctx.guild.get_role(roleping.role) role = await ctx.guild.get_role(roleping.role)
bypass_roles = list(filter(lambda x: x.id in roleping.bypass["roles"], ctx.guild.roles)) broles = find_all(lambda x: x.id in roleping.bypass["roles"], ctx.guild.roles)
bypass_roles = [r.mention or "||`[redacted]`||" for r in bypass_roles] bypass_roles = [r.mention or "||`[redacted]`||" for r in broles]
bypass_users = [ bypass_users = [
await ctx.guild.get_member(u).mention or "||`[redacted]`||" await ctx.guild.get_member(u).mention or "||`[redacted]`||"
for u in roleping.bypass["users"] for u in roleping.bypass["users"]
@ -118,14 +105,6 @@ class RolepingCog(CacheCog):
paginator = Paginator.create_from_embeds(self.bot, *embeds, timeout=300) paginator = Paginator.create_from_embeds(self.bot, *embeds, timeout=300)
self.cache[hash(paginator)] = {
"user": ctx.author.id,
"guild": ctx.guild.id,
"timeout": datetime.utcnow() + timedelta(minutes=5),
"command": ctx.subcommand_name,
"paginator": paginator,
}
await paginator.send(ctx) await paginator.send(ctx)
@slash_command( @slash_command(

View file

@ -1,6 +1,4 @@
"""J.A.R.V.I.S. WarningCog.""" """J.A.R.V.I.S. WarningCog."""
from datetime import datetime, timedelta
from dis_snek import InteractionContext, Permissions, Snake from dis_snek import InteractionContext, Permissions, Snake
from dis_snek.ext.paginators import Paginator from dis_snek.ext.paginators import Paginator
from dis_snek.models.discord.user import User from dis_snek.models.discord.user import User
@ -87,14 +85,7 @@ class WarningCog(CacheCog):
@check(admin_or_permissions(Permissions.MANAGE_GUILD)) @check(admin_or_permissions(Permissions.MANAGE_GUILD))
async def _warnings(self, ctx: InteractionContext, user: User, active: bool = 1) -> None: async def _warnings(self, ctx: InteractionContext, user: User, active: bool = 1) -> None:
active = bool(active) active = bool(active)
exists = self.check_cache(ctx, user_id=user.id, active=active)
if exists:
await ctx.defer(ephemeral=True)
await ctx.send(
f"Please use existing interaction: {exists['paginator']._message.jump_url}",
ephemeral=True,
)
return
warnings = Warning.objects( warnings = Warning.objects(
user=user.id, user=user.id,
guild=ctx.guild.id, guild=ctx.guild.id,
@ -171,14 +162,4 @@ class WarningCog(CacheCog):
paginator = Paginator(bot=self.bot, *pages, timeout=300) paginator = Paginator(bot=self.bot, *pages, timeout=300)
self.cache[hash(paginator)] = {
"guild": ctx.guild.id,
"user": ctx.author.id,
"timeout": datetime.utcnow() + timedelta(minutes=5),
"command": ctx.subcommand_name,
"user_id": user.id,
"active": active,
"paginator": paginator,
}
await paginator.send(ctx) await paginator.send(ctx)

View file

@ -1,8 +1,8 @@
"""J.A.R.V.I.S. GitLab Cog.""" """J.A.R.V.I.S. GitLab Cog."""
from datetime import datetime, timedelta from datetime import datetime
import gitlab import gitlab
from dis_snek import InteractionContext, Snake from dis_snek import InteractionContext, Scale, Snake
from dis_snek.ext.paginators import Paginator from dis_snek.ext.paginators import Paginator
from dis_snek.models.discord.embed import Embed, EmbedField from dis_snek.models.discord.embed import Embed, EmbedField
from dis_snek.models.snek.application_commands import ( from dis_snek.models.snek.application_commands import (
@ -14,16 +14,15 @@ from dis_snek.models.snek.application_commands import (
from jarvis.config import get_config from jarvis.config import get_config
from jarvis.utils import build_embed from jarvis.utils import build_embed
from jarvis.utils.cachecog import CacheCog
guild_ids = [862402786116763668] guild_ids = [862402786116763668]
class GitlabCog(CacheCog): class GitlabCog(Scale):
"""J.A.R.V.I.S. GitLab Cog.""" """J.A.R.V.I.S. GitLab Cog."""
def __init__(self, bot: Snake): def __init__(self, bot: Snake):
super().__init__(bot) self.bot = bot
config = get_config() config = get_config()
self._gitlab = gitlab.Gitlab("https://git.zevaryx.com", private_token=config.gitlab_token) self._gitlab = gitlab.Gitlab("https://git.zevaryx.com", private_token=config.gitlab_token)
# J.A.R.V.I.S. GitLab ID is 29 # J.A.R.V.I.S. GitLab ID is 29
@ -236,10 +235,11 @@ class GitlabCog(CacheCog):
title += f"J.A.R.V.I.S. {name}s" title += f"J.A.R.V.I.S. {name}s"
fields = [] fields = []
for item in api_list: for item in api_list:
description = item.description or "No description"
fields.append( fields.append(
EmbedField( EmbedField(
name=f"[#{item.iid}] {item.title}", name=f"[#{item.iid}] {item.title}",
value=item.description + f"\n\n[View this {name}]({item.web_url})", value=(description[:200] + f"...\n\n[View this {name}]({item.web_url})"),
inline=False, inline=False,
) )
) )
@ -275,14 +275,6 @@ class GitlabCog(CacheCog):
], ],
) )
async def _issues(self, ctx: InteractionContext, state: str = "opened") -> None: async def _issues(self, ctx: InteractionContext, state: str = "opened") -> None:
exists = self.check_cache(ctx, state=state)
if exists:
await ctx.defer(ephemeral=True)
await ctx.send(
"Please use existing interaction: " + f"{exists['paginator']._message.jump_url}",
ephemeral=True,
)
return
await ctx.defer() await ctx.defer()
m_state = state m_state = state
if m_state == "all": if m_state == "all":
@ -319,15 +311,6 @@ class GitlabCog(CacheCog):
paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300) paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300)
self.cache[hash(paginator)] = {
"user": ctx.author.id,
"guild": ctx.guild.id,
"timeout": datetime.utcnow() + timedelta(minutes=5),
"command": ctx.subcommand_name,
"state": state,
"paginator": paginator,
}
await paginator.send(ctx) await paginator.send(ctx)
@slash_command( @slash_command(
@ -348,14 +331,6 @@ class GitlabCog(CacheCog):
], ],
) )
async def _mergerequests(self, ctx: InteractionContext, state: str = "opened") -> None: async def _mergerequests(self, ctx: InteractionContext, state: str = "opened") -> None:
exists = self.check_cache(ctx, state=state)
if exists:
await ctx.defer(ephemeral=True)
await ctx.send(
"Please use existing interaction: " + f"{exists['paginator']._message.jump_url}",
ephemeral=True,
)
return
await ctx.defer() await ctx.defer()
m_state = state m_state = state
if m_state == "all": if m_state == "all":
@ -394,15 +369,6 @@ class GitlabCog(CacheCog):
paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300) paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300)
self.cache[hash(paginator)] = {
"user": ctx.author.id,
"guild": ctx.guild.id,
"timeout": datetime.utcnow() + timedelta(minutes=5),
"command": ctx.subcommand_name,
"state": state,
"paginator": paginator,
}
await paginator.send(ctx) await paginator.send(ctx)
@slash_command( @slash_command(
@ -412,14 +378,6 @@ class GitlabCog(CacheCog):
scopes=guild_ids, scopes=guild_ids,
) )
async def _milestones(self, ctx: InteractionContext) -> None: async def _milestones(self, ctx: InteractionContext) -> None:
exists = self.check_cache(ctx)
if exists:
await ctx.defer(ephemeral=True)
await ctx.send(
f"Please use existing interaction: {exists['paginator']._message.jump_url}",
ephemeral=True,
)
return
await ctx.defer() await ctx.defer()
milestones = [] milestones = []
page = 1 page = 1
@ -450,14 +408,6 @@ class GitlabCog(CacheCog):
paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300) paginator = Paginator.create_from_embeds(self.bot, *pages, timeout=300)
self.cache[hash(paginator)] = {
"user": ctx.author.id,
"guild": ctx.guild.id,
"timeout": datetime.utcnow() + timedelta(minutes=5),
"command": ctx.subcommand_name,
"paginator": paginator,
}
await paginator.send(ctx) await paginator.send(ctx)

View file

@ -13,6 +13,8 @@ from dis_snek.models.snek.cooldowns import Buckets
from jarvis.utils import build_embed, convert_bytesize, unconvert_bytesize from jarvis.utils import build_embed, convert_bytesize, unconvert_bytesize
MIN_ACCURACY = 0.80
class ImageCog(Scale): class ImageCog(Scale):
""" """
@ -64,8 +66,8 @@ class ImageCog(Scale):
ratio = max(tgt_size / size - 0.02, 0.50) ratio = max(tgt_size / size - 0.02, 0.50)
accuracy = 0.0 accuracy = 0.0
# TODO: Optimize to not run multiple times
while len(file) > tgt_size or (len(file) <= tgt_size and accuracy < 0.65): while len(file) > tgt_size or (len(file) <= tgt_size and accuracy < MIN_ACCURACY):
old_file = file old_file = file
buffer = np.frombuffer(file, dtype=np.uint8) buffer = np.frombuffer(file, dtype=np.uint8)

View file

@ -2,7 +2,7 @@
from dis_snek import Snake, listen from dis_snek import Snake, listen
from dis_snek.models.discord.user import Member from dis_snek.models.discord.user import Member
from jarvis.db.models import Mute, Setting from jarvis.db.models import Setting
class MemberEventHandler(object): class MemberEventHandler(object):
@ -16,11 +16,6 @@ class MemberEventHandler(object):
async def on_member_join(self, user: Member) -> None: async def on_member_join(self, user: Member) -> None:
"""Handle on_member_join event.""" """Handle on_member_join event."""
guild = user.guild guild = user.guild
mute = Mute.objects(guild=guild.id, user=user.id, active=True).first()
if mute:
mute_role = Setting.objects(guild=guild.id, setting="mute").first()
role = guild.get_role(mute_role.value)
await user.add_roles(role, reason="User is still muted from prior mute")
unverified = Setting.objects(guild=guild.id, setting="unverified").first() unverified = Setting.objects(guild=guild.id, setting="unverified").first()
if unverified: if unverified:
role = guild.get_role(unverified.value) role = guild.get_role(unverified.value)

View file

@ -8,7 +8,7 @@ from dis_snek.models.discord.message import Message
from jarvis.config import get_config from jarvis.config import get_config
from jarvis.db.models import Autopurge, Autoreact, Roleping, Setting, Warning from jarvis.db.models import Autopurge, Autoreact, Roleping, Setting, Warning
from jarvis.utils import build_embed, find from jarvis.utils import build_embed, find, find_all
invites = re.compile( invites = re.compile(
r"(?:https?://)?(?:www.)?(?:discord.(?:gg|io|me|li)|discord(?:app)?.com/invite)/([^\s/]+?)(?=\b)", # noqa: E501 r"(?:https?://)?(?:www.)?(?:discord.(?:gg|io|me|li)|discord(?:app)?.com/invite)/([^\s/]+?)(?=\b)", # noqa: E501
@ -150,13 +150,13 @@ class MessageEventHandler(object):
roleping_ids = [r.role for r in rolepings] roleping_ids = [r.role for r in rolepings]
# Get roles in rolepings # Get roles in rolepings
role_in_rolepings = list(filter(lambda x: x in roleping_ids, roles)) role_in_rolepings = find_all(lambda x: x in roleping_ids, roles)
# Check if the user has the role, so they are allowed to ping it # Check if the user has the role, so they are allowed to ping it
user_missing_role = any(x.id not in roleping_ids for x in message.author.roles) user_missing_role = any(x.id not in roleping_ids for x in message.author.roles)
# Admins can ping whoever # Admins can ping whoever
user_is_admin = message.author.guild_permissions.administrator user_is_admin = message.author.guild_permissions.ADMINISTRATOR
# Check if user in a bypass list # Check if user in a bypass list
user_has_bypass = False user_has_bypass = False
@ -217,10 +217,3 @@ class MessageEventHandler(object):
await self.checks(after) await self.checks(after)
await self.roleping(after) await self.roleping(after)
await self.checks(after) await self.checks(after)
"""Handle on_message_edit event. Calls other event handlers."""
if not isinstance(after.channel, DMChannel) and not after.author.bot:
await self.massmention(after)
await self.roleping(after)
await self.checks(after)
await self.roleping(after)
await self.checks(after)

View file

@ -1,106 +0,0 @@
"""Logos for J.A.R.V.I.S."""
logo_doom = r"""
___ ___ ______ _ _ _____ _____
|_ | / _ \ | ___ \ | | | | |_ _| / ___|
| | / /_\ \ | |_/ / | | | | | | \ `--.
| | | _ | | / | | | | | | `--. \
/\__/ / _ | | | | _ | |\ \ _ \ \_/ / _ _| |_ _ /\__/ / _
\____/ (_)\_| |_/(_)\_| \_|(_) \___/ (_) \___/ (_)\____/ (_)
"""
logo_epic = r"""
_________ _______ _______ _________ _______
\__ _/ ( ___ ) ( ____ ) |\ /| \__ __/ ( ____ \
) ( | ( ) | | ( )| | ) ( | ) ( | ( \/
| | | (___) | | (____)| | | | | | | | (_____
| | | ___ | | __) ( ( ) ) | | (_____ )
| | | ( ) | | (\ ( \ \_/ / | | ) |
|\_) ) _ | ) ( | _ | ) \ \__ _ \ / _ ___) (___ _ /\____) | _
(____/ (_)|/ \|(_)|/ \__/(_) \_/ (_)\_______/(_)\_______)(_)
"""
logo_ivrit = r"""
_ _ ____ __ __ ___ ____
| | / \ | _ \ \ \ / / |_ _| / ___|
_ | | / _ \ | |_) | \ \ / / | | \___ \
| |_| | _ / ___ \ _ | _ < _ \ V / _ | | _ ___) | _
\___/ (_) /_/ \_\ (_) |_| \_\ (_) \_/ (_) |___| (_) |____/ (_)
"""
logo_kban = r"""
'||' . | . '||''|. . '||' '|' . '||' . .|'''.| .
|| ||| || || '|. .' || ||.. '
|| | || ||''|' || | || ''|||.
|| .''''|. || |. ||| || . '||
|| .|' .|. .||. .||. '|' | .||. |'....|'
'''
"""
logo_larry3d = r"""
_____ ______ ____ __ __ ______ ____
/\___ \ /\ _ \ /\ _`\ /\ \/\ \ /\__ _\ /\ _`\
\/__/\ \ \ \ \L\ \ \ \ \L\ \ \ \ \ \ \ \/_/\ \/ \ \,\L\_\
_\ \ \ \ \ __ \ \ \ , / \ \ \ \ \ \ \ \ \/_\__ \
/\ \_\ \ __ \ \ \/\ \ __ \ \ \\ \ __ \ \ \_/ \ __ \_\ \__ __ /\ \L\ \ __
\ \____//\_\ \ \_\ \_\/\_\ \ \_\ \_\/\_\ \ `\___//\_\ /\_____\/\_\ \ `\____\/\_\
\/___/ \/_/ \/_/\/_/\/_/ \/_/\/ /\/_/ `\/__/ \/_/ \/_____/\/_/ \/_____/\/_/
"""
logo_slane = r"""
__ ___ ____ _ __ ____ _____
/ / / | / __ \ | | / / / _/ / ___/
__ / / / /| | / /_/ / | | / / / / \__ \
/ /_/ / _ / ___ | _ / _, _/ _ | |/ / _ _/ / _ ___/ / _
\____/ (_)/_/ |_|(_)/_/ |_| (_)|___/ (_)/___/ (_)/____/ (_)
"""
logo_standard = r"""
_ _ ____ __ __ ___ ____
| | / \ | _ \ \ \ / / |_ _| / ___|
_ | | / _ \ | |_) | \ \ / / | | \___ \
| |_| | _ / ___ \ _ | _ < _ \ V / _ | | _ ___) | _
\___/ (_) /_/ \_\ (_) |_| \_\ (_) \_/ (_) |___| (_) |____/ (_)
"""
logo_alligator = r"""
::::::::::: ::: ::::::::: ::: ::: ::::::::::: ::::::::
:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +#++:++#++: +#++:++#: +#+ +:+ +#+ +#++:++#++
+#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+
#+# #+# #+# #+# #+# #+# #+# #+# #+# #+#+#+# #+# #+# #+# #+# #+# #+#
##### ### ### ### ### ### ### ### ### ### ########### ### ######## ###
""" # noqa: E501
logo_alligator2 = r"""
::::::::::: ::: ::::::::: ::: ::: ::::::::::: ::::::::
:+: :+: :+: :+: :+: :+: :+: :+: :+: :+:
+:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+
+#+ +#++:++#++: +#++:++#: +#+ +:+ +#+ +#++:++#++
+#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+
#+# #+# #+# #+# #+# #+# #+# #+# #+# #+#+#+# #+# #+# #+# #+# #+# #+#
##### ### ### ### ### ### ### ### ### ### ########### ### ######## ###
"""
def get_logo(lo: str) -> str:
"""Get a logo."""
if "logo_" not in lo:
lo = "logo_" + lo
return globals()[lo] if lo in globals() else logo_alligator2