/
bot.py
499 lines (462 loc) · 16.4 KB
/
bot.py
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
import discord
import os
import random
import asyncio
from discord.ext import commands
import math
from datetime import datetime
import time
import psycopg2
import wikipedia
import string
import json
bot_token = os.getenv('BOT_TOKEN')
DATABASE_URL = os.getenv('DATABASE_URL')
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
c = conn.cursor()
#c.execute("CREATE TABLE userxp (id BIGINT, name TEXT, xp INT, level INT, badges INT[], mc_username TEXT, mc_uuid TEXT);")
#c.execute("ALTER TABLE guilds ADD COLUMN show_level_messages BOOL;")
#c.execute("DELETE FROM guilds;")
#c.execute("INSERT INTO ping VALUES (0, 1000, 'default');")
#c.execute("INSERT INTO ping VALUES (1, 1000, 'default');")
#c.execute("UPDATE userxp SET badges = %s WHERE id = 508863359777505290;", ([2, 8],))\
#c.execute("CREATE TABLE ping (type INT, time INT, person TEXT);")
'''
with open('dataclips.json', 'r') as myfile:
data = json.load(myfile)
for i in data['values']:
c.execute("UPDATE userxp SET mc_username = %s, mc_uuid = %s WHERE id = %s;", (i[5], i[6], i[0]))
'''
conn.commit()
default_prefixes = ['y.', 'yoidbot please ', 'Y.']
async def determine_prefix(bot, message):
guild = message.guild
if guild:
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (guild.id,))
data = c.fetchone()
if data and data[1]:
return data[1] + ['yoidbot please ']
return default_prefixes
intents = discord.Intents.default()
intents.members = True
intents.presences = True
client = commands.Bot(command_prefix = determine_prefix, intents = intents)
for file in os.listdir('./cogs'):
if file.endswith('.py'):
client.load_extension(f'cogs.{file[:-3]}')
client.remove_command('help')
@client.event
async def on_ready():
await client.change_presence(activity = discord.Activity(type = discord.ActivityType.listening, name = "y.help"))
print('bot has connected to discord')
for guild in client.guilds:
print(guild.name)
if guild.name == "!hsoy":
guild.leave()
deleted = {}
@client.event
async def on_message_delete(message):
deleted[message.channel.id] = message
@client.command(aliases = ['sn'])
@commands.guild_only()
async def snipe(ctx):
if ctx.channel.id not in deleted:
await ctx.send("No messages to snipe.")
return
if ctx.author.id == 642967924541489163:
return
msg = deleted[ctx.channel.id]
embed = discord.Embed(
description = msg.content,
timestamp = msg.created_at
)
embed.set_author(name = msg.author.name, icon_url = msg.author.avatar_url)
await ctx.send(embed = embed)
@client.command(aliases = ['dlm'])
@commands.guild_only()
async def disablelevelmessages(ctx):
if not ctx.author.guild_permissions.administrator:
await ctx.send("You do not have the permissions to use this command.")
return
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (ctx.guild.id,))
data = c.fetchone()
if not data:
c.execute("INSERT INTO guilds VALUES (%s, %s, %s);", (ctx.guild.id, [], False))
else:
c.execute("UPDATE guilds SET show_level_messages = %s WHERE guild_id = %s;", (False, ctx.guild.id))
await ctx.send("Level messages were turned off for this server.")
@client.command(aliases = ['elm'])
@commands.guild_only()
async def enablelevelmessages(ctx):
if not ctx.author.guild_permissions.administrator:
await ctx.send("You do not have the permissions to use this command.")
return
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (ctx.guild.id,))
data = c.fetchone()
if not data:
c.execute("INSERT INTO guilds VALUES (%s, %s, %s);", (ctx.guild.id, [], True))
else:
c.execute("UPDATE guilds SET show_level_messages = %s WHERE guild_id = %s;", (True, ctx.guild.id))
await ctx.send("Level messages were turned on for this server.")
@client.command(aliases = ['ap'])
@commands.has_permissions(manage_guild = True)
@commands.guild_only()
async def addprefix(ctx, *, prefix):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
' '.join(prefix)
if prefix[0] == '"' and prefix[-1] == '"':
prefix = prefix[1:-1]
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (ctx.guild.id,))
data = c.fetchone()
if not data:
c.execute("INSERT INTO guilds VALUES (%s, %s, %s);", (ctx.guild.id, [prefix], True))
else:
if prefix in data[1]:
await ctx.send("This server already has that prefix.")
c.execute("UPDATE guilds SET prefixes = prefixes || %s WHERE guild_id = %s;", ([prefix], ctx.guild.id))
conn.commit()
await ctx.send(f"Added prefix `{prefix}`")
@addprefix.error
async def addprefix_error(ctx, error):
print(error)
if type(error) == discord.ext.commands.errors.MissingPermissions:
await ctx.send("You do not have the permissions to use this command.")
else:
await ctx.send("Please follow format: `y.addprefix {prefix}` (use quotes around prefix if prefix has space at the end)")
@client.command(aliases = ['rp'])
@commands.has_permissions(manage_guild = True)
@commands.guild_only()
async def removeprefix(ctx, *, prefix):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
' '.join(prefix)
if prefix[0] == '"' and prefix[-1] == '"':
prefix = prefix[1:-1]
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (ctx.guild.id,))
data = c.fetchone()
if not data:
await ctx.send("This server does not have any custom prefixes set.")
return
if prefix not in data[1]:
await ctx.send("This server does not have this prefix.")
return
s = f"Removed prefix `{prefix}`"
if len(data[1]) <= 1:
s += "\nPrefixes were reset to the default prefixes (`y.`, `Y.`)."
c.execute("UPDATE guilds SET prefixes = array_remove(prefixes, %s) WHERE guild_id = %s;", (prefix, ctx.guild.id))
conn.commit()
await ctx.send(s)
@removeprefix.error
async def removeprefix_error(ctx, error):
print(error)
if type(error) == discord.ext.commands.errors.MissingPermissions:
await ctx.send("You do not have the permissions to use this command.")
else:
await ctx.send("Please follow format: `y.addprefix {prefix}` (use quotes around prefix if prefix has space at the end)")
@client.command(aliases = ['pr'])
@commands.guild_only()
async def prefixes(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
c.execute("SELECT * FROM guilds WHERE guild_id = %s;", (ctx.guild.id,))
data = c.fetchone()
prefixes = ''
if not data:
prefixes = "This server does not have any custom prefixes.\nTo add a custom prefix, do `y.addprefix {prefix}`.\n\nThese are the default prefixes:\n"
data2 = default_prefixes
else:
data2 = data[1]
for i in data2:
prefixes += f"`{i}`\n"
embed = discord.Embed(
title = f"{ctx.guild.name}'s prefixes",
description = prefixes,
color = ctx.author.color
)
await ctx.send(embed = embed)
@client.command(aliases = ['h'])
async def help(ctx, command = None):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
file = open('help.json', 'r')
data = json.load(file)
if command:
for category in data:
for data_command in data[category]['commands']:
client_command = None
for c in client.commands:
if c.name == data_command or data_command in c.aliases:
client_command = c
if not client.command:
continue
if command == data_command or command in client_command.aliases:
command_data = data[category]['commands'][data_command]
aliases = ''
for a in [client_command.name] + client_command.aliases:
if data_command != a:
aliases += f"`{a}`, "
embed = discord.Embed(
title = data_command,
color = ctx.author.color,
)
usage = ''
if command_data['usage']:
usage = ' ' + command_data['usage']
embed.add_field(name = "Usage", value = f"`y.{data_command}{usage}`", inline = False)
if aliases:
embed.add_field(name = "Other Names", value = aliases[:-2], inline = False)
embed.add_field(name = "Description", value = f"{command_data['long']}", inline = False)
await ctx.send(embed = embed)
return
await ctx.send("Could not find that command.")
return
pages = [["Useful"], ["Levels", "Moderation", "Reddit"], ["Games", "Minecraft", "Hypixel"]]
def generate(page):
embed = discord.Embed(
title = 'Help',
color = ctx.author.color,
description = "Use the reactions below to go to the next page.\nIf you want to get further help, report issues, or suggest new ideas, join the Yoidbot discord: https://discord.gg/NPVFbnF"
)
embed.set_thumbnail(url = "https://i.imgur.com/0GEBD3t.png")
for category in page:
commands = ''
for c in data[category]['commands']:
usage = ''
if data[category]['commands'][c]['usage']:
usage = ' ' + data[category]['commands'][c]['usage']
commands += f"`y.{c}{usage}` - {data[category]['commands'][c]['brief']}\n"
embed.add_field(name = f"{data[category]['emoji']} {category}", value = commands, inline = False)
return embed
embeds = [generate(p) for p in pages]
for i in range(len(embeds)):
embeds[i].set_footer(text = f"Page {i + 1}/{len(embeds)}")
msg = await ctx.send(embed = embeds[0])
await msg.add_reaction('◀️')
await msg.add_reaction('▶️')
current = 0
def check(reaction, user):
return reaction.message.id == msg.id and user != client.user
while True:
try:
reaction, user = await client.wait_for('reaction_add', timeout = 300.0, check = check)
except asyncio.TimeoutError:
return
try:
await reaction.remove(user)
except:
pass
if reaction.emoji == '◀️':
if current == 0:
current = len(embeds) - 1
else:
current -= 1
elif reaction.emoji == '▶️':
if current == len(embeds) - 1:
current = 0
else:
current += 1
await msg.edit(embed = embeds[current])
@client.command()
async def hi(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
await ctx.send(f'Hello, {ctx.author.display_name}!')
@client.command()
async def invite(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
await ctx.send("https://discord.com/api/oauth2/authorize?client_id=680466714777223183&permissions=8&scope=bot")
@client.command(aliases = ['p'])
async def ping(ctx):
before = time.monotonic()
message = await ctx.send("Pong!")
ping = int((time.monotonic() - before) * 1000)
await message.edit(content = f"Pong! `{ping}ms`")
c.execute("SELECT * FROM ping ORDER BY type;")
data = c.fetchall()
if ping < data[0][1]:
c.execute("UPDATE ping SET time = %s, person = %s WHERE type = 0;", (ping, ctx.author.name))
conn.commit()
if ping > data[1][1]:
c.execute("UPDATE ping SET time = %s, person = %s WHERE type = 1;", (ping, ctx.author.name))
conn.commit()
@client.command(aliases = ['pl'])
async def pingleaderboard(ctx):
c.execute("SELECT * FROM ping ORDER BY type;")
data = c.fetchall()
await ctx.send(f'lowest: {data[0][1]}ms by {data[0][2]}\nhighest: {data[1][1]}ms by {data[1][2]}')
'''
@client.command(aliases = ['s'])
async def say(ctx, *, message):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
await ctx.send(f'{message}')
@say.error
async def say_error(ctx, error):
print(error)
await ctx.send('Please follow format: `y.say {message}`')
@client.command(aliases = ['sp'])
async def spam(ctx, *, message):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
s = message.split()
if int(s[-1]) > 20:
await ctx.send('You cannot spam that much.')
else:
out = message[0:len(message) - len(s[-1]) - 1]
await ctx.send((out + '\n') * int(s[-1]))
@spam.error
async def spam_error(ctx, error):
print(error)
await ctx.send('Please follow format: `y.spam {message} {amount}`')
'''
@client.command(aliases = ['8ball', '8b'])
async def eightball(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
answers = [
"As I see it, yes.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don’t count on it.",
"It is certain.",
"It is decidedly so.",
"Most likely.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Outlook good.",
"Reply hazy, try again.",
"Signs point to yes.",
"Very doubtful.",
"Without a doubt.",
"Yes.",
"Yes – definitely.",
"You may rely on it.",
]
await ctx.send(":8ball: " + random.choice(answers))
@client.command(aliases = ['cf'])
async def coinflip(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
rand = random.randint(0, 1)
if rand:
await ctx.send("Heads!")
else:
await ctx.send("Tails!")
@client.command()
async def speakthetruth(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
truth = [
'subscribe to https://www.youtube.com/channel/UCbpHaJIAapKyQGT8qleP2lg',
'subscribe to https://www.youtube.com/channel/UCEANNnWCyRCbkk-DHEMbgtA',
'subscribe to https://www.youtube.com/channel/UCfjfrAYcwqXk13xeLZlftSw',
'subscribe to https://www.youtube.com/channel/UCQwgWTzqnHUPsWoOEbgJOZQ',
'subscribe to https://www.youtube.com/channel/UC4tlxtGBz_JV77dohCDFB2w'
]
await ctx.send(truth[random.randint(0, len(truth) - 1)])
@client.command()
async def dog(ctx):
await ctx.send("https://i.imgur.com/u4agHtY.jpeg")
@client.command(aliases = ['wikipedia', 'w'])
async def wiki(ctx, *, subject):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
' '.join(subject)
suggest = wikipedia.suggest(subject)
if not suggest:
suggest = subject
summary = ''
try:
summary = wikipedia.summary(suggest, sentences = 4)
except wikipedia.exceptions.DisambiguationError as e:
suggest = e.options[0]
except wikipedia.exceptions.PageError as e:
await ctx.send(f'"{subject}" does not match any pages.')
return
num = 4
while len(summary) > 1000 or not summary:
num -= 1
summary = wikipedia.summary(suggest, sentences = num)
page = wikipedia.page(suggest)
summary = f"{page.url}\n\n{summary}"
embed = discord.Embed(
title = page.title,
color = ctx.author.color,
description = summary
)
if page.images[0]:
embed.set_image(url = page.images[0])
await ctx.send(embed = embed)
@wiki.error
async def wiki_error(ctx, error):
print(error)
await ctx.send("Please follow format: `y.wikipedia {subject}`")
@client.command(aliases = ['server', 'si'])
async def serverinfo(ctx):
print(f"{ctx.guild.name} - #{ctx.channel.name} - {ctx.author.name} - {ctx.message.content}")
embed = discord.Embed(
title = f":desktop: {ctx.guild.name} info",
color = ctx.author.color,
description = "_ _"
)
embed.set_thumbnail(url = ctx.guild.icon_url)
owner = ctx.guild.owner
if owner.display_name != owner.name:
name = owner.display_name + f" ({owner.name})"
else:
name = owner.name
embed.add_field(name = ":bust_in_silhouette: Owner", value = name)
embed.add_field(name = ":date: Date Created", value = ctx.guild.created_at.strftime("%B %d, %Y"))
public = 'Private'
if 'PUBLIC' in ctx.guild.features:
public = 'Public'
embed.add_field(name = ":wrench: Server Type", value = public, inline = False)
if ctx.guild.premium_subscription_count:
embed.add_field(name = ":gem: Nitro Level", value = f"Level {ctx.guild.premium_tier} ({ctx.guild.premium_subscription_count} boosts)")
total, member, bot, online, dnd, idle, offline = 0, 0, 0, 0, 0, 0, 0
for m in ctx.guild.members:
total += 1
if m.bot:
bot += 1
else:
member += 1
if m.status == discord.Status.online:
online += 1
elif m.status == discord.Status.dnd:
dnd += 1
elif m.status == discord.Status.idle:
idle += 1
else:
offline += 1
if total == 1:
totalS = ''
else:
totalS = 's'
if bot == 1:
botS = ''
else:
botS = 's'
if member == 1:
memberS = ''
else:
memberS = 's'
embed.add_field(name = ":busts_in_silhouette: Members", value = f"**{total}** total member{totalS}\n**{bot}** bot{botS}\n**{member}** member{memberS}")
embed.add_field(name = ":green_circle: Member Status", value = f"**{online}** online\n**{idle}** idle\n**{dnd}** do not disturb\n**{offline}** offline")
text = 0
voice = 0
category = 0
for c in ctx.guild.channels:
if c.type == discord.ChannelType.text:
text += 1
elif c.type == discord.ChannelType.voice:
voice += 1
else:
category += 1
if category == 1:
categoryS = 'y'
else:
categoryS = 'ies'
if text == 1:
textS = ''
else:
textS = 's'
if voice == 1:
voiceS = ''
else:
voiceS = 's'
embed.add_field(name = ":page_facing_up: Channels", value = f"**{category}** categor{categoryS}\n**{text}** text channel{textS}\n**{voice}** voice channel{voiceS}", inline = False)
await ctx.send(embed = embed)
client.run(bot_token)