Skip to content

Commit

Permalink
refactor: made repeated code into a loop
Browse files Browse the repository at this point in the history
  • Loading branch information
namemcguffin committed Aug 13, 2021
1 parent a70a5db commit 9cc215b
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions cogs/sanitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,32 @@ async def unroll_tiktok(link) -> str:
allow_redirects=True) as r:
return str(r.url)

async def short_replace(msg, match) -> str:
short_match = match.group()
return msg.replace(short_match, await unroll_tiktok(short_match))

async def mobile_replace(msg, match) -> str:
full, clean = match.group(0, 1)
return msg.replace(full, await unroll_tiktok(clean))

async def desktop_replace(msg, match) -> str:
full, clean = match.group(0, 1)
return msg.replace(full, clean)

class Sanitizer(commands.Cog):
def __init__(self, bot):
self.bot = bot

@commands.Cog.listener("on_message")
async def tiktok_link_sanitizer(self, msg):
replace: bool = False
msg_txt: str = str(msg.content)
for short in TIKTOK_SHORTLINK.finditer(msg_txt):
short_match = short.group()
msg_txt = msg_txt.replace(short_match, await
unroll_tiktok(short_match))
replace = True
for mobile in TIKTOK_MOBILE.finditer(msg_txt):
full, clean = mobile.group(0, 1)
msg_txt = msg_txt.replace(full, await unroll_tiktok(clean))
replace = True
for desktop in TIKTOK_DESKTOP.finditer(msg_txt):
full, clean = desktop.group(0, 1)
msg_txt = msg_txt.replace(full, clean)
replace = True
replace: bool = False

for reg, fun in [(TIKTOK_SHORTLINK, short_replace), (TIKTOK_MOBILE, mobile_replace), (TIKTOK_DESKTOP, desktop_replace)]:
for match in reg.finditer(msg_txt):
msg_txt = await fun(msg_txt, match)
replace = True

if replace:
await msg.delete()
await msg.channel.send(embed=discord.Embed().set_author(
Expand Down

0 comments on commit 9cc215b

Please sign in to comment.