Skip to content
This repository has been archived by the owner on Nov 30, 2022. It is now read-only.

Fix entry_message_validity_check(), format code with black #376

Merged
merged 1 commit into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 77 additions & 45 deletions pgbot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ def format_entries_message(msg: discord.Message, entry_type: str):
return title, fields


def entry_message_validity_check(message: discord.Message, min_chars=32, max_chars=float("inf")):
def entry_message_validity_check(
message: discord.Message, min_chars=32, max_chars=float("inf")
):
"""Checks if a message posted in a showcase channel for projects has the right format.

Returns:
Expand All @@ -129,19 +131,28 @@ def entry_message_validity_check(message: discord.Message, min_chars=32, max_cha
url_regex_pattern = r"(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])"
# https://stackoverflow.com/a/6041965/14826938

match_obj = re.match(url_regex_pattern, (message.content if message.content else ""))
link_in_msg = bool(match_obj)
first_link_str = match_obj.string if link_in_msg else ""

if (message.content and (link_in_msg and len(message.content) > len(first_link_str)) and min_chars < len(message.content) < max_chars):
search_obj = re.search(
url_regex_pattern, (message.content if message.content else "")
)
link_in_msg = bool(search_obj)
first_link_str = search_obj.group() if link_in_msg else ""

if (
message.content
and (link_in_msg and len(message.content) > len(first_link_str))
and min_chars < len(message.content) < max_chars
):
return True
elif ((message.content or message.reference) and message.attachments):

elif (message.content or message.reference) and message.attachments:
return True

return False

async def delete_bad_entry_and_warning(entry_msg: discord.Message, warn_msg: discord.Message, delay: float = 0.):

async def delete_bad_entry_and_warning(
entry_msg: discord.Message, warn_msg: discord.Message, delay: float = 0.0
):
"""A function to pardon a bad entry message with a grace period. If this coroutine is not cancelled during the
grace period specified in `delay` in seconds, it will delete both `entry_msg` and `warn_msg`, if possible.

