-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
367 lines (303 loc) · 11.9 KB
/
bot.py
File metadata and controls
367 lines (303 loc) · 11.9 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
import discord
from discord.ext import commands
import os
from os import system
import random
import json
import platform
#region Init
def read(readFilename):
try:
with open(readFilename) as json_file:
return json.load(json_file)
except FileNotFoundError:
return None
def write(data, writeFilename):
with open(writeFilename, 'w') as outfile:
json.dump(data, outfile, indent=4)
return
def convertDictionaryKeyFromStringToInteger(oldDict):
if oldDict == None:
return None
newDict = {}
for oldKey in oldDict:
if isinstance(oldKey, str):
newKey = int(oldKey)
newDict[newKey] = oldDict[oldKey]
else:
newDict[oldKey] = oldDict[oldKey]
return newDict
if not os.path.isfile('config.json'):
def_config = {
'token': 'TOKEN',
'name': 'SecretSantaSnek',
'intents': {'messages': True, 'members': True, 'guilds': True},
'prefix': '-',
'admins': []
}
write(def_config, 'config.json')
config = read('config.json')
intents = discord.Intents.default()
intents.messages = config['intents']['messages']
intents.members = config['intents']['members']
intents.guilds = config['intents']['guilds']
activity = discord.Game(name=f"{config['prefix']}help")
bot = commands.Bot(command_prefix = config['prefix'], intents=intents, activity=activity, status=discord.Status.online, case_insensitive=True)
bot.remove_command('help')
bot.token = config['token']
bot.admins = config['admins']
filename = 'nice_list.json'
def admin(user):
return user.id in bot.admins or user.guild_permissions.administrator
system('cls')
print('Booting Up...')
#endregion
@bot.event
async def on_ready():
system('cls')
print(f'{bot.user} has connected to Discord!')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send('That user does not exist!')
elif isinstance(error, commands.MissingPermissions):
await ctx.send('You are not allowed to do that!')
@bot.command()
async def join(ctx, user: discord.Member = None):
if user != None:
if not admin(ctx.author):
await ctx.send('You are not allowed to do that!')
return
else:
user = ctx.author
if user.bot:
await ctx.send('Bots can not be part of the secret santa!')
return
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
if niceList == None:
niceList = {}
if ctx.guild.id not in niceList or niceList[ctx.guild.id]['unshuffled'] == []:
niceList[ctx.guild.id] = {'unshuffled' : [], 'shuffled' : []}
if user.id not in niceList[ctx.guild.id]['unshuffled']:
niceList[ctx.guild.id]['unshuffled'].append(user.id)
niceList[ctx.guild.id]['shuffled'].append(user.id)
await ctx.send(f'{user.name} has been put on the nice list!')
else:
await ctx.send(f'{user.name} is already on the nice list!')
write(niceList, filename)
@bot.command()
async def setPrefix(ctx, char = None):
if not admin(ctx.author):
await ctx.send('You are not allowed to do that!')
elif char == None:
await ctx.send(f'Usage: `{bot.command_prefix}setPrefix <char>`')
return
else:
config['prefix'] = char[0]
write(config, 'config.json')
bot.command_prefix = char[0]
await bot.change_presence(activity=discord.Game(name=f"{bot.command_prefix}help"))
await ctx.send(f'Bot command prefix changed to `{bot.command_prefix}`')
@bot.command()
async def remove(ctx, user: discord.Member = None):
if not admin(ctx.author):
await ctx.send('You are not allowed to do that!')
return
if user == None:
await ctx.send(f'Usage: `{bot.command_prefix}remove <user>`')
return
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
if niceList == None or ctx.guild.id not in niceList or user.id not in niceList[ctx.guild.id]['unshuffled']:
await ctx.send(f'{user.name} is not on the list!')
else:
niceList[ctx.guild.id]['unshuffled'].remove(user.id)
niceList[ctx.guild.id]['shuffled'].remove(user.id)
await ctx.send(f'{user.name} has been taken off the list!')
write(niceList, filename)
@bot.command()
async def leave(ctx):
user = ctx.author
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
if niceList == None or ctx.guild.id not in niceList or user.id not in niceList[ctx.guild.id]['unshuffled']:
await ctx.send('You are not on the list!')
else:
niceList[ctx.guild.id]['unshuffled'].remove(user.id)
niceList[ctx.guild.id]['shuffled'].remove(user.id)
await ctx.send('You have been taken off the list!')
write(niceList, filename)
@bot.command()
async def list(ctx):
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
embed = discord.Embed ( # Message
title='Secret Santa List',
colour=discord.Colour.green()
)
if niceList == None or ctx.guild.id not in niceList or niceList[ctx.guild.id]['unshuffled'] == None:
embed.description = 'There is no one on the list!'
else:
list = ''
for userid in niceList[ctx.guild.id]['unshuffled']:
user = await bot.fetch_user(userid)
list+=f'\n{user.name}'
embed.description = list
await ctx.send(embed=embed)
@bot.command()
async def clear(ctx):
if not admin(ctx.author):
await ctx.send('You are not allowed to do that!')
return
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
if niceList == None or ctx.guild.id not in niceList or len(niceList[ctx.guild.id]['unshuffled']) == 0:
await ctx.send('List is already empty!')
return
await ctx.send('You are about to clear the current list!\nTo continue, please type "confirm clear"')
def check(m): # Check if author sent responce in same channel
return m.author == ctx.author and m.channel == ctx.channel
msg = await bot.wait_for('message', check=check)
if msg.content != 'confirm clear': # if confirmed
await ctx.send('The list was NOT cleared!')
return
niceList[ctx.guild.id]['unshuffled'] = []
niceList[ctx.guild.id]['shuffled'] = []
write(niceList, filename)
await ctx.send('The list has now been cleared!')
@bot.command()
async def shuffle(ctx, view = '', user: discord.Member = None):
if not admin(ctx.author):
await ctx.send('You are not allowed to do that!')
return
niceList = convertDictionaryKeyFromStringToInteger(read(filename))
if niceList == None or ctx.guild.id not in niceList or len(niceList[ctx.guild.id]['unshuffled']) == 0:
await ctx.send('Cant view/shuffle an empty list!')
return
shuffledList = niceList[ctx.guild.id]['shuffled']
if view == '':
random.shuffle(shuffledList)
niceList[ctx.guild.id]['shuffled'] = shuffledList
write(niceList, filename)
await ctx.send(f'List has been shuffled!\nView it with `{bot.command_prefix}shuffle view`')
elif view.lower() == 'view':
await ctx.send('DMing shuffled list...')
embed = discord.Embed (
title='Shuffled Secret Santa List',
colour=discord.Colour.green()
)
for i, userid in enumerate(shuffledList):
curr = await bot.fetch_user(shuffledList[i])
pair = await bot.fetch_user(shuffledList[(i+1) % len(shuffledList)])
embed.add_field(name=curr.name, value=pair.name, inline=False)
if user == None:
user = ctx.author
await user.send(embed=embed)
else:
await ctx.send(f'Usage: `{bot.command_prefix}shuffle [view] [user]`')
@bot.command()
async def start(ctx):
if not admin(ctx.author): # Check if user is admin
await ctx.send('You are not allowed to do that!')
return
niceList = convertDictionaryKeyFromStringToInteger(read(filename)) # Check if enough people on list
if niceList == None or ctx.guild.id not in niceList or len(niceList[ctx.guild.id]['unshuffled']) < 3:
await ctx.send('You need at least 3 people on the list!')
return
await ctx.send('You are about to start the secret santa!\nTo continue, please type "confirm start"')
def check(m): # Check if author sent responce in same channel
return m.author == ctx.author and m.channel == ctx.channel
msg = await bot.wait_for('message', check=check)
if msg.content != 'confirm start': # if confirmed
await ctx.send('The secret santa has been canceled!')
return
await ctx.send('Sending out your secret santa recipients now!')
shuffledList = niceList[ctx.guild.id]['shuffled']
for i, userid in enumerate(shuffledList):
curr = ctx.guild.get_member(shuffledList[i])
pair = ctx.guild.get_member(shuffledList[(i+1) % len(shuffledList)])
# await ctx.send(f'{curr.name} -> {pair.name}')
if pair.nick == None:
await curr.send(f'Ho Ho Ho!\nYour secret santa recipient is {pair.name}!')
else:
await curr.send(f'Ho Ho Ho!\nYour secret santa recipient is {pair.nick}! ({pair.name})')
await ctx.send('Messages sent! Ho ho ho')
@bot.command()
async def admins(ctx, action='list', user: discord.Member = None):
if action == 'list':
embed = discord.Embed (
title='Secret Santa Admins',
colour=discord.Colour.green()
)
list = ''
for userid in config['admins']:
user = await bot.fetch_user(userid)
list+=f'\n{user.name}'
embed.description = list
await ctx.send(embed=embed)
return
elif not admin(ctx.author):
await ctx.send('You do not have permission to do that!')
return
if user == None:
user == ctx.author
if action == 'add':
if user.id in config['admins']:
await ctx.send(f'"{user.name}" is already an admin!')
else:
config['admins'].append(user.id)
write(config, 'config.json')
await ctx.send(f'"{user.name}" is now an admin')
elif action == 'remove':
if user.id not in config['admins']:
await ctx.send(f'"{user.name}" is not an admin!')
else:
config['admins'].remove(user.id)
write(config, 'config.json')
await ctx.send(f'"{user.name}" is no longer an admin')
else:
await ctx.send(f'Usage: `{bot.command_prefix} admin add/remove <user>`')
@bot.command()
async def support(ctx):
embed = discord.Embed ( # Message
title='Bot Support Contact Info',
description='Hey! Problem with the bot? Want your own bot commissioned?\nSend me a friend request!\n\nJoshalot#1023',
colour=discord.Colour.orange()
)
await ctx.author.send(embed=embed)
@bot.command()
async def ping(ctx):
await ctx.send('Pong!')
@bot.command()
async def reload(ctx):
if admin(ctx.author):
await ctx.send('Reloading...')
if platform.system() == 'Windows' and os.path.isfile('run.bat'):
os.system('run.bat')
quit()
elif os.path.isfile('run.sh'):
os.system('./run.sh')
quit()
else:
await ctx.send('An error has occured')
else:
await ctx.send('You do not have permission to do that!')
@bot.command()
async def help(ctx):
embed = discord.Embed ( # Message
title='Help',
colour=discord.Colour.green(),
)
embed.add_field(name='join', value='Add yourself to the list', inline=False)
embed.add_field(name='join <user>', value='Add a specified user to the list\n(admin only)', inline=False)
embed.add_field(name='leave', value='Remove yourself from the list', inline=False)
embed.add_field(name='remove <user>', value='Removes a user to the list\n(admin only)', inline=False)
embed.add_field(name='list', value='Lists everyone currently on the list', inline=False)
embed.add_field(name='clear', value='Clears the current secret santa list\n(admin only)', inline=False)
embed.add_field(name='shuffle', value='Shuffles the list and assigns each member with a random recipient\n(admin only)', inline=False)
embed.add_field(name='shuffle view', value='DMs you the current secret santa pairings\n(admin only)', inline=False)
embed.add_field(name='shuffle view <user>', value='DMs a user the current secret santa pairings\n(admin only)', inline=False)
embed.add_field(name='start', value='Starts the secret santa, DMing each member with their assigned recipient\n(admin only)', inline=False)
embed.add_field(name='admins list', value='Lists users who have access to admin commands', inline=False)
embed.add_field(name='admins add <user>', value='Give user access to admin commands\n(admin only)', inline=False)
embed.add_field(name='admins remove <user>', value='Revoke user\'s access to admin commands\n(admin only)', inline=False)
embed.add_field(name='setPrefix <char>', value='Change bot\'s prefix\n(admin only)', inline=False)
embed.add_field(name='support', value='DMs bot support contact info to you', inline=False)
await ctx.send(embed=embed)
bot.run(bot.token)