aboutsummaryrefslogtreecommitdiff
path: root/wplink/wplink.py
diff options
context:
space:
mode:
authorArjun Satarkar <me@arjunsatarkar.net>2024-07-17 08:23:28 +0000
committerArjun Satarkar <me@arjunsatarkar.net>2024-07-17 08:23:28 +0000
commitb00c2e890aa741ed9260fb36bb87e15d8075c2d1 (patch)
treec5ce0613f195fc0b858f04e0b26147942b3ec4ff /wplink/wplink.py
parentdb8d2349175db503f2ce889a9928b22a3067b30c (diff)
downloadaps-cogs-b00c2e890aa741ed9260fb36bb87e15d8075c2d1.tar
aps-cogs-b00c2e890aa741ed9260fb36bb87e15d8075c2d1.tar.gz
aps-cogs-b00c2e890aa741ed9260fb36bb87e15d8075c2d1.zip
Add wplink cog
Diffstat (limited to 'wplink/wplink.py')
-rw-r--r--wplink/wplink.py35
1 files changed, 35 insertions, 0 deletions
diff --git a/wplink/wplink.py b/wplink/wplink.py
new file mode 100644
index 0000000..e9781fc
--- /dev/null
+++ b/wplink/wplink.py
@@ -0,0 +1,35 @@
+import aiohttp
+import discord
+from redbot.core import commands
+import re
+import urllib.parse
+
+
+class WPLink(commands.Cog):
+ def __init__(self, bot):
+ self.bot = bot
+
+ @commands.Cog.listener()
+ async def on_message(self, message: discord.Message):
+ wikilink_pattern = r"\[\[(.+)\]\]"
+ match = re.search(wikilink_pattern, message.content)
+ if match is not None:
+ title = match.group(1)
+ page_url = await self.look_up_page(title)
+ if page_url is not None:
+ await message.reply(
+ page_url, allowed_mentions=discord.AllowedMentions.none()
+ )
+
+ async def look_up_page(self, title: str) -> str | None:
+ query_url = f"https://en.wikipedia.org/wiki/Special:Search?search={urllib.parse.quote(title)}&go=Go"
+ async with aiohttp.ClientSession() as session:
+ async with session.get(query_url) as response:
+ result_url = str(response.url)
+ return (
+ result_url
+ if not result_url.startswith(
+ "https://en.wikipedia.org/wiki/Special:Search?"
+ )
+ else None
+ )