librebots-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ from __future__ import annotations
2
+
3
+ from librebots.kit.bot import BotInfo
4
+ from librebots.kit.config import Config, ConfigError
5
+ from librebots.kit.guilds import GuildReporter, SyncResult
6
+ from librebots.kit.hub import Hub, HubError, HubRequestError, HubUnavailableError, call_hub, connect_hub
7
+ from librebots.kit.i18n import LOCALES, Catalog, CatalogError
8
+ from librebots.kit.privacy import Privacy
9
+
10
+ __all__ = [
11
+ "LOCALES",
12
+ "BotInfo",
13
+ "Catalog",
14
+ "CatalogError",
15
+ "Config",
16
+ "ConfigError",
17
+ "GuildReporter",
18
+ "Hub",
19
+ "HubError",
20
+ "HubRequestError",
21
+ "HubUnavailableError",
22
+ "Privacy",
23
+ "SyncResult",
24
+ "call_hub",
25
+ "connect_hub",
26
+ ]
librebots/kit/bot.py ADDED
@@ -0,0 +1,18 @@
1
+ from __future__ import annotations
2
+
3
+ import msgspec
4
+
5
+ __all__ = ["BotInfo"]
6
+
7
+
8
+ class BotInfo(msgspec.Struct, frozen=True, kw_only=True):
9
+ """What `/info` shows about the bot. Its one-line description is the text `bot-description` in the bot's files.
10
+
11
+ `hub_name` is the bot's name in the hub's `HUB_BOT_TOKENS`, such as `"starboard"`.
12
+ """
13
+
14
+ name: str
15
+ hub_name: str
16
+ version: str
17
+ accent_color: int
18
+ source_url: str
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import Mapping
5
+ from pathlib import Path
6
+ from typing import Annotated, Literal, Self
7
+ from urllib.parse import urlsplit
8
+
9
+ import msgspec
10
+
11
+ __all__ = ["Config", "ConfigError", "LogLevel"]
12
+
13
+ LogLevel = Literal["TRACE_HIKARI", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
14
+
15
+ _UINT32_MAX = 2**32 - 1
16
+ _ShardId = Annotated[int, msgspec.Meta(ge=0, le=_UINT32_MAX)]
17
+ _ShardCount = Annotated[int, msgspec.Meta(ge=1, le=_UINT32_MAX)]
18
+
19
+ _SECRETS = frozenset({"discord_token", "hub_token"})
20
+
21
+
22
+ class ConfigError(Exception):
23
+ """The environment does not describe a valid configuration."""
24
+
25
+
26
+ class Config(msgspec.Struct, frozen=True, kw_only=True, rename="upper"):
27
+ """The settings of one bot process, each field read from the environment variable of the same name in upper case."""
28
+
29
+ discord_token: str
30
+ hub_address: str
31
+ hub_token: str
32
+ hub_tls: bool
33
+ hub_ca_file: str | None = None
34
+ shard_ids: tuple[_ShardId, ...] | None = None
35
+ shard_count: _ShardCount | None = None
36
+ operator_name: str
37
+ operator_contact: str
38
+ privacy_policy_url: str
39
+ support_url: str | None = None
40
+ rest_url: str | None = None
41
+ log_level: LogLevel = "INFO"
42
+
43
+ @classmethod
44
+ def from_env(cls, environ: Mapping[str, str] | None = None) -> Self:
45
+ """Read the configuration from `environ`, by default `os.environ`.
46
+
47
+ `DISCORD_TOKEN` and `HUB_TOKEN` can instead be read from the file a `_FILE` variable names. Raises
48
+ `ConfigError` on the first problem.
49
+ """
50
+ values = _collect(os.environ if environ is None else environ)
51
+ try:
52
+ return msgspec.convert(values, cls, strict=False)
53
+ except msgspec.ValidationError as exc:
54
+ raise ConfigError(str(exc)) from exc
55
+
56
+ def __post_init__(self) -> None:
57
+ if (self.shard_ids is None) != (self.shard_count is None):
58
+ raise ValueError("Set SHARD_IDS and SHARD_COUNT together, or neither")
59
+ if self.shard_ids is not None and self.shard_count is not None:
60
+ if len(set(self.shard_ids)) != len(self.shard_ids):
61
+ raise ValueError("SHARD_IDS names a shard twice")
62
+ if max(self.shard_ids) >= self.shard_count:
63
+ raise ValueError("Every id in SHARD_IDS must be below SHARD_COUNT")
64
+ if self.hub_ca_file is not None and not self.hub_tls:
65
+ raise ValueError("HUB_CA_FILE needs HUB_TLS=true")
66
+ for name, url in (
67
+ ("PRIVACY_POLICY_URL", self.privacy_policy_url),
68
+ ("SUPPORT_URL", self.support_url),
69
+ ("REST_URL", self.rest_url),
70
+ ):
71
+ if url is not None and not _is_http_url(url):
72
+ raise ValueError(f"{name} must be an http or https URL with a host")
73
+
74
+ def __repr__(self) -> str:
75
+ fields = ", ".join(f"{name}={value!r}" for name, value in self.__rich_repr__())
76
+ return f"{type(self).__name__}({fields})"
77
+
78
+ def __rich_repr__(self) -> list[tuple[str, object]]:
79
+ return [(name, "***" if name in _SECRETS else getattr(self, name)) for name in self.__struct_fields__]
80
+
81
+
82
+ def _collect(environ: Mapping[str, str]) -> dict[str, str | list[str]]:
83
+ values: dict[str, str | list[str]] = {}
84
+ for field in msgspec.structs.fields(Config):
85
+ name = field.encode_name
86
+ value = _read_secret(environ, name) if field.name in _SECRETS else _clean(environ.get(name))
87
+ if value is None:
88
+ continue
89
+ if name == "SHARD_IDS":
90
+ values[name] = [part.strip() for part in value.split(",")]
91
+ elif name == "LOG_LEVEL":
92
+ values[name] = value.upper()
93
+ else:
94
+ values[name] = value
95
+ return values
96
+
97
+
98
+ def _read_secret(environ: Mapping[str, str], name: str) -> str | None:
99
+ value = _clean(environ.get(name))
100
+ path = _clean(environ.get(f"{name}_FILE"))
101
+ if path is None:
102
+ return value
103
+ if value is not None:
104
+ raise ConfigError(f"Set {name} or {name}_FILE, not both")
105
+ try:
106
+ content = Path(path).read_text(encoding="utf-8")
107
+ except (OSError, UnicodeDecodeError) as exc:
108
+ raise ConfigError(f"Cannot read {name}_FILE: {exc}") from exc
109
+ secret = _clean(content)
110
+ if secret is None:
111
+ raise ConfigError(f"{name}_FILE names an empty file")
112
+ return secret
113
+
114
+
115
+ def _is_http_url(url: str) -> bool:
116
+ if any(char.isspace() for char in url):
117
+ return False
118
+ try:
119
+ parts = urlsplit(url)
120
+ return parts.scheme in {"http", "https"} and bool(parts.hostname) and (parts.port is None or parts.port > 0)
121
+ except ValueError:
122
+ return False
123
+
124
+
125
+ def _clean(value: str | None) -> str | None:
126
+ if value is None:
127
+ return None
128
+ return value.strip() or None
@@ -0,0 +1 @@
1
+ from __future__ import annotations
@@ -0,0 +1,100 @@
1
+ """Answers a failed command or click that no handler of the bot took, and logs it.
2
+
3
+ Needs a `Catalog` with kit's texts (`kit.LOCALES`) and a risa client in lightbulb's dependency injection. Its handlers
4
+ run last, so a bot's own error handlers at the default priority come first.
5
+
6
+ The answer is visible to the caller only, except after a public defer: it then replaces the "thinking" message, and
7
+ Discord keeps that message's visibility.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import re
14
+ import secrets
15
+ import traceback
16
+ from collections.abc import Sequence
17
+
18
+ import hikari
19
+ import lightbulb
20
+ import risa
21
+ from risa import ui
22
+
23
+ from librebots.kit.hub import HubUnavailableError
24
+ from librebots.kit.i18n import Catalog
25
+
26
+ __all__ = ["loader"]
27
+
28
+ _LOGGER = logging.getLogger(__name__)
29
+ _PRIORITY = -100
30
+ _RED = 0xE24B4A
31
+ # hikari puts the request URL into its HTTP errors, and these URLs carry the interaction token.
32
+ _TOKEN_IN_URL = re.compile(r"(/(?:interactions|webhooks)/\d+/)[^/\s?#']+")
33
+
34
+ loader = lightbulb.Loader()
35
+
36
+
37
+ @loader.error_handler(priority=_PRIORITY)
38
+ async def _answer_failed_command(
39
+ exc: lightbulb.exceptions.ExecutionPipelineFailedException, catalog: Catalog = lightbulb.di.INJECTED
40
+ ) -> bool:
41
+ ctx = exc.context
42
+ layout = _build_error_reply(
43
+ catalog, ctx.interaction.locale, exc.causes, f"Command /{ctx.command_data.qualified_name}"
44
+ )
45
+ try:
46
+ await ctx.respond(**ui.render(layout), ephemeral=True)
47
+ except hikari.HTTPError as error:
48
+ _LOGGER.warning("Could not tell the caller that a command failed: %s", _redact_tokens(str(error)))
49
+ return True
50
+
51
+
52
+ async def _answer_failed_click(
53
+ pipeline: risa.ExecutionPipeline, ctx: risa.ComponentContext, catalog: Catalog = risa.INJECTED
54
+ ) -> bool:
55
+ layout = _build_error_reply(
56
+ catalog, ctx.interaction.locale, [failure.error for failure in pipeline.failures], "A click"
57
+ )
58
+ try:
59
+ await ctx.respond(**ui.render(layout), ephemeral=True)
60
+ except hikari.HTTPError as error:
61
+ _LOGGER.warning("Could not tell the clicker that a click failed: %s", _redact_tokens(str(error)))
62
+ return True
63
+
64
+
65
+ # Resolving risa's client while the extension loads would freeze the registry before the bot is done with it.
66
+ @loader.listener(hikari.StartedEvent)
67
+ async def _register_click_fallback(_: hikari.StartedEvent, views: risa.Client = lightbulb.di.INJECTED) -> None:
68
+ views.error_handler(_answer_failed_click, priority=_PRIORITY)
69
+
70
+
71
+ def _build_error_reply(
72
+ catalog: Catalog, locale: hikari.Locale | str, errors: Sequence[Exception], failed: str
73
+ ) -> ui.Container:
74
+ key, reference = _log_and_pick_text(errors, failed)
75
+ text = catalog.text(locale, key) if reference is None else catalog.text(locale, key, reference=reference)
76
+ return ui.Container(
77
+ ui.TextDisplay(f"### {catalog.text(locale, f'{key}.title')}"),
78
+ ui.TextDisplay(text),
79
+ accent_color=_RED,
80
+ )
81
+
82
+
83
+ def _log_and_pick_text(errors: Sequence[Exception], failed: str) -> tuple[str, str | None]:
84
+ for error in errors:
85
+ if isinstance(error, HubUnavailableError):
86
+ _LOGGER.warning("%s failed because the hub is unavailable: %s", failed, _redact_tokens(str(error)))
87
+ return "kit-error-hub", None
88
+ for error in errors:
89
+ if isinstance(error, hikari.ForbiddenError):
90
+ _LOGGER.info("%s failed for a missing permission: %s", failed, _redact_tokens(str(error)))
91
+ return "kit-error-forbidden", None
92
+ reference = secrets.token_hex(3)
93
+ for error in errors:
94
+ described = _redact_tokens("".join(traceback.format_exception(error)).rstrip())
95
+ _LOGGER.error("%s failed, reference %s\n%s", failed, reference, described)
96
+ return "kit-error-unknown", reference
97
+
98
+
99
+ def _redact_tokens(text: str) -> str:
100
+ return _TOKEN_IN_URL.sub(r"\1***", text)
@@ -0,0 +1,76 @@
1
+ """Reports joins and leaves to the hub, and syncs a shard's guilds when it opens a session and daily at 04:00 UTC.
2
+
3
+ Needs a `GuildReporter` in lightbulb's dependency injection.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import logging
9
+ from collections.abc import Collection
10
+
11
+ import hikari
12
+ import lightbulb
13
+
14
+ from librebots.kit.guilds import GuildReporter
15
+ from librebots.kit.hub import HubError
16
+
17
+ __all__ = ["loader", "sync_own_shards"]
18
+
19
+ _LOGGER = logging.getLogger(__name__)
20
+
21
+ loader = lightbulb.Loader()
22
+
23
+
24
+ @loader.listener(hikari.GuildJoinEvent)
25
+ async def _report_join(event: hikari.GuildJoinEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None:
26
+ guild = event.guild
27
+ try:
28
+ await reporter.joined(guild.id, preferred_locale=str(guild.preferred_locale), member_count=guild.member_count)
29
+ except HubError as exc:
30
+ _LOGGER.warning("Could not report joining guild %s, the next sync will: %s", guild.id, exc)
31
+
32
+
33
+ @loader.listener(hikari.GuildLeaveEvent)
34
+ async def _report_leave(event: hikari.GuildLeaveEvent, reporter: GuildReporter = lightbulb.di.INJECTED) -> None:
35
+ try:
36
+ await reporter.left(event.guild_id)
37
+ except HubError as exc:
38
+ _LOGGER.warning("Could not report leaving guild %s, the next sync will: %s", event.guild_id, exc)
39
+
40
+
41
+ @loader.listener(hikari.ShardReadyEvent)
42
+ async def _sync_shard(
43
+ event: hikari.ShardReadyEvent,
44
+ reporter: GuildReporter = lightbulb.di.INJECTED,
45
+ rest: hikari.api.RESTClient = lightbulb.di.INJECTED,
46
+ ) -> None:
47
+ await _sync(reporter, rest, [event.shard.id], event.shard.shard_count)
48
+
49
+
50
+ @lightbulb.di.with_di
51
+ async def sync_own_shards(
52
+ bot: hikari.GatewayBot = lightbulb.di.INJECTED,
53
+ reporter: GuildReporter = lightbulb.di.INJECTED,
54
+ rest: hikari.api.RESTClient = lightbulb.di.INJECTED,
55
+ ) -> None:
56
+ """Sync the guilds of every shard this process runs, as the extension does daily at 04:00 UTC.
57
+
58
+ Takes its arguments from lightbulb's dependency injection, so call it from a command, listener or task.
59
+ """
60
+ await _sync(reporter, rest, bot.shards.keys(), bot.shard_count)
61
+
62
+
63
+ # With lightbulb's default of one failure, a single error would stop the daily sync until the next restart.
64
+ loader.task(lightbulb.crontrigger("0 4 * * *"), max_failures=-1)(sync_own_shards)
65
+
66
+
67
+ async def _sync(
68
+ reporter: GuildReporter, rest: hikari.api.RESTClient, shard_ids: Collection[int], shard_count: int
69
+ ) -> None:
70
+ shards = sorted(shard_ids)
71
+ try:
72
+ result = await reporter.sync(rest, shards, shard_count)
73
+ except HubError as exc:
74
+ _LOGGER.warning("Could not sync the guilds of shards %s: %s", shards, exc)
75
+ return
76
+ _LOGGER.info("Synced the guilds of shards %s: %d joined, %d left", shards, result.joined, result.left)
@@ -0,0 +1,75 @@
1
+ """Adds `/info`: the bot's name, description and version, how many servers it serves, who runs it, and links.
2
+
3
+ Needs `BotInfo`, `Config`, `Hub` and a `Catalog` with kit's texts and the bot's `bot-description` in lightbulb's
4
+ dependency injection.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+
11
+ import hikari
12
+ import lightbulb
13
+ from librebots.hub.v1.stats_pb2 import GetStatsRequest
14
+ from risa import ui
15
+
16
+ from librebots.kit.bot import BotInfo
17
+ from librebots.kit.config import Config
18
+ from librebots.kit.hub import Hub, HubError, call_hub
19
+ from librebots.kit.i18n import Catalog
20
+
21
+ __all__ = ["loader"]
22
+
23
+ _LOGGER = logging.getLogger(__name__)
24
+ # Discord fails a command that gets no answer within three seconds.
25
+ _STATS_TIMEOUT = 2
26
+
27
+ loader = lightbulb.Loader()
28
+
29
+
30
+ @loader.command
31
+ class _Info(
32
+ lightbulb.SlashCommand,
33
+ name="kit-cmd-info.name",
34
+ description="kit-cmd-info.description",
35
+ localize=True,
36
+ contexts=[hikari.ApplicationContextType.GUILD, hikari.ApplicationContextType.BOT_DM],
37
+ ):
38
+ @lightbulb.invoke
39
+ async def show_info(
40
+ self,
41
+ ctx: lightbulb.Context,
42
+ bot: BotInfo = lightbulb.di.INJECTED,
43
+ config: Config = lightbulb.di.INJECTED,
44
+ catalog: Catalog = lightbulb.di.INJECTED,
45
+ hub: Hub = lightbulb.di.INJECTED,
46
+ ) -> None:
47
+ servers: int | None = None
48
+ try:
49
+ stats = await call_hub("GetStats", hub.stats.GetStats(GetStatsRequest(), timeout=_STATS_TIMEOUT))
50
+ except HubError as exc:
51
+ _LOGGER.warning("Showing /info without a server count: %s", exc)
52
+ else:
53
+ servers = next((entry.figures.guild_count for entry in stats.bots if entry.bot == bot.hub_name), None)
54
+ if servers is None:
55
+ _LOGGER.warning("Showing /info without a server count: the hub has no bot named %r", bot.hub_name)
56
+
57
+ locale = ctx.interaction.locale
58
+ details = {"version": bot.version, "operator": config.operator_name, "contact": config.operator_contact}
59
+ if servers is None:
60
+ meta = catalog.text(locale, "kit-info-meta-without-servers", **details)
61
+ else:
62
+ meta = catalog.text(locale, "kit-info-meta", servers=servers, **details)
63
+ links = [ui.LinkButton(bot.source_url, label=catalog.text(locale, "kit-info-source"))]
64
+ if config.support_url is not None:
65
+ links.append(ui.LinkButton(config.support_url, label=catalog.text(locale, "kit-info-support")))
66
+ links.append(ui.LinkButton(config.privacy_policy_url, label=catalog.text(locale, "kit-info-privacy-policy")))
67
+
68
+ layout = ui.Container(
69
+ ui.TextDisplay(f"### {bot.name}"),
70
+ ui.TextDisplay(catalog.text(locale, "bot-description")),
71
+ ui.TextDisplay(f"-# {meta}\n-# {catalog.text(locale, 'kit-info-privacy')}"),
72
+ ui.Row(*links),
73
+ accent_color=bot.accent_color,
74
+ )
75
+ await ctx.respond(**ui.render(layout), ephemeral=True)