Expand All @@ -154,7 +165,7 @@ async def delete_bad_entry_and_warning(entry_msg: discord.Message, warn_msg: dis
await asyncio.sleep(delay) # allow cancelling during delay
except asyncio.CancelledError:
return

try:
await warn_msg.edit("Sorry, but your showcase entry will now be deleted.")
await asyncio.sleep(0)
Expand All @@ -164,7 +175,6 @@ async def delete_bad_entry_and_warning(entry_msg: discord.Message, warn_msg: dis
finally:
await entry_msg.delete()
await warn_msg.delete()



async def member_join(member: discord.Member):
Expand Down Expand Up @@ -229,13 +239,18 @@ async def message_delete(msg: discord.Message):
return

if msg.channel in common.entry_channels.values():
if msg.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"] and msg.id in common.entry_message_deletion_dict: # for case where user deletes their bad entry by themselves
if (
msg.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"]
and msg.id in common.entry_message_deletion_dict
): # for case where user deletes their bad entry by themselves
deletion_data_list = common.entry_message_deletion_dict[msg.id]
deletion_task = deletion_data_list[0]
if not deletion_task.done():
deletion_task.cancel()
try:
warn_msg = await msg.channel.fetch_message(deletion_data_list[1]) # warning and entry message were already deleted
warn_msg = await msg.channel.fetch_message(
deletion_data_list[1]
) # warning and entry message were already deleted
await warn_msg.delete()
except discord.NotFound:
pass
Expand Down Expand Up @@ -283,39 +298,48 @@ async def message_edit(old: discord.Message, new: discord.Message):
del common.entry_message_deletion_dict[new.id]
else:
try:
deletion_task.cancel() # try to cancel deletion after noticing edit by sender
warn_msg = await new.channel.fetch_message(deletion_data_list[1])
deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(minutes=2)
deletion_task.cancel() # try to cancel deletion after noticing edit by sender
warn_msg = await new.channel.fetch_message(
deletion_data_list[1]
)
deletion_datetime = (
datetime.datetime.utcnow()
+ datetime.timedelta(minutes=2)
)
await warn_msg.edit(
content=(
"I noticed your edit, but: Your entry message must contain an attachment or a (Discord recognized) link to be valid."+\
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."+\
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."+\
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."+\
" If no changes are made, your entry message will be"+\
"I noticed your edit, but: Your entry message must contain an attachment or a (Discord recognized) link to be valid."
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
" If no changes are made, your entry message will be"
f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
)
)
common.entry_message_deletion_dict[new.id] = [
asyncio.create_task(
delete_bad_entry_and_warning(new, warn_msg, delay=120)
),
delete_bad_entry_and_warning(
new, warn_msg, delay=120
)
),
warn_msg.id,
]
except discord.NotFound: # cancelling didn't work, warning and entry message were already deleted
del common.entry_message_deletion_dict[new.id]

else: # an edit led to an invalid entry message from a valid one
deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(minutes=2)
deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(
minutes=2
)
warn_msg = await new.reply(
"Your entry message must contain an attachment or a (Discord recognized) link to be valid."+\
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."+\
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."+\
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."+\
" If no changes are made, your entry message will be"+\
"Your entry message must contain an attachment or a (Discord recognized) link to be valid."
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
" If no changes are made, your entry message will be"
f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
)

common.entry_message_deletion_dict[new.id] = [
asyncio.create_task(
delete_bad_entry_and_warning(new, warn_msg, delay=120)
Expand All @@ -324,19 +348,23 @@ async def message_edit(old: discord.Message, new: discord.Message):
]
return

elif entry_message_validity_check(new) and new.id in common.entry_message_deletion_dict: # an invalid entry was corrected
elif (
entry_message_validity_check(new)
and new.id in common.entry_message_deletion_dict
): # an invalid entry was corrected
deletion_data_list = common.entry_message_deletion_dict[new.id]
deletion_task = deletion_data_list[0]
if not deletion_task.done(): # too late to do anything
if not deletion_task.done(): # too late to do anything
try:
deletion_task.cancel() # try to cancel deletion after noticing valid edit by sender
warn_msg = await new.channel.fetch_message(deletion_data_list[1])
deletion_task.cancel() # try to cancel deletion after noticing valid edit by sender
warn_msg = await new.channel.fetch_message(
deletion_data_list[1]
)
await warn_msg.delete()
except discord.NotFound: # cancelling didn't work, warning and entry message were already deleted
pass
del common.entry_message_deletion_dict[new.id]



async for message in common.entries_discussion_channel.history(
around=old.created_at, limit=5
):
Expand All @@ -356,7 +384,9 @@ async def message_edit(old: discord.Message, new: discord.Message):
pass

if not embed_repost_edited:
if (datetime.datetime.utcnow() - old.created_at) < datetime.timedelta(minutes=5): # for new, recently corrected entry messages
if (datetime.datetime.utcnow() - old.created_at) < datetime.timedelta(
minutes=5
): # for new, recently corrected entry messages
entry_type = "showcase"
color = 0xFF8800

Expand Down Expand Up @@ -417,7 +447,7 @@ async def handle_message(msg: discord.Message):
del common.cmd_logs[list(common.cmd_logs.keys())[0]]

await emotion.update("bored", -10)

elif not common.TEST_MODE:
await emotion.check_bonk(msg)

Expand All @@ -439,13 +469,15 @@ async def handle_message(msg: discord.Message):

if msg.channel.id == common.ServerConstants.ENTRY_CHANNEL_IDS["showcase"]:
if not entry_message_validity_check(msg):
deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(minutes=2)
deletion_datetime = datetime.datetime.utcnow() + datetime.timedelta(
minutes=2
)
warn_msg = await msg.reply(
"Your entry message must contain an attachment or a (Discord recognized) link to be valid."+\
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."+\
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."+\
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."+\
" If no changes are made, your entry message will be"+\
"Your entry message must contain an attachment or a (Discord recognized) link to be valid."
" If it doesn't contain any characters but an attachment, it must be a reply to another entry you created."
f" If no attachments are present, it must contain at least 32 characters (including any links, but not links alone)."
f" If you meant to comment on another entry, please delete your message and go to {common.entries_discussion_channel.mention}."
" If no changes are made, your entry message will be"
f" deleted {utils.format_datetime(deletion_datetime, tformat='R')}."
)
common.entry_message_deletion_dict[msg.id] = [
Expand Down
6 changes: 3 additions & 3 deletions pgbot/commands/admin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,13 +629,13 @@ async def cmd_archive(
elif msg.type == discord.MessageType.pins_add:
await embed_utils.send(
channel=destination,
description=f"**{msg.author.name}#{msg.author.discriminator}** pinned a message in #{origin.name}"
description=f"**{msg.author.name}#{msg.author.discriminator}** pinned a message in #{origin.name}",
)

elif msg.type == discord.MessageType.premium_guild_subscription:
await embed_utils.send(
await embed_utils.send(
channel=destination,
description=f"{msg.author.name}#{msg.author.discriminator} just boosted this server!"
description=f"{msg.author.name}#{msg.author.discriminator} just boosted this server!",
)

if len(attached_files) > 1:
Expand Down