Skip to content

Commit 7ea4a6c

Browse files
committed
updates from the last few months
- move to database for configs - don't try to update messages in the database that are older then the max storage duration - bunch of general bugfixes
1 parent d36a751 commit 7ea4a6c

33 files changed

+325
-280
lines changed

GearBot/Bot/GearBot.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ def dispatch(self, event_name, *args, **kwargs):
5252

5353
#### event handlers, basically bouncing everything to TheRealGearBot file so we can hotreload our listeners
5454

55+
async def on_connect(self):
56+
await TheRealGearBot.on_connect(self)
57+
5558
async def on_ready(self):
5659
await TheRealGearBot.on_ready(self)
5760

GearBot/Bot/TheRealGearBot.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
from Util import Configuration, GearbotLogging, Emoji, Pages, Utils, Translator, InfractionUtils, MessageUtils, \
2424
server_info, DashConfig
25+
from Util.Configuration import ConfigNotLoaded
2526
from Util.Permissioncheckers import NotCachedException
2627
from Util.Utils import to_pretty_time
2728
from database import DatabaseConnector, DBUtils
@@ -34,7 +35,7 @@ def prefix_callable(bot, message):
3435
if message.guild is None:
3536
prefixes.append('!') #use default ! prefix in DMs
3637
elif bot.STARTUP_COMPLETE:
37-
prefixes.append(Configuration.get_var(message.guild.id, "GENERAL", "PREFIX"))
38+
prefixes.append(Configuration.legacy_get_var(message.guild.id, "GENERAL", "PREFIX"))
3839
return prefixes
3940

4041

@@ -126,6 +127,9 @@ async def on_message(bot, message:Message):
126127
else:
127128
await bot.invoke(ctx)
128129

130+
async def on_connect(bot):
131+
await Configuration.load_bulk([guild.id for guild in bot.guilds])
132+
129133

130134
async def on_guild_join(bot, guild: Guild):
131135
blocked = Configuration.get_persistent_var("server_blocklist", [])
@@ -145,7 +149,7 @@ async def on_guild_join(bot, guild: Guild):
145149
await guild.leave()
146150
else:
147151
GearbotLogging.info(f"A new guild came up: {guild.name} ({guild.id}).")
148-
Configuration.load_config(guild.id)
152+
await Configuration.load_config(guild.id)
149153
name = await Utils.clean(guild.name)
150154
await guild.chunk(cache=True)
151155
await GearbotLogging.bot_log(f"{Emoji.get_chat_emoji('JOIN')} A new guild came up: {name} ({guild.id}).", embed=server_info.server_info_embed(guild))
@@ -178,6 +182,8 @@ def __init__(self, type, error):
178182

179183

