-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMod_bot.py
More file actions
385 lines (328 loc) · 12.6 KB
/
Mod_bot.py
File metadata and controls
385 lines (328 loc) · 12.6 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
import os
import discord
from discord.ext import commands
from discord import app_commands
from dotenv import load_dotenv
import datetime
import sqlite3
# Base directory
Base_dir = os.path.dirname(os.path.abspath(__file__))
# Add your naughty words here
load_dotenv()
intents = discord.Intents.default()
intents.message_content = True
def create_logs_table():
conn = sqlite3.connect(os.path.join(Base_dir, "mod_logs.db"))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS mod_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
guild_id INTEGER,
infraction_type TEXT, -- 'Warning' or 'Timeout'
message_content TEXT,
timestamp DATETIME
)
""")
conn.commit()
conn.close()
# save data
def log_infraction(user_id, username, guild_id, infraction_type, content):
conn = sqlite3.connect(os.path.join(Base_dir, "mod_logs.db"))
cursor = conn.cursor()
cursor.execute("""
INSERT INTO mod_logs (user_id, username, guild_id, infraction_type, message_content, timestamp)
VALUES (?, ?, ?, ?, ?, ?)
""", (user_id, username, guild_id, infraction_type, content, datetime.datetime.now()))
conn.commit()
conn.close()
#create a database to store the number of warnings per user
def create_user_table():
conn = sqlite3.connect(os.path.join(Base_dir, "users_warning.db"))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users_per_guild (
user_id INTEGER,
warning_count INTEGER,
guild_id INTEGER,
PRIMARY KEY(user_id, guild_id)
)
""")
conn.commit()
conn.close()
#create a database to store the naughty words
def naughty_words_table():
conn = sqlite3.connect(os.path.join(Base_dir, "naughty_words.db"))
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS naughty_words (
word TEXT,
guild_id INTEGER,
PRIMARY KEY(word, guild_id)
)
""")
conn.commit()
conn.close()
create_logs_table()
naughty_words_table()
create_user_table()
#increase the number of warnings per user
def increase_and_get_warning_count(user_id, guild_id):
conn = sqlite3.connect(os.path.join(Base_dir, "users_warning.db"))
cursor = conn.cursor()
cursor.execute(
"""
SELECT warning_count
FROM users_per_guild
WHERE user_id = ? AND guild_id = ?
""",
(user_id, guild_id),
)
result = cursor.fetchone()
if result is None:
cursor.execute(
"""
INSERT INTO users_per_guild (user_id, warning_count, guild_id)
VALUES (?, 1, ?)
""",
(user_id, guild_id),
)
conn.commit()
conn.close()
return 1
cursor.execute(
"""
UPDATE users_per_guild
SET warning_count = ?
WHERE user_id = ? AND guild_id = ?
""",
(result[0] + 1, user_id, guild_id),
)
conn.commit()
conn.close()
return result[0] + 1
def get_naughty_words(guild_id):
conn = sqlite3.connect(os.path.join(Base_dir, "naughty_words.db"))
cursor = conn.cursor()
cursor.execute(
"""
SELECT word
FROM naughty_words
WHERE guild_id = ?
""",
(guild_id,),
)
result = cursor.fetchall()
conn.close()
return [word[0] for word in result]
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}, bot is online")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have permission to use this command.")
elif isinstance(error, commands.MemberNotFound):
await ctx.send("Member not found.")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Missing argument: `{error.param.name}`. Use `!commands` to see how to use it.")
elif isinstance(error, commands.CommandNotFound):
return
else:
raise error
#send a message when the bot joins a server
@bot.event
async def on_guild_join(guild):
intro_message = ("Hello! I am a moderation bot built by Allancash123.\n"
"My main purpose is to assist with moderation tasks.\n"
"I automatically filter banned words and warn users.\n\n"
"Use `!about` to learn about me.\n"
"Use `!commands` to see my command list.")
target_channel = None
if guild.system_channel and guild.system_channel.permissions_for(guild.me).send_messages:
target_channel = guild.system_channel
else:
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
target_channel = channel
break
if target_channel:
await target_channel.send(intro_message)
#check if the message contains a naughty word
@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if not message.author.guild_permissions.moderate_members:
naughty_words = get_naughty_words(message.guild.id)
for word in naughty_words:
if word.lower() in message.content.lower():
num_warnings = increase_and_get_warning_count(
message.author.id, message.guild.id
)
clean_content = (message.content[:100] + '..') if len(message.content) > 100 else message.content
if num_warnings >= 3:
log_infraction(message.author.id, str(message.author), message.guild.id, "Timeout (2hr)", clean_content)
await message.author.timeout(
datetime.timedelta(minutes=120),
reason="Exceeded naughty word limit (3+ warnings)",
)
await message.channel.send(
f"{message.author.mention} has been timed out for 2 hours for saying too many naughty words."
)
await message.delete()
break
if num_warnings == 1:
log_infraction(message.author.id, str(message.author), message.guild.id, "Warning #1", clean_content)
try:
await message.author.send(
"Please do not say naughty words. You have been warned. One more time and you'll be timed out for an hour."
)
except discord.Forbidden:
pass
await message.channel.send(
f"{message.author.mention} Please do not say naughty words."
)
await message.delete()
break
if num_warnings == 2:
log_infraction(message.author.id, str(message.author), message.guild.id, "Timeout (1hr)", clean_content)
await message.author.timeout(
datetime.timedelta(minutes=60),
reason="Second naughty word warning",
)
try:
await message.author.send(
"You have been timed out for an hour for saying too many naughty words. One more time and you'll be timed out for 2 hours."
)
except discord.Forbidden:
pass
await message.channel.send(
f"{message.author.mention} has been timed out for an hour for saying too many naughty words."
)
await message.delete()
break
await bot.process_commands(message)
#clear the number of warnings per user
@bot.command()
@commands.has_permissions(moderate_members=True)
async def clearwarnings(ctx, member: discord.Member):
conn = sqlite3.connect(os.path.join(Base_dir, "users_warning.db"))
cursor = conn.cursor()
cursor.execute(
"""
DELETE FROM users_per_guild
WHERE user_id = ? AND guild_id = ?
""",
(member.id, ctx.guild.id),
)
conn.commit()
conn.close()
await ctx.send(f"Warnings for {member.mention} have been cleared.")
@clearwarnings.error
async def clearwarnings_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You do not have permission to use this command.")
elif isinstance(error, commands.MemberNotFound):
await ctx.send("Member not found.")
# add a naughty word to the database
@bot.command()
@commands.has_permissions(moderate_members=True)
async def addword(ctx, word: str):
conn = sqlite3.connect(os.path.join(Base_dir, "naughty_words.db"))
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO naughty_words (word, guild_id) VALUES (?, ?)",
(word.lower(), ctx.guild.id)
)
conn.commit()
await ctx.send(f"Added '{word}' to the banned words list for this server.")
except sqlite3.IntegrityError:
await ctx.send(f"'{word}' is already in the banned words list.")
finally:
conn.close()
#remove a naughty word from the database
@bot.command()
@commands.has_permissions(moderate_members=True)
async def removeword(ctx, word: str):
conn = sqlite3.connect(os.path.join(Base_dir, "naughty_words.db"))
cursor = conn.cursor()
cursor.execute(
"DELETE FROM naughty_words WHERE word = ? AND guild_id = ?",
(word.lower(), ctx.guild.id)
)
conn.commit()
removed = cursor.rowcount
conn.close()
if removed:
await ctx.send(f"Removed '{word}' from the banned words list for this server.")
else:
await ctx.send(f"'{word}' is not in the banned words list.")
# Print logs of what happened
@bot.command()
@commands.has_permissions(moderate_members=True)
async def logs(ctx, member: discord.Member):
conn = sqlite3.connect(os.path.join(Base_dir, "mod_logs.db"))
cursor = conn.cursor()
cursor.execute("""
SELECT infraction_type, message_content, timestamp
FROM mod_logs
WHERE user_id = ? AND guild_id = ?
ORDER BY timestamp DESC LIMIT 10
""", (member.id, ctx.guild.id))
rows = cursor.fetchall()
conn.close()
if not rows:
await ctx.send(f"No logs found for {member.display_name}.")
return
log_text = f"**Recent logs for {member.mention}:**\n"
for type, content, time in rows:
# Formatting the timestamp string for readability
clean_time = time[:19]
log_text += f"• `[{clean_time}]` **{type}**: \"{content}\"\n"
await ctx.send(log_text)
# List all naughty words for the current server
@bot.command()
@commands.has_permissions(moderate_members=True)
async def listwords(ctx):
words = get_naughty_words(ctx.guild.id)
if not words:
await ctx.send("There are currently no banned words in this server.")
return
# Joining the words into a readable string
word_list_string = ", ".join(f"`{word}`" for word in words)
embed = discord.Embed(
title="Banned Words List",
description=word_list_string,
color=discord.Color.red()
)
await ctx.send(embed=embed)
#command list
@bot.command(name="commands")
async def list_commands(ctx):
commands_list = ("**Bot Command List**\n\n"
"`!about` - Shows information about the bot\n"
"`!commands` - Shows this command list\n"
"`!addword <word>` - Add a banned word (Moderators only)\n"
"`!removeword <word>` - Remove a banned word (Moderators only)\n"
"`!listwords` - See all banned words (Moderators only)\n"
"`!clearwarnings <member>` - Clear a user's warnings (Moderators only)\n")
await ctx.send(commands_list)
#about section
@bot.command()
async def about(ctx):
about_message = ("**Moderation Bot**\n"
"This bot helps moderate the server by filtering banned words "
"and issuing warnings to users who use them.\n\n"
"**How it works:**\n"
"- If a user says a banned word, they get a warning.\n"
"- 2nd warning = 1 hour timeout.\n"
"- 3rd warning = 2 hour timeout.\n\n"
"Use `!commands` to see the full list of commands."
)
await ctx.send(about_message)
TOKEN = os.getenv("DISCORD_TOKEN")
bot.run(TOKEN)