-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRialoDiscordBot.py
More file actions
512 lines (427 loc) · 21.8 KB
/
RialoDiscordBot.py
File metadata and controls
512 lines (427 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import os
import io
import re
from dotenv import load_dotenv
import discord as RialoDiscordBot
from discord.ext import commands
from homoglyphs import Homoglyphs
# Load environment variables
load_dotenv()
# Get the token from environment variables
TOKEN = os.getenv('DISCORD_TOKEN')
# Check if token is available
if not TOKEN:
print("Error: DISCORD_TOKEN environment variable is not set!")
print("Please create a .env file in the project root with your Discord bot token:")
print("DISCORD_TOKEN=your_bot_token_here")
exit(1)
intents = RialoDiscordBot.Intents.default()
# Note: members and guilds intents are privileged and need to be enabled in Discord Developer Portal
# For now, we'll disable them to make the bot work immediately
intents.members = True
intents.guilds = True
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
hg = Homoglyphs(languages=["en", "ru", "el"])
URL_PATTERN = re.compile(r"(https?://[^\s]+|www\.[^\s]+)")
#Normalize text for detecting a homoglyps
async def normalise_text(text: str, member=None) -> str:
# If homoglyph detection is disabled, just return the text as-is
if not HOMOGLYPH_DETECTION_ENABLED:
return text.casefold()
normalized = hg.to_ascii(text)
# Convert list to string if needed
if isinstance(normalized, list):
normalized = ''.join(normalized) if normalized else text
if normalized.casefold() != text.casefold():
if member is not None:
await send_log(
f"⚠️ User with possible homoglyphs in username detected: "
f"{member.mention} ({member.id})\n"
f"Original: `{text}` → Normalized: `{normalized}`",
guild_id=member.guild.id,
)
else:
print(f"Homoglyph detected in text: {text} → {normalized}")
return normalized.casefold()
banned_keywords = ["mee6", "MEE6", "mee6.xyz", "mee6.gg", "mee6.com", "mee6.net", "mee6.org", "mee6.io", "mee6.club", "mee6.fun", "mee6.top", "mee6.xyz", "mee6.gg", "mee6.com", "mee6.net", "mee6.org", "mee6.io", "mee6.club", "mee6.fun", "mee6.top"]
# Feature toggles
LINK_FILTER_ENABLED = True
HOMOGLYPH_DETECTION_ENABLED = True
# Channel ID to send logs (legacy, single-channel). Prefer per-guild map below.
LOG_CHANNEL_ID = None # Backward compatibility fallback
# Per-guild log channel mapping: { guild_id: channel_id }
GUILD_LOG_CHANNEL_IDS = {}
async def send_log(message: str, guild_id: int | None = None):
"""Send a log message to the configured log channel for a guild.
If per-guild channel is not set, falls back to the legacy global LOG_CHANNEL_ID.
"""
channel_id = None
if guild_id is not None:
channel_id = GUILD_LOG_CHANNEL_IDS.get(guild_id)
if channel_id is None:
channel_id = LOG_CHANNEL_ID
if channel_id is None:
# Nothing configured
return
channel = bot.get_channel(channel_id)
if channel is None:
try:
channel = await bot.fetch_channel(channel_id)
except Exception as e:
print(f"send_log: failed to fetch channel {channel_id}: {e}")
return
try:
await channel.send(message)
except Exception as e:
print(f"send_log: failed to send message to channel {channel_id}: {e}")
@bot.event
async def on_ready():
# Sync commands globally (they'll still be permission-checked at runtime)
await bot.tree.sync()
print(f'Logged in as {bot.user.name}')
# Optional: print configured log channels for visibility
if LOG_CHANNEL_ID:
print(f"Global log channel configured: {LOG_CHANNEL_ID}")
if GUILD_LOG_CHANNEL_IDS:
for gid, cid in GUILD_LOG_CHANNEL_IDS.items():
print(f"Guild {gid} -> log channel {cid}")
# Print guild information for debugging
print(f"Bot is in {len(bot.guilds)} guilds:")
for guild in bot.guilds:
print(f" - {guild.name} (ID: {guild.id})")
# Check if bot has admin permissions
bot_member = guild.get_member(bot.user.id)
if bot_member:
has_admin = bot_member.guild_permissions.administrator
print(f" Bot has admin permissions: {has_admin}")
@bot.event
async def on_member_join(member):
# This event requires the "Server Members Intent" to be enabled in Discord Developer Portal
# If you get errors, enable the intent or comment out this event handler
try:
username = await normalise_text(member.name)
nickname = await normalise_text(member.display_name)
if any(keyword in username for keyword in banned_keywords) or any(keyword in nickname for keyword in banned_keywords):
try:
await member.ban(reason="Banned for blacklisted username or nickname")
print(f"Banned {member.name} (nickname: {member.display_name}) for blacklisted username or nickname")
await send_log(
f"Auto-ban on join: {member.mention} ({member.id}) for blacklisted username or nickname. Username: '{member.name}', Nickname: '{member.display_name}'.",
guild_id=member.guild.id,
)
except RialoDiscordBot.Forbidden:
print(f"Failed to ban {member.name} due to insufficient permissions")
except RialoDiscordBot.HTTPException:
print(f"Failed to ban {member.name} due to an HTTP error")
except Exception as e:
print(f"Error in on_member_join: {e}")
print("Note: This event requires 'Server Members Intent' to be enabled in Discord Developer Portal")
@bot.event
async def on_member_update(before, after):
try:
username = await normalise_text(after.name, after)
nickname = await normalise_text(after.display_name, after)
if any(keyword in username for keyword in banned_keywords) or any(keyword in nickname for keyword in banned_keywords):
try:
await after.ban(reason="Banned for blacklisted username or nickname")
print(f"Banned {after.name} (nickname: {after.display_name})")
await send_log(
f"🚫 Auto-ban on name change: {after.mention} ({after.id})\n"
f"Username: '{after.name}', Nickname: '{after.display_name}'",
guild_id=after.guild.id,
)
except RialoDiscordBot.Forbidden:
print(f"Failed to ban {after.name} due to insufficient permissions")
except RialoDiscordBot.HTTPException:
print(f"Failed to ban {after.name} due to an HTTP error")
except Exception as e:
print(f"Error in on_member_update: {e}")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
# Only process link filtering if enabled
if LINK_FILTER_ENABLED:
# Check embeds
for embed in message.embeds:
if embed.url: # The main URL of the embed
try:
await message.delete()
await send_log(f"Deleted embed with URL from {message.author.mention}: {embed.url}", guild_id=message.guild.id)
except RialoDiscordBot.Forbidden:
print(f"Cannot delete embed message from {message.author} due to permissions.")
except Exception as e:
print(f"Failed to delete embed message: {e}")
# Also check fields with links
for field in embed.fields:
if re.search(r"(https?://[^\s]+|www\.[^\s]+)", field.value):
try:
await message.delete()
await send_log(f"Deleted embed field with link from {message.author.mention}", guild_id=message.guild.id)
except:
pass
# Also check plain text for regular URLs
if URL_PATTERN.search(message.content):
try:
await message.delete()
await send_log(f"Deleted message from {message.author.mention} containing a link.", guild_id=message.guild.id)
except:
pass
await bot.process_commands(message)
#Admin Commands:
# Slash Commands: /addword
@bot.tree.command(name="addword", description="Add a word to the banned list")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def addword(interaction: RialoDiscordBot.Interaction, word: str):
word = word.lower()
if word not in banned_keywords:
banned_keywords.append(word)
await interaction.response.send_message(f"Added '{word}' to the banned list", ephemeral=True)
try:
if interaction.guild:
await send_log(f"Banned word added by {interaction.user.mention}: '{word}'", guild_id=interaction.guild.id)
except Exception:
pass
else:
await interaction.response.send_message(f"'{word}' is already in the banned list", ephemeral=True)
# Slash Commands: /removeword
@bot.tree.command(name="removeword", description="Remove a word from the banned list")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def removeword(interaction: RialoDiscordBot.Interaction, word: str):
word = word.lower()
if word in banned_keywords:
banned_keywords.remove(word)
await interaction.response.send_message(f"Removed '{word}' from the banned list")
try:
if interaction.guild:
await send_log(f"Banned word removed by {interaction.user.mention}: '{word}'", guild_id=interaction.guild.id)
except Exception:
pass
else:
await interaction.response.send_message(f"'{word}' is not in the banned list", ephemeral=True)
# Slash Commands: /listwords
@bot.tree.command(name="listwords", description="List all banned words")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def listwords(interaction: RialoDiscordBot.Interaction):
if not banned_keywords:
await interaction.response.send_message("No banned words found", ephemeral=True)
else:
await interaction.response.send_message(f"Banned words: {', '.join(banned_keywords)}", ephemeral=True)
#Slash Commands: /clearbannedword
@bot.tree.command(name="clearbannedword", description="Remove a specific word from the banned list")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def clearbannedword(interaction: RialoDiscordBot.Interaction, word: str):
word = word.lower()
if word in banned_keywords:
banned_keywords.remove(word)
await interaction.response.send_message(f"Removed '{word}' from the banned list", ephemeral=True)
try:
if interaction.guild:
await send_log(f"Banned word removed by {interaction.user.mention}: '{word}'", guild_id=interaction.guild.id)
except Exception:
pass
else:
await interaction.response.send_message(f"'{word}' is not in the banned list", ephemeral=True)
# Slash Commands: /clearbannedwords
@bot.tree.command(name="clearbannedwords", description="Clear all banned words")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def clearbannedwords(interaction: RialoDiscordBot.Interaction):
banned_keywords.clear()
await interaction.response.send_message("All banned words have been cleared", ephemeral=True)
try:
if interaction.guild:
await send_log(f"Banned words list cleared by {interaction.user.mention}", guild_id=interaction.guild.id)
except Exception:
pass
#User Commands:
#SLash Commands: /Listbanusers
@bot.tree.command(name="listbanusers", description="List all banned users in this server")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def listbanusers(interaction: RialoDiscordBot.Interaction):
if interaction.guild is None:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return
try:
await interaction.response.defer(ephemeral=True)
bans = []
async for ban_entry in interaction.guild.bans(limit=None):
bans.append(ban_entry)
if not bans:
await interaction.followup.send("No banned users in this server.", ephemeral=True)
return
lines = []
for entry in bans:
user = entry.user
reason = entry.reason or "No reason provided"
lines.append(f"{user} ({user.id}) - {reason}")
content = "\n".join(lines)
if len(content) <= 1900:
await interaction.followup.send(content, ephemeral=True)
else:
buffer = io.StringIO(content)
buffer.seek(0)
await interaction.followup.send(file=RialoDiscordBot.File(buffer, filename="banned_users.txt"), ephemeral=True)
except Exception as e:
await interaction.followup.send(f"Failed to list banned users: {e}", ephemeral=True)
# Also log the action (non-ephemeral log)
try:
await send_log(f"Ban list requested by {interaction.user.mention}", guild_id=interaction.guild.id)
except Exception:
pass
# Slash Commands: /banuser
@bot.tree.command(name="banuser", description="Ban a user")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def banuser(interaction: RialoDiscordBot.Interaction, user: RialoDiscordBot.Member, reason: str = "No reason provided"):
await user.ban(reason=reason)
await interaction.response.send_message(f"Banned {user.name} for {reason}", ephemeral=True)
try:
if interaction.guild:
await send_log(f"Manual ban: {user.mention} ({user.id}) by {interaction.user.mention}. Reason: {reason}", guild_id=interaction.guild.id)
except Exception:
pass
# Slash Commands: /unbanuser
@bot.tree.command(name="unbanuser", description="Unban a user by selecting them or providing their ID")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def unbanuser(interaction: RialoDiscordBot.Interaction, user: RialoDiscordBot.User):
if interaction.guild is None:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return
try:
await interaction.guild.unban(user, reason=f"Unbanned by {interaction.user} via command")
await interaction.response.send_message(f"Unbanned {user} ({user.id})", ephemeral=True)
await send_log(
f"Manual unban: {user.mention} ({user.id}) by {interaction.user.mention}",
guild_id=interaction.guild.id,
)
except RialoDiscordBot.NotFound:
await interaction.response.send_message("That user is not currently banned.", ephemeral=True)
except RialoDiscordBot.Forbidden:
await interaction.response.send_message("I don't have permission to unban this user.", ephemeral=True)
except RialoDiscordBot.HTTPException as e:
await interaction.response.send_message(f"Failed to unban user: {e}", ephemeral=True)
# Slash Commands: /unbanuserid
@bot.tree.command(name="unbanuserid", description="Unban a user by their numeric user ID")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def unbanuserid(interaction: RialoDiscordBot.Interaction, user_id: str):
if interaction.guild is None:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return
try:
await interaction.response.defer(ephemeral=True)
# Normalize the ID (strip whitespace and mention formatting)
cleaned = user_id.strip().replace("<@", "").replace(">", "").replace("!", "")
target_id = int(cleaned)
# Unban using a lightweight object
await interaction.guild.unban(RialoDiscordBot.Object(id=target_id), reason=f"Unbanned by {interaction.user} via ID command")
mention = f"<@{target_id}>"
await interaction.followup.send(f"Unbanned {mention} ({target_id})", ephemeral=True)
await send_log(
f"Manual unban (by ID): {mention} ({target_id}) by {interaction.user.mention}",
guild_id=interaction.guild.id,
)
except ValueError:
await interaction.followup.send("Please provide a valid numeric user ID.", ephemeral=True)
except RialoDiscordBot.NotFound:
await interaction.followup.send("That user is not currently banned.", ephemeral=True)
except RialoDiscordBot.Forbidden:
await interaction.followup.send("I don't have permission to unban this user.", ephemeral=True)
except RialoDiscordBot.HTTPException as e:
await interaction.followup.send(f"Failed to unban user: {e}", ephemeral=True)
#Slash Commands: /kickuser
@bot.tree.command(name="kickuser", description="Kick a user")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def kickuser(interaction: RialoDiscordBot.Interaction, user: RialoDiscordBot.Member, reason: str = "No reason provided"):
await user.kick(reason=reason)
await interaction.response.send_message(f"Kicked {user.name} for {reason}", ephemeral=True)
try:
if interaction.guild:
await send_log(f"Manual kick: {user.mention} ({user.id}) by {interaction.user.mention}. Reason: {reason}", guild_id=interaction.guild.id)
except Exception:
pass
#Slash Commands: /addlogchannelid
@bot.tree.command(name="addlogchannelid", description="Add a log channel ID")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def addlogchannelid(interaction: RialoDiscordBot.Interaction, channel: RialoDiscordBot.TextChannel):
global LOG_CHANNEL_ID, GUILD_LOG_CHANNEL_IDS
# Set both: per-guild mapping and legacy fallback
if interaction.guild:
GUILD_LOG_CHANNEL_IDS[interaction.guild.id] = channel.id
LOG_CHANNEL_ID = channel.id
await interaction.response.send_message(f"Added {channel.name} as the log channel for this server", ephemeral=True)
try:
await channel.send("This channel has been set as the log channel for moderation events.")
except Exception:
pass
try:
if interaction.guild:
await send_log(f"Log channel set to {channel.mention} by {interaction.user.mention}", guild_id=interaction.guild.id)
except Exception:
pass
# Feature Toggle Commands
@bot.tree.command(name="linkfilter", description="Enable or disable link filtering")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def linkfilter(interaction: RialoDiscordBot.Interaction, status: str):
global LINK_FILTER_ENABLED
status_lower = status.lower()
if status_lower in ["on", "true", "yes", "1", "enable"]:
LINK_FILTER_ENABLED = True
response = "✅ Link filtering is now enabled"
elif status_lower in ["off", "false", "no", "0", "disable"]:
LINK_FILTER_ENABLED = False
response = "❌ Link filtering is now disabled"
else:
await interaction.response.send_message("❌ Invalid status. Use 'on' or 'off'", ephemeral=True)
return
await interaction.response.send_message(response, ephemeral=True)
try:
if interaction.guild:
status_text = "enabled" if LINK_FILTER_ENABLED else "disabled"
await send_log(f"Link filtering {status_text} by {interaction.user.mention}", guild_id=interaction.guild.id)
except Exception:
pass
@bot.tree.command(name="homoglyph", description="Enable or disable homoglyph detection")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def homoglyph(interaction: RialoDiscordBot.Interaction, status: str):
global HOMOGLYPH_DETECTION_ENABLED
status_lower = status.lower()
if status_lower in ["on", "true", "yes", "1", "enable"]:
HOMOGLYPH_DETECTION_ENABLED = True
response = "✅ Homoglyph detection is now enabled"
elif status_lower in ["off", "false", "no", "0", "disable"]:
HOMOGLYPH_DETECTION_ENABLED = False
response = "❌ Homoglyph detection is now disabled"
else:
await interaction.response.send_message("❌ Invalid status. Use 'on' or 'off'", ephemeral=True)
return
await interaction.response.send_message(response, ephemeral=True)
try:
if interaction.guild:
status_text = "enabled" if HOMOGLYPH_DETECTION_ENABLED else "disabled"
await send_log(f"Homoglyph detection {status_text} by {interaction.user.mention}", guild_id=interaction.guild.id)
except Exception:
pass
@bot.tree.command(name="featurestatus", description="Show current status of bot features")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def featurestatus(interaction: RialoDiscordBot.Interaction):
link_status = "✅ Enabled" if LINK_FILTER_ENABLED else "❌ Disabled"
homoglyph_status = "✅ Enabled" if HOMOGLYPH_DETECTION_ENABLED else "❌ Disabled"
embed = RialoDiscordBot.Embed(
title="🤖 Bot Feature Status",
color=0x00ff00,
description="Current status of bot features"
)
embed.add_field(name="🔗 Link Filtering", value=link_status, inline=True)
embed.add_field(name="🔍 Homoglyph Detection", value=homoglyph_status, inline=True)
await interaction.response.send_message(embed=embed, ephemeral=True)
# Utility: test log command
@bot.tree.command(name="testlog", description="Send a test message to the configured log channel for this server")
@RialoDiscordBot.app_commands.checks.has_permissions(administrator=True)
async def testlog(interaction: RialoDiscordBot.Interaction):
if interaction.guild is None:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return
await interaction.response.send_message("Attempting to send a test log...", ephemeral=True)
await send_log("This is a test log message.", guild_id=interaction.guild.id)
#Slash Commands: /stats
bot.run(TOKEN)