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.
- librebots/kit/__init__.py +26 -0
- librebots/kit/bot.py +18 -0
- librebots/kit/config.py +128 -0
- librebots/kit/ext/__init__.py +1 -0
- librebots/kit/ext/errors.py +100 -0
- librebots/kit/ext/guilds.py +76 -0
- librebots/kit/ext/info.py +75 -0
- librebots/kit/ext/privacy.py +374 -0
- librebots/kit/guilds.py +101 -0
- librebots/kit/hub.py +176 -0
- librebots/kit/i18n.py +209 -0
- librebots/kit/locales/de/kit.ftl +55 -0
- librebots/kit/locales/en-US/kit.ftl +58 -0
- librebots/kit/privacy.py +126 -0
- librebots/kit/py.typed +0 -0
- librebots_kit-0.1.0.dist-info/METADATA +42 -0
- librebots_kit-0.1.0.dist-info/RECORD +19 -0
- librebots_kit-0.1.0.dist-info/WHEEL +4 -0
- librebots_kit-0.1.0.dist-info/licenses/LICENSE +21 -0
librebots/kit/i18n.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Iterable, Mapping
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Self
|
|
7
|
+
|
|
8
|
+
import hikari
|
|
9
|
+
import msgspec
|
|
10
|
+
from fluent.runtime import FluentBundle
|
|
11
|
+
from fluent.runtime.errors import FluentFormatError
|
|
12
|
+
from fluent.runtime.resolver import Pattern
|
|
13
|
+
from fluent.syntax import FluentParser, ast
|
|
14
|
+
from fluent.syntax.visitor import Visitor
|
|
15
|
+
|
|
16
|
+
__all__ = ["LOCALES", "Catalog", "CatalogError"]
|
|
17
|
+
|
|
18
|
+
_LOGGER = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
LOCALES = Path(__file__).parent / "locales"
|
|
21
|
+
"""kit's own texts. A bot loads them before its own: `Catalog.load(LOCALES, "locales")`."""
|
|
22
|
+
_ENGLISH = "en-US"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CatalogError(Exception):
|
|
26
|
+
"""The translation files are broken or incomplete."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Catalog(msgspec.Struct, frozen=True):
|
|
30
|
+
"""Texts from Fluent files, one folder per Discord locale such as `en-US` or `de`."""
|
|
31
|
+
|
|
32
|
+
_bundles: Mapping[str, FluentBundle]
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def load(cls, *folders: Path | str) -> Self:
|
|
36
|
+
"""Read the `.ftl` files in the language folders inside each of `folders`.
|
|
37
|
+
|
|
38
|
+
English (`en-US`) is required. Raises `CatalogError` for a syntax error, a key defined twice in one language,
|
|
39
|
+
or a text, attribute or variable that a translation has and English does not.
|
|
40
|
+
"""
|
|
41
|
+
resources = _read(map(Path, folders))
|
|
42
|
+
if _ENGLISH not in resources:
|
|
43
|
+
raise CatalogError(f"There are no English ({_ENGLISH}) texts")
|
|
44
|
+
keys = {code: _keys(code, parsed) for code, parsed in resources.items()}
|
|
45
|
+
for code, found in keys.items():
|
|
46
|
+
_check_against_english(code, found, keys[_ENGLISH])
|
|
47
|
+
bundles: dict[str, FluentBundle] = {}
|
|
48
|
+
for code, parsed in resources.items():
|
|
49
|
+
bundle = FluentBundle([code], use_isolating=False)
|
|
50
|
+
for resource in parsed:
|
|
51
|
+
bundle.add_resource(resource)
|
|
52
|
+
bundles[code] = bundle
|
|
53
|
+
return cls(_bundles=bundles)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def locales(self) -> frozenset[hikari.Locale]:
|
|
57
|
+
"""The languages that have texts, for example to offer them in a set-up command."""
|
|
58
|
+
return frozenset(hikari.Locale(code) for code in self._bundles)
|
|
59
|
+
|
|
60
|
+
def text(self, locale: hikari.Locale | str, key: str, **args: str | int | float) -> str:
|
|
61
|
+
"""Return the text for `key` in `locale`, else in another variant of that language, else in English.
|
|
62
|
+
|
|
63
|
+
`key` is a message id, or `message.attribute` for an attribute. Raises `KeyError` if no language has it.
|
|
64
|
+
"""
|
|
65
|
+
for code in self._fallbacks(str(locale)):
|
|
66
|
+
bundle = self._bundles[code]
|
|
67
|
+
pattern = _pattern(bundle, key)
|
|
68
|
+
if pattern is not None:
|
|
69
|
+
return _format(bundle, code, key, pattern, args)
|
|
70
|
+
raise KeyError(key)
|
|
71
|
+
|
|
72
|
+
def localization_provider(self, key: str) -> Mapping[hikari.Locale, str]:
|
|
73
|
+
"""Return `key` in every language that has it; pass this to lightbulb as `localization_provider`."""
|
|
74
|
+
found: dict[hikari.Locale, str] = {}
|
|
75
|
+
for code, bundle in self._bundles.items():
|
|
76
|
+
pattern = _pattern(bundle, key)
|
|
77
|
+
if pattern is not None:
|
|
78
|
+
found[hikari.Locale(code)] = _format(bundle, code, key, pattern, {})
|
|
79
|
+
return found
|
|
80
|
+
|
|
81
|
+
def _fallbacks(self, code: str) -> list[str]:
|
|
82
|
+
language = code.partition("-")[0]
|
|
83
|
+
chain = [code] if code in self._bundles else []
|
|
84
|
+
chain += sorted(other for other in self._bundles if other != code and other.partition("-")[0] == language)
|
|
85
|
+
if _ENGLISH not in chain:
|
|
86
|
+
chain.append(_ENGLISH)
|
|
87
|
+
return chain
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _read(folders: Iterable[Path]) -> dict[str, list[ast.Resource]]:
|
|
91
|
+
discord_locales = {locale.value for locale in hikari.Locale}
|
|
92
|
+
resources: dict[str, list[ast.Resource]] = {}
|
|
93
|
+
for folder in folders:
|
|
94
|
+
if not folder.is_dir():
|
|
95
|
+
raise CatalogError(f"{folder} is missing or not a folder")
|
|
96
|
+
for language in sorted(path for path in folder.iterdir() if path.is_dir()):
|
|
97
|
+
if language.name not in discord_locales:
|
|
98
|
+
raise CatalogError(f"{language} is not named after a Discord locale")
|
|
99
|
+
for file in sorted(language.glob("*.ftl")):
|
|
100
|
+
resources.setdefault(language.name, []).append(_parse(file))
|
|
101
|
+
return resources
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _parse(file: Path) -> ast.Resource:
|
|
105
|
+
try:
|
|
106
|
+
source = file.read_text(encoding="utf-8")
|
|
107
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
108
|
+
raise CatalogError(f"Cannot read {file}: {exc}") from exc
|
|
109
|
+
resource = FluentParser().parse(source)
|
|
110
|
+
for entry in resource.body:
|
|
111
|
+
if isinstance(entry, ast.Junk):
|
|
112
|
+
line = source.count("\n", 0, entry.span.start if entry.span else 0) + 1
|
|
113
|
+
problem = entry.annotations[0].message if entry.annotations else "unreadable entry"
|
|
114
|
+
raise CatalogError(f"{file}:{line}: {problem}")
|
|
115
|
+
return resource
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class _Uses(Visitor):
|
|
119
|
+
def __init__(self) -> None:
|
|
120
|
+
super().__init__()
|
|
121
|
+
self.variables: set[str] = set()
|
|
122
|
+
self.messages: set[str] = set()
|
|
123
|
+
|
|
124
|
+
def visit_VariableReference(self, node: ast.VariableReference) -> None:
|
|
125
|
+
self.variables.add(node.id.name)
|
|
126
|
+
self.generic_visit(node)
|
|
127
|
+
|
|
128
|
+
def visit_MessageReference(self, node: ast.MessageReference) -> None:
|
|
129
|
+
self.messages.add(node.id.name if node.attribute is None else f"{node.id.name}.{node.attribute.name}")
|
|
130
|
+
self.generic_visit(node)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _uses(pattern: ast.Pattern) -> _Uses:
|
|
134
|
+
visitor = _Uses()
|
|
135
|
+
visitor.visit(pattern)
|
|
136
|
+
return visitor
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _keys(code: str, resources: list[ast.Resource]) -> dict[str, frozenset[str]]:
|
|
140
|
+
uses: dict[str, _Uses] = {}
|
|
141
|
+
defined: set[str] = set()
|
|
142
|
+
for resource in resources:
|
|
143
|
+
for entry in resource.body:
|
|
144
|
+
if not isinstance(entry, ast.Message | ast.Term):
|
|
145
|
+
continue
|
|
146
|
+
name = entry.id.name if isinstance(entry, ast.Message) else f"-{entry.id.name}"
|
|
147
|
+
if name in defined:
|
|
148
|
+
raise CatalogError(f"{code}: {name} is defined twice")
|
|
149
|
+
defined.add(name)
|
|
150
|
+
if isinstance(entry, ast.Term):
|
|
151
|
+
continue
|
|
152
|
+
if entry.value is not None:
|
|
153
|
+
uses[name] = _uses(entry.value)
|
|
154
|
+
for attribute in entry.attributes:
|
|
155
|
+
key = f"{name}.{attribute.id.name}"
|
|
156
|
+
if key in uses:
|
|
157
|
+
raise CatalogError(f"{code}: {key} is defined twice")
|
|
158
|
+
uses[key] = _uses(attribute.value)
|
|
159
|
+
return _with_referenced_variables(uses)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _with_referenced_variables(uses: Mapping[str, _Uses]) -> dict[str, frozenset[str]]:
|
|
163
|
+
result: dict[str, frozenset[str]] = {}
|
|
164
|
+
for key in uses:
|
|
165
|
+
variables: set[str] = set()
|
|
166
|
+
reached, pending = {key}, [key]
|
|
167
|
+
while pending:
|
|
168
|
+
current = uses.get(pending.pop())
|
|
169
|
+
if current is None:
|
|
170
|
+
continue
|
|
171
|
+
variables |= current.variables
|
|
172
|
+
for reference in current.messages - reached:
|
|
173
|
+
reached.add(reference)
|
|
174
|
+
pending.append(reference)
|
|
175
|
+
result[key] = frozenset(variables)
|
|
176
|
+
return result
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _check_against_english(
|
|
180
|
+
code: str, keys: Mapping[str, frozenset[str]], english: Mapping[str, frozenset[str]]
|
|
181
|
+
) -> None:
|
|
182
|
+
for key, variables in keys.items():
|
|
183
|
+
if key not in english:
|
|
184
|
+
raise CatalogError(f"{code}: {key} has no English text")
|
|
185
|
+
if extra := variables - english[key]:
|
|
186
|
+
names = ", ".join(f"${name}" for name in sorted(extra))
|
|
187
|
+
raise CatalogError(f"{code}: {key} uses {names}, which the English text does not")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _pattern(bundle: FluentBundle, key: str) -> Pattern | None:
|
|
191
|
+
message_id, _, attribute = key.partition(".")
|
|
192
|
+
if not bundle.has_message(message_id):
|
|
193
|
+
return None
|
|
194
|
+
message = bundle.get_message(message_id)
|
|
195
|
+
if attribute:
|
|
196
|
+
return message.attributes.get(attribute)
|
|
197
|
+
return message.value
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _format(bundle: FluentBundle, code: str, key: str, pattern: Pattern, args: Mapping[str, str | int | float]) -> str:
|
|
201
|
+
value, errors = bundle.format_pattern(pattern, dict(args))
|
|
202
|
+
if errors:
|
|
203
|
+
_LOGGER.warning("Formatting %s in %s: %s", key, code, "; ".join(_describe(error) for error in errors))
|
|
204
|
+
return str(value)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _describe(error: Exception) -> str:
|
|
208
|
+
# Other errors can quote the arguments, and those may hold what users wrote.
|
|
209
|
+
return str(error) if isinstance(error, FluentFormatError) else type(error).__name__
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
kit-error-hub = Ich komme gerade nicht an meine Daten. Versuch es in einer Minute noch einmal.
|
|
2
|
+
.title = Gerade nicht erreichbar
|
|
3
|
+
kit-error-forbidden = Mir fehlt dafür eine Berechtigung. Bitte einen Server-Admin, meine Rolle zu prüfen.
|
|
4
|
+
.title = Berechtigung fehlt
|
|
5
|
+
kit-error-unknown = Versuch es später noch einmal. Wenn es wieder passiert, gib dem Betreiber des Bots diese Referenz: `{ $reference }`
|
|
6
|
+
.title = Etwas ist schiefgelaufen
|
|
7
|
+
|
|
8
|
+
kit-cmd-info =
|
|
9
|
+
.name = info
|
|
10
|
+
.description = Zeigt, was dieser Bot ist, wer ihn betreibt und wo sein Code liegt
|
|
11
|
+
kit-info-meta = Version { $version } · { $servers } Server · Betrieben von { $operator } ({ $contact })
|
|
12
|
+
kit-info-meta-without-servers = Version { $version } · Betrieben von { $operator } ({ $contact })
|
|
13
|
+
kit-info-privacy = Mit /privacy siehst, exportierst oder löschst du, was dieser Bot über dich speichert.
|
|
14
|
+
kit-info-source = Quellcode
|
|
15
|
+
kit-info-support = Support
|
|
16
|
+
kit-info-privacy-policy = Datenschutzerklärung
|
|
17
|
+
|
|
18
|
+
kit-cmd-privacy =
|
|
19
|
+
.name = privacy
|
|
20
|
+
.description = Sieh dir an, was dieser Bot über dich speichert, exportiere oder lösche es
|
|
21
|
+
kit-privacy-overview = { $operator } ({ $contact }) betreibt diese Instanz von { $bot }.
|
|
22
|
+
.title = Deine Daten
|
|
23
|
+
.stored = Über dich gespeichert:
|
|
24
|
+
.nothing = Über dich ist nichts gespeichert.
|
|
25
|
+
.policy = Datenschutzerklärung
|
|
26
|
+
kit-privacy-export = Diese Datei enthält alles, was { $bot } über dich speichert.
|
|
27
|
+
.title = Dein Datenexport
|
|
28
|
+
.button = Meine Daten exportieren
|
|
29
|
+
kit-privacy-delete = Damit löschst du alles, was { $bot } über dich speichert, in jedem Server:
|
|
30
|
+
.title = Alles über dich löschen?
|
|
31
|
+
.warning = Das lässt sich nicht rückgängig machen. Exportiere deine Daten vorher, wenn du eine Kopie willst.
|
|
32
|
+
.button = Meine Daten löschen
|
|
33
|
+
.confirm = Alles löschen
|
|
34
|
+
.modal = Alle deine Daten löschen
|
|
35
|
+
.input = Gib zur Bestätigung deinen Nutzernamen ein
|
|
36
|
+
.mismatch = Das ist nicht dein Nutzername, deshalb wurde nichts gelöscht.
|
|
37
|
+
kit-privacy-deleting = Deine Daten werden im Hintergrund gelöscht. Das kann ein paar Minuten dauern.
|
|
38
|
+
.title = Löschung gestartet
|
|
39
|
+
kit-privacy-server = Damit löschst du alles, was { $bot } über diesen Server speichert:
|
|
40
|
+
.title = Daten dieses Servers löschen?
|
|
41
|
+
.warning = Das lässt sich nicht rückgängig machen. Die Nachrichten des Bots im Server bleiben.
|
|
42
|
+
.button = Daten dieses Servers löschen
|
|
43
|
+
.confirm = Serverdaten löschen
|
|
44
|
+
.modal = Daten dieses Servers löschen
|
|
45
|
+
.input = Gib zur Bestätigung den Servernamen ein
|
|
46
|
+
.mismatch = Das ist nicht der Name des Servers, deshalb wurde nichts gelöscht.
|
|
47
|
+
.owner-only = Nur der Eigentümer des Servers kann dessen Daten löschen.
|
|
48
|
+
kit-privacy-server-deleted = { $bot } hat gelöscht:
|
|
49
|
+
.title = Serverdaten gelöscht
|
|
50
|
+
.nothing = { $bot } hatte über diesen Server nichts gespeichert.
|
|
51
|
+
kit-privacy-unconfirmed = Ich konnte meine Daten nicht erreichen, um das abzuschließen, und weiß deshalb nicht, ob gelöscht wurde. Prüfe es in einer Minute mit /privacy.
|
|
52
|
+
.title = Löschung nicht bestätigt
|
|
53
|
+
kit-privacy-not-deleted =
|
|
54
|
+
.title = Nichts gelöscht
|
|
55
|
+
kit-privacy-cancel = Abbrechen
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
kit-error-hub = I can't reach my data at the moment. Try again in a minute.
|
|
2
|
+
.title = Not reachable right now
|
|
3
|
+
kit-error-forbidden = I'm missing a permission for this. Ask a server admin to check my role.
|
|
4
|
+
.title = Missing permission
|
|
5
|
+
kit-error-unknown = Try again later. If it keeps happening, give the bot's operator this reference: `{ $reference }`
|
|
6
|
+
.title = Something went wrong
|
|
7
|
+
|
|
8
|
+
kit-cmd-info =
|
|
9
|
+
.name = info
|
|
10
|
+
.description = Shows what this bot is, who runs it and where its code is
|
|
11
|
+
kit-info-meta = Version { $version } · { $servers ->
|
|
12
|
+
[one] { $servers } server
|
|
13
|
+
*[other] { $servers } servers
|
|
14
|
+
} · Run by { $operator } ({ $contact })
|
|
15
|
+
kit-info-meta-without-servers = Version { $version } · Run by { $operator } ({ $contact })
|
|
16
|
+
kit-info-privacy = Use /privacy to see, export or delete what this bot stores about you.
|
|
17
|
+
kit-info-source = Source code
|
|
18
|
+
kit-info-support = Support
|
|
19
|
+
kit-info-privacy-policy = Privacy policy
|
|
20
|
+
|
|
21
|
+
kit-cmd-privacy =
|
|
22
|
+
.name = privacy
|
|
23
|
+
.description = See, export or delete what this bot stores about you
|
|
24
|
+
kit-privacy-overview = { $operator } ({ $contact }) runs this instance of { $bot }.
|
|
25
|
+
.title = Your data
|
|
26
|
+
.stored = It stores about you:
|
|
27
|
+
.nothing = It stores nothing about you.
|
|
28
|
+
.policy = Privacy policy
|
|
29
|
+
kit-privacy-export = This file holds everything { $bot } stores about you.
|
|
30
|
+
.title = Your data export
|
|
31
|
+
.button = Export my data
|
|
32
|
+
kit-privacy-delete = This deletes everything { $bot } stores about you, in every server:
|
|
33
|
+
.title = Delete everything about you?
|
|
34
|
+
.warning = It cannot be undone. Export your data first if you want a copy.
|
|
35
|
+
.button = Delete my data
|
|
36
|
+
.confirm = Delete everything
|
|
37
|
+
.modal = Delete all your data
|
|
38
|
+
.input = Type your username to confirm
|
|
39
|
+
.mismatch = That is not your username, so nothing was deleted.
|
|
40
|
+
kit-privacy-deleting = Your data is being deleted in the background. This can take a few minutes.
|
|
41
|
+
.title = Deletion started
|
|
42
|
+
kit-privacy-server = This deletes everything { $bot } stores about this server:
|
|
43
|
+
.title = Delete this server's data?
|
|
44
|
+
.warning = It cannot be undone. The bot's messages in this server stay.
|
|
45
|
+
.button = Delete this server's data
|
|
46
|
+
.confirm = Delete server data
|
|
47
|
+
.modal = Delete this server's data
|
|
48
|
+
.input = Type the server name to confirm
|
|
49
|
+
.mismatch = That is not the server's name, so nothing was deleted.
|
|
50
|
+
.owner-only = Only the server owner can delete this server's data.
|
|
51
|
+
kit-privacy-server-deleted = { $bot } deleted:
|
|
52
|
+
.title = Server data deleted
|
|
53
|
+
.nothing = { $bot } stored nothing about this server.
|
|
54
|
+
kit-privacy-unconfirmed = I could not reach my data to finish this, so I cannot tell whether it was deleted. Run /privacy again in a minute to check.
|
|
55
|
+
.title = Deletion not confirmed
|
|
56
|
+
kit-privacy-not-deleted =
|
|
57
|
+
.title = Nothing was deleted
|
|
58
|
+
kit-privacy-cancel = Cancel
|
librebots/kit/privacy.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
6
|
+
|
|
7
|
+
from librebots.hub.v1.privacy_pb2 import (
|
|
8
|
+
CategoryCount,
|
|
9
|
+
CountGuildDataRequest,
|
|
10
|
+
CountUserDataRequest,
|
|
11
|
+
DeleteGuildDataRequest,
|
|
12
|
+
DeleteUserDataRequest,
|
|
13
|
+
ExportUserDataRequest,
|
|
14
|
+
ListPendingUserDeletionsRequest,
|
|
15
|
+
RequestUserDeletionRequest,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from librebots.kit.hub import Hub, call_hub
|
|
19
|
+
|
|
20
|
+
__all__ = ["Privacy"]
|
|
21
|
+
|
|
22
|
+
_LOGGER = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Privacy:
|
|
26
|
+
"""Counts, exports and deletes what the bot stores in the hub about a person or a guild.
|
|
27
|
+
|
|
28
|
+
Deleting a person's data runs in the background and survives a restart: the hub records the request first, then
|
|
29
|
+
`on_user_deletion` removes what the bot keeps on Discord for that person, then the hub deletes the rest. A deletion
|
|
30
|
+
that fails stays pending, and `resume_deletions` starts it again. `on_user_deletion` can therefore run several
|
|
31
|
+
times for one person, also after an earlier run removed some or all of it, and must succeed when nothing is left
|
|
32
|
+
to remove. Every call to the hub gives up after `timeout` seconds.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
hub: Hub,
|
|
38
|
+
*,
|
|
39
|
+
on_user_deletion: Callable[[int], Awaitable[None]] | None = None,
|
|
40
|
+
timeout: float = 30,
|
|
41
|
+
) -> None:
|
|
42
|
+
self._hub = hub
|
|
43
|
+
self._on_user_deletion = on_user_deletion
|
|
44
|
+
self._timeout = timeout
|
|
45
|
+
self._deletions: dict[int, asyncio.Task[None]] = {}
|
|
46
|
+
|
|
47
|
+
async def count_user(self, user_id: int) -> dict[str, int]:
|
|
48
|
+
"""Return what the bot stores about a person, counted by category. Raises `HubError` if the hub fails."""
|
|
49
|
+
request = CountUserDataRequest(user_id=user_id)
|
|
50
|
+
response = await call_hub("CountUserData", self._hub.privacy.CountUserData(request, timeout=self._timeout))
|
|
51
|
+
return _by_category(response.categories)
|
|
52
|
+
|
|
53
|
+
async def export_user(self, user_id: int) -> str:
|
|
54
|
+
"""Return everything the bot stores about a person as a JSON document. Raises `HubError` if the hub fails."""
|
|
55
|
+
request = ExportUserDataRequest(user_id=user_id)
|
|
56
|
+
response = await call_hub("ExportUserData", self._hub.privacy.ExportUserData(request, timeout=self._timeout))
|
|
57
|
+
return response.json
|
|
58
|
+
|
|
59
|
+
async def delete_user(self, user_id: int) -> None:
|
|
60
|
+
"""Record that a person's data is to be deleted and start deleting it in the background.
|
|
61
|
+
|
|
62
|
+
Returns once the hub has recorded the request. Raises `HubError` if it cannot.
|
|
63
|
+
"""
|
|
64
|
+
request = RequestUserDeletionRequest(user_id=user_id)
|
|
65
|
+
await call_hub("RequestUserDeletion", self._hub.privacy.RequestUserDeletion(request, timeout=self._timeout))
|
|
66
|
+
self._start(user_id)
|
|
67
|
+
|
|
68
|
+
async def resume_deletions(self) -> int:
|
|
69
|
+
"""Start every pending deletion that is not running yet and return how many it started.
|
|
70
|
+
|
|
71
|
+
Raises `HubError` if the hub fails.
|
|
72
|
+
"""
|
|
73
|
+
request = ListPendingUserDeletionsRequest()
|
|
74
|
+
response = await call_hub(
|
|
75
|
+
"ListPendingUserDeletions", self._hub.privacy.ListPendingUserDeletions(request, timeout=self._timeout)
|
|
76
|
+
)
|
|
77
|
+
return sum(self._start(deletion.user_id) for deletion in response.deletions)
|
|
78
|
+
|
|
79
|
+
async def wait_for_deletions(self) -> None:
|
|
80
|
+
"""Wait until every running deletion has finished or failed."""
|
|
81
|
+
while self._deletions:
|
|
82
|
+
await asyncio.wait(list(self._deletions.values()))
|
|
83
|
+
|
|
84
|
+
async def count_guild(self, guild_id: int) -> dict[str, int]:
|
|
85
|
+
"""Return what the bot stores about a guild, counted by category. Raises `HubError` if the hub fails."""
|
|
86
|
+
request = CountGuildDataRequest(guild_id=guild_id)
|
|
87
|
+
response = await call_hub("CountGuildData", self._hub.privacy.CountGuildData(request, timeout=self._timeout))
|
|
88
|
+
return _by_category(response.categories)
|
|
89
|
+
|
|
90
|
+
async def delete_guild(self, guild_id: int) -> dict[str, int]:
|
|
91
|
+
"""Delete what the bot stores about a guild and return what was deleted. Raises `HubError` if the hub fails."""
|
|
92
|
+
request = DeleteGuildDataRequest(guild_id=guild_id)
|
|
93
|
+
response = await call_hub("DeleteGuildData", self._hub.privacy.DeleteGuildData(request, timeout=self._timeout))
|
|
94
|
+
return _by_category(response.deleted)
|
|
95
|
+
|
|
96
|
+
async def close(self) -> None:
|
|
97
|
+
"""Stop the running deletions; they stay pending in the hub."""
|
|
98
|
+
tasks = list(self._deletions.values())
|
|
99
|
+
for task in tasks:
|
|
100
|
+
task.cancel()
|
|
101
|
+
await asyncio.gather(*tasks, return_exceptions=True)
|
|
102
|
+
|
|
103
|
+
def _start(self, user_id: int) -> bool:
|
|
104
|
+
if user_id in self._deletions:
|
|
105
|
+
return False
|
|
106
|
+
task = asyncio.create_task(self._delete(user_id), name=f"delete the data of user {user_id}")
|
|
107
|
+
self._deletions[user_id] = task
|
|
108
|
+
task.add_done_callback(lambda done: self._forget(user_id, done))
|
|
109
|
+
return True
|
|
110
|
+
|
|
111
|
+
def _forget(self, user_id: int, task: asyncio.Task[None]) -> None:
|
|
112
|
+
if self._deletions.get(user_id) is task:
|
|
113
|
+
del self._deletions[user_id]
|
|
114
|
+
|
|
115
|
+
async def _delete(self, user_id: int) -> None:
|
|
116
|
+
try:
|
|
117
|
+
if self._on_user_deletion is not None:
|
|
118
|
+
await self._on_user_deletion(user_id)
|
|
119
|
+
request = DeleteUserDataRequest(user_id=user_id)
|
|
120
|
+
await call_hub("DeleteUserData", self._hub.privacy.DeleteUserData(request, timeout=self._timeout))
|
|
121
|
+
except Exception:
|
|
122
|
+
_LOGGER.exception("Deleting the data of user %s failed; it stays pending and is tried again later", user_id)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _by_category(categories: Iterable[CategoryCount]) -> dict[str, int]:
|
|
126
|
+
return {category.category: category.count for category in categories}
|
librebots/kit/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: librebots-kit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Shared functions and extensions every Libre Bot uses
|
|
5
|
+
Project-URL: Source, https://github.com/libre-bots/kit
|
|
6
|
+
Author: Libre Bots
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.12
|
|
10
|
+
Requires-Dist: fluent-runtime>=0.4.0
|
|
11
|
+
Requires-Dist: hikari-lightbulb[crontrigger]>=3.2.7
|
|
12
|
+
Requires-Dist: hikari-risa>=1.4.0
|
|
13
|
+
Requires-Dist: hikari>=2.6.0
|
|
14
|
+
Requires-Dist: librebots-hub>=0.1.1
|
|
15
|
+
Requires-Dist: msgspec>=0.22.0
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# Libre Bots kit
|
|
19
|
+
|
|
20
|
+
The functions and lightbulb extensions every Libre Bot shares: configuration, the hub connection, translations,
|
|
21
|
+
guild reporting and privacy. It is a toolbox, not a framework. A bot calls it from its own start-up code,
|
|
22
|
+
and nothing in it runs unless the bot names it.
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pip install librebots-kit
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Development
|
|
29
|
+
|
|
30
|
+
You need [mise](https://mise.jdx.dev).
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
mise install
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- `make lint`: ruff, pyright and `actionlint`
|
|
37
|
+
- `make test`: the tests
|
|
38
|
+
|
|
39
|
+
## Releases
|
|
40
|
+
|
|
41
|
+
A maintainer runs `release` in the Actions tab on `main` and chooses `patch`, `minor` or `major`, optionally as a
|
|
42
|
+
release candidate. The run publishes the package to PyPI.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
librebots/kit/__init__.py,sha256=da5uRTXKED9-0-mC0NWld8HZ--YPqU6UM5sdLQ_lbS4,674
|
|
2
|
+
librebots/kit/bot.py,sha256=3zIlSQUvg80bIo_xs9nfelPtn9jOGn93or9TnDNB8Jk,438
|
|
3
|
+
librebots/kit/config.py,sha256=6w7-XwM4BTHntEOPeo8FPjU1k9ca6mDKLPz3RSCmYIE,4743
|
|
4
|
+
librebots/kit/guilds.py,sha256=7FWQWQcyu6hMrieRa0khPBY9JVVp5Efpd2BDFS_IflA,4486
|
|
5
|
+
librebots/kit/hub.py,sha256=HPxV1abOHEr0OhuiD9lp8NCH7LUDe-3oYO--vitpXZ4,6435
|
|
6
|
+
librebots/kit/i18n.py,sha256=YLWwRydh-TJshDQ4mAQX0URRsBzTvasBkgct5U8Q6sU,8431
|
|
7
|
+
librebots/kit/privacy.py,sha256=cJCYVlvn7omW_NCV8CecnNVQRCXH14whOzByEya4XzI,5685
|
|
8
|
+
librebots/kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
librebots/kit/ext/__init__.py,sha256=U4S_2y3zgLZVfMenHRaJFBW8yqh2mUBuI291LGQVOJ8,35
|
|
10
|
+
librebots/kit/ext/errors.py,sha256=dV557kUKdcEkuhCE1FeDFm7ggy-V-kDmjSOCQ7mOETs,3824
|
|
11
|
+
librebots/kit/ext/guilds.py,sha256=vGyiC1bTjzAo4s4k7unNbkjxqvY6DoJilZhTd5x1SM8,2743
|
|
12
|
+
librebots/kit/ext/info.py,sha256=G8uO3mQhIjy7D6ciR7WOkPGV4dT9S6oSQwY92RpTFoE,2950
|
|
13
|
+
librebots/kit/ext/privacy.py,sha256=O9BrPxPjFQsVoCssgH1UDxYR1FsDtp_0JN0paSthvH8,15212
|
|
14
|
+
librebots/kit/locales/de/kit.ftl,sha256=5d9ugdxiP5xHsXgi043utadOVZIuPBTxEGX9M8i0m5A,3169
|
|
15
|
+
librebots/kit/locales/en-US/kit.ftl,sha256=08qzd7JWStD4x_d1N3RHZmvmZu7E5nKCcsUeO4ojz-k,2860
|
|
16
|
+
librebots_kit-0.1.0.dist-info/METADATA,sha256=9DyudkXSXB01d1Pty9u69o3BjXPk7oxPS7rlw4JupJI,1182
|
|
17
|
+
librebots_kit-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
18
|
+
librebots_kit-0.1.0.dist-info/licenses/LICENSE,sha256=tnQYYU7FJSJJw76yv4fO62yxKgWlCf2zwBilB6Ga-Cg,1067
|
|
19
|
+
librebots_kit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Libre Bots
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|