Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sir Robin Error Handling & Help Command updates #105

Merged
merged 5 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 14 additions & 18 deletions bot/exts/advent_of_code/_cog.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
import json
import logging
from datetime import UTC, datetime, timedelta
from pathlib import Path

import arrow
import discord
from async_rediscache import RedisCache
from discord import app_commands
from discord.ext import commands, tasks

from bot.bot import SirRobin
from bot.constants import (
AdventOfCode as AocConfig,
Bot,
Channels,
Colours,
Emojis,
Month,
Roles,
WHITELISTED_CHANNELS,
)
from bot.exts.advent_of_code import _helpers
from bot.exts.advent_of_code.views.dayandstarview import AoCDropdownView
from bot.utils import members
from bot.utils.decorators import InChannelCheckFailure, in_month, whitelist_override, with_role
from bot.utils.decorators import in_month, with_role, in_whitelist

log = logging.getLogger(__name__)

Check failure on line 28 in bot/exts/advent_of_code/_cog.py

View workflow job for this annotation

GitHub Actions / lint-test / Run linting & tests

Ruff (I001)

bot/exts/advent_of_code/_cog.py:1:1: I001 Import block is un-sorted or un-formatted

AOC_REQUEST_HEADER = {"user-agent": "PythonDiscord AoC Event Bot"}

Expand All @@ -35,6 +35,8 @@
# They aren't spammy and foster discussion
AOC_WHITELIST = AOC_WHITELIST_RESTRICTED + (Channels.advent_of_code,)

AOC_REDIRECT = (Channels.advent_of_code_commands, Channels.sir_lancebot_playground, Channels.bot_commands)


class AdventOfCode(commands.Cog):
"""Advent of Code festivities! Ho Ho Ho!"""
Expand Down Expand Up @@ -128,7 +130,7 @@
await members.handle_role_change(member, member.add_roles, completionist_role)

@commands.group(name="adventofcode", aliases=("aoc",))
@whitelist_override(channels=AOC_WHITELIST)
ChrisLovering marked this conversation as resolved.
Show resolved Hide resolved
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
ChrisLovering marked this conversation as resolved.
Show resolved Hide resolved
async def adventofcode_group(self, ctx: commands.Context) -> None:
"""All of the Advent of Code commands."""
if not ctx.invoked_subcommand:
Expand All @@ -149,7 +151,7 @@
await ctx.send(f":+1: Blocked {member.mention} from getting the AoC completionist role.")

@adventofcode_group.command(name="countdown", aliases=("count", "c"), brief="Return time left until next day")
@whitelist_override(channels=AOC_WHITELIST)
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
async def aoc_countdown(self, ctx: commands.Context) -> None:
"""Return time left until next day."""
if _helpers.is_in_advent():
Expand All @@ -174,13 +176,13 @@
)

@adventofcode_group.command(name="about", aliases=("ab", "info"), brief="Learn about Advent of Code")
@whitelist_override(channels=AOC_WHITELIST)
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
async def about_aoc(self, ctx: commands.Context) -> None:
"""Respond with an explanation of all things Advent of Code."""
await ctx.send(embed=self.cached_about_aoc)