180184
async def on_command_error(bot, ctx: commands.Context, error):
185+
if isinstance(error, ConfigNotLoaded):
186+
return
181187
if isinstance(error, NotCachedException):
182188
if bot.loading_task is not None:
183189
if bot.initial_fill_complete:
@@ -190,7 +196,7 @@ async def on_command_error(bot, ctx: commands.Context, error):
190196
GearbotLogging.error(f"Encountered a permission error while executing {ctx.command}: {error}")
191197
await send(ctx, error)
192198
elif isinstance(error, commands.CheckFailure):
193-
if ctx.command.qualified_name != "latest" and ctx.guild is not None and Configuration.get_var(ctx.guild.id, "GENERAL", "PERM_DENIED_MESSAGE"):
199+
if ctx.command.qualified_name != "latest" and ctx.guild is not None and await Configuration.get_var(ctx.guild.id, "GENERAL", "PERM_DENIED_MESSAGE"):
194200
await MessageUtils.send_to(ctx, 'LOCK', 'permission_denied')
195201
elif isinstance(error, commands.CommandOnCooldown):
196202
await send(ctx, error)
@@ -393,7 +399,7 @@ async def handle_exception(exception_type, bot, exception, event=None, message=N
393399

394400

395401

396-
for t in [ConnectionClosed, ClientOSError, ServerDisconnectedError]:
402+
for t in [ConnectionClosed, ClientOSError, ServerDisconnectedError, ConfigNotLoaded]:
397403
if isinstance(exception, t):
398404
return
399405
#nice embed for info on discord

GearBot/Cogs/Admin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,7 @@ async def reset_cache(self, ctx):
185185
async def thread_migration(self, ctx):
186186
await MessageUtils.send_to(ctx, "LOADING", "Thread migration initiated", translate=False)
187187
for guild in self.bot.guilds:
188-
role_id = Configuration.get_var(guild.id, 'ROLES', 'MUTE_ROLE')
188+
role_id = await Configuration.get_var(guild.id, 'ROLES', 'MUTE_ROLE')
189189
if role_id != 0:
190190
role = guild.get_role(role_id)
191191
if role is not None:

GearBot/Cogs/AntiRaid.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __init__(self, bot):
2424

2525
@commands.Cog.listener()
2626
async def on_member_join(self, member: disnake.Member):
27-
raid_settings = Configuration.get_var(member.guild.id, "RAID_HANDLING")
27+
raid_settings = await Configuration.get_var(member.guild.id, "RAID_HANDLING")
2828
if not raid_settings["ENABLED"]:
2929
return
3030

@@ -175,15 +175,15 @@ async def raid_end(self, ctx):
175175
await MessageUtils.send_to(ctx, 'YES', 'raid_terminated')
176176

177177
async def terminate_raid(self, guild):
178-
raid_settings = Configuration.get_var(guild, "RAID_HANDLING")
178+
raid_settings = await Configuration.get_var(guild, "RAID_HANDLING")
179179
for shield in raid_settings["SHIELDS"]:
180180
if guild in self.raid_trackers and shield["id"] in self.raid_trackers[guild]["SHIELDS"]:
181181
h = self.raid_trackers[guild]["SHIELDS"][shield["id"]]
182182
await self.terminate_shield(guild, h, shield)
183183

184184
@raid.command('status')
185185
async def raid_status(self, ctx):
186-
raid_settings = Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
186+
raid_settings = await Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
187187
if len(raid_settings.get('SHIELDS', [])) == 0:
188188
await MessageUtils.send_to(ctx, 'WRENCH', 'raid_shields_not_configured')
189189
elif raid_settings['ENABLED']:
@@ -193,7 +193,7 @@ async def raid_status(self, ctx):
193193

194194
@raid.command('enable')
195195
async def raid_enable(self, ctx):
196-
raid_settings = Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
196+
raid_settings = await Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
197197
if len(raid_settings.get('SHIELDS', [])) == 0:
198198
await MessageUtils.send_to(ctx, 'NO', 'raid_shields_not_configured')
199199
else:
@@ -202,11 +202,11 @@ async def raid_enable(self, ctx):
202202

203203
@raid.command('disable')
204204
async def raid_disable(self, ctx):
205-
raid_settings = Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
205+
raid_settings = await Configuration.get_var(ctx.guild.id, "RAID_HANDLING")
206206
if len(raid_settings.get('SHIELDS', [])) == 0:
207207
await MessageUtils.send_to(ctx, 'NO', 'raid_shields_not_configured')
208208
else:
209-
Configuration.set_var(ctx.guild.id, 'RAID_HANDLING', 'ENABLED', False)
209+
await Configuration.set_var(ctx.guild.id, 'RAID_HANDLING', 'ENABLED', False)
210210
await MessageUtils.send_to(ctx, 'YES', 'raid_shields_disabled')
211211

212212

GearBot/Cogs/AntiSpam.py

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,15 @@ def get_bucket(self, guild_id, rule_name, bucket_info):
100100
async def on_message(self, message: Message):
101101
if message.author.id == self.bot.user.id or message.guild is None:
102102
return # Don't track anti-spam for ourselves or DMs
103-
cfg = Configuration.get_var(message.guild.id, "ANTI_SPAM")
103+
cfg = await Configuration.get_var(message.guild.id, "ANTI_SPAM")
104104
if not cfg.get("ENABLED", False) or message.id in self.processed:
105105
return
106106
self.processed.append(message.id)
107107
await self.process_message(message)
108108

109109
async def process_message(self, message: Message):
110110
# print(f'{datetime.datetime.now().isoformat()} - Processing message')
111-
if message.webhook_id is not None or self.is_exempt(message.guild.id, message.author):
111+
if message.webhook_id is not None or await self.is_exempt(message.guild.id, message.author):
112112
return
113113

114114
# Use the discord's message timestamp to hopefully not trigger false positives
@@ -131,7 +131,7 @@ async def check_bucket(check, friendly_text, amount, b):
131131
b, count)))
132132

