Skip to content

Commit 3193284

Browse files
committed
Add debugging logging to 'anti_crosspost' extension
1 parent 8c78bf4 commit 3193284

File tree

2 files changed

+47
-18
lines changed

2 files changed

+47
-18
lines changed

Diff for: pcbot/exts/anti_crosspost.py

+41-16
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,27 @@
88
import snakecore
99
from typing import TypedDict, Collection
1010
from collections import OrderedDict
11+
import logging
1112

1213
from ..base import BaseExtensionCog
1314

1415
# Define the type for the bot, supporting both Bot and AutoShardedBot from snakecore
1516
BotT = snakecore.commands.Bot | snakecore.commands.AutoShardedBot
1617

18+
logger = logging.getLogger(__name__)
1719

1820
fetched_attachments: dict[int, bytes] = {}
1921

2022

2123
async def fetch_attachment(attachment: discord.Attachment, cache: bool = True) -> bytes:
2224
if cache and attachment.id in fetched_attachments:
25+
logger.debug(f"Fetched attachment from cache: {attachment.id}")
2326
return fetched_attachments[attachment.id]
24-
return await attachment.read()
27+
data = await attachment.read()
28+
if cache:
29+
fetched_attachments[attachment.id] = data
30+
logger.debug(f"Fetched attachment from source: {attachment.id}")
31+
return data
2532

2633

2734
async def crosspost_cmp(message: discord.Message, other: discord.Message) -> bool:
@@ -43,22 +50,20 @@ async def crosspost_cmp(message: discord.Message, other: discord.Message) -> boo
4350
have_content = message.content and other.content
4451
have_attachments = message.attachments and other.attachments
4552

53+
logger.debug(
54+
f"Comparing messages {message.jump_url} and {other.jump_url} from {message.author.name}"
55+
)
56+
4657
if have_content:
4758
hamming_score = sum(
4859
x != y for x, y in zip(message.content, other.content)
4960
) / max(len(message.content), len(other.content))
5061
similarity_score = min(max(0, 1 - hamming_score), 1)
62+
logger.debug(f"Computed similarity score for content: {similarity_score}")
5163
else:
5264
similarity_score = 0
5365

5466
if have_attachments:
55-
# Check if the attachments are the same:
56-
# - Sort the attachments by filename and size
57-
# - Compare the sorted lists of attachments
58-
# - if filename and size are the same,
59-
# additionally check if the content is the same
60-
# (only if under 8mb)
61-
6267
try:
6368
matching_attachments = all(
6469
[
@@ -74,7 +79,9 @@ async def crosspost_cmp(message: discord.Message, other: discord.Message) -> boo
7479
)
7580
]
7681
)
77-
except discord.HTTPException:
82+
logger.debug(f"Attachment comparison result: {matching_attachments}")
83+
except discord.HTTPException as e:
84+
logger.debug(f"HTTPException during attachment comparison: {e}")
7885
matching_attachments = False
7986
else:
8087
matching_attachments = False
@@ -155,6 +162,8 @@ async def on_message(self, message: discord.Message):
155162
):
156163
return
157164

165+
logger.debug(f"Received message from {message.author.name}: {message.jump_url}")
166+
158167
# Attempt to enforce the cache size limit
159168
for user_id in list(self.crossposting_cache.keys()):
160169
if len(self.crossposting_cache) <= self.max_tracked_users:
@@ -163,15 +172,18 @@ async def on_message(self, message: discord.Message):
163172
user_cache = self.crossposting_cache[user_id]
164173
if not any(len(group) > 1 for group in user_cache["message_groups"]):
165174
self.crossposting_cache.pop(user_id)
175+
logger.debug(f"Removed user {user_id} from cache to enforce size limit")
166176

