Skip to content

Commit b649c48

Browse files
committed
chore: debug the bot so that it starts
1 parent ae01fae commit b649c48

8 files changed

Lines changed: 63 additions & 49 deletions

File tree

cogs/debug_cog.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -326,9 +326,10 @@ async def redis(
326326
"This command is restricted to owners only, but you are not an owner"
327327
)
328328
if not isinstance(self.bot.cache, RedisCache):
329-
raise RuntimeError(
330-
"/redis is not supported if the cache is not a RedisCache"
331-
)
329+
return await inter.send(ErrorEmbed("/redis is not supported if the cache is not a RedisCache"))
330+
#raise RuntimeError(
331+
#
332+
#)
332333
raise NotImplementedError("This isn't implemented yet")
333334

334335
@commands.is_owner()

cogs/handle_errors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from disnake.ext.commands import CommandOnCooldown, NotOwner
3030

3131
from helpful_modules._error_logging import log_error
32-
from helpful_modules.base_on_error import get_git_revision_hash
32+
from helpful_modules.threads_or_useful_funcs import get_git_revision_hash
3333
from helpful_modules.cooldowns import OnCooldown
3434
from helpful_modules.custom_embeds import ErrorEmbed
3535

cogs/misc_commands_cog.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
from disnake.ext import commands
3838

