From b00c2e890aa741ed9260fb36bb87e15d8075c2d1 Mon Sep 17 00:00:00 2001 From: Arjun Satarkar Date: Wed, 17 Jul 2024 13:53:28 +0530 Subject: Add wplink cog --- wplink/__init__.py | 5 +++++ wplink/info.json | 4 ++++ wplink/wplink.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 wplink/__init__.py create mode 100644 wplink/info.json create mode 100644 wplink/wplink.py (limited to 'wplink') diff --git a/wplink/__init__.py b/wplink/__init__.py new file mode 100644 index 0000000..f82c406 --- /dev/null +++ b/wplink/__init__.py @@ -0,0 +1,5 @@ +from .wplink import WPLink + + +async def setup(bot): + await bot.add_cog(WPLink(bot)) diff --git a/wplink/info.json b/wplink/info.json new file mode 100644 index 0000000..bd066ba --- /dev/null +++ b/wplink/info.json @@ -0,0 +1,4 @@ +{ + "author": ["Arjun Satarkar"], + "requirements": ["aiohttp"] +} 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 + ) -- cgit v1.2.3-57-g22cb