167177
# Initialize cache for new users
168178
if message.author.id not in self.crossposting_cache:
169179
self.crossposting_cache[message.author.id] = UserCrosspostCache(
170180
message_groups=[[message]],
171181
message_to_alert={},
172182
)
183+
logger.debug(f"Initialized cache for new user {message.author.name}")
173184
else:
174185
user_cache = self.crossposting_cache[message.author.id]
186+
logger.debug(f"Checking for crossposts for user {message.author.name}")
175187

176188
# Check for crossposts or duplicates in existing message groups
177189
for messages in user_cache["message_groups"]:
@@ -183,8 +195,10 @@ async def on_message(self, message: discord.Message):
183195
<= self.crosspost_timedelta_threshold
184196
):
185197
messages.append(message)
198+
logger.debug(
199+
f"Found crosspost for user {message.author.name}, message URL {message.jump_url}!!!!!!!!!!"
200+
)
186201

187-
# Send an alert message and add its ID to the alert list
188202
try:
189203
alert_message = await message.reply(
190204
"This message is a recent crosspost/duplicate among the following messages: "
@@ -194,15 +208,18 @@ async def on_message(self, message: discord.Message):
194208
user_cache["message_to_alert"][
195209
message.id
196210
] = alert_message.id
197-
except discord.HTTPException:
198-
# Silently handle errors
199-
pass
211+
logger.debug(f"Sent alert message for crosspost URL {message.jump_url}")
212+
except discord.HTTPException as e:
213+
logger.debug(f"Failed to send alert message: {e}")
200214
break
201215
else:
202216
continue
203217
break
204218
else:
205219
user_cache["message_groups"].append([message])
220+
logger.debug(
221+
f"Added message to new group for user {message.author.name}"
222+
)
206223

207224
# Remove oldest message groups if limit is exceeded and the group is too small
208225
if (
@@ -214,6 +231,9 @@ async def on_message(self, message: discord.Message):
214231
):
215232
if len(messages) < 2:
216233
user_cache["message_groups"].pop(i)
234+
logger.debug(
235+
f"Removed oldest message group for user {message.author.name}"
236+
)
217237
break
218238

219239
@commands.Cog.listener()
@@ -241,6 +261,9 @@ async def on_message_delete(self, message: discord.Message):
241261
stale_alert_message_ids.append(
242262
user_cache["message_to_alert"].pop(message.id)
243263
)
264+
logger.debug(
265+
f"Removed message {message.jump_url} from user {message.author.name}'s cache due to deletion"
266+
)
244267
break
245268

246269
# Mark last alert message for this crosspost group as stale if the group
@@ -256,9 +279,11 @@ async def on_message_delete(self, message: discord.Message):
256279
await discord.PartialMessage(
257280
channel=message.channel, id=alert_message_id
258281
).delete()
259-
except (discord.NotFound, discord.Forbidden):
260-
# Silently handle errors
261-
pass
282+
logger.debug(f"Deleted stale alert message ID {alert_message_id}")
283+
except (discord.NotFound, discord.Forbidden) as e:
284+
logger.debug(
285+
f"Failed to delete alert message ID {alert_message_id}: {e}"
286+
)
262287

263288
def _is_valid_channel(self, channel: discord.abc.GuildChannel) -> bool:
264289
"""

Diff for: pcbot/exts/bot_management.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -531,13 +531,17 @@ async def eval(self, ctx: commands.Context[BotT], code: CodeBlock):
531531
embed=discord.Embed(
532532
title=f"Return output (code executed in "
533533
f"{snakecore.utils.format_time_by_units(total)}):",
534-
description=snakecore.utils.code_block(eval_output, max_characters=4096),
534+
description=snakecore.utils.code_block(
535+
eval_output, max_characters=4096
536+
),
535537
color=int(self.theme_color),
536538
),
537539
file=discord.File(
538540
io.StringIO(repr(eval_output)), # type: ignore
539541
filename=f"eval_output_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.txt",
540-
) if len(eval_output) > 4096 else None,
542+
)
543+
if len(eval_output) > 4096
544+
else None,
541545
)
542546

543547
@is_bot_manager()

0 commit comments

Comments
 (0)