From 77e51c8229ce74969f26c953f21d67247b478204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Sk=C3=BDpala?= Date: Tue, 7 Nov 2023 22:30:45 +0100 Subject: [PATCH] News: Autocomplete --- hrochobot/cogs/news.py | 19 ++++++++++++++++--- hrochobot/utils/ksp_utils.py | 6 ++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/hrochobot/cogs/news.py b/hrochobot/cogs/news.py index 71e3f9b..e635576 100644 --- a/hrochobot/cogs/news.py +++ b/hrochobot/cogs/news.py @@ -6,11 +6,24 @@ from markdownify import markdownify import re from bs4 import BeautifulSoup -from hrochobot.utils.ksp_utils import ksp_feed, KSP_URL +from hrochobot.utils.ksp_utils import ksp_feed, strip_id, KSP_URL import hrochobot.utils.data as data NEWS_JSON = "news" +async def get_news_ids(): + feed = await ksp_feed() + return list(map(lambda e: e.id, feed.entries)) + +async def autocomplete_news_ids(ctx): + value = ctx.value.lower() + options = [] + for id_ in map(strip_id, await get_news_ids()): + lid = id_.lower() + if lid.startswith(value) or lid.split("_", 1)[1].startswith(value): + options.append(id_) + return options + def guess_color(title): """ Automagically guess color of given post. @@ -57,7 +70,7 @@ async def post_news(bot, guild, entry_id): channel = get(guild.channels, id=news_json["news_channel"]) feed = await ksp_feed() - entries_with_id = list(filter(lambda e: e.id == f"{KSP_URL}/{entry_id}", feed.entries)) + entries_with_id = list(filter(lambda e: strip_id(e.id) == entry_id, feed.entries)) if len(entries_with_id) == 0: return f"Entry with id ``{entry_id}`` not found." @@ -92,7 +105,7 @@ class News(commands.Cog): return await ctx.respond(f"News channel set to {channel.mention}.", ephemeral=True) @news.command(description="Synchronize news feed.") - @discord.option("id", str, description="Id of entry to send.") + @discord.option("id", str, description="Id of entry to send.", autocomplete=autocomplete_news_ids) async def post_news(self, ctx, id: int): err = await post_news(self.bot, ctx.guild, id) if err: diff --git a/hrochobot/utils/ksp_utils.py b/hrochobot/utils/ksp_utils.py index 08c73df..b4a5710 100644 --- a/hrochobot/utils/ksp_utils.py +++ b/hrochobot/utils/ksp_utils.py @@ -37,3 +37,9 @@ def active_deadlines() -> List[Tuple[str, datetime]]: async def ksp_feed() -> feedparser.util.FeedParserDict: return feedparser.parse(f"{KSP_URL}/ksp.feed") + +def strip_id(id_): + text = f"{KSP_URL}/" + if id_.startswith(text): + id_ = id_[len(text):] + return id_