Enable commands globally if not sandboxing, add support for test guilds in env, monitor slash command & context menu usage, create error handler for slash commands, log slash commands in terminal

This commit is contained in:
Stijn De Clercq 2021-09-03 20:40:03 +02:00
parent ef547a7090
commit a28bd116f0
12 changed files with 117 additions and 62 deletions

View file

@ -1,9 +1,11 @@
from dislash import SlashInteraction
from data import constants
from data.snipe import Snipe, Action, should_snipe
import datetime
import discord
from discord.ext import commands
from functions import checks, easterEggResponses
from functions import checks, easterEggResponses, stringFormatters
from functions.database import stats, muttn, custom_commands, commands as command_stats
import pytz
from settings import READY_MESSAGE, SANDBOX, STATUS_MESSAGE
@ -87,12 +89,9 @@ class Events(commands.Cog):
Logs commands in your terminal.
:param ctx: Discord Context
"""
DM = ctx.guild is None
print("{} in {}: {}".format(ctx.author.display_name,
"DM" if DM else "{} ({})".format(ctx.channel.name, ctx.guild.name),
ctx.message.content))
print(stringFormatters.format_command_usage(ctx))
command_stats.invoked()
command_stats.invoked(command_stats.InvocationType.TextCommand)
@commands.Cog.listener()
async def on_command_error(self, ctx, err):
@ -123,14 +122,22 @@ class Events(commands.Cog):
elif isinstance(err, (commands.BadArgument, commands.MissingRequiredArgument, commands.UnexpectedQuoteError)):
await ctx.send("Controleer je argumenten.")
else:
# Remove the InvokeCommandError because it's useless information
x = traceback.format_exception(type(err), err, err.__traceback__)
errorString = ""
for line in x:
if "direct cause of the following" in line:
break
errorString += line.replace("*", "") + "\n" if line.strip() != "" else ""
await self.sendErrorEmbed(ctx, err, errorString)
usage = stringFormatters.format_command_usage(ctx)
await self.sendErrorEmbed(err, "Command", usage)
@commands.Cog.listener()
async def on_slash_command(self, interaction: SlashInteraction):
"""
Function called whenever someone uses a slash command
"""
print(stringFormatters.format_slash_command_usage(interaction))
command_stats.invoked(command_stats.InvocationType.SlashCommand)
@commands.Cog.listener()
async def on_slash_command_error(self, interaction, error):
usage = stringFormatters.format_slash_command_usage(interaction)
await self.sendErrorEmbed(error, "Slash Command", usage)
@commands.Cog.listener()
async def on_raw_reaction_add(self, react):
@ -286,19 +293,15 @@ class Events(commands.Cog):
self.client.snipe[message.channel.id] = Snipe(message.author.id, message.channel.id, message.guild.id,
Action.Remove, message.content)
async def sendErrorEmbed(self, ctx, error: Exception, trace):
async def sendErrorEmbed(self, error: Exception, error_type: str, usage: str):
"""
Function that sends an error embed in #ErrorLogs.
:param ctx: Discord Context
:param error: the error thrown
:param trace: the stacktrace of the error
"""
trace = stringFormatters.format_error_tb(error)
embed = discord.Embed(colour=discord.Colour.red())
embed.set_author(name="Error")
embed.add_field(name="Command:", value="{} in {}: {}".format(ctx.author.display_name,
ctx.channel.name if str(
ctx.channel.type) != "private" else "DM",
ctx.message.content), inline=False)
embed.set_author(name=f"{error_type} Error")
embed.add_field(name="Command:", value=usage, inline=False)
embed.add_field(name="Error:", value=str(error)[:1024], inline=False)
embed.add_field(name="Message:", value=str(trace)[:1024], inline=False)

View file

@ -1,4 +1,3 @@
import discord
from discord.ext import commands
from decorators import help
from enums.help_categories import Category

View file

@ -42,7 +42,7 @@ class School(commands.Cog):
embed.set_footer(text="Omwille van de coronamaatregelen is er een beperkter aanbod, en kan je enkel nog eten afhalen. Ter plaatse eten is niet meer mogelijk.")
await ctx.send(embed=embed)
# @commands.command(name="Les", aliases=["Class", "Classes", "Sched", "Schedule"], usage="[Jaargang]* [Dag]*")
# @commands.command(name="Les", aliases=["Class", "Classes", "Sched", "Schedule"], usage="[Dag]*")
# @commands.check(checks.allowedChannels)
# @help.Category(category=Category.School)
async def les(self, ctx, day=None):

View file

@ -13,8 +13,7 @@ class DefineSlash(commands.Cog):
description="Urban Dictionary",
options=[
Option("query", "Search query", OptionType.STRING, required=True)
],
guild_ids=[728361030404538488, 880175869841277008]
]
)
async def _define_slash(self, interaction: SlashInteraction, query):
embed = Definition(query).to_embed()

View file

@ -12,8 +12,7 @@ class GoogleSlash(commands.Cog):
description="Google search",
options=[
Option("query", "Search query", OptionType.STRING, required=True)
],
guild_ids=[728361030404538488, 880175869841277008]
]
)
async def _google_slash(self, interaction: SlashInteraction, query: str):
result = google_search(query)

View file

@ -14,11 +14,12 @@ class TranslateSlash(commands.Cog):
description="Google Translate",
options=[
Option("text", "Tekst om te vertalen", OptionType.STRING, required=True),
Option("to", "Taal om naar te vertalen (default NL)", OptionType.STRING)
Option("from_lang", "Taal om van te vertalen (default auto-detect)", OptionType.STRING),
Option("to_lang", "Taal om naar te vertalen (default NL)", OptionType.STRING)
]
)
async def _translate_slash(self, interaction: SlashInteraction, text: str, to: str = "nl"):
translation = Translation(text=text, to=to.lower())
async def _translate_slash(self, interaction: SlashInteraction, text: str, from_lang: str = "auto", to_lang: str = "nl"):
translation = Translation(text=text, fr=from_lang.lower(), to=to_lang.lower())
await interaction.reply(embed=translation.to_embed())