-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_send.py
More file actions
398 lines (339 loc) · 17.1 KB
/
message_send.py
File metadata and controls
398 lines (339 loc) · 17.1 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
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
from datetime import timezone
import discord
import helpers
import database
from header_state import header_state
from logger_config import get_logger
logger = get_logger(__name__)
async def handle_message(bot, message: discord.Message):
"""Handles incoming messages and forwards them to linked channels."""
timestamp = message.created_at
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
# Try to find linked channels
target_channel_ids = helpers.find_linked_channels(str(message.channel.id))
if target_channel_ids is None:
return
logger.info(f"Forwarding message from {message.author} in {message.guild.name}#{message.channel.name} to {len(target_channel_ids)} linked channels")
# Form first message entry
message_group_entry = [{
"guild_id": helpers.get_guild_id_from_channel_id(str(message.channel.id)),
"channel_id": str(message.channel.id),
"message_id": str(message.id)
}]
group_name = helpers.get_group_name(str(message.channel.id))
guild_name = message.guild.name if message.guild else "Unknown Guild"
channel_group_len = len(target_channel_ids)
author_id = str(message.author.id)
source_guild_id = str(message.guild.id) if message.guild else "unknown"
source_changed = header_state.update_group_source(group_name, source_guild_id)
if source_changed:
logger.debug("[header] group source changed group=%s source_guild=%s", group_name, source_guild_id)
for target_channel_id in target_channel_ids:
target_channel = bot.get_channel(int(target_channel_id))
target_guild_id = helpers.get_guild_id_from_channel_id(target_channel_id)
if target_channel:
lock = header_state.get_lock(group_name, target_channel_id, None)
async with lock:
include_header = header_state.should_include_header(
group_name=group_name,
channel_id=target_channel_id,
thread_id=None,
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
is_reply=False,
)
include_header, reason, prev_state = header_state.decide_header(
group_name=group_name,
channel_id=target_channel_id,
thread_id=None,
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
is_reply=False,
)
logger.debug(
"[header] decision group=%s dest=%s thread=%s include=%s reason=%s author=%s source_guild=%s prev_state=%s",
group_name, target_channel_id, None, include_header, reason, author_id, source_guild_id, prev_state,
)
header = helpers.form_header(message, guild_name, channel_group_len) if include_header else ""
msg = helpers.form_message_text(header, message.content)
# Send the message to the target channel
try:
# Process attachments and stickers
files = await helpers.process_attachments(message)
global_stickers, guild_sticker_files = await helpers.process_stickers(message)
# Merge attachments + guild-native sticker files
files += guild_sticker_files
result = await target_channel.send(
content=msg,
embed=message.embeds[0] if message.embeds else None,
files=files if files else None,
stickers=global_stickers if global_stickers else None
)
header_state.update_state(
group_name=group_name,
channel_id=target_channel_id,
thread_id=None,
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
)
logger.debug(f"Message forwarded to {target_channel.guild.name}#{target_channel.name}")
except Exception as e:
logger.error(f"Failed to send message to {target_channel.guild.name}#{target_channel.name}: {e}")
continue
# Form message entry for every linked channel
message_group_entry.append({
"guild_id": target_guild_id,
"channel_id": target_channel_id,
"message_id": str(result.id)
})
else:
logger.error(f"Target channel with ID {target_channel_id} not found")
return
# Save the message group entry to the database
group_name = helpers.get_group_name(str(message.channel.id))
try:
database.save_message_group_entry(group_name, message_group_entry)
logger.debug(f"Message group entry saved for group {group_name}")
except Exception as e:
logger.error(f"Failed to save message group entry: {e}")
async def handle_thread_message(bot, message: discord.Message):
"""Handles messages in threads and forwards them to linked channels."""
logger.info(f"Handling thread message from {message.author} in thread {message.channel.name}")
timestamp = message.created_at
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
# Get the parent channel ID
parent_channel_id = str(message.channel.parent_id)
# Try to find linked channels for the parent channel
target_channel_ids = helpers.find_linked_channels(parent_channel_id)
if target_channel_ids is None:
logger.debug(f"No linked channels found for parent channel {parent_channel_id}")
return
logger.info(f"Forwarding thread message to {len(target_channel_ids)} linked channels")
# Form first message entry
message_group_entry = [{
"guild_id": helpers.get_guild_id_from_channel_id(parent_channel_id),
"channel_id": parent_channel_id,
"thread_id": str(message.channel.id),
"message_id": str(message.id)
}]
group_name = helpers.get_group_name(parent_channel_id)
guild_name = message.guild.name if message.guild else "Unknown Guild"
thread_name = message.channel.name
channel_group_len = len(target_channel_ids)
author_id = str(message.author.id)
source_guild_id = str(message.guild.id) if message.guild else "unknown"
source_changed = header_state.update_group_source(group_name, source_guild_id)
if source_changed:
logger.debug("[header] group source changed group=%s source_guild=%s", group_name, source_guild_id)
thread_message_entry = database.get_message_group_entry_by_message_id(message.channel.id, group_name)
for target_channel_id in target_channel_ids:
target_channel = bot.get_channel(int(target_channel_id))
target_guild_id = helpers.get_guild_id_from_channel_id(target_channel_id)
if target_channel:
target_thread_message_id = None
target_thread = None
try:
for entry in thread_message_entry:
if entry["guild_id"] == target_guild_id and entry["channel_id"] == target_channel_id:
target_thread_message_id = entry["message_id"]
break
else:
logger.info(f"No entry found for target channel {target_channel_id} in thread message group entry")
if not target_thread_message_id:
logger.warning(f"No parent thread message found for target channel {target_channel_id}")
continue
try:
parent_message = await target_channel.fetch_message(target_thread_message_id)
except Exception as e:
logger.warning(f"Failed to fetch parent message in {target_channel.guild.name}#{target_channel.name}: {e}")
return
parent_text = parent_message.content
thread_name = " ".join(parent_text.split()[:5])
# Process attachments and stickers
files = await helpers.process_attachments(message)
global_stickers, guild_sticker_files = await helpers.process_stickers(message)
# Merge attachments + guild-native sticker files
files += guild_sticker_files
if parent_message.thread:
target_thread = parent_message.thread
else:
try:
thread = await parent_message.create_thread(
name=f"{thread_name}",
)
target_thread = thread
except Exception as e:
logger.info(f"Error while creating a new thread: {e}")
except Exception as e:
logger.error(f"Some error occurred while sending thread message to {target_channel.guild.name}#{target_channel.name}: {e}")
if not target_thread:
logger.error(f"Could not resolve target thread for {target_channel.guild.name}#{target_channel.name}")
continue
lock = header_state.get_lock(group_name, target_channel_id, target_thread.id)
async with lock:
include_header, reason, prev_state = header_state.decide_header(
group_name=group_name,
channel_id=target_channel_id,
thread_id=str(target_thread.id),
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
is_reply=False,
)
logger.debug(
"[header] decision group=%s dest=%s thread=%s include=%s reason=%s author=%s source_guild=%s prev_state=%s",
group_name, target_channel_id, target_thread.id, include_header, reason, author_id, source_guild_id, prev_state,
)
header = helpers.form_header(message, guild_name, channel_group_len) if include_header else ""
msg = helpers.form_message_text(header, message.content)
try:
result = await target_thread.send(
content=msg,
embed=message.embeds[0] if message.embeds else None,
files=files if files else None,
stickers=global_stickers if global_stickers else None
)
header_state.update_state(
group_name=group_name,
channel_id=target_channel_id,
thread_id=str(target_thread.id),
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
)
except Exception as e:
logger.error(f"Some error occurred while sending thread message to {target_channel.guild.name}#{target_channel.name}: {e}")
continue
# Form message entry for every linked channel
entry = {
"guild_id": target_guild_id,
"channel_id": target_channel_id,
"thread_id": target_thread_message_id,
"message_id": str(result.id)
}
message_group_entry.append(entry)
else:
logger.error(f"Target channel with ID {target_channel_id} not found")
return
# Save the message group entry to the database
group_name = helpers.get_group_name(parent_channel_id)
try:
database.save_message_group_entry(group_name, message_group_entry)
logger.info(f"Thread message successfully forwarded and saved")
except Exception as e:
logger.error(f"Failed to save thread message group entry: {e}")
def _is_forum_thread(thread: discord.Thread) -> bool:
parent = thread.parent
if parent is None:
return False
if isinstance(parent, discord.ForumChannel):
return True
return getattr(parent, "type", None) == discord.ChannelType.forum
def _is_forum_starter_message(message: discord.Message, thread_entry: list, parent_channel_id: str) -> bool:
source_guild_id = helpers.get_guild_id_from_channel_id(parent_channel_id)
for entry in thread_entry:
if (
entry.get("guild_id") == source_guild_id
and entry.get("channel_id") == parent_channel_id
and entry.get("thread_id") == str(message.channel.id)
):
starter_message_id = entry.get("starter_message_id")
if starter_message_id and str(message.id) == str(starter_message_id):
return True
return str(message.id) == str(message.channel.id)
async def handle_forum_thread_message(bot, message: discord.Message, ignore_reference: bool = False):
"""Handles messages in forum threads and forwards them to linked forum threads."""
if message.author == bot.user:
return
if message.webhook_id:
return
if not isinstance(message.channel, discord.Thread):
return
if not _is_forum_thread(message.channel):
return
parent_channel_id = str(message.channel.parent_id)
group_name = helpers.get_group_name(parent_channel_id)
if not group_name:
return
thread_entry = database.get_forum_thread_group_entry_by_thread_id(str(message.channel.id), group_name)
if not thread_entry:
return
if _is_forum_starter_message(message, thread_entry, parent_channel_id):
return
if message.reference and not ignore_reference:
return
target_channel_ids = helpers.find_linked_channels(parent_channel_id)
if not target_channel_ids:
return
timestamp = message.created_at
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
guild_name = message.guild.name if message.guild else "Unknown Guild"
channel_group_len = len(target_channel_ids)
author_id = str(message.author.id)
source_guild_id = str(message.guild.id) if message.guild else "unknown"
header_state.update_group_source(group_name, source_guild_id)
message_group_entry = [{
"guild_id": helpers.get_guild_id_from_channel_id(parent_channel_id),
"channel_id": parent_channel_id,
"thread_id": str(message.channel.id),
"message_id": str(message.id)
}]
for entry in thread_entry:
if entry["thread_id"] == str(message.channel.id):
continue
target_thread = bot.get_channel(int(entry["thread_id"]))
if not target_thread:
try:
target_thread = await bot.fetch_channel(int(entry["thread_id"]))
except Exception as e:
logger.error(f"Failed to fetch target forum thread {entry['thread_id']}: {e}")
continue
lock = header_state.get_lock(group_name, entry["channel_id"], entry["thread_id"])
async with lock:
include_header, _, _ = header_state.decide_header(
group_name=group_name,
channel_id=entry["channel_id"],
thread_id=entry["thread_id"],
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
is_reply=False,
)
header = helpers.form_header(message, guild_name, channel_group_len) if include_header else ""
msg = helpers.form_message_text(header, message.content)
try:
files = await helpers.process_attachments(message)
global_stickers, guild_sticker_files = await helpers.process_stickers(message)
files += guild_sticker_files
result = await target_thread.send(
content=msg,
embed=message.embeds[0] if message.embeds else None,
files=files if files else None,
stickers=global_stickers if global_stickers else None
)
header_state.update_state(
group_name=group_name,
channel_id=entry["channel_id"],
thread_id=entry["thread_id"],
author_id=author_id,
source_guild_id=source_guild_id,
timestamp=timestamp,
)
message_group_entry.append({
"guild_id": entry["guild_id"],
"channel_id": entry["channel_id"],
"thread_id": entry["thread_id"],
"message_id": str(result.id)
})
except Exception as e:
logger.error(f"Failed to send forum thread message to {entry['thread_id']}: {e}")
try:
database.save_message_group_entry(group_name, message_group_entry)
except Exception as e:
logger.error(f"Failed to save forum message group entry: {e}")