133133
counters = dict()
134-
buckets = Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
134+
buckets = await Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
135135

136136
# so if someone does 20 levels of too many mentions for some stupid reason we don't end up running the same regex 20 times for nothing
137137
cache = dict()
@@ -235,7 +235,9 @@ async def mute_punishment(self, v: Violation, member):
235235
duration = v.bucket["PUNISHMENT"]["DURATION"]
236236
until = time.time() + duration
237237
reason = self.assemble_reason(v)
238-
role = AntiSpam._get_mute_role(v.guild)
238+
role = await AntiSpam._get_mute_role(v.guild)
239+
if role is None:
240+
return
239241
i = await Infraction.get_or_none(user_id = member.id, type = "Mute", guild_id = member.guild.id, active=True)
240242
if i is None:
241243
i = await InfractionUtils.add_infraction(v.guild.id, member.id, self.bot.user.id, 'Mute', reason,
@@ -256,7 +258,7 @@ async def mute_punishment(self, v: Violation, member):
256258
moderator_id=v.guild.me.id,
257259
duration=Utils.to_pretty_time(duration, v.guild.id),
258260
reason=reason, inf=i.id)
259-
if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_MUTE"):
261+
if await Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_MUTE"):
260262
await Utils.send_infraction(self.bot, member, v.guild, 'MUTE', 'mute', reason, duration=Utils.to_pretty_time(duration, v.guild.id))
261263
else:
262264
i.end += duration
@@ -282,7 +284,7 @@ async def kick_punishment(self, v: Violation, member):
282284
active=False)
283285
await self.bot.redis_pool.psetex(f"forced_exits:{v.guild.id}-{member.id}", 8000, "1")
284286
try:
285-
if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_KICK"):
287+
if await Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_KICK"):
286288
asyncio.create_task(Utils.send_infraction(self.bot, member, v.guild, 'BOOT', 'kick', "Spam"))
287289
await v.guild.kick(member, reason=reason)
288290
except Forbidden:
@@ -302,7 +304,7 @@ async def temp_ban_punishment(self, v: Violation, member):
302304
await v.guild.ban(member, reason=reason, delete_message_days=0)
303305
i = await InfractionUtils.add_infraction(v.guild.id, member.id, self.bot.user.id, 'Tempban', reason,
304306
end=until)
305-
if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_TEMPBAN"):
307+
if await Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_TEMPBAN"):
306308
dur = Utils.to_pretty_time(duration, None)
307309
asyncio.create_task(Utils.send_infraction(self.bot, member, v.guild, 'BAN', 'tempban', "Spam", duration=dur))
308310
GearbotLogging.log_key(v.guild.id, 'tempban_log', user=Utils.clean_user(member),
@@ -319,7 +321,7 @@ async def ban_punishment(self, v: Violation, member):
319321
GearbotLogging.log_key(v.guild.id, 'ban_log', user=Utils.clean_user(member), user_id=member.id,
320322
moderator=Utils.clean_user(v.guild.me), moderator_id=v.guild.me.id,
321323
reason=reason, inf=i.id)
322-
if Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_BAN"):
324+
if await Configuration.get_var(v.guild.id, "INFRACTIONS", "DM_ON_BAN"):
323325
asyncio.create_task(Utils.send_infraction(self.bot, member, v.guild, 'BAN', 'ban', "Spam"))
324326

325327

@@ -335,10 +337,10 @@ async def censor_detector(self):
335337
return
336338

337339
# make sure anti-spam is enabled
338-
cfg = Configuration.get_var(message.guild.id, "ANTI_SPAM")
340+
cfg = await Configuration.get_var(message.guild.id, "ANTI_SPAM")
339341
if not cfg.get("ENABLED", False) or message.id in self.censor_processed:
340342
continue
341-
buckets = Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
343+
buckets = await Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
342344
count = 0
343345
for b in buckets:
344346
t = b["TYPE"]
@@ -372,10 +374,10 @@ async def voice_spam_detector(self):
372374
return
373375

374376
# make sure anti-spam is enabled
375-
cfg = Configuration.get_var(member.guild.id, "ANTI_SPAM")
376-
if after.channel is None or before.channel == after.channel or member is None or not cfg.get("ENABLED", False) or self.is_exempt(member.guild.id, member):
377+
cfg = await Configuration.get_var(member.guild.id, "ANTI_SPAM")
378+
if after.channel is None or before.channel == after.channel or member is None or not cfg.get("ENABLED", False) or await self.is_exempt(member.guild.id, member):
377379
continue
378-
buckets = Configuration.get_var(member.guild.id, "ANTI_SPAM", "BUCKETS", [])
380+
buckets = await Configuration.get_var(member.guild.id, "ANTI_SPAM", "BUCKETS", [])
379381
count = 0
380382
for b in buckets:
381383
t = b["TYPE"]
@@ -405,15 +407,15 @@ async def on_raw_message_delete(self, data: RawMessageDeleteEvent):
405407
member = await Utils.get_member(self.bot, self.bot.get_guild(data.guild_id), message.author)
406408
if member is None:
407409
return # user no longer present, probably already actioned
408-
if self.is_exempt(data.guild_id, member):
410+
if await self.is_exempt(data.guild_id, member):
409411
return # don't action except users
410412

411-
if data.message_id in self.bot.deleted_messages and not Configuration.get_var("GENERAL", "BOT_DELETED_STILL_GHOSTS"):
413+
if data.message_id in self.bot.deleted_messages and not await Configuration.get_var(data.guild_id, "GENERAL", "BOT_DELETED_STILL_GHOSTS"):
412414
return
413415

414-
ghost_message_threshold = Configuration.get_var(data.guild_id, "GENERAL", "GHOST_MESSAGE_THRESHOLD")
415-
ghost_ping_threshold = Configuration.get_var(data.guild_id, "GENERAL", "GHOST_PING_THRESHOLD")
416-
buckets = Configuration.get_var(data.guild_id, "ANTI_SPAM", "BUCKETS", [])
416+
ghost_message_threshold = await Configuration.get_var(data.guild_id, "GENERAL", "GHOST_MESSAGE_THRESHOLD")
417+
ghost_ping_threshold = await Configuration.get_var(data.guild_id, "GENERAL", "GHOST_PING_THRESHOLD")
418+
buckets = await Configuration.get_var(data.guild_id, "ANTI_SPAM", "BUCKETS", [])
417419
mentions = len(MENTION_MATCHER.findall(message.content))
418420

419421
msg_time = int(snowflake_time(message.messageid).timestamp())
@@ -456,9 +458,9 @@ async def on_raw_message_delete(self, data: RawMessageDeleteEvent):
456458

457459

458460
async def handle_failed_ping(self, message: disnake.Message, amount):
459-
if self.is_exempt(message.guild.id, message.author) or message.author.bot or message.webhook_id is not None:
461+
if await self.is_exempt(message.guild.id, message.author) or message.author.bot or message.webhook_id is not None:
460462
return # don't action except users
461-
buckets = Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
463+
buckets = await Configuration.get_var(message.guild.id, "ANTI_SPAM", "BUCKETS", [])
462464
msg_time = int(snowflake_time(message.id).timestamp())
463465
for b in buckets:
464466
t = b["TYPE"]
@@ -485,18 +487,18 @@ def assemble_reason(v):
485487
friendly=v.friendly)
486488

