Skip to content

Commit

Permalink
Merge pull request #3 from ZelGray/discord-meow-bot-1
Browse files Browse the repository at this point in the history
#1: Correct a link to Reddit if a post contai…
  • Loading branch information
soksanichenko authored Feb 7, 2024
2 parents 5a77a2b + c5e4d3c commit f76f3f0
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions sources/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
"""Main module of the bot"""

import os
from urllib.parse import urlparse, ParseResult

import discord

intents = discord.Intents.default()
# access to a message content
intents.message_content = True
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

Expand All @@ -21,6 +25,65 @@ async def ping(interaction):
await interaction.response.send_message('pong')


def replace_domain(url: ParseResult):
"""
Replace an original domain by a fixer
:param url: an original parsed URL
:return: a fixed parsed URL
"""
domains = {
'reddit.com': 'rxddit.com',
'tiktok.com': 'vxtiktok.com',
'vm.tiktok.com': 'vm.vxtiktok.com',
'twitter.com': 'vxtwitter.com',
}
for key, value in domains.items():
if url.netloc == key:
return ParseResult(
url.scheme,
netloc=value,
path=url.path,
query=url.query,
params=url.params,
fragment=url.fragment,
)
return url


@client.event
async def on_message(message: discord.Message):
"""
Process a new message
:param message: a new message posted in Discord
:return: None
"""

if message.author == client.user:
return
if not message.embeds:
return
processed_urls = (
replace_domain(urlparse(embed.url)) for embed in message.embeds
)
final_urls = {
embed.url: processed_url.geturl() for processed_url, embed in zip(
processed_urls,
message.embeds
)
}
content = message.content
for origin_url, final_url in final_urls.items():
content = content.replace(origin_url, final_url)
# An embed URL uses original domain even if you replaced it by a fixer.
# So you need to compare replaced content and original one
# and do nothing if they are identical.
if message.content == content:
return
content += f'\nOriginal message posted by {message.author.mention}'
await message.channel.send(content=content)
await message.delete()


@client.event
async def on_ready():
"""
Expand Down

0 comments on commit f76f3f0

Please sign in to comment.