@aoc_slash_group.command(name="join", description="Get the join code for our community Advent of Code leaderboard")
@whitelist_override(channels=AOC_WHITELIST)
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
@app_commands.guild_only()
async def join_leaderboard(self, interaction: discord.Interaction) -> None:
"""Send the user an ephemeral message with the information for joining the Python Discord leaderboard."""
Expand Down Expand Up @@ -236,7 +238,7 @@
aliases=("connect",),
brief="Tie your Discord account with your Advent of Code name."
)
@whitelist_override(channels=AOC_WHITELIST)
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
async def aoc_link_account(self, ctx: commands.Context, *, aoc_name: str | None = None) -> None:
"""
Link your Discord Account to your Advent of Code name.
Expand Down Expand Up @@ -288,7 +290,7 @@
aliases=("disconnect",),
brief="Untie your Discord account from your Advent of Code name."
)
@whitelist_override(channels=AOC_WHITELIST)
@in_whitelist(channels=AOC_WHITELIST, redirect=AOC_REDIRECT)
async def aoc_unlink_account(self, ctx: commands.Context) -> None:
"""
Unlink your Discord ID with your Advent of Code leaderboard name.
Expand All @@ -309,7 +311,7 @@
aliases=("daynstar", "daystar"),
brief="Get a view that lets you filter the leaderboard by day and star",
)
@whitelist_override(channels=AOC_WHITELIST_RESTRICTED)
@in_whitelist(channels=AOC_WHITELIST_RESTRICTED, redirect=AOC_REDIRECT)
async def aoc_day_and_star_leaderboard(
self,
ctx: commands.Context,
Expand Down Expand Up @@ -347,7 +349,7 @@
aliases=("board", "lb"),
brief="Get a snapshot of the PyDis private AoC leaderboard",
)
@whitelist_override(channels=AOC_WHITELIST_RESTRICTED)
@in_whitelist(channels=AOC_WHITELIST_RESTRICTED, redirect=AOC_REDIRECT)
async def aoc_leaderboard(self, ctx: commands.Context, *, aoc_name: str | None = None) -> None:
"""
Get the current top scorers of the Python Discord Leaderboard.
Expand Down Expand Up @@ -381,7 +383,7 @@
table = (
"```\n"
f"{leaderboard['placement_leaderboard'] if aoc_name else leaderboard['top_leaderboard']}"
"\n```"
"\n```"
)
info_embed = _helpers.get_summary_embed(leaderboard)

Expand All @@ -394,7 +396,7 @@
aliases=("globalboard", "gb"),
brief="Get a link to the global leaderboard",
)
@whitelist_override(channels=AOC_WHITELIST_RESTRICTED)
@in_whitelist(channels=AOC_WHITELIST_RESTRICTED, redirect=AOC_REDIRECT)
async def aoc_global_leaderboard(self, ctx: commands.Context) -> None:
"""Get a link to the global Advent of Code leaderboard."""
url = self.global_leaderboard_url
Expand All @@ -410,7 +412,7 @@
aliases=("dailystats", "ds"),
brief="Get daily statistics for the Python Discord leaderboard"
)
@whitelist_override(channels=AOC_WHITELIST_RESTRICTED)
@in_whitelist(channels=AOC_WHITELIST_RESTRICTED, redirect=AOC_REDIRECT)
async def private_leaderboard_daily_stats(self, ctx: commands.Context) -> None:
"""Send an embed with daily completion statistics for the Python Discord leaderboard."""
try:
Expand Down Expand Up @@ -479,9 +481,3 @@

about_embed.set_footer(text="Last Updated")
return about_embed

async def cog_command_error(self, ctx: commands.Context, error: Exception) -> None:
"""Custom error handler if an advent of code command was posted in the wrong channel."""
if isinstance(error, InChannelCheckFailure):
await ctx.send(f":x: Please use <#{Channels.advent_of_code_commands}> for aoc commands instead.")
error.handled = True
Empty file added bot/exts/core/__init__.py
Empty file.
20 changes: 17 additions & 3 deletions bot/exts/error_handler.py → bot/exts/core/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@

from bot.bot import SirRobin
from bot.log import get_logger
from bot.utils.exceptions import CodeJamCategoryCheckFailure
from bot.utils.exceptions import (
CodeJamCategoryCheckFailure,
InMonthCheckFailure,
InWhitelistCheckFailure,
)

log = get_logger(__name__)

Expand Down Expand Up @@ -64,17 +68,27 @@ async def on_command_error(self, ctx: Context, error: CommandError) -> None:
embed = self._get_error_embed("Permission error", "You are not allowed to use this command!")
await ctx.send(embed=embed)
return
if isinstance(error, InMonthCheckFailure):
embed = self._get_error_embed("Command not available", str(error))
await ctx.send(embed=embed)
return
if isinstance(error, InWhitelistCheckFailure):
ChrisLovering marked this conversation as resolved.
Show resolved Hide resolved
embed = self._get_error_embed("Wrong Channel", error)
await ctx.send(embed=embed)
return
if isinstance(error, CodeJamCategoryCheckFailure):
# Silently fail, as SirRobin should not respond
# to any of the CJ related commands outside of the CJ categories.
log.error(exc_info=error)
return

# If we haven't handled it by this point, it is considered an unexpected/handled error.
await ctx.send(
f"Sorry, an unexpected error occurred. Please let us know!\n\n"
embed = self._get_error_embed(
"Unexpected error",
"Sorry, an unexpected error occurred. Please let us know!\n\n"
f"```{error.__class__.__name__}: {error}```"
)
await ctx.send(embed=embed)
log.error(f"Error executing command invoked by {ctx.message.author}: {ctx.message.content}", exc_info=error)


Expand Down
Loading
Loading