rubydc 0.1.0__tar.gz

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.
rubydc-0.1.0/LICENCE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2026 NotHMRC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
rubydc-0.1.0/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2026 NotHMRC
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
rubydc-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: rubydc
3
+ Version: 0.1.0
4
+ Summary: A small Discord bot framework built on discord.py
5
+ Keywords: discord,discord.py,discord bot,bot
6
+ Author: NotHMRC
7
+ Author-email: NotHMRC <dcreator112@proton.me>
8
+ License-Expression: MIT
9
+ License-File: LICENCE
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Topic :: Communications :: Chat
15
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
16
+ Classifier: Topic :: Communications :: Chat
17
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
22
+ Classifier: Programming Language :: Python :: 3.16
23
+ Requires-Dist: aiohttp>=3.14.3
24
+ Requires-Dist: discord-py>=2.7.1
25
+ Requires-Dist: pydantic>=2.13.5
26
+ Requires-Dist: pymongo>=4.17.0
27
+ Requires-Dist: python-dotenv>=1.2.2
28
+ Requires-Dist: ruamel-yaml>=0.19.1
29
+ Requires-Dist: rich>=15.0.0
30
+ Requires-Dist: typer>=0.29.1
31
+ Requires-Dist: uv>=0.13.8
32
+ Requires-Dist: questionary>=2.1.1
33
+ Requires-Python: >=3.14
34
+ Project-URL: Homepage, https://ruby.toaster.quest
35
+ Project-URL: Documentation, https://ruby.toaster.quest
36
+ Project-URL: Repository, https://codeberg.org/NotHMRC/Ruby
37
+ Project-URL: Issues, https://codeberg.org/NotHMRC/Ruby/issues
38
+ Project-URL: Changelog, https://codeberg.org/NotHMRC/Ruby/src/branch/main/CHANGELOG.md
39
+ Description-Content-Type: text/markdown
40
+
rubydc-0.1.0/README.md ADDED
File without changes
@@ -0,0 +1,76 @@
1
+ [project]
2
+ name = "rubydc"
3
+ version = "0.1.0"
4
+ description = "A small Discord bot framework built on discord.py"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICEN[CS]E*"]
8
+ keywords = [
9
+ "discord",
10
+ "discord.py",
11
+ "discord bot",
12
+ "bot",
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Framework :: AsyncIO",
17
+ "Intended Audience :: Developers",
18
+ "Topic :: Communications :: Chat",
19
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
20
+ "Topic :: Communications :: Chat",
21
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.14",
25
+ "Programming Language :: Python :: 3.15",
26
+ "Programming Language :: Python :: 3.16",
27
+ ]
28
+ requires-python = ">=3.14"
29
+ dependencies = [
30
+ "aiohttp>=3.14.3",
31
+ "discord-py>=2.7.1",
32
+ "pydantic>=2.13.5",
33
+ "pymongo>=4.17.0",
34
+ "python-dotenv>=1.2.2",
35
+ "ruamel-yaml>=0.19.1",
36
+ "rich>=15.0.0",
37
+ "typer>=0.29.1",
38
+ "uv>=0.13.8",
39
+ "questionary>=2.1.1",
40
+ ]
41
+
42
+ [[project.authors]]
43
+ name = "NotHMRC"
44
+ email = "dcreator112@proton.me"
45
+
46
+ [project.urls]
47
+ Homepage = "https://ruby.toaster.quest"
48
+ Documentation = "https://ruby.toaster.quest"
49
+ Repository = "https://codeberg.org/NotHMRC/Ruby"
50
+ Issues = "https://codeberg.org/NotHMRC/Ruby/issues"
51
+ Changelog = "https://codeberg.org/NotHMRC/Ruby/src/branch/main/CHANGELOG.md"
52
+
53
+ [project.scripts]
54
+ ruby = "ruby.cli:cli"
55
+ rubydc = "ruby.cli:cli"
56
+
57
+ [dependency-groups]
58
+ dev = [
59
+ "commitizen>=4.19.3",
60
+ "ruff>=0.16.0",
61
+ ]
62
+
63
+ [build-system]
64
+ requires = ["uv_build >= 0.13, <0.14"]
65
+ build-backend = "uv_build"
66
+
67
+ [tool.uv.build-backend]
68
+ module-name = "ruby"
69
+
70
+ [tool.commitizen]
71
+ name = "cz_conventional_commits"
72
+ tag_format = "$version"
73
+ version_scheme = "pep440"
74
+ version_provider = "pep621"
75
+ update_changelog_on_bump = true
76
+ major_version_zero = true
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "rubydc"
3
+ version = "0.1.0"
4
+ description = "A small Discord bot framework built on discord.py"
5
+ readme = "README.md"
6
+ authors = [
7
+ {name = "NotHMRC", email = "dcreator112@proton.me"},
8
+ ]
9
+ license = "MIT"
10
+ license-files = ["LICEN[CS]E*"]
11
+ keywords = ["discord", "discord.py", "discord bot", "bot"]
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Framework :: AsyncIO",
15
+ "Intended Audience :: Developers",
16
+ "Topic :: Communications :: Chat",
17
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
18
+ "Topic :: Communications :: Chat",
19
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: 3.15",
24
+ "Programming Language :: Python :: 3.16",
25
+ ]
26
+
27
+ requires-python = ">=3.14"
28
+ dependencies = [
29
+ "aiohttp>=3.14.3",
30
+ "discord-py>=2.7.1",
31
+ "pydantic>=2.13.5",
32
+ "pymongo>=4.17.0",
33
+ "python-dotenv>=1.2.2",
34
+ "ruamel-yaml>=0.19.1",
35
+ # For the CLI
36
+ "rich>=15.0.0",
37
+ "typer>=0.29.1",
38
+ "uv>=0.13.8",
39
+ "questionary>=2.1.1",
40
+ ]
41
+
42
+ [project.urls]
43
+ Homepage = "https://ruby.toaster.quest"
44
+ Documentation = "https://ruby.toaster.quest"
45
+ Repository = "https://codeberg.org/NotHMRC/Ruby"
46
+ Issues = "https://codeberg.org/NotHMRC/Ruby/issues"
47
+ Changelog = "https://codeberg.org/NotHMRC/Ruby/src/branch/main/CHANGELOG.md"
48
+
49
+
50
+ [dependency-groups]
51
+ dev = [
52
+ "commitizen>=4.19.3",
53
+ "ruff>=0.16.0",
54
+ ]
55
+
56
+ [project.scripts]
57
+ ruby = "ruby.cli:cli"
58
+ rubydc = "ruby.cli:cli"
59
+
60
+ [build-system]
61
+ requires = ["uv_build >= 0.13, <0.14"]
62
+ build-backend = "uv_build"
63
+
64
+ [tool.uv.build-backend]
65
+ module-name = "ruby"
66
+
67
+ [tool.commitizen]
68
+ name = "cz_conventional_commits"
69
+ tag_format = "$version"
70
+ version_scheme = "pep440"
71
+ version_provider = "pep621"
72
+ update_changelog_on_bump = true
73
+ major_version_zero = true
@@ -0,0 +1,5 @@
1
+ from .bot import RubyBot, run
2
+ from .cli import cli
3
+ from .provides import provides
4
+
5
+ __all__ = ["RubyBot", "cli", "provides", "run"]
@@ -0,0 +1,3 @@
1
+ from .cli import cli
2
+
3
+ cli()
@@ -0,0 +1,335 @@
1
+ """
2
+ Partially used code from https://github.com/kkrypt0nn/Python-Discord-Bot-Template
3
+ """
4
+
5
+ from discord.utils import MISSING
6
+
7
+ import logging
8
+ import logging.handlers
9
+ import os
10
+ from pathlib import Path
11
+ import random
12
+ import re
13
+ import sys
14
+ import time
15
+ from collections.abc import Callable
16
+ from typing import Any
17
+
18
+ import discord
19
+ from discord import app_commands
20
+ from discord.ext import commands, tasks
21
+ from discord.ext.commands import Context
22
+ from dotenv import load_dotenv
23
+ from pymongo import AsyncMongoClient
24
+
25
+ from . import utils
26
+ from .provides import provided_by
27
+ from .utils import get_config
28
+
29
+ # From the folder the bot is run in, like config.yaml and cogs/. With no path, python-dotenv searches upwards from
30
+ # this file (inside site-packages), which only finds .env when the virtualenv happens to be inside the bot's folder
31
+ load_dotenv(Path.cwd() / ".env")
32
+
33
+
34
+ intents = discord.Intents.default()
35
+ intents.message_content = True
36
+ intents.members = True
37
+
38
+
39
+ class WTFError(Exception):
40
+ pass
41
+
42
+
43
+ def prefix_pattern(prefix: str) -> re.Pattern[str]:
44
+ """The prefix in any case, plus any whitespace after it: "r!help", "R!help", "r! help", "r!\nhelp"."""
45
+ return re.compile(re.escape(prefix) + r"\s*", re.IGNORECASE)
46
+
47
+
48
+ def get_prefix(bot: "RubyBot", message: discord.Message) -> list[str]:
49
+ # discord.py wants the exact text the message starts with, so the match itself is the prefix
50
+ match = bot.prefix_regex.match(message.content)
51
+ return commands.when_mentioned_or(*([match.group(0)] if match else []))(
52
+ bot, message
53
+ )
54
+
55
+
56
+ class RubyBot(commands.Bot):
57
+ def __init__(self) -> None:
58
+ self.utils = utils
59
+ self.cfg = get_config()
60
+
61
+ self.logger = logging.getLogger(self.cfg.name)
62
+ self.logger.setLevel(self.cfg.log_level)
63
+ # Appends (so the reason for a crash survives the restart), with timestamps, and rotates at 5 MB
64
+ file_handler = logging.handlers.RotatingFileHandler(
65
+ filename="bot.log",
66
+ encoding="utf-8",
67
+ maxBytes=5 * 1024 * 1024,
68
+ backupCount=3,
69
+ )
70
+ file_handler.setFormatter(
71
+ logging.Formatter(
72
+ "[%(asctime)s] [%(levelname)-8s] %(message)s", "%Y-%m-%d %H:%M:%S"
73
+ )
74
+ )
75
+ self.logger.addHandler(file_handler)
76
+
77
+ self.prefix = self.cfg.prefix
78
+ self.prefix_regex = prefix_pattern(self.prefix)
79
+ self.name = self.cfg.name
80
+ self.friendly_name = self.cfg.friendly_name
81
+ self.server = self.cfg.server
82
+
83
+ self.mongo = AsyncMongoClient(os.getenv("MONGO_URI"))
84
+ self.db = self.mongo[self.name]
85
+
86
+ self.status_task = tasks.loop(seconds=self.cfg.status_interval)(
87
+ self.status_task_func
88
+ )
89
+
90
+ # What cogs provide for other cogs, by kind and then name (see ruby.provides)
91
+ self.provided: dict[str, dict[str, Callable[..., Any]]] = {}
92
+
93
+ super().__init__(
94
+ command_prefix=get_prefix,
95
+ intents=intents,
96
+ help_command=None,
97
+ owner_ids=self.cfg.owners,
98
+ )
99
+ # Plain slash commands (not hybrid ones) report their errors here, so they get the same handling
100
+ self.tree.on_error = self.on_app_command_error
101
+
102
+ async def discord_log(self, level: int, msg: str) -> None:
103
+ if not self.logger.isEnabledFor(level): # same log_level as the file
104
+ return
105
+ if self.cfg.server.channels.get("log"):
106
+ channel = self.get_channel(int(self.cfg.server.channels["log"]))
107
+ if channel:
108
+ if level >= logging.ERROR:
109
+ colour = discord.Colour.red()
110
+ elif level >= logging.WARNING:
111
+ colour = discord.Colour.yellow()
112
+ else:
113
+ colour = discord.Colour.blurple()
114
+
115
+ await channel.send( # type: ignore[reportAttributeAccessIssue] shut up pylance
116
+ embed=discord.Embed(
117
+ colour=colour,
118
+ title=f"{logging.getLevelName(level)} Log Message",
119
+ description=msg,
120
+ ),
121
+ )
122
+
123
+ async def log(self, level: int, msg: str) -> None:
124
+ self.logger.log(level, msg)
125
+ await self.discord_log(level, msg)
126
+
127
+ async def load_cogs(self) -> None:
128
+ # The cogs are imported as the "cogs" package from the bot's folder. "python -m ruby" puts that folder on the
129
+ # import path, but the "ruby" command doesn't, so add it here or no cog can be found
130
+ if str(Path.cwd()) not in sys.path:
131
+ sys.path.insert(0, str(Path.cwd()))
132
+ for file in (Path.cwd() / "cogs").iterdir():
133
+ if file.suffix == ".py" and not file.stem.startswith("_"):
134
+ name = file.stem
135
+ try:
136
+ await self.load_extension(f"cogs.{name}")
137
+ await self.log(logging.DEBUG, f"Loaded cog '{name}'")
138
+ except Exception as e: # noqa: BLE001
139
+ exception = f"{type(e).__name__}: {e}"
140
+ await self.log(
141
+ logging.ERROR,
142
+ f"Failed to load cog {name}\n{exception}",
143
+ )
144
+
145
+ async def add_cog(
146
+ self, cog: commands.Cog, /, *, override: bool = False, **kwargs: Any
147
+ ) -> None:
148
+ await super().add_cog(cog, override=override, **kwargs)
149
+ for kind, name, func in provided_by(cog):
150
+ existing = self.provided.setdefault(kind, {}).get(name)
151
+ if existing is not None and getattr(existing, "__self__", None) is not cog:
152
+ owner = type(existing.__self__).__name__ # type: ignore[attr-defined]
153
+ await self.log(
154
+ logging.WARNING,
155
+ f"{type(cog).__name__} replaces {owner} as the provider of {kind} {name!r}",
156
+ )
157
+ self.provided[kind][name] = func
158
+
159
+ async def remove_cog(self, name: str, /, **kwargs: Any) -> commands.Cog | None:
160
+ cog = await super().remove_cog(name, **kwargs)
161
+ if cog is not None:
162
+ for kind, provided_name, _ in provided_by(cog):
163
+ current = self.provided.get(kind, {}).get(provided_name)
164
+ if current is not None and getattr(current, "__self__", None) is cog:
165
+ del self.provided[kind][provided_name]
166
+ return cog
167
+
168
+ async def status_task_func(self) -> None:
169
+ if self.cfg.statuses is None:
170
+ await self.change_presence(
171
+ status=discord.Status(self.cfg.status),
172
+ )
173
+ return
174
+
175
+ await self.change_presence(
176
+ activity=discord.CustomActivity(random.choice(self.cfg.statuses)),
177
+ status=discord.Status(self.cfg.status),
178
+ )
179
+
180
+ async def setup_hook(self) -> None:
181
+ # Loaded before connecting, so cogs get the first on_ready too
182
+ await self.load_cogs()
183
+
184
+ async def on_ready(self) -> None:
185
+ if not self.user:
186
+ raise WTFError("Something happened")
187
+ await self.log(
188
+ logging.INFO,
189
+ f"Logged in as {self.user.name}#{self.user.discriminator}\n",
190
+ )
191
+ if not self.status_task.is_running(): # on_ready fires again after reconnects
192
+ self.status_task.start()
193
+ await self.tree.sync()
194
+
195
+ async def on_command_completion(self, ctx: Context) -> None:
196
+ if not ctx.command:
197
+ raise WTFError("Something happened")
198
+ full_command_name = ctx.command.qualified_name
199
+ split = full_command_name.split(" ")
200
+ executed_command = split[0]
201
+ if ctx.guild is not None:
202
+ await self.log(
203
+ logging.DEBUG,
204
+ f"Executed {executed_command} command in {ctx.guild.name} (ID: {ctx.guild.id}) by {ctx.author} (ID: {ctx.author.id})",
205
+ )
206
+ else:
207
+ await self.log(
208
+ logging.DEBUG,
209
+ f"Executed {executed_command} command by {ctx.author} (ID: {ctx.author.id}) in DMs",
210
+ )
211
+
212
+ async def on_app_command_error(
213
+ self,
214
+ interaction: discord.Interaction,
215
+ error: app_commands.AppCommandError,
216
+ ) -> None:
217
+ try:
218
+ ctx = await Context.from_interaction(interaction)
219
+ except (
220
+ ValueError,
221
+ TypeError,
222
+ RuntimeError,
223
+ ): # no usable command data, so nobody to answer
224
+ await self.log(logging.ERROR, f"Slash command error: {error}")
225
+ return
226
+ await self.on_command_error(ctx, error)
227
+
228
+ async def on_command_error(
229
+ self,
230
+ ctx: Context,
231
+ error: commands.CommandError | app_commands.AppCommandError,
232
+ ) -> None:
233
+ if isinstance(error, commands.HybridCommandError):
234
+ # A hybrid command used as a slash command: the real error is the app_commands one inside
235
+ error = error.original
236
+
237
+ if isinstance(
238
+ error, (commands.CommandOnCooldown, app_commands.CommandOnCooldown)
239
+ ):
240
+ retry_at = int(time.time() + error.retry_after)
241
+ await self.utils.error(
242
+ ctx,
243
+ self.utils.get_string("COMMAND_ON_COOLDOWN").format(timestamp=retry_at),
244
+ )
245
+ elif isinstance(error, commands.NotOwner):
246
+ await self.utils.error(ctx, "NOT_OWNER")
247
+ if ctx.guild:
248
+ await self.log(
249
+ logging.WARNING,
250
+ f"{ctx.author} (ID: {ctx.author.id}) tried to execute an owner only command in the guild {ctx.guild.name} (ID: {ctx.guild.id}), but the user is not an owner of the bot.",
251
+ )
252
+ else:
253
+ await self.log(
254
+ logging.WARNING,
255
+ f"{ctx.author} (ID: {ctx.author.id}) tried to execute an owner only command in the bot's DMs, but the user is not an owner of the bot.",
256
+ )
257
+ elif isinstance(error, commands.CommandNotFound):
258
+ await self.utils.error(
259
+ ctx,
260
+ self.utils.get_string("COMMAND_NOT_FOUND"),
261
+ )
262
+ if ctx.guild:
263
+ await self.log(
264
+ logging.WARNING,
265
+ f"{ctx.author} (ID: {ctx.author.id}) tried to execute a command that does not exist in the server {ctx.guild.name} (ID: {ctx.guild.id}).",
266
+ )
267
+ else:
268
+ await self.log(
269
+ logging.WARNING,
270
+ f"{ctx.author} (ID: {ctx.author.id}) tried to execute a command that does not exist in the bot's DMs.",
271
+ )
272
+ elif isinstance(
273
+ error, (commands.MissingPermissions, app_commands.MissingPermissions)
274
+ ):
275
+ msg = (
276
+ self.utils.get_string("COMMAND_MISSING_PERMISSION").format(
277
+ permission=error.missing_permissions[0],
278
+ )
279
+ if len(error.missing_permissions) == 1
280
+ else self.utils.get_string("COMMAND_MISSING_PERMISSIONS").format(
281
+ permissions=", ".join(error.missing_permissions),
282
+ )
283
+ )
284
+ await self.utils.error(ctx, msg)
285
+ elif isinstance(
286
+ error, (commands.BotMissingPermissions, app_commands.BotMissingPermissions)
287
+ ):
288
+ msg = (
289
+ self.utils.get_string("COMMAND_BOT_MISSING_PERMISSION").format(
290
+ permission=error.missing_permissions[0],
291
+ )
292
+ if len(error.missing_permissions) == 1
293
+ else self.utils.get_string("COMMAND_BOT_MISSING_PERMISSIONS").format(
294
+ permissions=", ".join(error.missing_permissions),
295
+ )
296
+ )
297
+ await self.utils.error(ctx, msg)
298
+ elif isinstance(error, commands.MissingRequiredArgument):
299
+ await self.utils.error(ctx, str(error).capitalize())
300
+ elif isinstance(
301
+ error,
302
+ (
303
+ commands.UserInputError,
304
+ commands.CheckFailure,
305
+ app_commands.TransformerError,
306
+ app_commands.CheckFailure,
307
+ commands.MaxConcurrencyReached,
308
+ commands.DisabledCommand,
309
+ ),
310
+ ):
311
+ # The user's mistake (bad member, wrong channel, etc.) or a limit, not the bot's
312
+ await self.utils.error(ctx, str(error))
313
+ elif isinstance(
314
+ error, (commands.CommandInvokeError, app_commands.CommandInvokeError)
315
+ ):
316
+ original = error.original
317
+ if isinstance(original, ZeroDivisionError):
318
+ # Used by cogs to return early
319
+ pass
320
+ else:
321
+ await self.utils.error(ctx, "UNKNOWN_ERROR")
322
+ await self.log(logging.ERROR, str(error))
323
+
324
+ else:
325
+ await self.utils.error(ctx, "UNKNOWN_COMMAND_ERROR")
326
+ await self.log(logging.ERROR, str(error))
327
+
328
+
329
+ def run() -> None:
330
+ bot = RubyBot()
331
+ bot.run(os.environ["TOKEN"])
332
+
333
+
334
+ if __name__ == "__main__":
335
+ run()
@@ -0,0 +1,129 @@
1
+ import shutil
2
+ import subprocess
3
+ import urllib
4
+ import urllib.request
5
+ from pathlib import Path
6
+ from typing import Annotated
7
+
8
+ import questionary
9
+ import typer
10
+ from rich.console import Console
11
+ from rich.panel import Panel
12
+ from rich.style import Style
13
+ from ruamel.yaml import YAML
14
+ from uv import find_uv_bin
15
+
16
+ RUBY = "git+https://codeberg.org/NotHMRC/Ruby"
17
+ CONFIG_EXAMPLE = "https://codeberg.org/NotHMRC/Ruby/raw/commit/ec7e3e16494a66207737aee8e2c047a0fecde92f/config.example.yaml"
18
+
19
+ app = typer.Typer()
20
+ con = Console()
21
+ cwd = Path(".")
22
+
23
+
24
+ @app.command(short_help="Run Ruby.")
25
+ def main() -> None:
26
+ from . import run
27
+
28
+ run()
29
+
30
+
31
+ def ask_config() -> dict[str, str | int | list[str] | list[int] | dict[str, str | int]]:
32
+ doc = {}
33
+ print("Settings")
34
+ print("Note: most settings are optional and can be skipped by pressing enter.")
35
+ doc["friendly_name"] = (
36
+ questionary.text("Bot name (displayed to users)").ask() or "Ruby"
37
+ )
38
+ doc["name"] = (
39
+ questionary.text("Bot name (machine-readable, a-z and _ is allowed)").ask()
40
+ or "ruby"
41
+ )
42
+ doc["prefix"] = questionary.text("Bot prefix").ask() or doc["name"][0] + "!"
43
+ doc["invite_link"] = (
44
+ questionary.text(
45
+ "Bot invite link (leave blank if users shouldn't add your bot)"
46
+ ).ask()
47
+ or "No invite link"
48
+ )
49
+ doc["owners"] = [
50
+ int(o.strip())
51
+ for o in (
52
+ questionary.text("Comma-separated list of bot owner IDs").ask() or ""
53
+ ).split(",")
54
+ ]
55
+ doc["statuses"] = [
56
+ o.strip()
57
+ for o in (
58
+ questionary.text(
59
+ "Comma-separated list of statuses the bot should cycle"
60
+ ).ask()
61
+ or ""
62
+ ).split(",")
63
+ ]
64
+ doc["status_interval"] = int(
65
+ questionary.text("Interval in seconds between status changes").ask() or 60
66
+ )
67
+ doc["server"] = {}
68
+ doc["server"]["id"] = int(
69
+ questionary.text("ID of your bot's main server").ask() or 0
70
+ )
71
+ doc["server"]["name"] = (
72
+ questionary.text("Name of your bot's main server").ask() or ""
73
+ )
74
+ doc["server"]["invite"] = (
75
+ questionary.text("Invite link of your bot's main server").ask() or ""
76
+ )
77
+ return doc
78
+
79
+
80
+ @app.command(help="Create a new Ruby bot.")
81
+ def init(
82
+ path: Annotated[
83
+ Path,
84
+ typer.Argument(help="The folder to use. Will be created if it does not exist"),
85
+ ] = cwd,
86
+ interactive: bool = True,
87
+ ) -> None:
88
+ uv = find_uv_bin()
89
+ subprocess.run([uv, "init", "--no-package", str(path)], check=True)
90
+ shutil.rmtree(path / "src", True)
91
+ (path / "main.py").unlink(True)
92
+ subprocess.run([uv, "add", RUBY], cwd=path, check=True)
93
+ (path / "cogs").mkdir()
94
+
95
+ if not interactive:
96
+ urllib.request.urlretrieve(CONFIG_EXAMPLE, path / "config.yaml")
97
+ (path / ".env").write_text(
98
+ "TOKEN=DISCORD_TOKEN_HERE\nMONGO_URI=MONGODB_URI_HERE"
99
+ )
100
+ else:
101
+ yaml = YAML()
102
+ doc = ask_config()
103
+ yaml.dump(doc, path / "config.yaml")
104
+ token = questionary.password("Bot token (required)").ask() or "BLANK"
105
+ mongo_uri = questionary.password("MongoDB URI (optional)").ask() or "BLANK"
106
+ (path / ".env").write_text(
107
+ f"TOKEN={token}\nMONGO_URI={mongo_uri}" if mongo_uri else f"TOKEN={token}"
108
+ )
109
+
110
+ con.print(
111
+ Panel(
112
+ f"Created new Ruby project at {path.resolve()}.\n"
113
+ f"Next: Replace `TOKEN` in .env, optionally fill in config.yaml, then run `uv run ruby` in {path.resolve()}."
114
+ if not interactive
115
+ else f"Run the bot with `uv run ruby` in {path.resolve()}.",
116
+ border_style=Style(color="bright_green"),
117
+ )
118
+ )
119
+
120
+
121
+ @app.command(help="Upgrade the Ruby version.")
122
+ def upgrade() -> None:
123
+ uv = find_uv_bin()
124
+ subprocess.run([uv, "lock", "--upgrade-package", "ruby"], check=True)
125
+ subprocess.run([uv, "sync"], check=True)
126
+
127
+
128
+ def cli() -> None:
129
+ app()
@@ -0,0 +1,58 @@
1
+ from logging import INFO
2
+ from pathlib import Path
3
+ from typing import Any, Literal
4
+
5
+ from pydantic import BaseModel, model_validator
6
+ from ruamel.yaml import YAML
7
+
8
+ CONFIG_PATH = Path("config.yaml")
9
+
10
+
11
+ class Currency(BaseModel):
12
+ currency: str = "points"
13
+
14
+
15
+ class Server(BaseModel):
16
+ id: int = 0
17
+ name: str = "Server"
18
+ invite: str = "No invite link"
19
+ channels: dict[str, int] = {}
20
+
21
+
22
+ class Config(BaseModel):
23
+ # Bot identity
24
+ name: str = "ruby"
25
+ friendly_name: str = "Ruby"
26
+ version: str = "v0.1.0"
27
+ prefix: str = "r!"
28
+ invite_link: str = "No invite link"
29
+ owners: list[int] = []
30
+
31
+ # Bot config
32
+ statuses: list[str] | None = (
33
+ None # null in config.yaml = no status; left out = "<friendly_name> <version>"
34
+ )
35
+ status_interval: float = 60
36
+ status: Literal["online", "offline", "idle", "dnd", "invisible"] = "online"
37
+ strings: dict[str, str] = {}
38
+ log_level: str | int = INFO
39
+ embeds: bool = True
40
+
41
+ # Cog config
42
+ currency: Currency = Currency()
43
+ cogs: dict[str, Any] = {}
44
+
45
+ # Server
46
+ server: Server = Server()
47
+
48
+ @model_validator(mode="after")
49
+ def default_status(self) -> Config:
50
+ if "statuses" not in self.model_fields_set:
51
+ self.statuses = [f"{self.friendly_name} {self.version}"]
52
+ return self
53
+
54
+
55
+ def load_config(path: Path = CONFIG_PATH) -> Config:
56
+ yaml = YAML(typ="safe")
57
+ raw = yaml.load(path) or {}
58
+ return Config(**raw)
@@ -0,0 +1,38 @@
1
+ """Lets cogs provide named things for other cogs to use, without Ruby knowing what they are.
2
+
3
+ A cog marks methods with ``@provides(kind, name)``. When the cog is added to the bot they're collected into
4
+ ``bot.provided[kind][name]``, and when it's removed (or reloaded) they go again. ``kind`` is just a string the
5
+ cogs agree on: an AutoMod cog might look up ``bot.provided["automod.if"]`` for the conditions other cogs offer,
6
+ so a scam image cog can add an ``is_scam_image`` check without the AutoMod cog knowing about it.
7
+ """
8
+
9
+ from collections.abc import Callable
10
+ from typing import Any, TypeVar
11
+
12
+ F = TypeVar("F", bound=Callable[..., Any])
13
+
14
+ ATTRIBUTE = "__ruby_provides__"
15
+
16
+
17
+ def provides(kind: str, name: str) -> Callable[[F], F]:
18
+ """Marks a cog method as providing ``name`` under ``kind``. Can be stacked to provide it under several names."""
19
+
20
+ def decorator(func: F) -> F:
21
+ setattr(func, ATTRIBUTE, [*getattr(func, ATTRIBUTE, []), (kind, name)])
22
+ return func
23
+
24
+ return decorator
25
+
26
+
27
+ def provided_by(cog: object) -> list[tuple[str, str, Callable[..., Any]]]:
28
+ """Everything a cog provides: (kind, name, bound method)."""
29
+ found = []
30
+ seen: set[str] = set()
31
+ for cls in type(cog).__mro__:
32
+ for attribute, value in vars(cls).items():
33
+ if attribute in seen: # overridden in a subclass
34
+ continue
35
+ seen.add(attribute)
36
+ for kind, name in getattr(value, ATTRIBUTE, []):
37
+ found.append((kind, name, getattr(cog, attribute)))
38
+ return found
@@ -0,0 +1,175 @@
1
+ from pathlib import Path
2
+ from typing import TYPE_CHECKING, Literal
3
+
4
+ import discord
5
+ import discord.utils
6
+ from discord import Role, Embed, Colour
7
+ from discord.utils import MISSING
8
+
9
+ from .config import Config, load_config
10
+
11
+ if TYPE_CHECKING:
12
+ from discord.ext.commands import Context
13
+
14
+ CONFIG_PATH = Path("config.yaml")
15
+
16
+ DEFAULT_STRINGS = {
17
+ "NO_SERVER": "This command is only supported in a server!",
18
+ "UNSUPPORTED_CHANNEL": "Unsupported channel type!",
19
+ "NOT_OWNER": "You are not the owner of the bot!",
20
+ "COMMAND_ON_COOLDOWN": "**Please slow down** - You can use this command again <t:{timestamp}:R>.",
21
+ "COMMAND_NOT_FOUND": "Command not found!",
22
+ "COMMAND_MISSING_PERMISSION": "You are missing the permission `{permission}` to run this command!",
23
+ "COMMAND_MISSING_PERMISSIONS": "You are missing the permissions `{permissions}` to run this command!",
24
+ "COMMAND_BOT_MISSING_PERMISSION": "I am missing the permission `{permission}` to run this command!",
25
+ "COMMAND_BOT_MISSING_PERMISSIONS": "I am missing the permissions `{permissions}` to run this command!",
26
+ "UNKNOWN_ERROR": "Unknown error.",
27
+ "UNKNOWN_COMMAND_ERROR": "Unknown command error.",
28
+ "CRASH_REPORT_FOOTER": "Tell the bot developer this code: {code}",
29
+ }
30
+
31
+ config = None
32
+
33
+
34
+ def get_config(path: Path = CONFIG_PATH, force: bool = False) -> Config:
35
+ global config
36
+ if not config or force:
37
+ config = load_config(path)
38
+ return config
39
+
40
+
41
+ def get_string(
42
+ string: str,
43
+ default: str = "",
44
+ config: Config | None = None,
45
+ default_table: dict[str, str] = DEFAULT_STRINGS,
46
+ ) -> str:
47
+ cfg = config or get_config()
48
+ string_table = default_table | (
49
+ cfg.strings or {}
50
+ ) # config strings override defaults, not replace them
51
+ return string_table.get(string, default)
52
+
53
+
54
+ async def _react(ctx: Context, emoji: str) -> bool:
55
+ """React to the command message. False if that failed (message deleted, no permission, bot blocked)."""
56
+ try:
57
+ await ctx.message.add_reaction(emoji)
58
+ except discord.HTTPException:
59
+ return False
60
+ return True
61
+
62
+
63
+ async def _reply(
64
+ ctx: Context, content: str | None = None, embed: Embed | MISSING = MISSING
65
+ ) -> None:
66
+ if ctx.interaction:
67
+ await ctx.reply(content, embed=embed)
68
+ else:
69
+ # Still sends if the command message is gone (e.g. purged), just without the reply link
70
+ await ctx.send(
71
+ content,
72
+ embed=embed,
73
+ reference=ctx.message.to_reference(fail_if_not_exists=False),
74
+ )
75
+
76
+
77
+ async def error(
78
+ ctx: Context,
79
+ message: str | None = None,
80
+ silent_on_slash: bool = False,
81
+ default_table: dict[str, str] = DEFAULT_STRINGS,
82
+ ) -> None:
83
+ message = (
84
+ get_string(
85
+ message,
86
+ message,
87
+ default_table=default_table,
88
+ )
89
+ if message
90
+ else None
91
+ )
92
+
93
+ if ctx.interaction is None: # prefix command
94
+ if await _react(ctx, "❌") and message is None: # the reaction says it all
95
+ return
96
+ match message, silent_on_slash:
97
+ case None, True:
98
+ # remain silent, without "The application did not respond"
99
+ await ctx.defer(ephemeral=True)
100
+ if ctx.interaction:
101
+ await ctx.interaction.delete_original_response()
102
+ case None, False:
103
+ await _reply(ctx, "❌")
104
+ case msg, _:
105
+ if get_config().embeds:
106
+ await _reply(ctx, embed=Embed(colour=Colour.red(), description=msg))
107
+ else:
108
+ await _reply(ctx, f"❌ | {msg}")
109
+
110
+
111
+ async def success(
112
+ ctx: Context,
113
+ message: str | None = None,
114
+ silent_on_slash: bool = False,
115
+ default_table: dict[str, str] = DEFAULT_STRINGS,
116
+ ) -> None:
117
+ message = (
118
+ get_string(
119
+ message,
120
+ message,
121
+ default_table=default_table,
122
+ )
123
+ if message
124
+ else None
125
+ )
126
+
127
+ if ctx.interaction is None: # prefix command
128
+ if await _react(ctx, "✅") and message is None: # the reaction says it all
129
+ return
130
+ match message, silent_on_slash:
131
+ case None, True:
132
+ # remain silent, without "The application did not respond"
133
+ await ctx.defer(ephemeral=True)
134
+ if ctx.interaction:
135
+ await ctx.interaction.delete_original_response()
136
+ case None, False:
137
+ await _reply(ctx, "✅")
138
+ case msg, _:
139
+ if get_config().embeds:
140
+ await _reply(ctx, embed=Embed(colour=Colour.green(), description=msg))
141
+ else:
142
+ await _reply(ctx, f"✅ | {msg}")
143
+
144
+
145
+ async def require_guild(ctx: Context) -> Literal[1] | None:
146
+ if not ctx.guild:
147
+ await error(ctx, "NO_SERVER")
148
+ return 1
149
+ return None
150
+
151
+
152
+ async def require_normal(ctx: Context) -> Literal[1] | None:
153
+ if await require_guild(ctx):
154
+ return 1
155
+ if isinstance(
156
+ ctx.channel,
157
+ (
158
+ discord.GroupChannel,
159
+ discord.Thread,
160
+ discord.DMChannel,
161
+ discord.PartialMessageable,
162
+ ),
163
+ ):
164
+ await error(ctx, "UNSUPPORTED_CHANNEL")
165
+ return 1
166
+ return None
167
+
168
+
169
+ async def get_role(ctx: Context, role_id: int) -> Role | Literal[1] | None:
170
+ if await require_guild(ctx):
171
+ return 1
172
+ assert ctx.guild
173
+ if ctx.guild.get_role(role_id):
174
+ return ctx.guild.get_role(role_id)
175
+ return discord.utils.get(await ctx.guild.fetch_roles(), id=role_id)