-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
thread.py
1278 lines (1083 loc) · 46.2 KB
/
thread.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
import asyncio
import copy
import io
import re
import time
import typing
from datetime import datetime, timedelta
from types import SimpleNamespace
import isodate
import discord
from discord.ext.commands import MissingRequiredArgument, CommandError
from core.models import DMDisabled, DummyMessage, getLogger
from core.time import human_timedelta
from core.utils import (
is_image_url,
days,
match_title,
match_user_id,
truncate,
format_channel_name,
)
logger = getLogger(__name__)
class Thread:
"""Represents a discord Modmail thread"""
def __init__(
self,
manager: "ThreadManager",
recipient: typing.Union[discord.Member, discord.User, int],
channel: typing.Union[discord.DMChannel, discord.TextChannel] = None,
):
self.manager = manager
self.bot = manager.bot
if isinstance(recipient, int):
self._id = recipient
self._recipient = None
else:
if recipient.bot:
raise CommandError("Recipient cannot be a bot.")
self._id = recipient.id
self._recipient = recipient
self._channel = channel
self.genesis_message = None
self._ready_event = asyncio.Event()
self.wait_tasks = []
self.close_task = None
self.auto_close_task = None
self._cancelled = False
def __repr__(self):
return f'Thread(recipient="{self.recipient or self.id}", channel={self.channel.id})'
async def wait_until_ready(self) -> None:
"""Blocks execution until the thread is fully set up."""
# timeout after 30 seconds
task = asyncio.create_task(asyncio.wait_for(self._ready_event.wait(), timeout=25))
self.wait_tasks.append(task)
try:
await task
except asyncio.TimeoutError:
pass
self.wait_tasks.remove(task)
@property
def id(self) -> int:
return self._id
@property
def channel(self) -> typing.Union[discord.TextChannel, discord.DMChannel]:
return self._channel
@property
def recipient(self) -> typing.Optional[typing.Union[discord.User, discord.Member]]:
return self._recipient
@property
def ready(self) -> bool:
return self._ready_event.is_set()
@ready.setter
def ready(self, flag: bool):
if flag:
self._ready_event.set()
self.bot.dispatch("thread_create", self)
else:
self._ready_event.clear()
@property
def cancelled(self) -> bool:
return self._cancelled
@cancelled.setter
def cancelled(self, flag: bool):
self._cancelled = flag
if flag:
for i in self.wait_tasks:
i.cancel()
async def setup(self, *, creator=None, category=None, initial_message=None):
"""Create the thread channel and other io related initialisation tasks"""
self.bot.dispatch("thread_initiate", self, creator, category, initial_message)
recipient = self.recipient
# in case it creates a channel outside of category
overwrites = {
self.bot.modmail_guild.default_role: discord.PermissionOverwrite(read_messages=False)
}
category = category or self.bot.main_category
if category is not None:
overwrites = None
try:
channel = await self.bot.modmail_guild.create_text_channel(
name=format_channel_name(self.bot, recipient),
category=category,
overwrites=overwrites,
reason="Creating a thread channel.",
)
except discord.HTTPException as e:
# try again but null-discrim (name could be banned)
try:
channel = await self.bot.modmail_guild.create_text_channel(
name=format_channel_name(self.bot, recipient, force_null=True),
category=category,
overwrites=overwrites,
reason="Creating a thread channel.",
)
except discord.HTTPException as e: # Failed to create due to missing perms.
logger.critical("An error occurred while creating a thread.", exc_info=True)
self.manager.cache.pop(self.id)
embed = discord.Embed(color=self.bot.error_color)
embed.title = "Error while trying to create a thread."
embed.description = str(e)
embed.add_field(name="Recipient", value=recipient.mention)
if self.bot.log_channel is not None:
await self.bot.log_channel.send(embed=embed)
return
self._channel = channel
try:
log_url, log_data = await asyncio.gather(
self.bot.api.create_log_entry(recipient, channel, creator or recipient),
self.bot.api.get_user_logs(recipient.id),
)
log_count = sum(1 for log in log_data if not log["open"])
except Exception:
logger.error("An error occurred while posting logs to the database.", exc_info=True)
log_url = log_count = None
# ensure core functionality still works
await channel.edit(topic=f"User ID: {recipient.id}")
self.ready = True
if creator is not None and creator != recipient:
mention = None
else:
mention = self.bot.config["mention"]
async def send_genesis_message():
info_embed = self._format_info_embed(
recipient, log_url, log_count, self.bot.main_color
)
try:
msg = await channel.send(mention, embed=info_embed)
self.bot.loop.create_task(msg.pin())
self.genesis_message = msg
except Exception:
logger.error("Failed unexpectedly:", exc_info=True)
async def send_recipient_genesis_message():
# Once thread is ready, tell the recipient.
thread_creation_response = self.bot.config["thread_creation_response"]
embed = discord.Embed(
color=self.bot.mod_color,
description=thread_creation_response,
timestamp=channel.created_at,
)
recipient_thread_close = self.bot.config.get("recipient_thread_close")
if recipient_thread_close:
footer = self.bot.config["thread_self_closable_creation_footer"]
else:
footer = self.bot.config["thread_creation_footer"]
embed.set_footer(text=footer, icon_url=self.bot.guild.icon_url)
embed.title = self.bot.config["thread_creation_title"]
if creator is None or creator == recipient:
msg = await recipient.send(embed=embed)
if recipient_thread_close:
close_emoji = self.bot.config["close_emoji"]
close_emoji = await self.bot.convert_emoji(close_emoji)
await self.bot.add_reaction(msg, close_emoji)
async def send_persistent_notes():
notes = await self.bot.api.find_notes(self.recipient)
ids = {}
class State:
def store_user(self, user):
return user
for note in notes:
author = note["author"]
class Author:
name = author["name"]
id = author["id"]
discriminator = author["discriminator"]
avatar_url = author["avatar_url"]
data = {
"id": round(time.time() * 1000 - discord.utils.DISCORD_EPOCH) << 22,
"attachments": {},
"embeds": {},
"edited_timestamp": None,
"type": None,
"pinned": None,
"mention_everyone": None,
"tts": None,
"content": note["message"],
"author": Author(),
}
message = discord.Message(state=State(), channel=None, data=data)
ids[note["_id"]] = str(
(await self.note(message, persistent=True, thread_creation=True)).id
)
await self.bot.api.update_note_ids(ids)
async def activate_auto_triggers():
if initial_message:
message = DummyMessage(copy.copy(initial_message))
try:
return await self.bot.trigger_auto_triggers(message, channel)
except RuntimeError:
pass
await asyncio.gather(
send_genesis_message(),
send_recipient_genesis_message(),
activate_auto_triggers(),
send_persistent_notes(),
)
self.bot.dispatch("thread_ready", self, creator, category, initial_message)
def _format_info_embed(self, user, log_url, log_count, color):
"""Get information about a member of a server
supports users from the guild or not."""
member = self.bot.guild.get_member(user.id)
time = datetime.utcnow()
# key = log_url.split('/')[-1]
role_names = ""
if member is not None:
sep_server = self.bot.using_multiple_server_setup
separator = ", " if sep_server else " "
roles = []
for role in sorted(member.roles, key=lambda r: r.position):
if role.is_default():
# @everyone
continue
fmt = role.name if sep_server else role.mention
roles.append(fmt)
if len(separator.join(roles)) > 1024:
roles.append("...")
while len(separator.join(roles)) > 1024:
roles.pop(-2)
break
role_names = separator.join(roles)
created = str((time - user.created_at).days)
embed = discord.Embed(
color=color, description=f"{user.mention} was created {days(created)}", timestamp=time
)
# if not role_names:
# embed.add_field(name='Mention', value=user.mention)
# embed.add_field(name='Registered', value=created + days(created))
if user.dm_channel:
footer = f"User ID: {user.id} • DM ID: {user.dm_channel.id}"
else:
footer = f"User ID: {user.id}"
embed.set_author(name=str(user), icon_url=user.avatar_url, url=log_url)
# embed.set_thumbnail(url=avi)
if member is not None:
joined = str((time - member.joined_at).days)
# embed.add_field(name='Joined', value=joined + days(joined))
embed.description += f", joined {days(joined)}"
if member.nick:
embed.add_field(name="Nickname", value=member.nick, inline=True)
if role_names:
embed.add_field(name="Roles", value=role_names, inline=True)
embed.set_footer(text=footer)
else:
embed.set_footer(text=f"{footer} • (not in main server)")
if log_count is not None:
# embed.add_field(name="Past logs", value=f"{log_count}")
thread = "thread" if log_count == 1 else "threads"
embed.description += f" with **{log_count or 'no'}** past {thread}."
else:
embed.description += "."
mutual_guilds = [g for g in self.bot.guilds if user in g.members]
if member is None or len(mutual_guilds) > 1:
embed.add_field(
name="Mutual Server(s)", value=", ".join(g.name for g in mutual_guilds)
)
return embed
def _close_after(self, closer, silent, delete_channel, message):
return self.bot.loop.create_task(
self._close(closer, silent, delete_channel, message, True)
)
async def close(
self,
*,
closer: typing.Union[discord.Member, discord.User],
after: int = 0,
silent: bool = False,
delete_channel: bool = True,
message: str = None,
auto_close: bool = False,
) -> None:
"""Close a thread now or after a set time in seconds"""
# restarts the after timer
await self.cancel_closure(auto_close)
if after > 0:
# TODO: Add somewhere to clean up broken closures
# (when channel is already deleted)
now = datetime.utcnow()
items = {
# 'initiation_time': now.isoformat(),
"time": (now + timedelta(seconds=after)).isoformat(),
"closer_id": closer.id,
"silent": silent,
"delete_channel": delete_channel,
"message": message,
"auto_close": auto_close,
}
self.bot.config["closures"][str(self.id)] = items
await self.bot.config.update()
task = self.bot.loop.call_later(
after, self._close_after, closer, silent, delete_channel, message
)
if auto_close:
self.auto_close_task = task
else:
self.close_task = task
else:
await self._close(closer, silent, delete_channel, message)
async def _close(
self, closer, silent=False, delete_channel=True, message=None, scheduled=False
):
try:
self.manager.cache.pop(self.id)
except KeyError as e:
logger.error("Thread already closed: %s.", e)
return
await self.cancel_closure(all=True)
# Cancel auto closing the thread if closed by any means.
self.bot.config["subscriptions"].pop(str(self.id), None)
self.bot.config["notification_squad"].pop(str(self.id), None)
# Logging
if self.channel:
log_data = await self.bot.api.post_log(
self.channel.id,
{
"open": False,
"title": match_title(self.channel.topic),
"closed_at": str(datetime.utcnow()),
"nsfw": self.channel.nsfw,
"close_message": message if not silent else None,
"closer": {
"id": str(closer.id),
"name": closer.name,
"discriminator": closer.discriminator,
"avatar_url": str(closer.avatar_url),
"mod": True,
},
},
)
else:
log_data = None
if isinstance(log_data, dict):
prefix = self.bot.config["log_url_prefix"].strip("/")
if prefix == "NONE":
prefix = ""
log_url = f"{self.bot.config['log_url'].strip('/')}{'/' + prefix if prefix else ''}/{log_data['key']}"
if log_data["title"]:
sneak_peak = log_data["title"]
elif log_data["messages"]:
content = str(log_data["messages"][0]["content"])
sneak_peak = content.replace("\n", "")
else:
sneak_peak = "No content"
if self.channel.nsfw:
_nsfw = "NSFW-"
else:
_nsfw = ""
desc = f"[`{_nsfw}{log_data['key']}`]({log_url}): "
desc += truncate(sneak_peak, max=75 - 13)
else:
desc = "Could not resolve log url."
log_url = None
embed = discord.Embed(description=desc, color=self.bot.error_color)
if self.recipient is not None:
user = f"{self.recipient} (`{self.id}`)"
else:
user = f"`{self.id}`"
if self.id == closer.id:
_closer = "the Recipient"
else:
_closer = f"{closer} ({closer.id})"
embed.title = user
event = "Thread Closed as Scheduled" if scheduled else "Thread Closed"
# embed.set_author(name=f"Event: {event}", url=log_url)
embed.set_footer(text=f"{event} by {_closer}", icon_url=closer.avatar_url)
embed.timestamp = datetime.utcnow()
tasks = [self.bot.config.update()]
if self.bot.log_channel is not None and self.channel is not None:
tasks.append(self.bot.log_channel.send(embed=embed))
# Thread closed message
embed = discord.Embed(
title=self.bot.config["thread_close_title"], color=self.bot.error_color,
)
if self.bot.config["show_timestamp"]:
embed.timestamp = datetime.utcnow()
if not message:
if self.id == closer.id:
message = self.bot.config["thread_self_close_response"]
else:
message = self.bot.config["thread_close_response"]
message = self.bot.formatter.format(
message, closer=closer, loglink=log_url, logkey=log_data["key"] if log_data else None
)
embed.description = message
footer = self.bot.config["thread_close_footer"]
embed.set_footer(text=footer, icon_url=self.bot.guild.icon_url)
if not silent and self.recipient is not None:
tasks.append(self.recipient.send(embed=embed))
if delete_channel:
tasks.append(self.channel.delete())
await asyncio.gather(*tasks)
self.bot.dispatch("thread_close", self, closer, silent, delete_channel, message, scheduled)
async def cancel_closure(self, auto_close: bool = False, all: bool = False) -> None:
if self.close_task is not None and (not auto_close or all):
self.close_task.cancel()
self.close_task = None
if self.auto_close_task is not None and (auto_close or all):
self.auto_close_task.cancel()
self.auto_close_task = None
to_update = self.bot.config["closures"].pop(str(self.id), None)
if to_update is not None:
await self.bot.config.update()
async def _restart_close_timer(self):
"""
This will create or restart a timer to automatically close this
thread.
"""
timeout = self.bot.config.get("thread_auto_close")
# Exit if timeout was not set
if timeout == isodate.Duration():
return
# Set timeout seconds
seconds = timeout.total_seconds()
# seconds = 20 # Uncomment to debug with just 20 seconds
reset_time = datetime.utcnow() + timedelta(seconds=seconds)
human_time = human_timedelta(dt=reset_time)
if self.bot.config.get("thread_auto_close_silently"):
return await self.close(
closer=self.bot.user, silent=True, after=int(seconds), auto_close=True
)
# Grab message
close_message = self.bot.formatter.format(
self.bot.config["thread_auto_close_response"], timeout=human_time
)
time_marker_regex = "%t"
if len(re.findall(time_marker_regex, close_message)) == 1:
close_message = re.sub(time_marker_regex, str(human_time), close_message)
elif len(re.findall(time_marker_regex, close_message)) > 1:
logger.warning(
"The thread_auto_close_response should only contain one '%s' to specify time.",
time_marker_regex,
)
await self.close(
closer=self.bot.user, after=int(seconds), message=close_message, auto_close=True
)
async def find_linked_messages(
self,
message_id: typing.Optional[int] = None,
either_direction: bool = False,
message1: discord.Message = None,
note: bool = True,
) -> typing.Tuple[discord.Message, typing.Optional[discord.Message]]:
if message1 is not None:
if (
not message1.embeds
or not message1.embeds[0].author.url
or message1.author != self.bot.user
):
raise ValueError("Malformed thread message.")
elif message_id is not None:
try:
message1 = await self.channel.fetch_message(message_id)
except discord.NotFound:
raise ValueError("Thread message not found.")
if not (
message1.embeds
and message1.embeds[0].author.url
and message1.embeds[0].color
and message1.author == self.bot.user
):
raise ValueError("Thread message not found.")
if message1.embeds[0].color.value == self.bot.main_color and (
message1.embeds[0].author.name.startswith("Note")
or message1.embeds[0].author.name.startswith("Persistent Note")
):
if not note:
raise ValueError("Thread message not found.")
return message1, None
if message1.embeds[0].color.value != self.bot.mod_color and not (
either_direction and message1.embeds[0].color.value == self.bot.recipient_color
):
raise ValueError("Thread message not found.")
else:
async for message1 in self.channel.history():
if (
message1.embeds
and message1.embeds[0].author.url
and message1.embeds[0].color
and (
message1.embeds[0].color.value == self.bot.mod_color
or (
either_direction
and message1.embeds[0].color.value == self.bot.recipient_color
)
)
and message1.embeds[0].author.url.split("#")[-1].isdigit()
and message1.author == self.bot.user
):
break
else:
raise ValueError("Thread message not found.")
try:
joint_id = int(message1.embeds[0].author.url.split("#")[-1])
except ValueError:
raise ValueError("Malformed thread message.")
async for msg in self.recipient.history():
if either_direction:
if msg.id == joint_id:
return message1, msg
if not (msg.embeds and msg.embeds[0].author.url):
continue
try:
if int(msg.embeds[0].author.url.split("#")[-1]) == joint_id:
return message1, msg
except ValueError:
continue
raise ValueError("DM message not found. Plain messages are not supported.")
async def edit_message(self, message_id: typing.Optional[int], message: str) -> None:
try:
message1, message2 = await self.find_linked_messages(message_id)
except ValueError:
logger.warning("Failed to edit message.", exc_info=True)
raise
embed1 = message1.embeds[0]
embed1.description = message
tasks = [self.bot.api.edit_message(message1.id, message), message1.edit(embed=embed1)]
if message2 is not None:
embed2 = message2.embeds[0]
embed2.description = message
tasks += [message2.edit(embed=embed2)]
elif message1.embeds[0].author.name.startswith("Persistent Note"):
tasks += [self.bot.api.edit_note(message1.id, message)]
await asyncio.gather(*tasks)
async def delete_message(
self, message: typing.Union[int, discord.Message] = None, note: bool = True
) -> None:
if isinstance(message, discord.Message):
message1, message2 = await self.find_linked_messages(message1=message, note=note)
else:
message1, message2 = await self.find_linked_messages(message, note=note)
tasks = []
if not isinstance(message, discord.Message):
tasks += [message1.delete()]
elif message2 is not None:
tasks += [message2.delete()]
elif message1.embeds[0].author.name.startswith("Persistent Note"):
tasks += [self.bot.api.delete_note(message1.id)]
if tasks:
await asyncio.gather(*tasks)
async def find_linked_message_from_dm(self, message, either_direction=False):
if either_direction and message.embeds and message.embeds[0].author.url:
compare_url = message.embeds[0].author.url
compare_id = compare_url.split("#")[-1]
else:
compare_url = None
compare_id = None
if self.channel is not None:
async for linked_message in self.channel.history():
if not linked_message.embeds:
continue
url = linked_message.embeds[0].author.url
if not url:
continue
if url == compare_url:
return linked_message
msg_id = url.split("#")[-1]
if not msg_id.isdigit():
continue
msg_id = int(msg_id)
if int(msg_id) == message.id:
return linked_message
if compare_id is not None and compare_id.isdigit():
if int(msg_id) == int(compare_id):
return linked_message
raise ValueError("Thread channel message not found.")
async def edit_dm_message(self, message: discord.Message, content: str) -> None:
try:
linked_message = await self.find_linked_message_from_dm(message)
except ValueError:
logger.warning("Failed to edit message.", exc_info=True)
raise
embed = linked_message.embeds[0]
embed.add_field(name="**Edited, former message:**", value=embed.description)
embed.description = content
await asyncio.gather(
self.bot.api.edit_message(message.id, content), linked_message.edit(embed=embed)
)
async def note(
self, message: discord.Message, persistent=False, thread_creation=False
) -> None:
if not message.content and not message.attachments:
raise MissingRequiredArgument(SimpleNamespace(name="msg"))
msg = await self.send(
message,
self.channel,
note=True,
persistent_note=persistent,
thread_creation=thread_creation,
)
self.bot.loop.create_task(
self.bot.api.append_log(
message, message_id=msg.id, channel_id=self.channel.id, type_="system"
)
)
return msg
async def reply(
self, message: discord.Message, anonymous: bool = False, plain: bool = False
) -> None:
if not message.content and not message.attachments:
raise MissingRequiredArgument(SimpleNamespace(name="msg"))
if not any(g.get_member(self.id) for g in self.bot.guilds):
return await message.channel.send(
embed=discord.Embed(
color=self.bot.error_color,
description="Your message could not be delivered since "
"the recipient shares no servers with the bot.",
)
)
tasks = []
try:
user_msg = await self.send(
message,
destination=self.recipient,
from_mod=True,
anonymous=anonymous,
plain=plain,
)
except Exception as e:
logger.error("Message delivery failed:", exc_info=True)
if isinstance(e, discord.Forbidden):
description = (
"Your message could not be delivered as "
"the recipient is only accepting direct "
"messages from friends, or the bot was "
"blocked by the recipient."
)
else:
description = (
"Your message could not be delivered due "
"to an unknown error. Check `?debug` for "
"more information"
)
tasks.append(
message.channel.send(
embed=discord.Embed(color=self.bot.error_color, description=description,)
)
)
else:
# Send the same thing in the thread channel.
msg = await self.send(
message, destination=self.channel, from_mod=True, anonymous=anonymous, plain=plain
)
tasks.append(
self.bot.api.append_log(
message,
message_id=msg.id,
channel_id=self.channel.id,
type_="anonymous" if anonymous else "thread_message",
)
)
# Cancel closing if a thread message is sent.
if self.close_task is not None:
await self.cancel_closure()
tasks.append(
self.channel.send(
embed=discord.Embed(
color=self.bot.error_color,
description="Scheduled close has been cancelled.",
)
)
)
await asyncio.gather(*tasks)
self.bot.dispatch("thread_reply", self, True, message, anonymous, plain)
return (user_msg, msg) # sent_to_user, sent_to_thread_channel
async def send(
self,
message: discord.Message,
destination: typing.Union[
discord.TextChannel, discord.DMChannel, discord.User, discord.Member
] = None,
from_mod: bool = False,
note: bool = False,
anonymous: bool = False,
plain: bool = False,
persistent_note: bool = False,
thread_creation: bool = False,
) -> None:
self.bot.loop.create_task(
self._restart_close_timer()
) # Start or restart thread auto close
if self.close_task is not None:
# cancel closing if a thread message is sent.
self.bot.loop.create_task(self.cancel_closure())
self.bot.loop.create_task(
self.channel.send(
embed=discord.Embed(
color=self.bot.error_color,
description="Scheduled close has been cancelled.",
)
)
)
if not self.ready:
await self.wait_until_ready()
if not from_mod and not note:
self.bot.loop.create_task(self.bot.api.append_log(message, channel_id=self.channel.id))
destination = destination or self.channel
author = message.author
embed = discord.Embed(description=message.content)
if self.bot.config["show_timestamp"]:
embed.timestamp = message.created_at
system_avatar_url = "https://discordapp.com/assets/f78426a064bc9dd24847519259bc42af.png"
if not note:
if anonymous and from_mod and not isinstance(destination, discord.TextChannel):
# Anonymously sending to the user.
tag = self.bot.config["mod_tag"]
if tag is None:
tag = str(author.top_role)
name = self.bot.config["anon_username"]
if name is None:
name = tag
avatar_url = self.bot.config["anon_avatar_url"]
if avatar_url is None:
avatar_url = self.bot.guild.icon_url
embed.set_author(
name=name,
icon_url=avatar_url,
url=f"https://discordapp.com/channels/{self.bot.guild.id}#{message.id}",
)
else:
# Normal message
name = str(author)
avatar_url = author.avatar_url
embed.set_author(
name=name,
icon_url=avatar_url,
url=f"https://discordapp.com/users/{author.id}#{message.id}",
)
else:
# Special note messages
embed.set_author(
name=f"{'Persistent' if persistent_note else ''} Note ({author.name})",
icon_url=system_avatar_url,
url=f"https://discordapp.com/users/{author.id}#{message.id}",
)
ext = [(a.url, a.filename, False) for a in message.attachments]
images = []
attachments = []
for attachment in ext:
if is_image_url(attachment[0]):
images.append(attachment)
else:
attachments.append(attachment)
image_urls = re.findall(
r"http[s]?:\/\/(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
message.content,
)
image_urls = [
(is_image_url(url, convert_size=False), None, False)
for url in image_urls
if is_image_url(url, convert_size=False)
]
images.extend(image_urls)
images.extend(
(
str(i.image_url) if isinstance(i.image_url, discord.Asset) else i.image_url,
f"{i.name} Sticker",
True,
)
for i in message.stickers
)
embedded_image = False
prioritize_uploads = any(i[1] is not None for i in images)
additional_images = []
additional_count = 1
for url, filename, is_sticker in images:
if (
not prioritize_uploads or ((url is None or is_image_url(url)) and filename)
) and not embedded_image:
if url is not None:
embed.set_image(url=url)
if filename:
if is_sticker:
if url is None:
description = "Unable to retrieve sticker image"
else:
description = "\u200b"
embed.add_field(name=filename, value=description)
else:
embed.add_field(name="Image", value=f"[{filename}]({url})")
embedded_image = True
else:
if note:
color = self.bot.main_color
elif from_mod:
color = self.bot.mod_color
else:
color = self.bot.recipient_color
img_embed = discord.Embed(color=color)
if url is not None:
img_embed.set_image(url=url)
img_embed.url = url
if filename is not None:
img_embed.title = filename
img_embed.set_footer(text=f"Additional Image Upload ({additional_count})")
img_embed.timestamp = message.created_at
additional_images.append(destination.send(embed=img_embed))
additional_count += 1
file_upload_count = 1
for url, filename, _ in attachments:
embed.add_field(
name=f"File upload ({file_upload_count})", value=f"[{filename}]({url})"
)
file_upload_count += 1
if from_mod:
embed.colour = self.bot.mod_color
# Anonymous reply sent in thread channel
if anonymous and isinstance(destination, discord.TextChannel):
embed.set_footer(text="Anonymous Reply")
# Normal messages
elif not anonymous:
mod_tag = self.bot.config["mod_tag"]
if mod_tag is None:
mod_tag = str(message.author.top_role)
embed.set_footer(text=mod_tag) # Normal messages
else:
embed.set_footer(text=self.bot.config["anon_tag"])
elif note:
embed.colour = self.bot.main_color
else:
embed.set_footer(text=f"Message ID: {message.id}")
embed.colour = self.bot.recipient_color
if (from_mod or note) and not thread_creation:
delete_message = not bool(message.attachments)
if delete_message and destination == self.channel:
try:
await message.delete()
except Exception as e:
logger.warning("Cannot delete message: %s.", e)