Dough Git

commit

Make draws per guild id, not per bot

commit
de90770cf2d8bea229be962a585eaafdaa53779d
author
Clove Twilight <[email protected]>
date
2026-10-01 02:49

diff --git a/commands/cogs/fun/eightball.py b/commands/cogs/fun/eightball.py
index 0aeb2d7..5e584ea 100644
--- a/commands/cogs/fun/eightball.py
+++ b/commands/cogs/fun/eightball.py
@@ -1,7 +1,6 @@
 import discord
 from discord import app_commands
 from discord.ext import commands
-import random
 from sandrone import mood
 from utils import components
 
@@ -31,6 +30,8 @@ responses = [
     "Hah?! How should I know that? Figure it out on your own for once.",
 ]
 
+responses_bag = mood.ShuffleBag("eightball", responses)
+
 
 class EightBall(commands.Cog):
     def __init__(self, bot: commands.Bot) -> None:
@@ -51,7 +52,10 @@ class EightBall(commands.Cog):
         view = components.panel(
             fields=[
                 ("You asked", question),
-                ("Sandrone says", random.choice(mood.ShuffleBag(responses))),
+                (
+                    "Sandrone says",
+                    responses_bag.draw(interaction.guild_id),
+                ),
             ],
             footer="Sandrone",
         )
diff --git a/commands/cogs/fun/incidents.py b/commands/cogs/fun/incidents.py
index 7764f7e..566441f 100644
--- a/commands/cogs/fun/incidents.py
+++ b/commands/cogs/fun/incidents.py
@@ -94,7 +94,7 @@ class Incidents(commands.Cog):
         try:
             await channel.send(
                 view=components.panel(
-                    body=mood.randomIncident(),
+                    body=mood.randomIncident(channel.guild.id),
                     color=INCIDENT_COLOR,
                 )
             )
diff --git a/data/shuffle.example.jp b/data/shuffle.example.jp
new file mode 100644
index 0000000..3c393ae
--- /dev/null
+++ b/data/shuffle.example.jp
@@ -0,0 +1,17 @@
+# Per-guild shuffle bags, written by sandrone/mood.py's ShuffleBag. Each bag
+# hands out every line once before repeating, and keeps its state here so a
+# restart doesn't reset it and you can see exactly what's left to draw.
+#
+# Section names are guild IDs; [dm] holds draws made outside a guild. For each
+# bag (incident, sassy, eightball) there are two keys:
+#
+#   <bag>_remaining   lines still to come; the next draw is the LAST one
+#   <bag>_last        the line drawn most recently
+#
+# The bot rewrites this file, so comments survive only in this example copy.
+
+version: 1
+
+[1234567890]
+incident_remaining: ["The puppet has discovered doors.", "The puppet found the vents. Nobody tell it where they lead."]
+incident_last: "The puppet has escaped the workshop."
diff --git a/sandrone/mood.py b/sandrone/mood.py
index 7574d57..78acf0e 100644
--- a/sandrone/mood.py
+++ b/sandrone/mood.py
@@ -2,30 +2,55 @@ import discord
 from discord import app_commands
 import random
 from sandrone import config
-from utils import components
+from utils import components, jp_storage
 
 SASSY_CHANCE = 5
 
+bagDb = jp_storage.database("shuffle", version=1)
+
+# Where draws outside a guild (DMs) keep their bag.
+noGuildSection = "dm"
+
 
 class ShuffleBag:
-    """Hands out every item once, in random order, before any repeat."""
+    """Hands out every item once, in random order, before any repeat.
 
-    def __init__(self, items: list[str]) -> None:
+    Each guild gets its own bag, kept in data/shuffle.jp so it survives
+    restarts and can be read back when something looks off.
+    """
+
+    def __init__(self, name: str, items: list[str]) -> None:
+        self.name = name
         self.items = items
-        self.remaining: list[str] = []
-        self.last: str | None = None
 
-    def draw(self) -> str:
-        if not self.remaining:
-            self.remaining = random.sample(self.items, len(self.items))
+    def _scope(self, guildId: int | None) -> jp_storage.Scope:
+        if guildId is None:
+            return bagDb.section(noGuildSection)
+        return bagDb.guild(guildId)
+
+    def draw(self, guildId: int | None) -> str:
+        scope = self._scope(guildId)
+        remainingField = scope.key(f"{self.name}_remaining")
+        lastField = scope.key(f"{self.name}_last")
+
+        # Drop anything edited out of the list since the bag was filled,
+        # so a reworded line can't come back in its old form.
+        known = set(self.items)
+        remaining = [
+            item for item in remainingField.list() if item in known
+        ]
+        last = lastField.read()
+
+        if not remaining:
+            remaining = random.sample(self.items, len(self.items))
             # Don't repeat the last line straight across a refill.
