adamm-hf HF Staff commited on
Commit
49df2bd
·
verified ·
1 Parent(s): 5650928

some claudy fixes

Browse files
Files changed (1) hide show
  1. app.py +31 -68
app.py CHANGED
@@ -16,6 +16,7 @@ from pytz import timezone # for times
16
  import asyncio # check if used
17
  import logging
18
  import urllib.parse
 
19
 
20
  from discord.ui import Button, View
21
 
@@ -34,7 +35,15 @@ logger = logging.getLogger(__name__)
34
  logging.basicConfig(level=logging.DEBUG)
35
 
36
  #rate_limiter = RateLimiter(max_calls=10, period=60) # needs testing
37
- message_cache = {}
 
 
 
 
 
 
 
 
38
 
39
  AUTO_BAN_ALERT_THRESHOLD = 7
40
  AUTO_BAN_EXEMPT_ROLE_IDS = {897381378172264449, 897376942817419265}
@@ -51,42 +60,9 @@ user_cooldowns = {}
51
  @bot.event
52
  async def on_message(message):
53
  try:
54
- global number_of_messages
55
  if message.author != bot.user:
56
- message_cache[message.id] = message
57
- lunarflu = bot.get_user(811235357663297546) #811235357663297546
58
-
59
- """Backup"""
60
 
61
- number_of_messages = number_of_messages + 1
62
- message_link = f"[#{urllib.parse.quote(message.channel.name)}]({message.jump_url})"
63
- msgcnt = message.content
64
- backup_message = f"{number_of_messages} | {message_link} | {message.author.id} | {message.author}: {msgcnt}"
65
- # check for attachments
66
- if message.attachments:
67
- for attachment in message.attachments:
68
- attachment_url = attachment.url
69
- backup_message += f"\nAttachment: {attachment_url}"
70
- # check for embeds
71
- if message.embeds:
72
- for embed in message.embeds:
73
- backup_message += f"\nEmbed Title: {embed.title}\nEmbed Description: {embed.description}"
74
- dm_message = await lunarflu.send(backup_message)
75
-
76
- """Antispam"""
77
- #Detecting certain unwanted strings
78
- try:
79
- forbidden_patterns = [r"@everyone",
80
- r"@here",
81
- r"(https?:\/\/|http?:\/\/)?(www.)?(discord.(gg|io|me|li)|discordapp.com\/invite|discord.com\/invite)\/[^\s\/]+?(?=\b)"]
82
- if any(re.search(pattern, message.content, re.IGNORECASE) for pattern in forbidden_patterns):
83
- ignored_role_ids = [897381378172264449, 897376942817419265] #admins, huggingfolks
84
- if any(role.id in ignored_role_ids for role in message.author.roles):
85
- if message.author != lunarflu:
86
- return
87
- dm_unwanted = await lunarflu.send(f" {lunarflu.mention} [experimental] SUSPICIOUS MESSAGE: {message_link} | {message.author}: {message.content}")
88
- except Exception as e:
89
- print(f"Antispam->Detecting certain unwanted strings Error: {e}")
90
 
91
  #Posting too fast
92
  """
@@ -138,6 +114,7 @@ async def on_message(message):
138
  print(f"spam_count: {spam_count}")
139
 
140
  test_server = os.environ.get('TEST_SERVER')
 
141
  if test_server == 'True':
142
  alert = "<@&1106995261487710411>" # test @alerts role
143
  if test_server == 'False':
@@ -196,7 +173,7 @@ async def on_message(message):
196
  try:
197
  await member.send(
198
  f"You have been automatically banned from **{message.guild.name}** for repeated spam. "
199
- f"If this was an error, please contact @lunarflu."
200
  )
201
  except Exception as dm_err:
202
  print(f"Could not DM user before ban: {dm_err}")
@@ -227,7 +204,8 @@ async def on_message(message):
227
  user_cooldowns.pop(member.id, None)
228
  # ================= END AUTO BAN (hardened) =================
229
 
230
- user_cooldowns[message.author.id]['timestamp'] = message.created_at
 
231
 
232
  await bot.process_commands(message)
233
 
@@ -526,27 +504,6 @@ async def on_guild_role_delete(role):
526
  print(f"on_guild_role_delete Error: {e}")
527
 
528
 
529
- @bot.event
530
- async def on_guild_role_update(before, after):
531
- try:
532
- # editing roles, could expand this
533
- if before.name != after.name:
534
- embed = Embed(description=f'Role {before.mention} was renamed to {after.name}', color=Color.orange())
535
- await bot.log_channel.send(embed=embed)
536
-
537
- if before.permissions.administrator != after.permissions.administrator:
538
- # changes involving the administrator permission / sensitive permissions (can help to prevent mistakes)
539
- content = "<@&1108342563628404747>" # @alerts role
540
- embed = Embed(description=f'Role {after.mention} had its administrator permission {"enabled" if after.permissions.administrator else "disabled"}', color=Color.red())
541
- await bot.log_channel.send(content=content, embed=embed)
542
- except Exception as e:
543
- print(f"on_guild_role_update Error: {e}")
544
-
545
-
546
-
547
-
548
-
549
-
550
  @bot.event
551
  async def on_guild_role_update(before, after):
552
  try:
@@ -579,12 +536,17 @@ async def on_guild_role_update(before, after):
579
  change_status = "enabled" if value else "disabled"
580
  changed_permissions.append(f"{perm.replace('_', ' ').title()}: {change_status}")
581
 
582
- embed = Embed(color=Color.red() if "administrator" in changed_permissions else Color.orange())
 
 
583
  embed.set_author(name=f"{after.name} Role Updated", icon_url=after.guild.icon.url if after.guild.icon else "")
584
  embed.add_field(name="Changed By", value=changer.mention if changer else "Unknown", inline=True)
585
  embed.add_field(name="Changes", value="\n".join(changed_permissions) if changed_permissions else "No permissions changed", inline=False)
586
  embed.set_footer(text=f"Role ID: {after.id}")
587
- await bot.log_channel.send(embed=embed)
 
 
 
588
 
589
  except Exception as e:
590
  print(f"on_guild_role_update Error: {e}")
@@ -704,13 +666,14 @@ async def on_ready():
704
  persistent_view = PersistentRoleSelectionView(roles)
705
  bot.add_view(persistent_view) # This makes the view persistent across restarts.
706
 
707
- for channel in guild.text_channels: # helps with more accurate logging across restarts
708
- try:
709
- message_cache.update({m.id: m async for m in channel.history(limit=10000)})
710
- print(f"Finished caching messages for channel: {channel.name}")
711
- except Exception as e:
712
- print(f"An error occurred while fetching messages from {channel.name}: {e}")
713
- await asyncio.sleep(0.1)
 
714
 
715
 
716
 
@@ -729,4 +692,4 @@ with gr.Blocks() as demo:
729
  # Client for the [HuggingFace Discord](https://hf.co/join/discord) bot
730
  All code for this bot is under the [app.py](https://huggingface.co/spaces/discord-community/HuggingMod/blob/main/app.py) file.
731
  """)