3939
from helpful_modules import checks, cooldowns, problems_module
40-
from helpful_modules.base_on_error import get_git_revision_hash
40+
from helpful_modules.threads_or_useful_funcs import get_git_revision_hash
4141
from helpful_modules.problems_module.denylistable import DenylistType
4242
from helpful_modules.custom_bot import TheDiscordMathProblemBot
4343
from helpful_modules.custom_buttons import *
@@ -159,7 +159,7 @@ async def list_trusted_users(self, inter):
159159
try:
160160
result = await self.cache.run_sql(
161161
"SELECT * FROM user_data"
162-
) # TODO: support redis + other caches
162+
) # TODO: implement a method called get_all_trusted_users, that is independent of the database
163163
except problems_module.SQLNotSupportedInRedisException as err:
164164
raise NotImplementedError(
165165
"Redis cache implementation is not yet implemented"
@@ -185,7 +185,7 @@ async def list_trusted_users(self, inter):
185185
# A user with this ID does not exist
186186
self.bot.trusted_users.remove(user_id) # delete the user!
187187
try:
188-
f = FileSaver(name=4, enabled=True)
188+
f = FileSaver(name=4, enabled=True) # do we even need to do this? we just need to tell the cache to not save it
189189
f.save_files(
190190
self.bot.cache,
191191
vote_threshold=self.bot.vote_threshold,

helpful_modules/base_on_error.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@
3939
LinearAlgebraUserInputErrorException,
4040
LockedCacheException
4141
)
42-
from error_handler.handle_known_errors import handle_known_error
43-
from error_handler.handle_unexpected_error import handle_unexpected_error
42+
from .error_handler.handle_known_errors import handle_known_error
43+
from .error_handler.handle_unexpected_error import handle_unexpected_error
4444
from .the_documentation_file_loader import DocumentationFileLoader
4545

4646

@@ -63,5 +63,5 @@ async def base_on_error(
6363
known_error_result = handle_known_error(error)
6464
if known_error_result is not None:
6565
return known_error_result
66-
return handle_unexpected_error(error)
66+
return await handle_unexpected_error(inter, error)
6767

helpful_modules/custom_bot.py

Lines changed: 35 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
from helpful_modules.restart_the_bot import RestartTheBot
4646
from helpful_modules.save_files import FileSaver
4747
from helpful_modules.file_log import AuditLog
48+
from .rate_limit import RateLimiter
4849

4950
from ._error_logging import log_error
5051
from .errors import (
@@ -81,10 +82,13 @@ class TheDiscordMathProblemBot(disnake.ext.commands.Bot):
8182
total_stats: CommandStats | None
8283
queue: MessageQueue
8384
closing_things: list[typing.Callable]
84-
rate_limiters: list["RateLimiters"]
85+
rate_limiters: list["RateLimiter"]
86+
global_rate_limiter: RateLimiter
87+
appeal_rate_limiter: RateLimiter
8588

8689
def __init__(self, *args, **kwargs):
8790
self.is_closing = False
91+
8892
self.file_saver = None
8993
self.appeal_questions = {}
9094
self.tasks = kwargs.pop("tasks")
@@ -120,6 +124,8 @@ def __init__(self, *args, **kwargs):
120124
self.total_stats = None
121125
self.this_session = None
122126
self.queue = MessageQueue()
127+
self.appeal_rate_limiter = RateLimiter(self)
128+
self.global_rate_limiter = RateLimiter(self)
123129
self.initialize_stats()
124130
# self.trusted_users = kwargs.get("trusted_users", None)
125131
# if not self.trusted_users and self.trusted_users != []:
@@ -185,7 +191,7 @@ async def on_ready(self):
185191
await log_error(begroup)
186192
except Exception as e:
187193
self.log.exception(
188-
"The following exception happened while trying to register appeal views:",
194+
f"The following exception happened while trying to register appeal views: {traceback.format_exc()}",
189195
e,
190196
)
191197
await log_error(e)
@@ -600,32 +606,35 @@ async def on_slash_command_error(self, inter, error):
600606
if isinstance(error, KeyboardInterrupt):
601607
raise error
602608
try:
603-
dict_args = await base_on_error(inter, error)
604-
except Exception as e:
605-
print(traceback.format_exception(e))
606-
raise e
607-
608-
# print(dict_args)
609-
try:
610-
await inter.send(**dict_args)
611-
return
612-
except BaseException as be:
613-
await log_error(be)
614-
# os._exit(1)
615-
try:
616-
if inter.response.is_done():
617-
await inter.followup.send(**dict_args)
618-
else:
619-
await inter.response.send_message(**dict_args)
620-
except AttributeError as err:
621-
print(error, err)
622-
await log_error(error, f"error_logs/{str(datetime.datetime.now())}")
623-
await inter.send(
624-
"An error occurred, and the error message couldn't be sent. However, it has been saved!"
625-
)
609+
try:
610+
dict_args = await base_on_error(inter, error)
611+
except Exception as e:
612+
print(traceback.format_exception(e))
613+
raise e
626614

615+
print(dict_args)
616+
try:
617+
await inter.send(**dict_args)
618+
return
619+
except BaseException as be:
620+
await log_error(be)
621+
# os._exit(1)
622+
try:
623+
if inter.response.is_done():
624+
await inter.followup.send(**dict_args)
625+
else:
626+
await inter.response.send_message(**dict_args)
627+
except AttributeError as err:
628+
print(error, err)
629+
await log_error(error, f"error_logs/{str(datetime.datetime.now())}")
630+
await inter.send(
631+
"An error occurred, and the error message couldn't be sent. However, it has been saved!"
632+
)
627633
raise ExceptionGroup(error, err)
628-
634+
except Exception as e:
635+
await inter.send("An unexpected error occurred.")
636+
await log_error(e, f"error_logs/{str(datetime.datetime.now())}")
637+
print("\n".join(traceback.format_exception(e)))
629638
async def on_error(self, event, *args, **kwargs):
630639
print(f"Error in {event}... uh oh", file=stderr)
631640
error = sys.exc_info()

helpful_modules/problems_module/cache/problems_related_cache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def __init__(
7474
# make_sql_table([], db_name = sql_dict_db_name)
7575
# make_sql_table([], db_name = "MathProblemCache1.db", table_name="kv_store")
7676
if use_sqlite:
77-
warnings.warn("Sqlite has been deprecated. Use MySQL instead.")
77+
warnings.warn("Sqlite has been deprecated. Use MySQL instead.", stacklevel=2)
7878
self.db_name = db_name
7979
self.db = db_name
8080
if warnings_or_errors not in ["warnings", "errors"]:

helpful_modules/rate_limit.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from .circular_deque import CircularDeque
1313
from .problems_module import UserData, DenylistType
14-
from .custom_bot import TheDiscordMathProblemBot
14+
#from .custom_bot import TheDiscordMathProblemBot
1515
from .threads_or_useful_funcs import first_true, last_true
1616

1717
ONE_SECOND = 1
@@ -36,7 +36,7 @@ def get_command_name(inter: disnake.ApplicationCommandInteraction):
3636

3737
async def autoban(
3838
user: disnake.User,
39-
bot: TheDiscordMathProblemBot,
39+
bot: "TheDiscordMathProblemBot",
4040
duration: float = 30.0,
4141
reason: str = "You've been temporarily denylisted for using the bot too much recently. ",
4242
):
@@ -87,12 +87,13 @@ class RateLimiter: # todo: more rate limits
8787

8888
def __init__(
8989
self,
90-
bot: TheDiscordMathProblemBot,
90+
bot: "TheDiscordMathProblemBot",
9191
*,
9292
global_limit: RateLimit | None = None,
9393
user_limits: list[RateLimit] | None = None,
9494
does_user_bypass: typing.Callable[[int], bool] | None = None,
9595
):
96+
from .custom_bot import TheDiscordMathProblemBot # avoid circular import
9697
if not isinstance(bot, TheDiscordMathProblemBot):
9798
raise TypeError("Bot must be of type TheDiscordMathProblemBot.")
9899
self.bot = bot
@@ -154,6 +155,7 @@ async def maybe_await(self, func, *args, **kwargs):
154155

155156
async def __call__(self, inter) -> str:
156157
"""Return whether inter causes the user to be denylisted. If False, means"""
158+
from .custom_bot import TheDiscordMathProblemBot # avoid circular import
157159
author_id = inter.author.id
158160
cur_time = time.time()
159161
if await self.will_bypass(author_id):
@@ -214,9 +216,10 @@ async def __call__(self, inter) -> str:
214216
return ""
215217

216218

217-
global_rate_limiter = RateLimiter()
218-
appeal_rate_limiter = RateLimiter()
219-
219+
#global_rate_limiter = RateLimiter()
220+
#appeal_rate_limiter = RateLimiter()
221+
global_rate_limiter = None
222+
appeal_rate_limiter = None
220223

221224
class RateLimitedException(disnake.ext.commands.CheckFailure):
222225
"""Raised when someone tries to run a command, but they're rate limited"""
@@ -226,6 +229,7 @@ class RateLimitedException(disnake.ext.commands.CheckFailure):
226229

227230
def rate_limit_check():
228231
async def predicate(inter: disnake.ApplicationCommandInteraction):
232+
from .custom_bot import TheDiscordMathProblemBot
229233
if not isinstance(inter.bot, TheDiscordMathProblemBot):
230234
await inter.send("The bot ran into an error.")
231235
raise TypeError()
@@ -259,11 +263,11 @@ async def predicate(inter: disnake.ApplicationCommandInteraction):
259263
)
260264
raise e
261265
if "appeal" not in command_name:
262-
global_rate_limited_msg = global_rate_limiter(inter)
266+
global_rate_limited_msg = await inter.bot.global_rate_limiter(inter)
263267
if global_rate_limited_msg:
264-
raise RateLimitedException(global_rate_limited_msg) # type: ignore
268+
raise RateLimitedException(str(global_rate_limited_msg)) # type: ignore
265269
else:
266-
appeal_rate_limited_msg = appeal_rate_limiter(inter)
270+
appeal_rate_limited_msg = await inter.bot.appeal_rate_limiter(inter)
267271
if appeal_rate_limited_msg:
268272
raise RateLimitedException(appeal_rate_limited_msg) # type: ignore
269273
return True

helpful_modules/the_documentation_file_loader.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,14 @@ def __init__(self):
4444
# this is deprecated
4545
warnings.warn(
4646
category=DeprecationWarning,
47-
stacklevel=-1,
47+
stacklevel=2,
4848
message="The DocumentationFileLoader is being deprecated",
4949
)
5050

5151
def _load_documentation_file(self):
5252
warnings.warn(
5353
category=DeprecationWarning,
54-
stacklevel=-1,
54+
stacklevel=2,
5555
message="The DocumentationFileLoader is being deprecated",
5656
)
5757
with open("docs/documentation.json", "r") as file:
@@ -60,7 +60,7 @@ def _load_documentation_file(self):
6060
def load_documentation_into_readable_files(self):
6161
warnings.warn(
6262
category=DeprecationWarning,
63-
stacklevel=-1,
63+
stacklevel=2,
6464
message="The DocumentationFileLoader is being deprecated",
6565
)
6666
dictToStoreFileContent = {}

0 commit comments

Comments
 (0)