-            if len(self.remaining) > 1 and self.remaining[-1] == self.last:
-                self.remaining[0], self.remaining[-1] = (
-                    self.remaining[-1],
-                    self.remaining[0],
-                )
-        self.last = self.remaining.pop()
-        return self.last
+            if len(remaining) > 1 and remaining[-1] == last:
+                remaining[0], remaining[-1] = remaining[-1], remaining[0]
+
+        drawn = remaining.pop()
+        remainingField.write(remaining)
+        lastField.write(drawn)
+        return drawn
 
 
 sassy_replies = [
@@ -43,7 +68,7 @@ sassy_replies = [
 ]
 
 
-sassy_bag = ShuffleBag(sassy_replies)
+sassy_bag = ShuffleBag("sassy", sassy_replies)
 
 
 class SassyDenial(app_commands.CheckFailure):
@@ -58,7 +83,7 @@ async def _sassyCheck(interaction: discord.Interaction) -> bool:
         view=components.panel(
             body=(
                 "<:sandrone_refuses:1546669792595939468> "
-                f"{sassy_bag.draw()}"
+                f"{sassy_bag.draw(interaction.guild_id)}"
             ),
             color=discord.Color.gold(),
         )
@@ -228,8 +253,8 @@ incident_replies = [
 ]
 
 
-incident_bag = ShuffleBag(incident_replies)
+incident_bag = ShuffleBag("incident", incident_replies)
 
 
-def randomIncident() -> str:
-    return incident_bag.draw()
+def randomIncident(guildId: int | None) -> str:
+    return incident_bag.draw(guildId)
diff --git a/tests/test_shuffle.py b/tests/test_shuffle.py
new file mode 100644
index 0000000..831df71
--- /dev/null
+++ b/tests/test_shuffle.py
@@ -0,0 +1,56 @@
+import pytest
+from sandrone import mood
+
+
[email protected](autouse=True)
+def store(tmp_path):
+    mood.bagDb.path = tmp_path / "shuffle.jp"
+    mood.bagDb.reload()
+    return mood.bagDb
+
+
+items = ["a", "b", "c", "d"]
+
+
+def test_every_item_comes_out_once_before_any_repeat() -> None:
+    bag = mood.ShuffleBag("test", items)
+    assert sorted(bag.draw(1) for _ in items) == items
+
+
+def test_each_guild_has_its_own_bag() -> None:
+    bag = mood.ShuffleBag("test", items)
+    first = [bag.draw(1) for _ in range(2)]
+    # Guild 2 drawing in between must not eat into guild 1's bag.
+    other = [bag.draw(2) for _ in items]
+    rest = [bag.draw(1) for _ in range(2)]
+    assert sorted(first + rest) == items
+    assert sorted(other) == items
+
+
+def test_no_repeat_straight_across_a_refill() -> None:
+    bag = mood.ShuffleBag("test", items)
+    previous = None
+    for _ in range(200):
+        drawn = bag.draw(1)
+        assert drawn != previous
+        previous = drawn
+
+
+def test_the_bag_survives_a_reload(store) -> None:
+    bag = mood.ShuffleBag("test", items)
+    first = [bag.draw(1) for _ in range(2)]
+    store.save()
+    store.reload()
+    rest = [bag.draw(1) for _ in range(2)]
+    assert sorted(first + rest) == items
+
+
+def test_lines_edited_out_are_dropped_from_the_bag() -> None:
+    mood.ShuffleBag("test", items).draw(1)
+    bag = mood.ShuffleBag("test", ["a", "z"])
+    assert {bag.draw(1) for _ in range(2)} == {"a", "z"}
+
+
+def test_dms_share_one_bag() -> None:
+    bag = mood.ShuffleBag("test", items)
+    assert sorted(bag.draw(None) for _ in items) == items
diff --git a/uv.lock b/uv.lock
index 42d16a1..080944c 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1716,7 +1716,7 @@ wheels = [
 
 [[package]]
 name = "sandrone"
-version = "2.5.0"
+version = "2.6.0"
 source = { virtual = "." }
 dependencies = [
     { name = "aiohttp" },