487489
@staticmethod
488-
def is_exempt(guild_id, member: Member):
490+
async def is_exempt(guild_id, member: Member):
489491
if not hasattr(member, "roles"):
490492
return False
491-
config = Configuration.get_var(guild_id, "ANTI_SPAM")
493+
config = await Configuration.get_var(guild_id, "ANTI_SPAM")
492494
for role in member.roles:
493495
if role.id in config["EXEMPT_ROLES"]:
494496
return True
495497
return member.id in config["EXEMPT_USERS"] or Permissioncheckers.is_mod(member)
496498

497499
@staticmethod
498-
def _get_mute_role(guild):
499-
role_id = Configuration.get_var(guild.id, "ROLES", "MUTE_ROLE")
500+
async def _get_mute_role(guild):
501+
role_id = await Configuration.get_var(guild.id, "ROLES", "MUTE_ROLE")
500502
if role_id == 0:
501503
return None
502504
role = guild.get_role(role_id)

GearBot/Cogs/Basic.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ async def about(self, ctx):
7474

7575
click_here = Translator.translate('click_here', ctx)
7676
embed.add_field(name=Translator.translate('support_server', ctx),
77-
value=f"[{click_here}](https://disnake.gg/vddW3D9)")
77+
value=f"[{click_here}](https://discord.gg/vddW3D9)")
7878
embed.add_field(name=Translator.translate('website', ctx), value=f"[{click_here}](https://gearbot.rocks)")
7979
embed.add_field(name=f"Github", value=f"[{click_here}](https://github.com/gearbot/GearBot)")
8080
embed.set_footer(text=self.bot.user.name, icon_url=self.bot.user.display_avatar.url)
@@ -115,7 +115,7 @@ async def quote(self, ctx: commands.Context, *, message: Message):
115115
if message.content is None or message.content == "":
116116
if attachment is not None:
117117
url = Utils.assemble_attachment(message.channel.id, attachment.id, attachment.name)
118-
if attachment.isImage:
118+
if attachment.isimage:
119119
embed.set_image(url=url)
120120
else:
121121
embed.add_field(name=Translator.translate("attachment_link", ctx),
@@ -128,7 +128,7 @@ async def quote(self, ctx: commands.Context, *, message: Message):
128128
value=f"[Jump to message]({message.jump_url})")
129129
if attachment is not None:
130130
url = Utils.assemble_attachment(message.channel.id, attachment.id, attachment.name)
131-
if attachment.isImage:
131+
if attachment.isimage:
132132
embed.set_image(url=url)
133133
else:
134134
embed.add_field(name=Translator.translate("attachment_link", ctx),
@@ -175,7 +175,7 @@ async def self_role(self, ctx: commands.Context, *, role: str = None):
175175
except BadArgument as ex:
176176
await ctx.send(Translator.translate("role_not_found", ctx))
177177
else:
178-
roles = Configuration.get_var(ctx.guild.id, "ROLES", "SELF_ROLES")
178+
roles = await Configuration.get_var(ctx.guild.id, "ROLES", "SELF_ROLES")
179179
if role.id in roles:
180180
try:
181181
if role in ctx.author.roles:
@@ -214,7 +214,7 @@ async def uid(self, ctx, *, text: str):
214214

215215
@commands.Cog.listener()
216216
async def on_guild_role_delete(self, role: disnake.Role):
217-
roles = Configuration.get_var(role.guild.id, "ROLES", "SELF_ROLES")
217+
roles = await Configuration.get_var(role.guild.id, "ROLES", "SELF_ROLES")
218218
if role.id in roles:
219219
roles.remove(role.id)
220220
Configuration.save(role.guild.id)

0 commit comments

Comments
 (0)