forked from eibex/reaction-light
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
1574 lines (1323 loc) · 59.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MIT License
Copyright (c) 2019-2021 eibex
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import datetime
import configparser
import asyncio
from shutil import copy
from sys import platform, exit as shutdown
import discord
from discord.ext import commands, tasks
from core import database, activity, github, schema
directory = os.path.dirname(os.path.realpath(__file__))
with open(f"{directory}/.version") as f:
__version__ = f.read().rstrip("\n").rstrip("\r")
folder = f"{directory}/files"
config = configparser.ConfigParser()
config.read(f"{directory}/config.ini")
logo = str(config.get("server", "logo"))
TOKEN = str(config.get("server", "token"))
botname = str(config.get("server", "name"))
prefix = str(config.get("server", "prefix"))
botcolour = discord.Colour(int(config.get("server", "colour"), 16))
system_channel = (
int(config.get("server", "system_channel"))
if config.get("server", "system_channel")
else None
)
intents = discord.Intents.default()
intents.members = True
intents.reactions = True
intents.messages = True
intents.emojis = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
bot.remove_command("help")
activities_file = f"{directory}/files/activities.csv"
activities = activity.Activities(activities_file)
db_file = f"{directory}/files/reactionlight.db"
db = database.Database(db_file)
class Locks:
def __init__(self):
self.locks = {}
self.main_lock = asyncio.Lock()
async def get_lock(self, user_id):
async with self.main_lock:
if not user_id in self.locks:
self.locks[user_id] = asyncio.Lock()
return self.locks[user_id]
lock_manager = Locks()
def isadmin(member, guild_id):
# Checks if command author has an admin role that was added with rl!admin
admins = db.get_admins(guild_id)
if isinstance(admins, Exception):
print(f"Error when checking if the member is an admin:\n{admins}")
return False
try:
member_roles = [role.id for role in member.roles]
return [admin_role for admin_role in admins if admin_role in member_roles]
except AttributeError:
# Error raised from 'fake' users, such as webhooks
return False
async def getchannel(channel_id):
channel = bot.get_channel(channel_id)
if not channel:
channel = await bot.fetch_channel(channel_id)
return channel
async def getguild(guild_id):
guild = bot.get_guild(guild_id)
if not guild:
guild = await bot.fetch_guild(guild_id)
return guild
async def getuser(user_id):
user = bot.get_user(user_id)
if not user:
user = await bot.fetch_user(user_id)
return user
def restart():
# Create a new python process of bot.py and stops the current one
os.chdir(directory)
python = "python" if platform == "win32" else "python3"
cmd = os.popen(f"nohup {python} bot.py &")
cmd.close()
async def database_updates():
handler = schema.SchemaHandler(db_file, bot)
if handler.version == 0:
handler.zero_to_one()
messages = db.fetch_all_messages()
for message in messages:
channel_id = message[1]
channel = await getchannel(channel_id)
db.add_guild(channel.id, channel.guild.id)
if handler.version == 1:
handler.one_to_two()
if handler.version == 2:
handler.two_to_three()
async def system_notification(guild_id, text, embed=None):
# Send a message to the system channel (if set)
if guild_id:
server_channel = db.fetch_systemchannel(guild_id)
if isinstance(server_channel, Exception):
await system_notification(
None,
"Database error when fetching guild system"
f" channels:\n```\n{server_channel}\n```\n\n{text}",
)
return
if server_channel:
server_channel = server_channel[0][0]
if server_channel:
try:
target_channel = await getchannel(server_channel)
if embed:
await target_channel.send(text, embed=embed)
else:
await target_channel.send(text)
except discord.Forbidden:
await system_notification(None, text)
else:
if embed:
await system_notification(None, text, embed=embed)
else:
await system_notification(None, text)
elif system_channel:
try:
target_channel = await getchannel(system_channel)
if embed:
await target_channel.send(text, embed=embed)
else:
await target_channel.send(text)
except discord.NotFound:
print("I cannot find the system channel.")
except discord.Forbidden:
print("I cannot send messages to the system channel.")
else:
print(text)
async def formatted_channel_list(channel):
all_messages = db.fetch_messages(channel.id)
if isinstance(all_messages, Exception):
await system_notification(
channel.guild.id,
f"Database error when fetching messages:\n```\n{all_messages}\n```",
)
return
formatted_list = []
counter = 1
for msg_id in all_messages:
try:
old_msg = await channel.fetch_message(int(msg_id))
except discord.NotFound:
# Skipping reaction-role messages that might have been deleted without updating CSVs
continue
except discord.Forbidden:
await system_notification(
channel.guild.id,
"I do not have permissions to edit a reaction-role message"
f" that I previously created.\n\nID: {msg_id} in"
f" {channel.mention}",
)
continue
entry = (
f"`{counter}`"
f" {old_msg.embeds[0].title if old_msg.embeds else old_msg.content}"
)
formatted_list.append(entry)
counter += 1
return formatted_list
@tasks.loop(seconds=30)
async def maintain_presence():
# Loops through the activities specified in activities.csv
activity = activities.get()
await bot.change_presence(activity=discord.Game(name=activity))
@tasks.loop(hours=24)
async def updates():
# Sends a reminder once a day if there are updates available
new_version = await github.check_for_updates(__version__)
if new_version:
changelog = await github.latest_changelog()
em = discord.Embed(
title=f"Reaction Light v{new_version} - Changes",
description=changelog,
colour=botcolour,
)
em.set_footer(text=f"{botname}", icon_url=logo)
await system_notification(
None,
f"An update is available. Download Reaction Light **v{new_version}** at"
f" <https://github.com/eibex/reaction-light> or simply use `{prefix}update`"
" (only works with git installations).",
embed=em,
)
@tasks.loop(hours=24)
async def cleandb():
# Cleans the database by deleting rows of reaction role messages that don't exist anymore
messages = db.fetch_all_messages()
guilds = db.fetch_all_guilds()
# Get the cleanup queued guilds
cleanup_guild_ids = db.fetch_cleanup_guilds(guild_ids_only=True)
if isinstance(messages, Exception):
await system_notification(
None,
"Database error when fetching messages during database"
f" cleaning:\n```\n{messages}\n```",
)
return
for message in messages:
try:
channel_id = message[1]
channel = await bot.fetch_channel(channel_id)
await channel.fetch_message(message[0])
except discord.NotFound as e:
# If unknown channel or unknown message
if e.code == 10003 or e.code == 10008:
delete = db.delete(message[0], message[3])
if isinstance(delete, Exception):
await system_notification(
channel.guild.id,
"Database error when deleting messages during database"
f" cleaning:\n```\n{delete}\n```",
)
return
await system_notification(
channel.guild.id,
"I deleted the database entries of a message that was removed."
f"\n\nID: {message} in {channel.mention}",
)
except discord.Forbidden:
# If we can't fetch the channel due to the bot not being in the guild or permissions we usually cant mention it or get the guilds id using the channels object
await system_notification(
message[3],
"I do not have access to a message I have created anymore. "
"I cannot manage the roles of users reacting to it."
f"\n\nID: {message[0]} in channel {message[1]}",
)
if isinstance(guilds, Exception):
await system_notification(
None,
"Database error when fetching guilds during database"
f" cleaning:\n```\n{guilds}\n```",
)
return
for guild_id in guilds:
try:
await bot.fetch_guild(guild_id)
if guild_id in cleanup_guild_ids:
db.remove_cleanup_guild(guild_id)
except discord.Forbidden:
# If unknown guild
if guild_id in cleanup_guild_ids:
continue
else:
db.add_cleanup_guild(
guild_id, round(datetime.datetime.utcnow().timestamp())
)
cleanup_guilds = db.fetch_cleanup_guilds()
if isinstance(cleanup_guilds, Exception):
await system_notification(
None,
"Database error when fetching cleanup guilds during"
f" cleaning:\n```\n{cleanup_guilds}\n```",
)
return
current_timestamp = round(datetime.datetime.utcnow().timestamp())
for guild in cleanup_guilds:
if int(guild[1]) - current_timestamp <= -86400:
# The guild has been invalid / unreachable for more than 24 hrs, try one more fetch then give up and purge the guilds database entries
try:
await bot.fetch_guild(guild[0])
db.remove_cleanup_guild(guild[0])
continue
except discord.Forbidden:
delete = db.remove_guild(guild[0])
delete2 = db.remove_cleanup_guild(guild[0])
if isinstance(delete, Exception):
await system_notification(
None,
"Database error when deleting a guilds datebase entries during"
f" database cleaning:\n```\n{delete}\n```",
)
return
elif isinstance(delete2, Exception):
await system_notification(
None,
"Database error when deleting a guilds datebase entries during"
f" database cleaning:\n```\n{delete2}\n```",
)
return
@tasks.loop(hours=6)
async def check_cleanup_queued_guilds():
cleanup_guild_ids = db.fetch_cleanup_guilds(guild_ids_only=True)
for guild_id in cleanup_guild_ids:
try:
await bot.fetch_guild(guild_id)
db.remove_cleanup_guild(guild_id)
except discord.Forbidden:
continue
@bot.event
async def on_ready():
print("Reaction Light ready!")
await database_updates()
maintain_presence.start()
cleandb.start()
check_cleanup_queued_guilds.start()
updates.start()
@bot.event
async def on_guild_remove(guild):
db.remove_guild(guild.id)
@bot.event
async def on_message(message):
await bot.process_commands(message)
@bot.event
async def on_raw_reaction_add(payload):
reaction = str(payload.emoji)
msg_id = payload.message_id
ch_id = payload.channel_id
user_id = payload.user_id
guild_id = payload.guild_id
exists = db.exists(msg_id)
async with (await lock_manager.get_lock(user_id)):
if isinstance(exists, Exception):
await system_notification(
guild_id,
f"Database error after a user added a reaction:\n```\n{exists}\n```",
)
elif exists:
# Checks that the message that was reacted to is a reaction-role message managed by the bot
reactions = db.get_reactions(msg_id)
if isinstance(reactions, Exception):
await system_notification(
guild_id,
f"Database error when getting reactions:\n```\n{reactions}\n```",
)
return
ch = await getchannel(ch_id)
msg = await ch.fetch_message(msg_id)
user = await getuser(user_id)
if reaction not in reactions:
# Removes reactions added to the reaction-role message that are not connected to any role
await msg.remove_reaction(reaction, user)
else:
# Gives role if it has permissions, else 403 error is raised
role_id = reactions[reaction]
server = await getguild(guild_id)
member = server.get_member(user_id)
role = discord.utils.get(server.roles, id=role_id)
if user_id != bot.user.id:
unique = db.isunique(msg_id)
if unique:
for existing_reaction in msg.reactions:
if str(existing_reaction.emoji) == reaction:
continue
async for reaction_user in existing_reaction.users():
if reaction_user.id == user_id:
await msg.remove_reaction(existing_reaction, user)
# We can safely break since a user can only have one reaction at once
break
try:
await member.add_roles(role)
notify = db.notify(guild_id)
if isinstance(notify, Exception):
await system_notification(
guild_id,
f"Database error when checking if role notifications are turned on:\n```\n{notify}\n```",
)
return
if notify:
await user.send(
f"You now have the following role: **{role.name}**"
)
except discord.Forbidden:
await system_notification(
guild_id,
"Someone tried to add a role to themselves but I do not have"
" permissions to add it. Ensure that I have a role that is"
" hierarchically higher than the role I have to assign, and"
" that I have the `Manage Roles` permission.",
)
@bot.event
async def on_raw_reaction_remove(payload):
reaction = str(payload.emoji)
msg_id = payload.message_id
user_id = payload.user_id
guild_id = payload.guild_id
exists = db.exists(msg_id)
if isinstance(exists, Exception):
await system_notification(
guild_id,
f"Database error after a user removed a reaction:\n```\n{exists}\n```",
)
elif exists:
# Checks that the message that was unreacted to is a reaction-role message managed by the bot
reactions = db.get_reactions(msg_id)
if isinstance(reactions, Exception):
await system_notification(
guild_id,
f"Database error when getting reactions:\n```\n{reactions}\n```",
)
elif reaction in reactions:
role_id = reactions[reaction]
# Removes role if it has permissions, else 403 error is raised
server = await getguild(guild_id)
member = server.get_member(user_id)
if not member:
member = await server.fetch_member(user_id)
role = discord.utils.get(server.roles, id=role_id)
try:
await member.remove_roles(role)
notify = db.notify(guild_id)
if isinstance(notify, Exception):
await system_notification(
guild_id,
f"Database error when checking if role notifications are turned on:\n```\n{notify}\n```",
)
return
if notify:
await member.send(
f"You do not have the following role anymore: **{role.name}**"
)
except discord.Forbidden:
await system_notification(
guild_id,
"Someone tried to remove a role from themselves but I do not have"
" permissions to remove it. Ensure that I have a role that is"
" hierarchically higher than the role I have to remove, and that I"
" have the `Manage Roles` permission.",
)
@bot.command(name="new", aliases=["create"])
async def new(ctx):
if isadmin(ctx.message.author, ctx.guild.id):
sent_initial_message = await ctx.send(
"Welcome to the Reaction Light creation program. Please provide the required information once requested. If you would like to abort the creation, do not respond and the program will time out."
)
rl_object = {}
cancelled = False
def check(message):
return message.author.id == ctx.message.author.id and message.content != ""
if not cancelled:
error_messages = []
user_messages = []
sent_reactions_message = await ctx.send(
"Attach roles and emojis separated by one space (one combination"
" per message). When you are done type `done`. Example:\n:smile:"
" `@Role`"
)
rl_object["reactions"] = {}
try:
while True:
reactions_message = await bot.wait_for(
"message", timeout=120, check=check
)
user_messages.append(reactions_message)
if reactions_message.content.lower() != "done":
reaction = (reactions_message.content.split())[0]
try:
role = reactions_message.role_mentions[0].id
except IndexError:
error_messages.append(
(
await ctx.send(
"Mention a role after the reaction. Example:\n:smile:"
" `@Role`"
)
)
)
continue
if reaction in rl_object["reactions"]:
error_messages.append(
(
await ctx.send(
"You have already used that reaction for another role. Please choose another reaction"
)
)
)
continue
else:
try:
await reactions_message.add_reaction(reaction)
rl_object["reactions"][reaction] = role
except discord.HTTPException:
error_messages.append(
(
await ctx.send(
"You can only use reactions uploaded to servers the bot has"
" access to or standard emojis."
)
)
)
continue
else:
break
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_reactions_message.delete()
for message in error_messages + user_messages:
await message.delete()
if not cancelled:
sent_limited_message = await ctx.send(
"Would you like to limit users to select only have one of the roles at a given time? Please react with a 🔒 to limit users or with a ♾️ to allow users to select multiple roles."
)
def reaction_check(payload):
return (
payload.member.id == ctx.message.author.id
and payload.message_id == sent_limited_message.id
and (str(payload.emoji) == "🔒" or str(payload.emoji) == "♾️")
)
try:
await sent_limited_message.add_reaction("🔒")
await sent_limited_message.add_reaction("♾️")
limited_message_response_payload = await bot.wait_for(
"raw_reaction_add", timeout=120, check=reaction_check
)
if str(limited_message_response_payload.emoji) == "🔒":
rl_object["limit_to_one"] = 1
else:
rl_object["limit_to_one"] = 0
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_limited_message.delete()
if not cancelled:
sent_oldmessagequestion_message = await ctx.send(
f"Would you like to use an existing message or create one using {bot.user.mention}? Please react with a 🗨️ to use an existing message or a 🤖 to create one."
)
def reaction_check2(payload):
return (
payload.member.id == ctx.message.author.id
and payload.message_id == sent_oldmessagequestion_message.id
and (str(payload.emoji) == "🗨️" or str(payload.emoji) == "🤖")
)
try:
await sent_oldmessagequestion_message.add_reaction("🗨️")
await sent_oldmessagequestion_message.add_reaction("🤖")
oldmessagequestion_response_payload = await bot.wait_for(
"raw_reaction_add", timeout=120, check=reaction_check2
)
if str(oldmessagequestion_response_payload.emoji) == "🗨️":
rl_object["old_message"] = True
else:
rl_object["old_message"] = False
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_oldmessagequestion_message.delete()
if not cancelled:
error_messages = []
user_messages = []
if rl_object["old_message"]:
sent_oldmessage_message = await ctx.send(
"Which message would you like to use? Please react with a 🔧 on the message you would like to use."
)
def reaction_check3(payload):
return (
payload.member.id == ctx.message.author.id
and payload.guild_id == sent_oldmessage_message.guild.id
and str(payload.emoji) == "🔧"
)
try:
while True:
oldmessage_response_payload = await bot.wait_for(
"raw_reaction_add", timeout=120, check=reaction_check3
)
try:
try:
channel = await getchannel(
oldmessage_response_payload.channel_id
)
except discord.InvalidData:
channel = None
except discord.HTTPException:
channel = None
if channel is None:
raise discord.NotFound
try:
message = await channel.fetch_message(
oldmessage_response_payload.message_id
)
except discord.HTTPException:
raise discord.NotFound
try:
await message.add_reaction("👌")
await message.remove_reaction("👌", message.guild.me)
await message.remove_reaction("🔧", ctx.author)
except discord.HTTPException:
raise discord.NotFound
if db.exists(message.id):
raise ValueError
rl_object["message"] = dict(
message_id=message.id,
channel_id=message.channel.id,
guild_id=message.guild.id,
)
final_message = message
break
except discord.NotFound:
error_messages.append(
(
await ctx.send(
"I can not access or add reactions to the requested message. Do I have sufficent permissions?"
)
)
)
except ValueError:
error_messages.append(
(
await ctx.send(
f"This message already got a reaction light instance attached to it, consider running `{prefix}edit` instead."
)
)
)
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_oldmessage_message.delete()
for message in error_messages:
await message.delete()
else:
sent_channel_message = await ctx.send(
"Mention the #channel where to send the auto-role message."
)
try:
while True:
channel_message = await bot.wait_for(
"message", timeout=120, check=check
)
if channel_message.channel_mentions:
rl_object[
"target_channel"
] = channel_message.channel_mentions[0]
break
else:
error_messages.append(
(
await message.channel.send(
"The channel you mentioned is invalid."
)
)
)
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_channel_message.delete()
for message in error_messages:
await message.delete()
if not cancelled and "target_channel" in rl_object:
error_messages = []
selector_embed = discord.Embed(
title="Embed_title",
description="Embed_content",
colour=botcolour,
)
selector_embed.set_footer(text=f"{botname}", icon_url=logo)
sent_message_message = await message.channel.send(
"What would you like the message to say?\nFormatting is:"
" `Message // Embed_title // Embed_content`.\n\n`Embed_title`"
" and `Embed_content` are optional. You can type `none` in any"
" of the argument fields above (e.g. `Embed_title`) to make the"
" bot ignore it.\n\n\nMessage",
embed=selector_embed,
)
try:
while True:
message_message = await bot.wait_for(
"message", timeout=120, check=check
)
# I would usually end up deleting message_message in the end but users usually want to be able to access the
# format they once used incase they want to make any minor changes
msg_values = message_message.content.split(" // ")
# This whole system could also be re-done using wait_for to make the syntax easier for the user
# But it would be a breaking change that would be annoying for thoose who have saved their message commands
# for editing.
selector_msg_body = (
msg_values[0] if msg_values[0].lower() != "none" else None
)
selector_embed = discord.Embed(colour=botcolour)
selector_embed.set_footer(text=f"{botname}", icon_url=logo)
if len(msg_values) > 1:
if msg_values[1].lower() != "none":
selector_embed.title = msg_values[1]
if len(msg_values) > 2 and msg_values[2].lower() != "none":
selector_embed.description = msg_values[2]
# Prevent sending an empty embed instead of removing it
selector_embed = (
selector_embed
if selector_embed.title or selector_embed.description
else None
)
if selector_msg_body or selector_embed:
target_channel = rl_object["target_channel"]
sent_final_message = None
try:
sent_final_message = await target_channel.send(
content=selector_msg_body, embed=selector_embed
)
rl_object["message"] = dict(
message_id=sent_final_message.id,
channel_id=sent_final_message.channel.id,
guild_id=sent_final_message.guild.id,
)
final_message = sent_final_message
break
except discord.Forbidden:
error_messages.append(
(
await message.channel.send(
"I don't have permission to send messages to"
f" the channel {target_channel.mention}. Please check my permissions and try again."
)
)
)
except asyncio.TimeoutError:
await ctx.author.send(
"Reaction Light creation failed, you took too long to provide the requested information."
)
cancelled = True
finally:
await sent_message_message.delete()
for message in error_messages:
await message.delete()
if not cancelled:
# Ait we are (almost) all done, now we just need to insert that into the database and add the reactions 💪
try:
r = db.add_reaction_role(rl_object)
except database.DuplicateInstance:
await ctx.send(
f"The requested message already got a reaction light instance attached to it, consider running `{prefix}edit` instead."
)
return
if isinstance(r, Exception):
await system_notification(
ctx.message.guild.id,
f"Database error when creating reaction-light instance:\n```\n{r}\n```",
)
return
for reaction, _ in rl_object["reactions"].items():
await final_message.add_reaction(reaction)
await ctx.message.add_reaction("✅")
await sent_initial_message.delete()
if not cancelled:
await ctx.message.add_reaction("❌")
else:
await ctx.send(
f"You do not have an admin role. You might want to use `{prefix}admin`"
" first."
)
@bot.command(name="edit")
async def edit_selector(ctx):
if isadmin(ctx.message.author, ctx.guild.id):
# Reminds user of formatting if it is wrong
msg_values = ctx.message.content.split()
if len(msg_values) < 2:
await ctx.send(
f"**Type** `{prefix}edit #channelname` to get started. Replace"
" `#channelname` with the channel where the reaction-role message you"
" wish to edit is located."
)
return
elif len(msg_values) == 2:
try:
channel_id = ctx.message.channel_mentions[0].id
except IndexError:
await ctx.send("You need to mention a channel.")
return
channel = await getchannel(channel_id)
all_messages = await formatted_channel_list(channel)
if len(all_messages) == 1:
await ctx.send(
"There is only one reaction-role message in this channel."
f" **Type**:\n```\n{prefix}edit #{channel.name} // 1 // New Message"
" // New Embed Title (Optional) // New Embed Description"
" (Optional)\n```\nto edit the reaction-role message. You can type"
" `none` in any of the argument fields above (e.g. `New Message`)"
" to make the bot ignore it."
)
elif len(all_messages) > 1:
await ctx.send(
f"There are **{len(all_messages)}** reaction-role messages in this"
f" channel. **Type**:\n```\n{prefix}edit #{channel.name} //"
" MESSAGE_NUMBER // New Message // New Embed Title (Optional) //"
" New Embed Description (Optional)\n```\nto edit the desired one."
" You can type `none` in any of the argument fields above (e.g."
" `New Message`) to make the bot ignore it. The list of the"
" current reaction-role messages is:\n\n" + "\n".join(all_messages)
)
else:
await ctx.send("There are no reaction-role messages in that channel.")
elif len(msg_values) > 2:
try:
# Tries to edit the reaction-role message
# Raises errors if the channel sent was invalid or if the bot cannot edit the message
channel_id = ctx.message.channel_mentions[0].id
channel = await getchannel(channel_id)
msg_values = ctx.message.content.split(" // ")
selector_msg_number = msg_values[1]
all_messages = db.fetch_messages(channel_id)
if isinstance(all_messages, Exception):
await system_notification(
ctx.message.guild.id,
"Database error when fetching"
f" messages:\n```\n{all_messages}\n```",
)
return
counter = 1
if all_messages:
message_to_edit_id = None
for msg_id in all_messages:
# Loop through all msg_ids and stops when the counter matches the user input
if str(counter) == selector_msg_number:
message_to_edit_id = msg_id
break
counter += 1
else:
await ctx.send(
"You selected a reaction-role message that does not exist."
)
return
if message_to_edit_id:
old_msg = await channel.fetch_message(int(message_to_edit_id))