Repository navigation
Show what the bot is and who runs it with /info #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import msgspec | ||
|
|
||
| __all__ = ["BotInfo"] | ||
|
|
||
|
|
||
| class BotInfo(msgspec.Struct, frozen=True, kw_only=True): | ||
| """What `/info` shows about the bot. Its one-line description is the text `bot-description` in the bot's files. | ||
|
|
||
| `hub_name` is the bot's name in the hub's `HUB_BOT_TOKENS`, such as `"starboard"`. | ||
| """ | ||
|
|
||
| name: str | ||
| hub_name: str | ||
| version: str | ||
| accent_color: int | ||
| source_url: str |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """Adds `/info`: the bot's name, description and version, how many servers it serves, who runs it, and links. | ||
|
|
||
| Needs `BotInfo`, `Config`, `Hub` and a `Catalog` with kit's texts and the bot's `bot-description` in lightbulb's | ||
| dependency injection. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
|
|
||
| import hikari | ||
| import lightbulb | ||
| from librebots.hub.v1.stats_pb2 import GetStatsRequest | ||
| from risa import ui | ||
|
|
||
| from librebots.kit.bot import BotInfo | ||
| from librebots.kit.config import Config | ||
| from librebots.kit.hub import Hub, HubError, call_hub | ||
| from librebots.kit.i18n import Catalog | ||
|
|
||
| __all__ = ["loader"] | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
| # Discord fails a command that gets no answer within three seconds. | ||
| _STATS_TIMEOUT = 2 | ||
|
|
||
| loader = lightbulb.Loader() | ||
|
|
||
|
|
||
| @loader.command | ||
| class _Info( | ||
| lightbulb.SlashCommand, | ||
| name="kit-cmd-info.name", | ||
| description="kit-cmd-info.description", | ||
| localize=True, | ||
| contexts=[hikari.ApplicationContextType.GUILD, hikari.ApplicationContextType.BOT_DM], | ||
| ): | ||
| @lightbulb.invoke | ||
| async def show_info( | ||
| self, | ||
| ctx: lightbulb.Context, | ||
| bot: BotInfo = lightbulb.di.INJECTED, | ||
| config: Config = lightbulb.di.INJECTED, | ||
| catalog: Catalog = lightbulb.di.INJECTED, | ||
| hub: Hub = lightbulb.di.INJECTED, | ||
| ) -> None: | ||
| servers: int | None = None | ||
| try: | ||
| stats = await call_hub("GetStats", hub.stats.GetStats(GetStatsRequest(), timeout=_STATS_TIMEOUT)) | ||
| except HubError as exc: | ||
| _LOGGER.warning("Showing /info without a server count: %s", exc) | ||
| else: | ||
| servers = next((entry.figures.guild_count for entry in stats.bots if entry.bot == bot.hub_name), None) | ||
| if servers is None: | ||
| _LOGGER.warning("Showing /info without a server count: the hub has no bot named %r", bot.hub_name) | ||
|
|
||
| locale = ctx.interaction.locale | ||
| details = {"version": bot.version, "operator": config.operator_name, "contact": config.operator_contact} | ||
| if servers is None: | ||
| meta = catalog.text(locale, "kit-info-meta-without-servers", **details) | ||
| else: | ||
| meta = catalog.text(locale, "kit-info-meta", servers=servers, **details) | ||
| links = [ui.LinkButton(bot.source_url, label=catalog.text(locale, "kit-info-source"))] | ||
| if config.support_url is not None: | ||
| links.append(ui.LinkButton(config.support_url, label=catalog.text(locale, "kit-info-support"))) | ||
| links.append(ui.LinkButton(config.privacy_policy_url, label=catalog.text(locale, "kit-info-privacy-policy"))) | ||
|
|
||
| layout = ui.Container( | ||
| ui.TextDisplay(f"### {bot.name}"), | ||
| ui.TextDisplay(catalog.text(locale, "bot-description")), | ||
| ui.TextDisplay(f"-# {meta}\n-# {catalog.text(locale, 'kit-info-privacy')}"), | ||
| ui.Row(*links), | ||
| accent_color=bot.accent_color, | ||
| ) | ||
| await ctx.respond(**ui.render(layout), ephemeral=True) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from collections.abc import AsyncGenerator, Awaitable | ||
| from pathlib import Path | ||
| from types import TracebackType | ||
| from typing import Self | ||
| from unittest.mock import AsyncMock, create_autospec | ||
|
|
||
| import grpc | ||
| import grpc.aio | ||
| import hikari | ||
| import lightbulb | ||
| import pytest | ||
| from hub_server import serving | ||
| from librebots.hub.v1 import stats_pb2, stats_pb2_grpc | ||
|
|
||
| from librebots.kit import LOCALES, BotInfo, Catalog, Config, Hub | ||
| from librebots.kit.ext import info | ||
|
|
||
| EXTENSION = "librebots.kit.ext.info" | ||
| STARBOARD = BotInfo( | ||
| name="LibreStarboard", | ||
| hub_name="starboard", | ||
| version="1.2.0", | ||
| accent_color=0xEF9F27, | ||
| source_url="https://github.com/libre-bots/starboard", | ||
| ) | ||
| SOURCE = ("Source code", "https://github.com/libre-bots/starboard") | ||
| SUPPORT = ("Support", "https://example.org/support") | ||
| POLICY = ("Privacy policy", "https://example.org/privacy") | ||
| PRIVACY = "-# Use /privacy to see, export or delete what this bot stores about you." | ||
|
|
||
|
|
||
| class FakeStats(stats_pb2_grpc.StatsServiceServicer): | ||
| def __init__(self) -> None: | ||
| self.guilds = {"starboard": 1234, "tickets": 7} | ||
| self.failing = False | ||
|
|
||
| async def GetStats( | ||
| self, | ||
| request: stats_pb2.GetStatsRequest, | ||
| context: grpc.aio.ServicerContext[stats_pb2.GetStatsRequest, Awaitable[stats_pb2.GetStatsResponse]], | ||
| ) -> stats_pb2.GetStatsResponse: | ||
| if self.failing: | ||
| await context.abort(grpc.StatusCode.UNAVAILABLE, "hub is down") | ||
| bots = [ | ||
| stats_pb2.BotFigures(bot=bot, figures=stats_pb2.Figures(guild_count=count)) | ||
| for bot, count in self.guilds.items() | ||
| ] | ||
| return stats_pb2.GetStatsResponse(bots=bots) | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| async def stats() -> AsyncGenerator[tuple[Hub, FakeStats]]: | ||
| fake = FakeStats() | ||
| async with serving(lambda server: stats_pb2_grpc.add_StatsServiceServicer_to_server(fake, server)) as hub: | ||
| yield hub, fake | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def catalog(tmp_path: Path) -> Catalog: | ||
| for locale, description in [ | ||
| ("en-US", "Pins the best messages of a server."), | ||
| ("de", "Heftet die besten Nachrichten eines Servers an."), | ||
| ]: | ||
| folder = tmp_path / locale | ||
| folder.mkdir() | ||
| (folder / "bot.ftl").write_text(f"bot-description = {description}\n", encoding="utf-8") | ||
| return Catalog.load(LOCALES, tmp_path) | ||
|
|
||
|
|
||
| def config(**values: str) -> Config: | ||
| return Config.from_env( | ||
| { | ||
| "DISCORD_TOKEN": "discord-token", | ||
| "HUB_ADDRESS": "127.0.0.1:1", | ||
| "HUB_TOKEN": "hub-token", | ||
| "HUB_TLS": "false", | ||
| "OPERATOR_NAME": "Example Operator", | ||
| "OPERATOR_CONTACT": "ops@example.org", | ||
| "PRIVACY_POLICY_URL": "https://example.org/privacy", | ||
| **values, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| class InfoBot: | ||
| def __init__(self, hub: Hub, catalog: Catalog, settings: Config) -> None: | ||
| app: hikari.GatewayBot = create_autospec(hikari.GatewayBot, instance=True) | ||
| self.client = lightbulb.client_from_app( | ||
| app, localization_provider=catalog.localization_provider, sync_commands=False | ||
| ) | ||
| registry = self.client.di.registry_for(lightbulb.di.Contexts.DEFAULT) | ||
| registry.register_value(Config, settings) | ||
| registry.register_value(Catalog, catalog) | ||
| registry.register_value(Hub, hub) | ||
| registry.register_value(BotInfo, STARBOARD) | ||
|
|
||
| async def __aenter__(self) -> Self: | ||
| await self.client.load_extensions(EXTENSION) | ||
| await self.client.start() | ||
| return self | ||
|
|
||
| async def __aexit__( | ||
| self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None | ||
| ) -> None: | ||
| await self.client.stop() | ||
| await self.client.unload_extensions(EXTENSION) | ||
|
|
||
| async def info( | ||
| self, locale: hikari.Locale = hikari.Locale.EN_US | ||
| ) -> tuple[hikari.Color, list[str], list[tuple[str, str]]]: | ||
| interaction = create_autospec(hikari.CommandInteraction, instance=True) | ||
| interaction.command_name = "info" | ||
| interaction.command_type = hikari.CommandType.SLASH | ||
| interaction.options = [] | ||
| interaction.registered_guild_id = None | ||
| interaction.locale = locale | ||
| response: AsyncMock = interaction.create_initial_response | ||
| await self.client.handle_interaction_create(interaction) | ||
|
|
||
| call = response.await_args | ||
| assert call is not None | ||
| assert call.kwargs["flags"] == hikari.MessageFlag.EPHEMERAL | ||
| (container,) = call.kwargs["components"] | ||
| payload, _ = container.build() | ||
| children = payload["components"] | ||
| texts = [child["content"] for child in children if child["type"] == hikari.ComponentType.TEXT_DISPLAY] | ||
| rows = [child for child in children if child["type"] == hikari.ComponentType.ACTION_ROW] | ||
| buttons = [(button["label"], button["url"]) for row in rows for button in row["components"]] | ||
| return payload["accent_color"], texts, buttons | ||
|
|
||
|
|
||
| async def test_shows_the_bot_its_operator_and_links(stats: tuple[Hub, FakeStats], catalog: Catalog) -> None: | ||
| async with InfoBot(stats[0], catalog, config(SUPPORT_URL="https://example.org/support")) as bot: | ||
| shown = await bot.info() | ||
|
|
||
| assert shown == ( | ||
| hikari.Color(0xEF9F27), | ||
| [ | ||
| "### LibreStarboard", | ||
| "Pins the best messages of a server.", | ||
| f"-# Version 1.2.0 · 1,234 servers · Run by Example Operator (ops@example.org)\n{PRIVACY}", | ||
| ], | ||
| [SOURCE, SUPPORT, POLICY], | ||
| ) | ||
|
|
||
|
|
||
| async def test_leaves_out_the_support_link_without_a_support_url( | ||
| stats: tuple[Hub, FakeStats], catalog: Catalog | ||
| ) -> None: | ||
| async with InfoBot(stats[0], catalog, config()) as bot: | ||
| _, _, buttons = await bot.info() | ||
|
|
||
| assert buttons == [SOURCE, POLICY] | ||
|
|
||
|
|
||
| async def test_counts_one_server_in_the_singular(stats: tuple[Hub, FakeStats], catalog: Catalog) -> None: | ||
| stats[1].guilds["starboard"] = 1 | ||
|
|
||
| async with InfoBot(stats[0], catalog, config()) as bot: | ||
| _, texts, _ = await bot.info() | ||
|
|
||
| assert texts[2].startswith("-# Version 1.2.0 · 1 server · ") | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("cause", ["hub down", "bot unknown to the hub"]) | ||
| async def test_shows_no_server_count_without_one_from_the_hub( | ||
| stats: tuple[Hub, FakeStats], catalog: Catalog, caplog: pytest.LogCaptureFixture, cause: str | ||
| ) -> None: | ||
| if cause == "hub down": | ||
| stats[1].failing = True | ||
| else: | ||
| del stats[1].guilds["starboard"] | ||
|
|
||
| with caplog.at_level(logging.WARNING, logger=info.__name__): | ||
| async with InfoBot(stats[0], catalog, config()) as bot: | ||
| _, texts, _ = await bot.info() | ||
|
|
||
| assert texts[2] == f"-# Version 1.2.0 · Run by Example Operator (ops@example.org)\n{PRIVACY}" | ||
| assert "server count" in caplog.text | ||
|
|
||
|
|
||
| async def test_answers_in_the_language_of_the_caller(stats: tuple[Hub, FakeStats], catalog: Catalog) -> None: | ||
| async with InfoBot(stats[0], catalog, config()) as bot: | ||
| _, texts, buttons = await bot.info(hikari.Locale.DE) | ||
|
|
||
| assert texts[1:] == [ | ||
| "Heftet die besten Nachrichten eines Servers an.", | ||
| "-# Version 1.2.0 · 1.234 Server · Betrieben von Example Operator (ops@example.org)\n" | ||
| "-# Mit /privacy siehst, exportierst oder löschst du, was dieser Bot über dich speichert.", | ||
| ] | ||
| assert [label for label, _ in buttons] == ["Quellcode", "Datenschutzerklärung"] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.