Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .coderabbit.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,9 @@ reviews:
major version once 1.0 is out.
- path: "src/librebots/kit/ext/**"
instructions: >-
Lightbulb extensions are thin loaders around the functions next to them. Logic belongs in those functions,
so that it can be tested without Discord; flag logic that only exists inside a command or listener.
Extensions keep their logic in the command, listener or handler itself; a separate function only when
several of them share it. Their tests drive them through lightbulb's and risa's real paths with mocked
Discord objects; flag tests that reach Discord or the network.
- path: "tests/**"
instructions: >-
Tests run against an in-process fake of the hub, never against Discord or the network. Flag sleeps used for
Expand Down
2 changes: 2 additions & 0 deletions src/librebots/kit/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

from librebots.kit.bot import BotInfo
from librebots.kit.config import Config, ConfigError
from librebots.kit.guilds import GuildReporter, SyncResult
from librebots.kit.hub import Hub, HubError, HubRequestError, HubUnavailableError, call_hub, connect_hub
Expand All @@ -8,6 +9,7 @@

__all__ = [
"LOCALES",
"BotInfo",
"Catalog",
"CatalogError",
"Config",
Expand Down
18 changes: 18 additions & 0 deletions src/librebots/kit/bot.py
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
75 changes: 75 additions & 0 deletions src/librebots/kit/ext/info.py
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))
Comment thread
rayakame marked this conversation as resolved.
Resolved
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)
10 changes: 10 additions & 0 deletions src/librebots/kit/locales/de/kit.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,13 @@ kit-error-forbidden = Mir fehlt dafür eine Berechtigung. Bitte einen Server-Adm
.title = Berechtigung fehlt
kit-error-unknown = Versuch es später noch einmal. Wenn es wieder passiert, gib dem Betreiber des Bots diese Referenz: `{ $reference }`
.title = Etwas ist schiefgelaufen

kit-cmd-info =
.name = info
.description = Zeigt, was dieser Bot ist, wer ihn betreibt und wo sein Code liegt
kit-info-meta = Version { $version } · { $servers } Server · Betrieben von { $operator } ({ $contact })
kit-info-meta-without-servers = Version { $version } · Betrieben von { $operator } ({ $contact })
kit-info-privacy = Mit /privacy siehst, exportierst oder löschst du, was dieser Bot über dich speichert.
kit-info-source = Quellcode
kit-info-support = Support
kit-info-privacy-policy = Datenschutzerklärung
13 changes: 13 additions & 0 deletions src/librebots/kit/locales/en-US/kit.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,16 @@ kit-error-forbidden = I'm missing a permission for this. Ask a server admin to c
.title = Missing permission
kit-error-unknown = Try again later. If it keeps happening, give the bot's operator this reference: `{ $reference }`
.title = Something went wrong

kit-cmd-info =
.name = info
.description = Shows what this bot is, who runs it and where its code is
kit-info-meta = Version { $version } · { $servers ->
[one] { $servers } server
*[other] { $servers } servers
} · Run by { $operator } ({ $contact })
kit-info-meta-without-servers = Version { $version } · Run by { $operator } ({ $contact })
kit-info-privacy = Use /privacy to see, export or delete what this bot stores about you.
kit-info-source = Source code
kit-info-support = Support
kit-info-privacy-policy = Privacy policy
194 changes: 194 additions & 0 deletions tests/test_ext_info.py
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"]