-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.py
432 lines (320 loc) · 13.2 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
# name checking
import os
import asyncio
import discord
from discord.ext import commands
from detect_names import exists_player
from connect_db import *
from datetime import datetime, timedelta
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents)
# client = discord.Client(intents=intents)
# LoA
# guild = client.get_guild(319781102950547457)
role_name = "Nickname Approved!"
@client.event
async def on_ready():
create_table()
print('Logged in as')
print(client.user.name)
# print(client.user.id)
for guild in client.guilds:
print(guild)
print(guild.id)
print(guild.roles)
print('------')
@client.event
async def on_member_update(before, after):
"""on_member_update Method
Detects and messages a user when their nickname changes
"""
# ignore if not a name change
if before.nick == after.nick:
return
if before.bot:
return
if before.name == after.nick:
return
print(before.name)
# if before.name.lower() == after.nick.lower() and exists_player(after.nick):
# await after.send(
# f'Appreciate your effort, {after.nick}!'
# )
if exists_player(after.nick):
await after.send(
f'Looks great, thanks {after.nick}!'
)
await grant_approval(after, after.nick)
return
elif after.nick is None and exists_player(after.name):
await after.send(
f'Looks great, thanks {after.name}!'
)
await grant_approval(after, after.name)
return
elif after.nick is None and not exists_player(after.name):
await after.send(
f'Did you just remove your nickname? It looks like your discord name doesn\'t quite match.'
)
await remove_approval(after, after.name)
return
# If no nickname and normal name doesn't exist
elif not exists_player(before.name) and not exists_player(after.nick):
await after.send(
f'Hmm, it looks like {after.nick} might not be right.'
)
await remove_approval(after, after.nick)
return
elif not exists_player(after.nick):
await after.send(
f'Hey {after.nick}, could there be a typo? I can\'t find you in the high scores.'
)
await remove_approval(after, after.nick)
return
def check(m):
return m.content != '' and m.author != client.user
@client.event
async def on_member_join(member: discord.Member):
await member.send(
f'Hi {member.name}, welcome to {member.guild.name}, we\'re glad to have you here!'
)
await member.send(
f"Please feel free to edit your nickname manually if your name doesn't match your in-game name - or I can take your username here (as it looks in-game):"
)
try:
msg = await client.wait_for("message", check=check)
ign = msg.content
# print(ign)
# member = ctx.message.author
if exists_player(ign):
await member.edit(nick=ign)
else:
await member.send(f"Hmm I'm not finding a match for {ign}. Please try changing your name manually")
# await name(member)
except discord.errors.Forbidden:
print(member.guild.name)
await member.send(
f"Ah dang, I don't have the permissions to edit nicknames in {member.guild.name}, please change it manually"
)
except asyncio.TimeoutError:
await member.send(
f"Or please change it manually"
)
# @bot.command(pass_context=True)
@commands.bot_has_permissions(manage_roles=True)
@commands.has_role(role_name)
async def remove_approval(user, username=None):
update_user_fail(user.id, rsn=user.name)
last_succeeded_at = last_pulled_at(user.id)
print(f'{user.name}, {user.nick} | considered role removal at {last_succeeded_at}, '
f'removal time {datetime.now(timezone.utc)}')
# message once per day
# wait just 10 mins while testing
if last_succeeded_at is None or last_succeeded_at + timedelta(days=5) > datetime.now(timezone.utc):
print(f"Didn't remove for {user.id}, within range of initial failure")
return
try:
role = discord.utils.get(guild.roles, name=role_name)
if role in user.roles:
await user.remove_roles(role)
await user.send("Sorry, gonna need you to update your name to your in-game name to approve you again!")
print(f'{user.name}, {user.nick} | role removed at {last_succeeded_at}')
except discord.errors.Forbidden:
print("Whoops, maybe you're trying to edit server admin?")
else:
print(f"End remove role attempt for {user.name}")
# @bot.command(pass_context=True)
@commands.bot_has_permissions(manage_roles=True)
@commands.has_role(role_name)
async def grant_approval(user, username=None):
update_user_info(discord_id=user.id, rsn=username)
try:
role = discord.utils.get(guild.roles, name=role_name)
if role not in user.roles:
await user.add_roles(role)
await user.send(f"You're awesome, and you can now speak in {user.guild.name}")
print(f"Role granted to {user.name} in {user.guild.name}")
except discord.errors.Forbidden:
print("Whoops, maybe you're trying to edit server admin?")
else:
print(f"Finished granting")
# await user.send("You've been granted the speaking stick!")
# check name
# if name exists, allow speaking
# if name no longer matches, give 5 days to change
# if not, then revoke role
# @client.command(pass_context=True)
@commands.bot_has_permissions(manage_roles=True)
@commands.has_role(role_name)
async def consider_approval(ctx):
member = ctx.message.author
role = discord.utils.get(member.guild.roles, name=role_name)
# await ctx.send(role)
if exists_player(member.nick):
try:
await member.add_roles(role)
except discord.ext.commands.errors.BotMissingPermissions:
await ctx.send("Ah, I don't have permission to save you, please contact your guild leader!")
else:
await ctx.send(f"hey {ctx.author.name}, {member.nick} has been giving a role called: {role.name}")
else:
await name_check(member)
# this is the main loop to check
async def background_check():
"""background_check Method
Checks all users in the background for whether their name is in the high scores.
Messages a max of 1x per day
"""
await client.wait_until_ready()
global guild
# hwuh
# guild = client.get_guild(797237739748851713)
# bot testing
# guild = client.get_guild(699647540340981790)
# LoA
guild = client.get_guild(319781102950547457)
global member_dict
member_dict = {member: None for member in guild.members}
check_counter = {member: 0 for member in guild.members}
print([(x.nick, x.guild) for x in member_dict])
while not client.is_closed():
print('----------')
for member in member_dict:
# skip bots
if member.bot:
continue
last_checked = last_pulled_at(member.id) or last_failed_at(member.id)
last_failed = last_failed_at(member.id)
print(f'\n {member.name}, {member.nick}, {member.id} \n'
f' Last checked at {last_checked}, {check_counter[member]} checks \n'
f' Last failed at {last_failed}')
if (last_failed is not None) and (last_checked is not None):
last_checked = max(last_checked, last_failed)
check_counter[member] += 1
# message once per day
if (last_checked is not None) and (last_checked + timedelta(hours=25) > datetime.now(timezone.utc)):
print("Good for the day, skipping checks")
continue
# cases:
# 1. exists nick: great
# 2. no nickname and exists name: ask once
# 3. no nick and not exists name: ask daily until fixed
# 4. no hs nick and exists name: ask daily until fixed
# 5. no hs nick and not exists name: ask daily until fixed
print(
f"Debug condition, should be mostly true: {last_checked}, {last_checked is not None} and"
f" {last_checked} vs {datetime.now(timezone.utc)}")
# 1. if player exists, set check time and we're good for the day
if exists_player(member.nick):
await grant_approval(member, member.nick)
continue
# 2. player exists but no nickname, maybe couldn't set nickname to exact name
elif member.nick is None and exists_player(member.name):
try:
await grant_approval(member, member.name)
await member.edit(nick=member.name, reason='update nickname to name for consistency')
except discord.errors.Forbidden:
print(f"Can't edit names in {member.guild.name}")
continue
# 3. if no nickname and regular name doesn't match
elif member.nick is None and not exists_player(member.name):
try:
await remove_approval(member)
await member.send(
f'Hello {member.name}, please remember to add your in-game name '
f'as your nickname in {member.guild.name}!'
)
except discord.errors.Forbidden:
await remove_approval(member)
print(f"Nickname missing but name doesn't work in {member.guild.name}")
continue
# if no nickname and regular name doesn't match
elif not exists_player(member.nick):
try:
await remove_approval(member)
await member.send(
f'Hey {member.nick}, friendly reminder to update your nickname '
f'in {member.guild.name} to your in-game name!'
)
except discord.errors.Forbidden:
await remove_approval(member)
print(f"Nickname missing but name doesn't work in {member.guild.name}")
continue
# seconds between loop
await asyncio.sleep(60)
@client.command(
name='ping',
brief="Returns bot latency"
)
async def ping(ctx) :
await ctx.send(f"🏓 Pong with {str(round(client.latency, 2))}")
@client.command(name="update")
async def update(ctx, *args):
member = ctx.message.author
# ign = ' '.join(args)
await name_check(member)
async def name_check(member):
await member.send(f"""I can update your nickname for {guild} here - \n Please enter as it appears in game, I'll ignore anything after a | sign."""
)
try:
msg = await client.wait_for("message", check=check, timeout=120) # 60 seconds to reply
ign = msg.content
print(ign)
await name_edit(member, ign)
except asyncio.TimeoutError:
await member.send("Please go ahead to manually edit your nickname, or try me again")
async def name_edit(member, name):
# member = ctx.message.author
if exists_player(name):
try:
await member.edit(nick=name)
except discord.errors.Forbidden:
await member.send(f"Ah, looks like I'm lacking permissions to edit in {guild.name}")
except AttributeError:
await member.send("Gotta invoke me from a guild channel! Sorry I don't make the rules.")
except discord.ext.commands.errors.CommandInvokeError:
await member.send("Something weird happened, sorry try again")
else:
# await member.send(f"Looks great, thanks {name}!")
print('successful name add')
else:
await member.send(f"Hmm I'm not finding a match for {name}. Try again?")
await name_check(member)
@client.command(
name="timer",
brief='Returns time until next check'
)
async def timer(ctx):
print(f'Success at: {last_pulled_at(ctx.message.author.id)} \n'
f'Failed at: {last_failed_at(ctx.message.author.id)} \n'
f'Current time: {datetime.now(timezone.utc)}')
last_checked = last_pulled_at(ctx.message.author.id) or last_failed_at(ctx.message.author.id)
if last_checked is None:
next_message = datetime.now(timezone.utc) + timedelta(days=1)
else:
next_message = last_checked + timedelta(days=1)
await ctx.send(f'Next check will be at: {next_message.strftime("%m/%d/%Y, %H:%M:%S")}.')
@client.command(
name="time",
brief='Returns bot time'
)
async def time(ctx):
current_time = datetime.now(timezone.utc)
await ctx.send(f'{current_time.strftime("%m/%d/%Y, %H:%M:%S")}')
@client.command(
name="ignore",
brief='Turn off notifications for a pretty long time'
)
async def ignore(ctx):
update_user_info(ctx.message.author.id, time=datetime.now(timezone.utc) + timedelta(days=365*2))
await ctx.send(f"You got it, no more from me.")
@client.command(pass_context=True)
@commands.has_any_role("Dev", "Leader")
async def user_list(ctx):
await ctx.send(*print_table(), sep='\n')
client.loop.create_task(background_check())
client.run(TOKEN)