init redbot and add core logic

This commit is contained in:
Ziad Arafat committed 2025-08-11 05:54:47 -06:00
1 parent 282fa81986
commit 4cffd703cb
11 files changed
+1393

No files matched your search

+1
View File
@@ -0,0 +1 @@
3.11
+5
View File
@@ -0,0 +1,5 @@
from .doge_alignment import MyCog
async def setup(bot):
await bot.add_cog(MyCog(bot))
+14
View File
@@ -0,0 +1,14 @@
from redbot.core import commands
class MyCog(commands.Cog):
"""My custom cog."""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def mycom(self, ctx):
"""This does stuff!"""
# Your code will go here
await ctx.send("I can do stuff!")
View File
Whitespace-only changes.
+136
View File
@@ -0,0 +1,136 @@
[project]
name = "doge-cogs"
version = "0.1.0"
description = "Redbot cogs for dogebot"
readme = "README.md"
authors = [
{ name = "Ziad Arafat", email = "anonymous0programmer@gmail.com" }
]
requires-python = ">=3.11"
dependencies = [
"pyyaml>=6.0.2",
"red-discordbot>=3.5.20",
]
[build-system]
requires = ["uv_build>=0.7.13,<0.8"]
build-backend = "uv_build"
[tool.ruff]
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]
# Same as Black.
line-length = 80
indent-width = 8
# Assume Python 3.13
target-version = "py313"
[tool.ruff.lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = [
"E2",
"E3",
"E4",
"E5",
"E7",
"E9",
"F",
"FAST",
"ANN",
"ASYNC",
"S",
"BLE",
"FBT",
"B",
"A",
# "COM",
"C4",
"DTZ",
"EM",
"FIX",
"INT",
"ISC",
"ICN",
"LOG",
"G",
"PIE",
"RET",
"SIM",
"TID",
"TC",
"ARG",
"PTH",
"I",
"C90",
"N",
"PERF",
"D",
"UP",
"TRY",
]
ignore = []
# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []
# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
[tool.ruff.format]
# Like Black, use double quotes for strings.
quote-style = "double"
# Like Black, indent with spaces, rather than tabs.
indent-style = "space"
# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false
# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"
# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = false
# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"
+5
View File
@@ -0,0 +1,5 @@
users:
'111222333':
alignment: Chaotic Good
display_name: EpicUser
avatar_url: https://cdn.discordapp.com/avatars/111222333/avatar.png
+2
View File
@@ -0,0 +1,2 @@
def hello() -> str:
return "Hello from doge-cogs!"
View File
Whitespace-only changes.
+115
View File
@@ -0,0 +1,115 @@
from __future__ import annotations
from io import BytesIO, StringIO
from pathlib import Path
from typing import Literal, TypedDict
import yaml
# Define all possible alignments (classic 3x3 chart)
AlignmentName = Literal[
"Lawful Good",
"Neutral Good",
"Chaotic Good",
"Lawful Neutral",
"True Neutral",
"Chaotic Neutral",
"Lawful Evil",
"Neutral Evil",
"Chaotic Evil",
]
# User entry in YAML
class UserAlignment(TypedDict):
alignment: AlignmentName
display_name: str
avatar_url: str | None
class AlignmentChart(TypedDict):
"""Whole server alignment chart."""
users: dict[str, UserAlignment] # key: user_id as string
def parse_alignment_chart(data: BytesIO) -> AlignmentChart:
"""Parse YAML bytes into a Python dict."""
data.seek(0)
text = data.read().decode("utf-8") or ""
loaded = yaml.safe_load(text)
if not loaded:
return {"users": {}}
if "users" not in loaded:
loaded["users"] = {}
return loaded # type: ignore
def serialize_alignment_chart(chart: AlignmentChart) -> BytesIO:
"""Convert Python dict into YAML BytesIO."""
text_buf = StringIO()
yaml.safe_dump(chart, text_buf, sort_keys=False)
bytes_buf = BytesIO(text_buf.getvalue().encode("utf-8"))
bytes_buf.seek(0)
return bytes_buf
def set_user_alignment(
chart: AlignmentChart,
user_id: str,
alignment: AlignmentName,
display_name: str,
avatar_url: str | None = None,
) -> AlignmentChart:
"""Return a new chart with updated alignment for a user."""
new_chart = {"users": dict(chart["users"])}
new_chart["users"][user_id] = {
"alignment": alignment,
"display_name": display_name,
"avatar_url": avatar_url,
}
return new_chart # type: ignore
def remove_user_alignment(chart: AlignmentChart, user_id: str) -> AlignmentChart:
"""Return a new chart with a user removed."""
new_chart = {"users": dict(chart["users"])}
new_chart["users"].pop(user_id, None)
return new_chart # type: ignore
def load_yaml_file(path: Path) -> BytesIO:
"""Load YAML file from disk into BytesIO. Creates empty if missing."""
if not path.exists():
return BytesIO()
return BytesIO(path.read_bytes())
def save_yaml_file(path: Path, data: BytesIO) -> None:
"""Write YAML BytesIO back to disk."""
path.write_bytes(data.getvalue())
if __name__ == "__main__":
file_path = Path("server_12345.yaml")
# Load from disk
raw_data = load_yaml_file(file_path)
# Parse
chart = parse_alignment_chart(raw_data)
# Modify (pure)
updated_chart = set_user_alignment(
chart,
user_id="111222333",
alignment="Chaotic Good",
display_name="EpicUser",
avatar_url="https://cdn.discordapp.com/avatars/111222333/avatar.png",
)
print(updated_chart, chart, raw_data)
# Serialize (pure)
new_bytes = serialize_alignment_chart(updated_chart)
# Save (impure)
save_yaml_file(file_path, new_bytes)
+79
View File
@@ -0,0 +1,79 @@
import tempfile
import unittest
from io import BytesIO
from pathlib import Path
from playground.alignment import ( # replace with actual module filename
AlignmentChart,
load_yaml_file,
parse_alignment_chart,
remove_user_alignment,
save_yaml_file,
serialize_alignment_chart,
set_user_alignment,
)
class TestAlignmentChart(unittest.TestCase):
def test_parse_empty_yaml(self):
buf = BytesIO()
chart = parse_alignment_chart(buf)
self.assertEqual(chart, {"users": {}})
def test_set_user_alignment(self):
chart: AlignmentChart = {"users": {}}
updated = set_user_alignment(
chart,
user_id="123",
alignment="Lawful Good",
display_name="Tester",
avatar_url=None,
)
self.assertIn("123", updated["users"])
self.assertEqual(
updated["users"]["123"]["alignment"], "Lawful Good"
)
self.assertEqual(
updated["users"]["123"]["display_name"], "Tester"
)
self.assertEqual(chart, {"users": {}}) # original unchanged
def test_remove_user_alignment(self):
chart: AlignmentChart = {
"users": {
"123": {
"alignment": "Lawful Good",
"display_name": "Tester",
"avatar_url": None,
}
}
}
updated = remove_user_alignment(chart, "123")
self.assertNotIn("123", updated["users"])
self.assertIn("123", chart["users"]) # original unchanged
def test_serialization_round_trip(self):
chart: AlignmentChart = {"users": {}}
buf = serialize_alignment_chart(chart)
parsed = parse_alignment_chart(buf)
self.assertEqual(chart, parsed)
def test_load_and_save_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
path = Path(tmpdir) / "test.yaml"
# Save initial
chart: AlignmentChart = {"users": {}}
buf = serialize_alignment_chart(chart)
save_yaml_file(path, buf)
self.assertTrue(path.exists())
# Load again
loaded_buf = load_yaml_file(path)
parsed = parse_alignment_chart(loaded_buf)
self.assertEqual(parsed, {"users": {}})
def main():
unittest.main()
if __name__ == "__main__":
unittest.main()
Generated
+1036
View File
File diff suppressed because it is too large. Load diff