732
- demo.launch()
 
16
  import asyncio # check if used
17
  import logging
18
  import urllib.parse
19
+ from collections import OrderedDict
20
 
21
  from discord.ui import Button, View
22
 
 
35
  logging.basicConfig(level=logging.DEBUG)
36
 
37
  #rate_limiter = RateLimiter(max_calls=10, period=60) # needs testing
38
+ # Bounded cache of recent messages, used for deleted-message logs.
39
+ # Oldest entries are dropped once it's full, so memory stays flat.
40
+ message_cache = OrderedDict()
41
+ MAX_CACHE = 50_000
42
+
43
+ def cache_message(m):
44
+ message_cache[m.id] = m
45
+ while len(message_cache) > MAX_CACHE:
46
+ message_cache.popitem(last=False)
47
 
48
  AUTO_BAN_ALERT_THRESHOLD = 7
49
  AUTO_BAN_EXEMPT_ROLE_IDS = {897381378172264449, 897376942817419265}
 
60
  @bot.event
61
  async def on_message(message):
62
  try:
 
63
  if message.author != bot.user:
64
+ cache_message(message)
 
 
 
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  #Posting too fast
68
  """
 
114
  print(f"spam_count: {spam_count}")
115
 
116
  test_server = os.environ.get('TEST_SERVER')
117
+ alert = "" # fallback so a missing/odd TEST_SERVER can't break auto-ban
118
  if test_server == 'True':
119
  alert = "<@&1106995261487710411>" # test @alerts role
120
  if test_server == 'False':
 
173
  try:
174
  await member.send(
175
  f"You have been automatically banned from **{message.guild.name}** for repeated spam. "
176
+ f"If this was an error, please contact @Adam."
177
  )
178
  except Exception as dm_err:
179
  print(f"Could not DM user before ban: {dm_err}")
 
204
  user_cooldowns.pop(member.id, None)
205
  # ================= END AUTO BAN (hardened) =================
206
 
207
+ if message.author.id in user_cooldowns: # may have been cleared by auto-ban above
208
+ user_cooldowns[message.author.id]['timestamp'] = message.created_at
209
 
210
  await bot.process_commands(message)
211
 
 
504
  print(f"on_guild_role_delete Error: {e}")
505
 
506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
507
  @bot.event
508
  async def on_guild_role_update(before, after):
509
  try:
 
536
  change_status = "enabled" if value else "disabled"
537
  changed_permissions.append(f"{perm.replace('_', ' ').title()}: {change_status}")
538
 
539
+ # administrator changes are sensitive: red embed + @alerts ping
540
+ admin_changed = before.permissions.administrator != after.permissions.administrator
541
+ embed = Embed(color=Color.red() if admin_changed else Color.orange())
542
  embed.set_author(name=f"{after.name} Role Updated", icon_url=after.guild.icon.url if after.guild.icon else "")
543
  embed.add_field(name="Changed By", value=changer.mention if changer else "Unknown", inline=True)
544
  embed.add_field(name="Changes", value="\n".join(changed_permissions) if changed_permissions else "No permissions changed", inline=False)
545
  embed.set_footer(text=f"Role ID: {after.id}")
546
+ await bot.log_channel.send(
547
+ content="<@&1108342563628404747>" if admin_changed else None, # @alerts role
548
+ embed=embed,
549
+ )
550
 
551
  except Exception as e:
552
  print(f"on_guild_role_update Error: {e}")
 
666
  persistent_view = PersistentRoleSelectionView(roles)
667
  bot.add_view(persistent_view) # This makes the view persistent across restarts.
668
 
669
+ for channel in guild.text_channels: # helps with more accurate logging across restarts
670
+ try:
671
+ async for m in channel.history(limit=500):
672
+ cache_message(m)
673
+ print(f"Finished caching messages for channel: {channel.name}")
674
+ except Exception as e:
675
+ print(f"An error occurred while fetching messages from {channel.name}: {e}")
676
+ await asyncio.sleep(0.1)
677
 
678
 
679
 
 
692
  # Client for the [HuggingFace Discord](https://hf.co/join/discord) bot
693
  All code for this bot is under the [app.py](https://huggingface.co/spaces/discord-community/HuggingMod/blob/main/app.py) file.
694
  """)
695
+ demo.launch()