From 2a3911360574c4138693c6ecde5f93f2645130d6 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 27 Nov 2026 17:50:11 +0000 Subject: [PATCH 1/2] =?UTF-8?q?feat(actions):=20/hug,=20/kiss,=20/slap?= =?UTF-8?q?=E2=80=A6=20anime=20action=20GIFs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fifteen commands (hug, kiss, slap, lick, pat, cuddle, poke, bite, bonk, punch, kick, tickle, highfive, handhold, feed) post an anime GIF of the caller doing the action to someone, built from one table in core/action_gifs.py. - GIFs: nekos.best first (names the anime), then otakugifs.xyz (the only one with lick); only those hosts are posted. Every GIF fetched is remembered (50 per action) and reused when both APIs are down; with none, the action goes out as text. nekos.best needs a User-Agent with a contact: the bot's name and invite link, or ACTIONS_USER_AGENT. - A Retribuir/Revidar/Devolver button only the target can press, once. - Counts per pair ("Ana já abraçou Bruno 5 vezes") in data/actions.db. - Doing an action to the bot gets an answer in character through the chat engine (ChatEngine.answer_action), costing one turn of the person's budget. - send_action_gif tool in the chat profile: the bot does actions itself, at most once per answer. - Per-channel `actions` setting, shared cooldown, target pinged (ACTIONS_PING_TARGET), self-hugs come from the bot, /help groups them. Co-Authored-By: Claude Opus 5.5 --- .env.example | 10 + README.md | 36 ++++ SETUP.md | 3 + cogs/actions.py | 317 ++++++++++++++++++++++++++++++ cogs/commands.py | 14 ++ config.py | 16 ++ core/action_gifs.py | 345 ++++++++++++++++++++++++++++++++ core/chat_engine.py | 49 +++++ core/profiles.py | 1 + core/settings.py | 4 + main.py | 1 + tests/test_actions.py | 445 ++++++++++++++++++++++++++++++++++++++++++ 12 files changed, 1241 insertions(+) create mode 100644 cogs/actions.py create mode 100644 core/action_gifs.py create mode 100644 tests/test_actions.py diff --git a/.env.example b/.env.example index 5fcf0de..6348625 100644 --- a/.env.example +++ b/.env.example @@ -130,6 +130,16 @@ TAVILY_API_KEY= # --- Server Wrapped (/wrapped, server_wrapped tool, automatic recaps) --- # WRAPPED_ENABLED=true # WRAPPED_HOUR=10 # Brasília hour automatic recaps go out (Mondays weekly / the 1st monthly; turn on with /config servidor) +# --- Action GIFs (/hug, /kiss, /slap…: an anime GIF of someone doing it to someone) --- +# ACTIONS_ENABLED=true +# ACTIONS_DB_PATH=data/actions.db +# ACTIONS_PING_TARGET=true # notify the person on the receiving end +# ACTIONS_COOLDOWN_SECONDS=5 # between two actions of one person +# ACTIONS_BOT_REPLY=true # doing an action to the bot gets an answer in character (one chat turn) +# ACTIONS_TOOL_ENABLED=true # send_action_gif: the bot does actions itself when asked or when it fits +# nekos.best refuses requests without "AppName (contact)": an email, site, repository or bot invite link. +# Empty = the bot's name and its invite link. +# ACTIONS_USER_AGENT=QuillBot (https://github.com/you/your-fork) # --- Voice calls (/voz entrar | sair: real-time voice conversation in voice channels) --- # Speech-to-speech with Qwen-Audio realtime (Alibaba Cloud Model Studio). Needs libopus on the host. # Servers also opt in: /config servidor opcao:Conversa por voz valor:sim diff --git a/README.md b/README.md index 3ae7173..35c7384 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,7 @@ Built with [discord.py](https://discordpy.readthedocs.io/) + RAG (Retrieval-Augm | **Channel Summaries** | `/resumo` and natural-language "o que perdi?" — map-reduce summaries of a channel or thread over any period, with jump links and permission checks | | **Monitors** | Standing triggers (channels, authors, mentions of a user, a content regex) that call the bot on matching messages; it answers like a mention, knows a monitor sent it, and may stay silent. Managed with `/monitor` or by asking the bot | | **Voice Calls** | `/voz entrar`: the bot joins your voice channel and talks in real time (speech-to-speech with Qwen-Audio realtime) — hears everyone in the call, stops when talked over, optionally writes the conversation in the call's chat. Off unless configured, and each server opts in | +| **Action GIFs** | `/hug`, `/kiss`, `/slap`, `/lick` and 11 more: an anime GIF of you doing it to someone, who can return it with a button. Done to the bot, it answers in character; asked ("dá um abraço no Bruno"), it does them itself. Counts per pair ("Ana já abraçou Bruno 5 vezes") | | **Persistent Memory** | The bot remembers: atomic facts about the server and its members, auto-injected into every conversation, with inline LLM writes, pinning, dedupe, full audit history and admin control. Each memory records who said it — a fact about someone told by someone else is shown as a report ("segundo Fulano") | All AI responses are in **Brazilian Portuguese**. @@ -228,6 +229,24 @@ A recap of the server over a period (`semana` = 7 days, default; `mes`; `ano`; o - **Data:** messages from the history index; reactions from a `reactions` table recorded live since this version (no backfill), also queryable with `sql_history` - Set `WRAPPED_ENABLED=false` to remove the command, the tool and the automatic posts +#### `/hug`, `/kiss`, `/slap`… — Action GIFs +`/ usuario:@Pessoa` posts an anime GIF of you doing the action to that person (`cogs/actions.py`, `core/action_gifs.py`): `🤗 **Ana** abraçou @Bruno!`, the GIF in an embed, and a footer with the count for that pair and the anime it's from. + +| Kind | Commands | Button | +|---|---|---| +| Affection | `/hug`, `/kiss`, `/pat`, `/cuddle`, `/highfive`, `/handhold`, `/feed` | Retribuir | +| Playful | `/lick`, `/poke`, `/bite`, `/bonk`, `/tickle` | Devolver | +| Rough | `/slap`, `/punch`, `/kick` | Revidar | + +- **Doing it back:** the button under the GIF works for its target only, once, for 10 minutes; it posts the same action the other way ("… de volta!"), without a button of its own +- **GIFs:** [nekos.best](https://nekos.best) first (it also names the anime), then [otakugifs.xyz](https://otakugifs.xyz) (the only one with `lick`); only GIFs on those hosts are posted. Each GIF fetched is remembered (50 per action, `ACTIONS_DB_PATH`), so when both APIs are down an earlier one is reused; with none, the action goes out as text. nekos.best refuses requests without a User-Agent naming the app and a contact: by default the bot's name and invite link, or `ACTIONS_USER_AGENT` +- **Doing it to the bot:** after the GIF, the bot answers in character, like a mention — a few words, a reaction on the GIF, doing it back with `send_action_gif`, or nothing. It costs the person one turn of their `CHAT_USER_BUDGET` (over it, the GIF stands alone), and replying to the answer continues the conversation. Not in channels where `respond` is `off`; `ACTIONS_BOT_REPLY=false` turns it off +- **The bot doing it:** the `send_action_gif` tool (chat profile) — when asked ("dá um abraço no Bruno", "bate nele") or when it fits its personality, at most once per answer; the GIF goes out before the answer, with a button for the person to do it back. `ACTIONS_TOOL_ENABLED=false` removes it +- **Yourself:** affection actions come from the bot instead ("Ninguém merece fazer isso sozinho: **QuillBot** abraçou @Ana!"); the others are refused +- **Pings:** the target is notified (`ACTIONS_PING_TARGET=false` for none); bots never are. Other bots can be targets, without a button +- **Limits:** one action per person every `ACTIONS_COOLDOWN_SECONDS` (all commands together); off per channel or server with `/config … actions não` +- `/help` lists them on one line; `ACTIONS_ENABLED=false` removes the commands and the tool + #### `/config` — Server and channel settings *(Manage Server)* | Subcommand | Description | |---|---| @@ -243,6 +262,7 @@ A recap of the server over a period (`semana` = 7 days, default; `mes`; `ano`; o | `threads` | channel | `auto`, `always`, `never` | | `reply_style` | channel | `auto`, `plain`, `embed` (default `CHAT_REPLY_STYLE`) | | `log_detection` | channel | react to log links, `.log`/`.txt` files and Spark links | +| `actions` | channel | `/hug`, `/slap`… and the bot's own action GIFs (default on) | | `instructions` | channel | text the model follows in that channel ("seja direto e técnico", "aqui é papo livre") | | `aliases` | server | extra names the bot answers to, comma-separated | | `wrapped`, `wrapped_channel` | server | automatic Wrapped: `off`/`weekly`/`monthly` and where | @@ -458,6 +478,7 @@ QuillBot/ │ ├── discord_text.py # Mentions/pings, identity block, canonical message lines, splitting │ ├── chat_threads.py # When conversations move into threads, the open_thread tool, bot-thread detection │ ├── message_media.py # Stickers, GIFs, custom emojis, reactions, the add_reaction tool +│ ├── action_gifs.py # Action GIFs: the actions, GIF APIs with fallbacks, counts, wording │ ├── image_store.py # Persisted, re-encoded images for vision │ ├── tavily_tools.py # Tavily web_search / web_extract │ ├── local_inference.py# Single-thread executor for local models @@ -473,6 +494,7 @@ QuillBot/ │ ├── persona.py # /persona, the persona_update tool, change log with Revert │ ├── wrapped.py # /wrapped, server_wrapped tool, automatic weekly/monthly recaps │ ├── voice.py # /voz entrar | sair — real-time voice calls +│ ├── actions.py # /hug, /kiss, /slap…, the return button, send_action_gif, the bot answering actions │ ├── docs_rag.py # Docs RAG — indexing, search, reranking, /reindex, search_docs/search_plugins tools │ ├── history_rag.py # Server-wide history RAG — backfill, live ingestion, reactions, history tools, Wrapped stats │ ├── log_analyzer.py # Passive log detection, pattern matching, /analyze, file upload to mclo.gs @@ -493,6 +515,7 @@ QuillBot/ ├── settings.db # /config settings ├── persona.db # Personality sections + history ├── conversations.db # Conversations (handles, triggers, episode state) + ├── actions.db # Action counts per pair, recent GIF URLs ├── lore.db # Legacy lore encyclopedia (kept as migration source) └── history/ # Per-guild history stores ``` @@ -706,6 +729,18 @@ cp .env.example .env # if available, otherwise create .env manually | `WRAPPED_ENABLED` | `true` | `/wrapped`, the `server_wrapped` tool and automatic recaps | | `WRAPPED_HOUR` | `10` | Brasília hour automatic recaps are posted (Mondays / the 1st) | +### Action GIFs + +| Variable | Default | Description | +|---|---|---| +| `ACTIONS_ENABLED` | `true` | `/hug`, `/kiss`, `/slap`… and the `send_action_gif` tool | +| `ACTIONS_DB_PATH` | `data/actions.db` | Counts per pair and recent GIF URLs | +| `ACTIONS_PING_TARGET` | `true` | Notify the person on the receiving end | +| `ACTIONS_COOLDOWN_SECONDS` | `5` | Between two actions of one person (all commands together) | +| `ACTIONS_BOT_REPLY` | `true` | Doing an action to the bot gets an answer in character (one chat turn) | +| `ACTIONS_TOOL_ENABLED` | `true` | The bot can do actions itself (`send_action_gif`) | +| `ACTIONS_USER_AGENT` | bot name + invite link | User-Agent for the GIF APIs. nekos.best asks for `AppName (contact)` — an email, site, repository or bot invite — and refuses requests without one | + ### Voice Calls `/voz` exists only when `VOICE_ENABLED=true`, both `VOICE_API_KEY` and `VOICE_REALTIME_URL` are set, and libopus is installed (the startup log says which one is missing). Servers then opt in with the `voice` setting. @@ -800,6 +835,7 @@ ruff check . # lint (rules configured in pyproject.toml) | File | Covers | |---|---| +| `test_actions.py` | Action GIFs: providers in order and fallbacks (recent GIF, then text), refused hosts, counts, wording, the return button (target only, once, back the other way), pings, cooldown and self-actions, the bot answering actions done to it (and returns of its own), the `send_action_gif` tool, the engine's answer starting a conversation | | `test_api_logger.py` | Request logging for aiohttp/httpx/httpx2, redaction, body capture, inbound interactions (runs in its own process) | | `test_attribution.py` | Author tags on every question, speaker changes marked in the tag (verbatim and compact replay), the conversation block naming who speaks now, byte-identical replay of per-turn blocks, memory block labels and person-memory rules | | `test_channel_context_images.py` | Images from automatically fetched channel context | diff --git a/SETUP.md b/SETUP.md index 89a0162..7541b82 100644 --- a/SETUP.md +++ b/SETUP.md @@ -216,6 +216,7 @@ Every message goes through one router (`core/router.py`): passive observers (his | `/resumo` | Summarize what happened in a channel | Yes | | `/wrapped` | Server recap: who talked most, channels, emojis… | Optional** | | `/config` | Server and channel settings (Manage Server) | No | +| `/hug`, `/kiss`, `/slap`… | Anime GIF of you doing it to someone (15 actions) | No*** | | `/persona` | The bot's personality on this server (editing needs Manage Server) | No | | `/memory`, `/monitor`, `/schedule` | Memories, standing triggers, scheduled tasks | Yes | | `/analyze` | Analyze a server log with AI (mclo.gs, pastebin, or file) | Yes | @@ -231,6 +232,7 @@ Every message goes through one router (`core/router.py`): passive observers (his *`/docs` with a query delegates to RAG search if available, otherwise shows a link. **The numbers come from the history index; the AI only writes the intro. +***The GIFs come from nekos.best and otakugifs.xyz; the AI only answers when the action is done to the bot. --- @@ -261,6 +263,7 @@ QuillBot/ │ ├── server_config.py# /config │ ├── persona.py # /persona and the bot's personality per server │ ├── wrapped.py # /wrapped and automatic recaps +│ ├── actions.py # /hug, /kiss, /slap… action GIFs │ ├── docs_rag.py # RAG pipeline: indexing, search, /reindex, search_docs tool │ ├── log_analyzer.py # Log analysis: pattern matching, /analyze, AI analysis │ ├── plugins.py # External API commands: /plugin, /status, /changelog diff --git a/cogs/actions.py b/cogs/actions.py new file mode 100644 index 0000000..8861a26 --- /dev/null +++ b/cogs/actions.py @@ -0,0 +1,317 @@ +"""Action GIFs: ``/hug``, ``/kiss``, ``/slap``… and the bot doing them too. + +Each command posts an anime GIF of the caller doing the action to someone +(:mod:`core.action_gifs` has the actions, where GIFs come from, the counts and +the wording), with a Retribuir/Revidar button that only that person can press, +once. Doing an action to the bot gets an answer in character from the chat +engine (``ACTIONS_BOT_REPLY``), and the ``send_action_gif`` tool lets the bot +do them itself (``ACTIONS_TOOL_ENABLED``). A channel turns all of it off with +the ``actions`` setting (``/config``). +""" + +from __future__ import annotations + +import asyncio +import logging +import time +from collections.abc import Awaitable, Callable +from typing import Any + +import aiohttp +import discord +from cachetools import TTLCache +from discord import app_commands +from discord.ext import commands + +from config import ( + ACTIONS_BOT_REPLY, + ACTIONS_COOLDOWN_SECONDS, + ACTIONS_DB_PATH, + ACTIONS_ENABLED, + ACTIONS_PING_TARGET, + ACTIONS_TOOL_ENABLED, + ACTIONS_USER_AGENT, +) +from core import action_gifs +from core.action_gifs import ACTIONS, AFFECTION, Action, ActionStore, GifPicker +from core.tools import Tool, tool_schema +from core.turn import NO_REPLY_TOKEN + +logger = logging.getLogger(__name__) + +TOOL_NAME = 'send_action_gif' +# How long the Retribuir button stays up (a slash command's messages can't be edited after 15 min). +RETURN_SECONDS = 600 +_HTTP_TIMEOUT = aiohttp.ClientTimeout(total=4) + +Sender = Callable[..., Awaitable[Any]] + +SEND_ACTION_TOOL = tool_schema( + TOOL_NAME, + 'Manda no canal atual um GIF de anime de você fazendo uma ação com alguém, como os comandos /hug, ' + '/slap etc.: ' + ', '.join(f'{a.key} ({a.past})' for a in ACTIONS.values()) + '. Use quando pedirem ' + '("dá um abraço no Bruno", "bate nele") ou quando combinar com o momento e com a sua personalidade; ' + 'no máximo um por resposta. O GIF sai antes da sua resposta, que pode ser curta ou nenhuma.', + { + 'action': {'type': 'string', 'enum': list(ACTIONS), 'description': 'A ação.'}, + 'user': { + 'type': 'string', + 'description': 'Quem recebe: o author_id da pessoa (de preferência), <@id> ou o nome.', + }, + }, + ['action', 'user'], +) + + +def tool_status(args: dict, ctx: Any) -> str: + action = ACTIONS.get(str(args.get('action') or '')) + return f'{action.emoji} Mandando um GIF de {action.key}' if action else '🎞️ Mandando um GIF' + + +def followup(interaction: discord.Interaction) -> Sender: + """Sends a message as *interaction*'s answer and returns it.""" + async def send(**kwargs: Any) -> Any: + return await interaction.followup.send(wait=True, **kwargs) + return send + + +class ReturnView(discord.ui.View): + """The Retribuir/Revidar button under an action: only its target may press it, once.""" + + def __init__(self, cog: Actions, action: Action, *, actor: Any, target: Any): + super().__init__(timeout=RETURN_SECONDS) + self.cog = cog + self.action = action + self.actor = actor + self.target = target + self.message: Any = None + self.done = False + button: discord.ui.Button = discord.ui.Button( + label=action.return_label, emoji=action.emoji, style=discord.ButtonStyle.secondary, + ) + button.callback = self.pressed + self.add_item(button) + + async def pressed(self, interaction: discord.Interaction) -> None: + if interaction.user.id != self.target.id: + await interaction.response.send_message( + f'Só {self.target.display_name} pode {self.action.return_label.lower()}.', ephemeral=True, + ) + return + if self.done: + await interaction.response.send_message('Já foi.', ephemeral=True) + return + if not self.cog.enabled_in(interaction.guild, interaction.channel): + await interaction.response.send_message( + 'Os comandos de ação foram desligados neste canal.', ephemeral=True, + ) + return + self.done = True + self.stop() + await interaction.response.defer() + try: + await interaction.edit_original_response(view=None) + except discord.HTTPException: + logger.debug('could not remove the return button', exc_info=True) + try: + await self.cog.perform( + self.action, actor=interaction.user, target=self.actor, guild=interaction.guild, + channel=interaction.channel, send=followup(interaction), returned=True, + ) + except discord.HTTPException: + logger.exception('[actions] could not send the return of %s', self.action.key) + + async def on_timeout(self) -> None: + if self.message is None or self.done: + return + try: + await self.message.edit(view=None) + except discord.HTTPException: + logger.debug('could not remove an expired return button', exc_info=True) + + +class Actions(commands.Cog): + """/hug, /kiss, /slap… (one command per action in core.action_gifs.ACTIONS).""" + + def __init__(self, bot: commands.Bot): + self.bot = bot + self.services = bot.services + self.store = ActionStore(ACTIONS_DB_PATH) + self.session: aiohttp.ClientSession | None = None + self.gifs: GifPicker | None = None + self._last_use: TTLCache = TTLCache(maxsize=4096, ttl=max(ACTIONS_COOLDOWN_SECONDS, 1.0)) + self._commands: list[app_commands.Command] = [] + + async def cog_load(self) -> None: + await asyncio.to_thread(self.store.load) + for action in ACTIONS.values(): + command = self.make_command(action) + self.bot.tree.add_command(command) + self._commands.append(command) + if ACTIONS_TOOL_ENABLED: + self.services.tools.register(Tool(TOOL_NAME, SEND_ACTION_TOOL, self.run_tool, tool_status)) + + async def cog_unload(self) -> None: + for command in self._commands: + self.bot.tree.remove_command(command.name) + self._commands.clear() + self.services.tools.unregister(TOOL_NAME) + if self.session is not None: + await self.session.close() + + def user_agent(self) -> str: + """How the GIF APIs see the bot: ``ACTIONS_USER_AGENT``, or its name and invite link.""" + if ACTIONS_USER_AGENT: + return ACTIONS_USER_AGENT + user = getattr(self.bot, 'user', None) + name = ''.join((getattr(user, 'name', None) or 'QuillBot').split()) + app_id = getattr(self.bot, 'application_id', None) or getattr(user, 'id', None) + return f'{name} (https://discord.com/oauth2/authorize?client_id={app_id})' if app_id else name + + def picker(self) -> GifPicker: + """The GIF picker, made on first use: the bot only knows its own id once logged in.""" + if self.gifs is None: + self.session = aiohttp.ClientSession(timeout=_HTTP_TIMEOUT, headers={'User-Agent': self.user_agent()}) + self.gifs = GifPicker(self.session, self.store) + return self.gifs + + def make_command(self, action: Action) -> app_commands.Command: + """The slash command for *action* (``/hug usuario:@Bruno``).""" + async def callback(interaction: discord.Interaction, usuario: discord.Member) -> None: + await self.use(interaction, action, usuario) + + callback = app_commands.describe(usuario='Quem recebe')(callback) + callback = app_commands.guild_only()(callback) + return app_commands.Command( + name=action.key, description=f'{action.emoji} {action.description}', + callback=callback, extras={'action': action.key}, + ) + + # ------------------------------------------------------------------ + + def is_me(self, person: Any) -> bool: + me = getattr(self.bot, 'user', None) + return me is not None and getattr(person, 'id', None) == me.id + + def enabled_in(self, guild: Any, channel: Any) -> bool: + return guild is not None and bool(self.services.settings.get(guild.id, channel, 'actions')) + + def _wait(self, guild_id: int, user_id: int) -> float: + last = self._last_use.get((guild_id, user_id)) + return 0.0 if last is None else max(0.0, ACTIONS_COOLDOWN_SECONDS - (time.monotonic() - last)) + + @staticmethod + def _mentions(target: Any) -> discord.AllowedMentions: + if ACTIONS_PING_TARGET and not getattr(target, 'bot', False): + return discord.AllowedMentions(everyone=False, roles=False, users=[target], replied_user=False) + return discord.AllowedMentions.none() + + async def use(self, interaction: discord.Interaction, action: Action, target: Any) -> None: + """Someone ran ``/ usuario:``.""" + guild, channel, user = interaction.guild, interaction.channel, interaction.user + if not self.enabled_in(guild, channel): + await interaction.response.send_message('Os comandos de ação estão desligados neste canal.', ephemeral=True) + return + wait = self._wait(guild.id, user.id) + if wait > 0: + await interaction.response.send_message(f'⏳ Aguarde {wait:.0f}s antes de outra ação.', ephemeral=True) + return + actor, note = user, '' + if target.id == user.id: + if action.kind != AFFECTION: + await interaction.response.send_message('Em você mesmo? Escolha outra pessoa 😅', ephemeral=True) + return + actor, note = guild.me or self.bot.user, 'Ninguém merece fazer isso sozinho' + self._last_use[(guild.id, user.id)] = time.monotonic() + await interaction.response.defer() + try: + await self.perform( + action, actor=actor, target=target, guild=guild, channel=channel, + send=followup(interaction), note=note, + ) + except discord.HTTPException: + logger.exception('[actions] could not send /%s', action.key) + try: + await interaction.followup.send('Não consegui mandar a ação aqui.', ephemeral=True) + except discord.HTTPException: + pass + + async def perform( + self, action: Action, *, actor: Any, target: Any, guild: Any, channel: Any, send: Sender, + note: str = '', returned: bool = False, + ) -> Any: + """Post *actor* doing *action* to *target* with *send*; returns the message. + + Under it goes a button for *target* to do it back, unless this already + is the return or *target* is a bot. Done to this bot, the bot then + answers in character. + """ + gif = await self.picker().pick(action) + count = await asyncio.to_thread(self.store.bump, guild.id, actor.id, target.id, action.key) + content, embed = action_gifs.render(action, actor, target, gif, count, note=note, returned=returned) + kwargs: dict[str, Any] = {'content': content, 'allowed_mentions': self._mentions(target)} + if embed is not None: + kwargs['embed'] = embed + view = None + if not returned and not getattr(target, 'bot', False): + view = kwargs['view'] = ReturnView(self, action, actor=actor, target=target) + sent = await send(**kwargs) + if view is not None: + view.message = sent + if self.is_me(target): + await self.answer_in_character(sent, action, actor=actor, guild=guild, channel=channel, returned=returned) + return sent + + async def answer_in_character( + self, sent: Any, action: Action, *, actor: Any, guild: Any, channel: Any, returned: bool, + ) -> None: + """The bot's own reaction to *actor* doing *action* to it (``ACTIONS_BOT_REPLY``).""" + chat = self.services.chat + if not ACTIONS_BOT_REPLY or chat is None or not self.services.llm.available: + return + if self.services.settings.get(guild.id, channel, 'respond') == 'off': + return # the bot doesn't converse in this channel + # A message from the channel (not the interaction's webhook): it knows its guild and jump URL. + anchor = channel.get_partial_message(sent.id) if hasattr(channel, 'get_partial_message') else sent + question = action_gifs.action_question( + action, actor, returned=returned, can_send=TOOL_NAME in self.services.tools, + ) + try: + await chat.answer_action(anchor, actor=actor, guild=guild, channel=channel, question=question) + except Exception: + logger.exception('[actions] answering /%s in character failed', action.key) + + async def run_tool(self, ctx: Any, args: dict) -> str: + """``send_action_gif``: the bot does an action to someone, in the turn's channel.""" + guild, channel = ctx.guild, ctx.channel + if guild is None or channel is None or not hasattr(channel, 'send'): + return 'GIFs de ação só funcionam num canal de servidor.' + if not self.enabled_in(guild, channel): + return 'Os GIFs de ação estão desligados neste canal (/config); não mande.' + if ctx.state.get(TOOL_NAME): + return 'Você já mandou um GIF de ação nesta resposta; não mande outro.' + action = ACTIONS.get(str(args.get('action') or '').strip().lower()) + if action is None: + return f'Ação desconhecida: {args.get("action")}. Use uma de: {", ".join(ACTIONS)}.' + target = action_gifs.find_member(guild, args.get('user')) + if target is None: + return f'Não encontrei "{args.get("user")}" neste servidor: use o author_id da pessoa (ou find_user).' + if self.is_me(target): + return 'Você não pode fazer uma ação em si mesmo.' + me = guild.me or self.bot.user + try: + sent = await self.perform(action, actor=me, target=target, guild=guild, channel=channel, send=channel.send) + except discord.HTTPException as e: + return f'Não foi possível mandar o GIF: {e.text or e}' + ctx.state[TOOL_NAME] = True + return ( + f'GIF enviado no canal: {me.display_name} {action.past} {target.display_name} (msg_id={sent.id}). ' + f'Ele já aparece no chat: não o descreva nem repita a ação; responda curto ou {NO_REPLY_TOKEN}.' + ) + + +async def setup(bot: commands.Bot): + if not ACTIONS_ENABLED: + logger.info('Action GIFs disabled via ACTIONS_ENABLED=false') + return + await bot.add_cog(Actions(bot)) diff --git a/cogs/commands.py b/cogs/commands.py index 18b26b3..531579d 100644 --- a/cogs/commands.py +++ b/cogs/commands.py @@ -135,7 +135,11 @@ async def help_command(self, interaction: discord.Interaction): # Dynamically list all registered slash commands cmds = self.bot.tree.get_commands() cmd_lines = [] + # Action GIF commands (/hug, /slap…) share one line in their own field. + actions = sorted(c.name for c in cmds if getattr(c, 'extras', {}).get('action')) for cmd in sorted(cmds, key=lambda c: c.name): + if getattr(cmd, 'extras', {}).get('action'): + continue params = '' if hasattr(cmd, 'parameters') and cmd.parameters: param_parts = [] @@ -148,6 +152,16 @@ async def help_command(self, interaction: discord.Interaction): cmd_lines.append(f'**/{cmd.name}**{params} — {cmd.description}') embed.description = '\n'.join(cmd_lines) + if actions: + embed.add_field( + name="🎭 Ações", + value=( + ' '.join(f'/{name}' for name in actions) + + "\nUm GIF de anime de você fazendo isso com alguém (`usuario`), que pode retribuir. " + "Pode fazer comigo também — e eu posso fazer com você." + ), + inline=False, + ) embed.add_field( name="💬 Conversa", diff --git a/config.py b/config.py index 19ee812..af05d02 100644 --- a/config.py +++ b/config.py @@ -311,6 +311,22 @@ def _is_openrouter_url(url: str) -> bool: # Hour (Brasília time) automatic recaps are posted: Mondays (weekly) or the 1st (monthly). WRAPPED_HOUR: Final[int] = int(os.getenv('WRAPPED_HOUR', '10')) +# --- Action GIFs (/hug, /kiss, /slap…: an anime GIF of someone doing it to someone) --- +ACTIONS_ENABLED: Final[bool] = _flag('ACTIONS_ENABLED') +# Action counts per pair and the GIF URLs seen lately (reused when the GIF APIs are down). +ACTIONS_DB_PATH: Final[str] = os.getenv('ACTIONS_DB_PATH', 'data/actions.db') +# Whether the person on the receiving end gets a notification. +ACTIONS_PING_TARGET: Final[bool] = _flag('ACTIONS_PING_TARGET') +# Seconds between two action commands of one person. +ACTIONS_COOLDOWN_SECONDS: Final[float] = max(0.0, float(os.getenv('ACTIONS_COOLDOWN_SECONDS', '5'))) +# Doing an action to the bot gets an answer in character (one chat turn of that person's budget). +ACTIONS_BOT_REPLY: Final[bool] = _flag('ACTIONS_BOT_REPLY') +# The send_action_gif tool: the bot hugs, slaps… people itself when asked or when it fits. +ACTIONS_TOOL_ENABLED: Final[bool] = _flag('ACTIONS_TOOL_ENABLED') +# User-Agent for the GIF APIs. nekos.best refuses requests without "AppName (contact)" +# (an email, site, repository or bot invite link); empty uses the bot's name and invite link. +ACTIONS_USER_AGENT: Final[str] = os.getenv('ACTIONS_USER_AGENT', '').strip() + # --- Scheduler (cron / one-shot delayed tasks) --- SCHEDULER_ENABLED: Final[bool] = os.getenv('SCHEDULER_ENABLED', 'true').strip().lower() in ('1', 'true', 'yes') SCHEDULER_DB_PATH: Final[str] = os.getenv('SCHEDULER_DB_PATH', 'data/scheduler.db') diff --git a/core/action_gifs.py b/core/action_gifs.py new file mode 100644 index 0000000..79a12f5 --- /dev/null +++ b/core/action_gifs.py @@ -0,0 +1,345 @@ +"""Action GIFs: an anime GIF of one person hugging, kissing, slapping… another. + +Used by ``/hug``, ``/kiss``, ``/slap`` and the rest (``cogs/actions.py``), by +their Retribuir/Revidar buttons and by the ``send_action_gif`` tool, where the +bot does the action itself. + +GIFs come from free anime GIF APIs, tried in each action's order: nekos.best +(which also names the anime) and otakugifs.xyz. Every GIF fetched is +remembered per action (``RECENT_GIFS`` of them), so when the APIs are down an +earlier one is reused; with none at all, the action goes out as text. How many +times each person did each action to each other person is counted in the +same SQLite file. +""" + +from __future__ import annotations + +import asyncio +import datetime +import logging +import os +import random +import re +import sqlite3 +import threading +import time +import unicodedata +from dataclasses import dataclass +from typing import Any +from urllib.parse import urlparse + +import aiohttp +import discord + +from core.turn import NO_REPLY_TOKEN + +logger = logging.getLogger(__name__) + +NEKOS = 'nekos.best' +OTAKU = 'otakugifs' + +# GIFs kept per action for when the APIs are down. +RECENT_GIFS = 50 +# Only GIFs hosted by the APIs themselves are posted: an embed shows whatever URL it gets. +_ALLOWED_HOSTS = ('nekos.best', 'otakugifs.xyz') +_NEKOS_URL = 'https://nekos.best/api/v2/{category}' +_OTAKU_URL = 'https://api.otakugifs.xyz/gif' + +AFFECTION = 'carinho' +PLAYFUL = 'brincadeira' +ROUGH = 'agressao' +_COLORS = {AFFECTION: 0xF47FFF, PLAYFUL: 0xF1C40F, ROUGH: 0xE74C3C} +_RETURN_LABELS = {AFFECTION: 'Retribuir', PLAYFUL: 'Devolver', ROUGH: 'Revidar'} + + +@dataclass(frozen=True) +class Action: + """One action: its command, how it reads and where its GIFs come from.""" + + key: str # command name (/hug) and the tool's value + emoji: str + past: str # "**Ana** abraçou @Bruno", "Ana já abraçou Bruno 3 vezes" + description: str # the slash command's description + kind: str # AFFECTION, PLAYFUL or ROUGH + sources: tuple[tuple[str, str], ...] # (provider, category), tried in order + + @property + def return_label(self) -> str: + """The button that does it back: Retribuir a hug, Revidar a slap.""" + return _RETURN_LABELS[self.kind] + + @property + def color(self) -> int: + return _COLORS[self.kind] + + +def _both(category: str) -> tuple[tuple[str, str], ...]: + return ((NEKOS, category), (OTAKU, category)) + + +ACTIONS: dict[str, Action] = {a.key: a for a in ( + Action('hug', '🤗', 'abraçou', 'Dê um abraço em alguém', AFFECTION, _both('hug')), + Action('kiss', '😘', 'beijou', 'Dê um beijo em alguém', AFFECTION, _both('kiss')), + Action('slap', '🖐️', 'deu um tapa em', 'Dê um tapa em alguém', ROUGH, _both('slap')), + Action('lick', '👅', 'lambeu', 'Lamba alguém', PLAYFUL, ((OTAKU, 'lick'),)), + Action('pat', '🫶', 'fez cafuné em', 'Faça cafuné em alguém', AFFECTION, _both('pat')), + Action('cuddle', '🥰', 'se aconchegou em', 'Aconchegue-se em alguém', AFFECTION, _both('cuddle')), + Action('poke', '👉', 'cutucou', 'Cutuque alguém', PLAYFUL, _both('poke')), + Action('bite', '😬', 'mordeu', 'Morda alguém', PLAYFUL, _both('bite')), + Action('bonk', '🔨', 'deu um bonk em', 'Dê um bonk em alguém', PLAYFUL, ((NEKOS, 'bonk'),)), + Action('punch', '👊', 'deu um soco em', 'Dê um soco em alguém', ROUGH, _both('punch')), + Action('kick', '🦵', 'chutou', 'Chute alguém', ROUGH, ((NEKOS, 'kick'),)), + Action('tickle', '🤭', 'fez cócegas em', 'Faça cócegas em alguém', PLAYFUL, _both('tickle')), + Action('highfive', '🙌', 'bateu um toca aqui com', 'Bata um toca aqui com alguém', AFFECTION, ((NEKOS, 'highfive'),)), + Action('handhold', '🤝', 'segurou a mão de', 'Segure a mão de alguém', AFFECTION, _both('handhold')), + Action('feed', '🍙', 'deu comida para', 'Dê comida para alguém', AFFECTION, ((NEKOS, 'feed'),)), +)} + + +# --------------------------------------------------------------------------- +# GIF providers +# --------------------------------------------------------------------------- + +@dataclass(frozen=True) +class Gif: + url: str + anime: str = '' + + +def allowed_url(url: Any) -> bool: + """Whether *url* is an https link on one of the APIs' own hosts.""" + if not isinstance(url, str): + return False + parsed = urlparse(url) + host = (parsed.hostname or '').lower() + return parsed.scheme == 'https' and any(host == h or host.endswith('.' + h) for h in _ALLOWED_HOSTS) + + +class ProviderError(Exception): + """A GIF API answered with an error status.""" + + +async def _nekos(session: aiohttp.ClientSession, category: str) -> Gif | None: + async with session.get(_NEKOS_URL.format(category=category)) as resp: + if resp.status != 200: + raise ProviderError(f'HTTP {resp.status}') + data = await resp.json(content_type=None) + result = ((data or {}).get('results') or [{}])[0] or {} + url = result.get('url') + return Gif(url, str(result.get('anime_name') or '')) if allowed_url(url) else None + + +async def _otaku(session: aiohttp.ClientSession, category: str) -> Gif | None: + async with session.get(_OTAKU_URL, params={'reaction': category, 'format': 'gif'}) as resp: + if resp.status != 200: + raise ProviderError(f'HTTP {resp.status}') + data = await resp.json(content_type=None) + url = (data or {}).get('url') + return Gif(url) if allowed_url(url) else None + + +PROVIDERS = {NEKOS: _nekos, OTAKU: _otaku} + + +class GifPicker: + """A GIF for an action: each of its sources in order, then a recent one.""" + + def __init__(self, session: aiohttp.ClientSession, store: ActionStore): + self.session = session + self.store = store + + async def pick(self, action: Action) -> Gif | None: + for provider, category in action.sources: + try: + gif = await PROVIDERS[provider](self.session, category) + except Exception as e: # network, timeout, error status, bad JSON: try the next source + logger.warning('[actions] %s failed for %s: %r', provider, category, e) + continue + if gif is not None: + await asyncio.to_thread(self.store.remember_gif, action.key, gif) + return gif + logger.info('[actions] %s had no GIF for %s', provider, category) + gif = await asyncio.to_thread(self.store.recent_gif, action.key) + if gif is None: + logger.warning('[actions] no GIF for %s: sending it as text', action.key) + return gif + + +# --------------------------------------------------------------------------- +# Counts and recent GIFs +# --------------------------------------------------------------------------- + +class ActionStore: + """SQLite (``ACTIONS_DB_PATH``): action counts per pair and recent GIF URLs.""" + + def __init__(self, path: str, *, recent: int = RECENT_GIFS): + self.path = path + self.recent = recent + self._lock = threading.Lock() + + def _connect(self) -> sqlite3.Connection: + return sqlite3.connect(self.path, timeout=30) + + def load(self) -> None: + directory = os.path.dirname(self.path) + if directory: + os.makedirs(directory, exist_ok=True) + con = self._connect() + try: + con.execute(""" + CREATE TABLE IF NOT EXISTS action_counts ( + guild_id INTEGER NOT NULL, + actor_id INTEGER NOT NULL, + target_id INTEGER NOT NULL, + action TEXT NOT NULL, + count INTEGER NOT NULL, + last_at TEXT NOT NULL, + PRIMARY KEY (guild_id, actor_id, target_id, action) + )""") + con.execute(""" + CREATE TABLE IF NOT EXISTS action_gifs ( + action TEXT NOT NULL, + url TEXT NOT NULL, + anime TEXT NOT NULL DEFAULT '', + seen_at REAL NOT NULL, + PRIMARY KEY (action, url) + )""") + con.commit() + finally: + con.close() + + def bump(self, guild_id: int, actor_id: int, target_id: int, action: str) -> int: + """Count one more *action* from *actor_id* to *target_id*; returns the new count.""" + key = (int(guild_id), int(actor_id), int(target_id), action) + now = datetime.datetime.now(datetime.timezone.utc).isoformat() + with self._lock: + con = self._connect() + try: + con.execute( + 'INSERT INTO action_counts (guild_id, actor_id, target_id, action, count, last_at) ' + 'VALUES (?,?,?,?,1,?) ON CONFLICT (guild_id, actor_id, target_id, action) ' + 'DO UPDATE SET count = count + 1, last_at = excluded.last_at', + (*key, now), + ) + con.commit() + row = con.execute( + 'SELECT count FROM action_counts WHERE guild_id=? AND actor_id=? AND target_id=? AND action=?', key, + ).fetchone() + finally: + con.close() + return int(row[0]) if row else 1 + + def remember_gif(self, action: str, gif: Gif) -> None: + """Keep *gif* among *action*'s newest ``recent`` GIFs.""" + with self._lock: + con = self._connect() + try: + con.execute( + 'INSERT OR REPLACE INTO action_gifs (action, url, anime, seen_at) VALUES (?,?,?,?)', + (action, gif.url, gif.anime, time.time()), + ) + con.execute( + 'DELETE FROM action_gifs WHERE action=? AND url NOT IN ' + '(SELECT url FROM action_gifs WHERE action=? ORDER BY seen_at DESC LIMIT ?)', + (action, action, self.recent), + ) + con.commit() + finally: + con.close() + + def recent_gif(self, action: str) -> Gif | None: + """One of *action*'s remembered GIFs, at random.""" + con = self._connect() + try: + rows = con.execute('SELECT url, anime FROM action_gifs WHERE action=?', (action,)).fetchall() + finally: + con.close() + if not rows: + return None + url, anime = random.choice(rows) + return Gif(url, anime or '') + + +# --------------------------------------------------------------------------- +# How an action reads +# --------------------------------------------------------------------------- + +def _name(person: Any) -> str: + return str(getattr(person, 'display_name', None) or getattr(person, 'name', None) or person) + + +def count_text(action: Action, actor: Any, target: Any, count: int) -> str: + """"Ana já abraçou Bruno 3 vezes" (plain text: an embed footer or a subtext line).""" + if count <= 1: + return f'Primeira vez que {_name(actor)} {action.past} {_name(target)}' + return f'{_name(actor)} já {action.past} {_name(target)} {count} vezes' + + +def render( + action: Action, actor: Any, target: Any, gif: Gif | None, count: int, *, + note: str = '', returned: bool = False, +) -> tuple[str, discord.Embed | None]: + """The message: ``(content, embed)``; without a GIF, text only (``embed`` is ``None``). + + The content names the actor in bold and mentions the target, so the chat + (and the bot, reading the channel) sees who did what to whom. + """ + actor_name = discord.utils.escape_markdown(_name(actor)) + line = f'**{actor_name}** {action.past} {getattr(target, "mention", _name(target))}' + if returned: + line += ' de volta' + content = f'{action.emoji} {note}: {line}!' if note else f'{action.emoji} {line}!' + counted = count_text(action, actor, target, count) + if gif is None: + return f'{content}\n-# {counted}', None + embed = discord.Embed(color=action.color) + embed.set_image(url=gif.url) + embed.set_footer(text=f'{counted} · Anime: {gif.anime}' if gif.anime else counted) + return content, embed + + +def action_question(action: Action, actor: Any, *, returned: bool = False, can_send: bool = True) -> str: + """The turn the bot answers when someone does *action* to it (``/hug @bot``).""" + did = 'devolveu o que você fez com' if returned else 'usou' + ways = 'uma resposta curta, uma reação com `add_reaction`' + if can_send: + ways += ', devolver a ação com `send_action_gif`' + (' (ela já está devolvendo: não precisa)' if returned else '') + header = ( + f'[{_name(actor)} {did} /{action.key} em você — o GIF já está no canal. Reaja do seu jeito, ' + f'como alguém do chat reagiria: {ways}, ou nada ({NO_REPLY_TOKEN}).]' + ) + return f'{header}\n---\n*{action.past} você* {action.emoji}' + + +# --------------------------------------------------------------------------- +# Who the tool means +# --------------------------------------------------------------------------- + +_USER_REF_RE = re.compile(r'<@!?(\d+)>|(\d+)') + + +def _norm(text: str) -> str: + text = unicodedata.normalize('NFKD', text or '') + text = ''.join(c for c in text if not unicodedata.combining(c)) + return ' '.join(text.lower().split()) + + +def find_member(guild: Any, raw: Any) -> Any: + """The member *raw* names: an id, ``<@id>``, a username or a display name.""" + text = str(raw or '').strip() + if not text or guild is None: + return None + m = _USER_REF_RE.fullmatch(text) + if m: + member = guild.get_member(int(m.group(1) or m.group(2))) + if member is not None or m.group(1): + return member + name = text.lstrip('@') + member = guild.get_member_named(name) + if member is not None: + return member + wanted = _norm(name) + return next( + (m for m in getattr(guild, 'members', None) or [] if wanted in (_norm(m.display_name), _norm(m.name))), + None, + ) diff --git a/core/chat_engine.py b/core/chat_engine.py index 042c477..143f2bc 100644 --- a/core/chat_engine.py +++ b/core/chat_engine.py @@ -742,6 +742,55 @@ async def answer_monitor(self, message: Any, header: str) -> bool: ) return True + async def answer_action(self, message: Any, *, actor: Any, guild: Any, channel: Any, question: str) -> bool: + """Answer, in character, an action someone did to the bot (``/hug @bot``). + + *message* is the bot's own post of the action (the GIF): a reaction + goes on it and the answer replies to it; replying to the answer + continues the conversation. It costs *actor* a turn of their budget — + over it, the GIF stands alone. The model may stay silent (a reaction + can be the whole answer). Returns whether an answer was sent. + """ + if not self.budget.try_spend(actor.id, getattr(guild, 'id', None)): + logger.info('[actions] budget used up for user=%s; no answer to the action', actor.id) + return False + settings = self.settings_for(guild, channel) + created = getattr(message, 'created_at', None) or datetime.datetime.now(datetime.timezone.utc) + ctx = TurnContext( + bot=self.bot, profile=CHAT, question=question, user=actor, guild=guild, channel=channel, + created_at=created, message=message, window_before=message, + participant_ids={str(actor.id)}, origin=getattr(message, 'jump_url', None), + thread_blocker=chat_threads.ANSWERS_IN_PLACE, channel_settings=settings, + ) + try: + async with channel.typing(): + result = await run_turn(ctx) + except Exception: + logger.exception('[actions] answering the action %s failed', getattr(message, 'id', None)) + return False + if is_silent(result.answer): + return False + out = self._outgoing(result, CHAT, settings) + try: + sent = await deliver(out, guild=guild, reply_to=message, mention_author=False) + except discord.HTTPException: + logger.exception('[actions] could not send the answer to action %s', getattr(message, 'id', None)) + return False + if not sent: + return False + turn = make_turn( + question, result.answer, author=author_info(actor), ts=created.timestamp(), + message_id=message.id, channel_id=getattr(channel, 'id', None), + channel_name=getattr(channel, 'name', None), sources=result.sources, + user_message=result.user_message, trajectory=result.trajectory, + context_images=result.context_image_urls, reply_ids=[m.id for m in sent], + ) + turn['answered_ts'] = time.time() + await self._create( + sent, turn, user=actor, guild=guild, channel=channel, profile=CHAT, trigger_ids=[message.id], + ) + return True + async def run_task(self, prompt: str, *, guild: Any, channel: Any, owner: Any = None) -> list[Any]: """Run a scheduled task's prompt and post the answer in *channel*. diff --git a/core/profiles.py b/core/profiles.py index 78558a7..05b4b41 100644 --- a/core/profiles.py +++ b/core/profiles.py @@ -70,6 +70,7 @@ class Profile: 'server_wrapped', 'persona_update', 'add_reaction', + 'send_action_gif', 'open_thread', ), model=CHAT_MODEL, diff --git a/core/settings.py b/core/settings.py index 7fe8604..eb4e6b3 100644 --- a/core/settings.py +++ b/core/settings.py @@ -67,6 +67,10 @@ class Setting: 'log_detection', 'channel', 'bool', True, 'Detectar logs e Spark', 'Reage a links de log (mclo.gs, pastebin), arquivos .log/.txt e relatórios Spark.', ), + Setting( + 'actions', 'channel', 'bool', True, 'Comandos de ação (GIFs)', + '/hug, /kiss, /slap e outros GIFs de ação neste canal, também quando o bot faz a ação.', + ), Setting( 'instructions', 'channel', 'text', '', 'Instruções do canal', 'Orientações para o bot neste canal (ex.: "seja direto e técnico", "aqui é papo livre").', diff --git a/main.py b/main.py index ddbf4d7..b66487d 100644 --- a/main.py +++ b/main.py @@ -61,6 +61,7 @@ 'cogs.summary', 'cogs.wrapped', 'cogs.voice', + 'cogs.actions', ] diff --git a/tests/test_actions.py b/tests/test_actions.py new file mode 100644 index 0000000..0a98ea4 --- /dev/null +++ b/tests/test_actions.py @@ -0,0 +1,445 @@ +"""Action GIFs: /hug, /slap…, their providers and fallbacks, counts, the return button, +the bot answering actions done to it, and the send_action_gif tool.""" + +from types import SimpleNamespace as NS + +import discord + +from chat_fakes import ASKER, BOT_ID, OTHER, Guild, Message, TextChannel, make_engine, make_services +from cogs import actions as actions_mod +from core import action_gifs +from core.action_gifs import ACTIONS, ActionStore, Gif, GifPicker +from core.budget import Budget +from core.profiles import CHAT +from core.settings import SETTINGS, parse_value +from core.turn import TurnContext + +from helpers import check + +NEKOS_GIF = 'https://nekos.best/api/v2/hug/abc.gif' +OTAKU_GIF = 'https://cdn.otakugifs.xyz/gifs/lick/123.gif' +BOT_MEMBER = NS(id=BOT_ID, name='quillbot', display_name='QuillBot', bot=True, mention=f'<@{BOT_ID}>') +OTHER_BOT = NS(id=444, name='musica', display_name='Música', bot=True, mention='<@444>') + + +# --------------------------------------------------------------------------- +# Fakes +# --------------------------------------------------------------------------- + +class _Resp: + def __init__(self, status, data): + self.status = status + self.data = data + + async def __aenter__(self): + if isinstance(self.data, Exception): + raise self.data + return self + + async def __aexit__(self, *exc): + return False + + async def json(self, content_type=None): + return self.data + + +class FakeSession: + """``aiohttp.ClientSession.get`` answering per host: (status, json) or an exception.""" + + def __init__(self, **by_host): + self.by_host = by_host + self.calls = [] + + def get(self, url, params=None): + self.calls.append((url, params)) + host = 'otaku' if 'otakugifs' in url else 'nekos' + status, data = self.by_host.get(host, (500, None)) + return _Resp(status, data) + + +def nekos_ok(url=NEKOS_GIF, anime='Sword Art Online'): + return 200, {'results': [{'anime_name': anime, 'url': url}]} + + +def otaku_ok(url=OTAKU_GIF): + return 200, {'url': url} + + +class Sent: + def __init__(self, mid, kwargs): + self.id = mid + self.kwargs = kwargs + self.edits = [] + + async def edit(self, **kwargs): + self.edits.append(kwargs) + return self + + +class Sender: + def __init__(self): + self.sent = [] + + async def __call__(self, **kwargs): + msg = Sent(7000 + len(self.sent), kwargs) + self.sent.append(msg) + return msg + + +class FakeResponse: + def __init__(self): + self.messages = [] + self.deferred = False + + async def send_message(self, content=None, **kwargs): + self.messages.append((content, kwargs)) + + async def defer(self, **kwargs): + self.deferred = True + + +class FakeInteraction: + def __init__(self, guild, channel, user): + self.guild = guild + self.channel = channel + self.user = user + self.response = FakeResponse() + self.sender = Sender() + self.followup = NS(send=self._followup) + self.edited = [] + + async def _followup(self, content=None, *, wait=False, **kwargs): + if content is not None: + kwargs['content'] = content + return await self.sender(**kwargs) + + async def edit_original_response(self, **kwargs): + self.edited.append(kwargs) + + +class FakeChat: + def __init__(self): + self.calls = [] + + async def answer_action(self, message, **kwargs): + self.calls.append((message, kwargs)) + return True + + +class ActionChannel(TextChannel): + def get_partial_message(self, mid): + return NS(id=mid, channel=self, guild=self.guild) + + +def make_cog(tmp_path, *, session=None, chat=None): + services = make_services(tmp_path) + services.chat = chat + bot = NS(services=services, user=BOT_MEMBER, tree=None) + cog = actions_mod.Actions(bot) + cog.store = ActionStore(str(tmp_path / 'actions.db')) + cog.store.load() + cog.gifs = GifPicker(session or FakeSession(nekos=nekos_ok(), otaku=otaku_ok()), cog.store) + guild = Guild(members=[ASKER, OTHER, BOT_MEMBER, OTHER_BOT]) + guild.me = BOT_MEMBER + channel = ActionChannel(guild) + return cog, guild, channel + + +# --------------------------------------------------------------------------- +# Providers, fallbacks and the store +# --------------------------------------------------------------------------- + +async def test_gif_comes_from_the_first_source_that_answers(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + session = FakeSession(nekos=nekos_ok(), otaku=otaku_ok()) + gif = await GifPicker(session, store).pick(ACTIONS['hug']) + check('nekos.best first, with the anime', gif == Gif(NEKOS_GIF, 'Sword Art Online'), gif) + check('one request', len(session.calls) == 1, session.calls) + + session = FakeSession(nekos=(503, None), otaku=otaku_ok()) + gif = await GifPicker(session, store).pick(ACTIONS['hug']) + check('falls back to otakugifs', gif == Gif(OTAKU_GIF), gif) + check('asks otakugifs for that reaction as a GIF', session.calls[-1][1] == {'reaction': 'hug', 'format': 'gif'}, session.calls) + + +async def test_lick_only_asks_otakugifs(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + session = FakeSession(nekos=nekos_ok(), otaku=otaku_ok()) + gif = await GifPicker(session, store).pick(ACTIONS['lick']) + check('nekos.best has no lick', gif.url == OTAKU_GIF and all('otakugifs' in u for u, _ in session.calls), session.calls) + + +async def test_apis_down_reuse_a_recent_gif_then_text(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + down = FakeSession(nekos=(0, OSError('connection refused')), otaku=(0, TimeoutError())) + check('nothing seen yet: no GIF', await GifPicker(down, store).pick(ACTIONS['hug']) is None) + await GifPicker(FakeSession(nekos=nekos_ok()), store).pick(ACTIONS['hug']) + gif = await GifPicker(down, store).pick(ACTIONS['hug']) + check('the GIF seen before is reused', gif == Gif(NEKOS_GIF, 'Sword Art Online'), gif) + check('per action', await GifPicker(down, store).pick(ACTIONS['kiss']) is None) + + +async def test_gifs_from_other_hosts_are_refused(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + session = FakeSession(nekos=nekos_ok(url='https://evil.example/hug.gif'), otaku=otaku_ok(url='http://cdn.otakugifs.xyz/x.gif')) + check('no foreign host, no plain http', await GifPicker(session, store).pick(ACTIONS['hug']) is None) + check('allowed hosts', action_gifs.allowed_url(NEKOS_GIF) and action_gifs.allowed_url(OTAKU_GIF)) + check('look-alike host refused', not action_gifs.allowed_url('https://notnekos.best/x.gif')) + + +def test_store_counts_per_pair_and_keeps_recent_gifs(tmp_path): + store = ActionStore(str(tmp_path / 'a.db'), recent=3) + store.load() + check('first', store.bump(1, 222, 333, 'hug') == 1) + check('second', store.bump(1, 222, 333, 'hug') == 2) + check('other direction apart', store.bump(1, 333, 222, 'hug') == 1) + check('other action apart', store.bump(1, 222, 333, 'slap') == 1) + check('other server apart', store.bump(2, 222, 333, 'hug') == 1) + for i in range(5): + store.remember_gif('hug', Gif(f'https://nekos.best/{i}.gif')) + urls = {store.recent_gif('hug').url for _ in range(40)} + check('only the newest are kept', urls <= {f'https://nekos.best/{i}.gif' for i in (2, 3, 4)} and urls, urls) + + +# --------------------------------------------------------------------------- +# Wording +# --------------------------------------------------------------------------- + +def test_render_with_and_without_a_gif(): + hug = ACTIONS['hug'] + content, embed = action_gifs.render(hug, ASKER, OTHER, Gif(NEKOS_GIF, 'K-On!'), 3) + check('actor in bold, target mentioned', content == '🤗 **John** abraçou <@333>!', content) + check('GIF in the embed', embed.image.url == NEKOS_GIF) + check('count and anime in the footer', embed.footer.text == 'John já abraçou Ana 3 vezes · Anime: K-On!', embed.footer.text) + content, embed = action_gifs.render(ACTIONS['slap'], ASKER, OTHER, None, 1, returned=True) + check('text only when there is no GIF', embed is None and content == '🖐️ **John** deu um tapa em <@333> de volta!\n-# Primeira vez que John deu um tapa em Ana', content) + content, _ = action_gifs.render(hug, BOT_MEMBER, ASKER, None, 1, note='Ninguém merece fazer isso sozinho') + check('note first', content.startswith('🤗 Ninguém merece fazer isso sozinho: **QuillBot** abraçou <@222>!'), content) + sneaky = NS(id=5, display_name='*__x__*', name='x') + content, _ = action_gifs.render(hug, sneaky, OTHER, None, 1) + check('names cannot break the markdown', '\\*\\_\\_x\\_\\_\\*' in content, content) + + +def test_every_action_has_a_source_and_a_return_label(): + check('fifteen actions', len(ACTIONS) == 15, list(ACTIONS)) + for action in ACTIONS.values(): + check(f'{action.key} sources', action.sources and all(p in action_gifs.PROVIDERS for p, _ in action.sources)) + check('labels by kind', (ACTIONS['hug'].return_label, ACTIONS['slap'].return_label, ACTIONS['poke'].return_label) + == ('Retribuir', 'Revidar', 'Devolver')) + + +def test_find_member(): + guild = Guild(members=[ASKER, OTHER, NS(id=123456789012345678, name='joao', display_name='João Silva', bot=False)]) + check('by id', action_gifs.find_member(guild, '123456789012345678').name == 'joao') + check('by mention', action_gifs.find_member(guild, '<@!123456789012345678>').name == 'joao') + check('by @name', action_gifs.find_member(guild, '@ana') is OTHER) + check('accent and case insensitive', action_gifs.find_member(guild, 'joao silva').name == 'joao') + check('unknown', action_gifs.find_member(guild, 'ninguém') is None) + + +def test_question_for_the_bot(): + q = action_gifs.action_question(ACTIONS['slap'], ASKER) + check('says who did what', q.startswith('[John usou /slap em você') and 'send_action_gif' in q and '[NO_REPLY]' in q, q) + q = action_gifs.action_question(ACTIONS['hug'], ASKER, returned=True, can_send=False) + check('a return is said to be one', 'devolveu o que você fez com /hug' in q and 'send_action_gif' not in q, q) + + +def test_setting_and_profile(): + check('on by default', SETTINGS['actions'].default is True and SETTINGS['actions'].scope == 'channel') + check('sim/não', parse_value(SETTINGS['actions'], 'não') == 'false') + check('chat offers the tool', 'send_action_gif' in CHAT.tools) + + +# --------------------------------------------------------------------------- +# Commands, the return button and the bot answering +# --------------------------------------------------------------------------- + +async def test_user_agent(tmp_path, monkeypatch): + cog, _, _ = make_cog(tmp_path) + cog.bot.application_id = 1234 + check('bot name and invite link', cog.user_agent() == 'quillbot (https://discord.com/oauth2/authorize?client_id=1234)', cog.user_agent()) + monkeypatch.setattr(actions_mod, 'ACTIONS_USER_AGENT', 'Quill (dev@example.com)') + check('override', cog.user_agent() == 'Quill (dev@example.com)') + + +async def test_commands_are_built_from_the_table(tmp_path): + cog, _, _ = make_cog(tmp_path) + command = cog.make_command(ACTIONS['hug']) + check('name and description', command.name == 'hug' and command.description == '🤗 Dê um abraço em alguém') + check('one member option', [(p.name, p.type) for p in command.parameters] == [('usuario', discord.AppCommandOptionType.user)]) + check('servers only, marked as an action', command.guild_only and command.extras == {'action': 'hug'}) + + +async def test_slash_command_posts_the_gif_with_a_return_button(tmp_path, monkeypatch): + monkeypatch.setattr(actions_mod, 'ACTIONS_PING_TARGET', True) + cog, guild, channel = make_cog(tmp_path) + inter = FakeInteraction(guild, channel, ASKER) + await cog.use(inter, ACTIONS['hug'], OTHER) + check('deferred, then sent', inter.response.deferred and len(inter.sender.sent) == 1) + kwargs = inter.sender.sent[0].kwargs + check('content', kwargs['content'] == '🤗 **John** abraçou <@333>!', kwargs['content']) + check('gif', kwargs['embed'].image.url == NEKOS_GIF) + check('pings only the target', [u.id for u in kwargs['allowed_mentions'].users] == [333] and not kwargs['allowed_mentions'].everyone) + view = kwargs['view'] + check('return button', isinstance(view, actions_mod.ReturnView) and view.children[0].label == 'Retribuir') + check('the view knows its message', view.message is inter.sender.sent[0]) + + # Another person can't press it; the target can, once, and it goes back the other way. + stranger = FakeInteraction(guild, channel, NS(id=999, display_name='Zé')) + await view.pressed(stranger) + check('only the target', stranger.response.messages[0][0] == 'Só Ana pode retribuir.' and stranger.response.messages[0][1]['ephemeral']) + press = FakeInteraction(guild, channel, OTHER) + await view.pressed(press) + back = press.sender.sent[0].kwargs + check('done back', back['content'] == '🤗 **Ana** abraçou <@222> de volta!', back['content']) + check('a return has no button', 'view' not in back) + check('button removed', press.edited == [{'view': None}]) + again = FakeInteraction(guild, channel, OTHER) + await view.pressed(again) + check('only once', again.response.messages[0][0] == 'Já foi.' and not again.sender.sent) + check('counted both ways', cog.store.bump(1, 222, 333, 'hug') == 2 and cog.store.bump(1, 333, 222, 'hug') == 2) + + +async def test_no_ping_setting(tmp_path, monkeypatch): + monkeypatch.setattr(actions_mod, 'ACTIONS_PING_TARGET', False) + cog, guild, channel = make_cog(tmp_path) + send = Sender() + await cog.perform(ACTIONS['pat'], actor=ASKER, target=OTHER, guild=guild, channel=channel, send=send) + check('nobody pinged', send.sent[0].kwargs['allowed_mentions'].users is False, send.sent[0].kwargs['allowed_mentions']) + + +async def test_refusals_cooldown_and_self_actions(tmp_path, monkeypatch): + monkeypatch.setattr(actions_mod, 'ACTIONS_COOLDOWN_SECONDS', 60) + cog, guild, channel = make_cog(tmp_path) + + inter = FakeInteraction(guild, channel, ASKER) + await cog.use(inter, ACTIONS['slap'], ASKER) + check('no slapping yourself', inter.response.messages[0][1].get('ephemeral') and not inter.sender.sent, inter.response.messages) + + inter = FakeInteraction(guild, channel, ASKER) + await cog.use(inter, ACTIONS['hug'], ASKER) + content = inter.sender.sent[0].kwargs['content'] + check('a hug to yourself comes from the bot', content == '🤗 Ninguém merece fazer isso sozinho: **QuillBot** abraçou <@222>!', content) + + inter = FakeInteraction(guild, channel, ASKER) + await cog.use(inter, ACTIONS['kiss'], OTHER) + check('cooldown shared by every action', inter.response.messages and inter.response.messages[0][0].startswith('⏳'), inter.response.messages) + + cog.services.settings.write(1, 0, 'actions', 'false') + inter = FakeInteraction(guild, channel, OTHER) + await cog.use(inter, ACTIONS['kiss'], ASKER) + check('off in the channel', 'desligados' in inter.response.messages[0][0] and not inter.sender.sent) + + +async def test_text_only_when_no_gif_at_all(tmp_path): + cog, guild, channel = make_cog(tmp_path, session=FakeSession(nekos=(0, OSError()), otaku=(0, OSError()))) + send = Sender() + await cog.perform(ACTIONS['bonk'], actor=ASKER, target=OTHER, guild=guild, channel=channel, send=send) + kwargs = send.sent[0].kwargs + check('still sent, without an embed', 'embed' not in kwargs and kwargs['content'].startswith('🔨 **John** deu um bonk em <@333>!'), kwargs) + + +async def test_doing_it_to_the_bot_gets_an_answer(tmp_path, monkeypatch): + monkeypatch.setattr(actions_mod, 'ACTIONS_BOT_REPLY', True) + chat = FakeChat() + cog, guild, channel = make_cog(tmp_path, chat=chat) + send = Sender() + await cog.perform(ACTIONS['slap'], actor=ASKER, target=BOT_MEMBER, guild=guild, channel=channel, send=send) + check('no button for a bot', 'view' not in send.sent[0].kwargs) + check('no ping for a bot', send.sent[0].kwargs['allowed_mentions'].users is False) + check('the chat engine answers it', len(chat.calls) == 1, chat.calls) + anchor, kwargs = chat.calls[0] + check('anchored on the GIF, in the channel', anchor.id == send.sent[0].id and kwargs['channel'] is channel and kwargs['actor'] is ASKER) + check('question says what happened', kwargs['question'].startswith('[John usou /slap em você'), kwargs['question']) + + send = Sender() + await cog.perform(ACTIONS['slap'], actor=ASKER, target=OTHER_BOT, guild=guild, channel=channel, send=send) + check('other bots: GIF only', len(chat.calls) == 1 and 'view' not in send.sent[0].kwargs) + + cog.services.settings.write(1, 0, 'respond', 'off') + await cog.perform(ACTIONS['hug'], actor=ASKER, target=BOT_MEMBER, guild=guild, channel=channel, send=Sender()) + check('not where the bot does not converse', len(chat.calls) == 1) + + monkeypatch.setattr(actions_mod, 'ACTIONS_BOT_REPLY', False) + cog.services.settings.write(1, 0, 'respond', None) + await cog.perform(ACTIONS['hug'], actor=ASKER, target=BOT_MEMBER, guild=guild, channel=channel, send=Sender()) + check('ACTIONS_BOT_REPLY=false', len(chat.calls) == 1) + + +async def test_returning_the_bots_action_tells_it_so(tmp_path, monkeypatch): + monkeypatch.setattr(actions_mod, 'ACTIONS_BOT_REPLY', True) + chat = FakeChat() + cog, guild, channel = make_cog(tmp_path, chat=chat) + send = Sender() + await cog.perform(ACTIONS['hug'], actor=BOT_MEMBER, target=ASKER, guild=guild, channel=channel, send=send) + press = FakeInteraction(guild, channel, ASKER) + await send.sent[0].kwargs['view'].pressed(press) + check('hugged back', press.sender.sent[0].kwargs['content'] == '🤗 **John** abraçou <@900> de volta!', press.sender.sent[0].kwargs['content']) + check('the bot hears it as a return', 'devolveu o que você fez com /hug' in chat.calls[0][1]['question']) + + +# --------------------------------------------------------------------------- +# The send_action_gif tool +# --------------------------------------------------------------------------- + +def tool_ctx(guild, channel): + return TurnContext(bot=None, profile=CHAT, question='dá um abraço na Ana', user=ASKER, guild=guild, channel=channel) + + +async def test_tool_sends_once_per_answer(tmp_path): + cog, guild, channel = make_cog(tmp_path) + ctx = tool_ctx(guild, channel) + result = await cog.run_tool(ctx, {'action': 'hug', 'user': '333'}) + check('posted in the channel by the bot', channel.sent and channel.sent[0].kwargs['content'] == '🤗 **QuillBot** abraçou <@333>!', channel.sent) + check('the target can hug back', isinstance(channel.sent[0].kwargs['view'], actions_mod.ReturnView)) + check('tells the model not to describe it', result.startswith('GIF enviado no canal: QuillBot abraçou Ana') and '[NO_REPLY]' in result, result) + again = await cog.run_tool(ctx, {'action': 'slap', 'user': '333'}) + check('once per answer', 'já mandou' in again and len(channel.sent) == 1, again) + + +async def test_tool_refusals(tmp_path): + cog, guild, channel = make_cog(tmp_path) + check('unknown action', 'Ação desconhecida' in await cog.run_tool(tool_ctx(guild, channel), {'action': 'dance', 'user': '333'})) + check('unknown person', 'Não encontrei' in await cog.run_tool(tool_ctx(guild, channel), {'action': 'hug', 'user': 'ninguém'})) + check('not itself', 'si mesmo' in await cog.run_tool(tool_ctx(guild, channel), {'action': 'hug', 'user': str(BOT_ID)})) + cog.services.settings.write(1, 0, 'actions', 'false') + check('off in the channel', 'desligados' in await cog.run_tool(tool_ctx(guild, channel), {'action': 'hug', 'user': '333'})) + check('nothing sent', not channel.sent) + + +# --------------------------------------------------------------------------- +# The chat engine's answer to an action +# --------------------------------------------------------------------------- + +async def test_engine_answers_the_action_and_starts_a_conversation(tmp_path, monkeypatch): + engine = make_engine(tmp_path, monkeypatch, answers=('Ai! Por que isso? 😭',)) + guild = Guild() + channel = TextChannel(guild) + gif_message = Message(800, channel, '🖐️ **John** deu um tapa em <@900>!', author=BOT_MEMBER) + question = action_gifs.action_question(ACTIONS['slap'], ASKER) + answered = await engine.answer_action(gif_message, actor=ASKER, guild=guild, channel=channel, question=question) + check('answered', answered and gif_message.replies and gif_message.replies[0]['content'] == 'Ai! Por que isso? 😭', gif_message.replies) + ctx = engine.turns[0] + check('the turn is the actor\'s', ctx.user is ASKER and ctx.question == question and ctx.message is gif_message) + check('reactions default to the GIF', ctx.message.id == 800) + conv = await engine.store.get_by_handle(801) + check('replying continues it', conv and conv['data']['turns'][0]['author']['id'] == '222', conv) + + +async def test_engine_action_silent_or_over_budget(tmp_path, monkeypatch): + engine = make_engine(tmp_path, monkeypatch, answers=('[NO_REPLY]',)) + guild = Guild() + channel = TextChannel(guild) + gif_message = Message(800, channel, '🤗', author=BOT_MEMBER) + check('may stay silent', not await engine.answer_action(gif_message, actor=ASKER, guild=guild, channel=channel, question='q')) + check('nothing sent', not gif_message.replies) + + (tmp_path / 'b').mkdir() + engine = make_engine(tmp_path / 'b', monkeypatch, budget=Budget(user_limit=1, user_window=60, guild_limit=10, guild_window=60)) + engine.budget.try_spend(ASKER.id, guild.id) + check('over budget: no turn', not await engine.answer_action(gif_message, actor=ASKER, guild=guild, channel=channel, question='q')) + check('no turn run', not engine.turns) From cc08c252f9871ae34e18126984e35559aecc91f9 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 27 Nov 2026 18:36:06 +0000 Subject: [PATCH 2/2] feat(actions): 12 more actions, keep every GIF, upload stored copies - New actions: peck, blowkiss (airkiss fallback), nuzzle, lappillow, handshake, brofist, wave, wink, stare, cheers, pinch, yeet (27 total). - Every distinct GIF URL the APIs return is kept (the 50-per-action cap is gone). - Each GIF's file is downloaded once in the background into ACTIONS_GIFS_DIR, named by its SHA-256 so identical GIFs are stored once; two downloads at a time, only real GIFs up to 10 MiB, retried the next time the GIF is served if a download failed. - When no API answers, a stored file is uploaded as an attachment and shown in the embed (attachment://.gif); then a stored URL; then text. ACTIONS_STORE_GIFS=false keeps URLs only. - .dockerignore keeps data/ out of the build context and the image. Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 3 + .env.example | 2 + README.md | 22 ++-- SETUP.md | 2 +- cogs/actions.py | 11 +- config.py | 5 +- core/action_gifs.py | 240 ++++++++++++++++++++++++++++++++++++------ tests/test_actions.py | 146 ++++++++++++++++++++++--- 8 files changed, 375 insertions(+), 56 deletions(-) create mode 100644 .dockerignore diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4b56b2a --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +# Runtime data (databases, vectors, stored action GIFs) is mounted by docker-compose +# (./data:/app/data); keeping it out of the build context and the image. +data/ diff --git a/.env.example b/.env.example index 6348625..6137c17 100644 --- a/.env.example +++ b/.env.example @@ -133,6 +133,8 @@ TAVILY_API_KEY= # --- Action GIFs (/hug, /kiss, /slap…: an anime GIF of someone doing it to someone) --- # ACTIONS_ENABLED=true # ACTIONS_DB_PATH=data/actions.db +# ACTIONS_STORE_GIFS=true # keep every distinct GIF; uploaded as an attachment when no GIF API answers +# ACTIONS_GIFS_DIR=data/action_gifs # ACTIONS_PING_TARGET=true # notify the person on the receiving end # ACTIONS_COOLDOWN_SECONDS=5 # between two actions of one person # ACTIONS_BOT_REPLY=true # doing an action to the bot gets an answer in character (one chat turn) diff --git a/README.md b/README.md index 35c7384..a5331f3 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Built with [discord.py](https://discordpy.readthedocs.io/) + RAG (Retrieval-Augm | **Channel Summaries** | `/resumo` and natural-language "o que perdi?" — map-reduce summaries of a channel or thread over any period, with jump links and permission checks | | **Monitors** | Standing triggers (channels, authors, mentions of a user, a content regex) that call the bot on matching messages; it answers like a mention, knows a monitor sent it, and may stay silent. Managed with `/monitor` or by asking the bot | | **Voice Calls** | `/voz entrar`: the bot joins your voice channel and talks in real time (speech-to-speech with Qwen-Audio realtime) — hears everyone in the call, stops when talked over, optionally writes the conversation in the call's chat. Off unless configured, and each server opts in | -| **Action GIFs** | `/hug`, `/kiss`, `/slap`, `/lick` and 11 more: an anime GIF of you doing it to someone, who can return it with a button. Done to the bot, it answers in character; asked ("dá um abraço no Bruno"), it does them itself. Counts per pair ("Ana já abraçou Bruno 5 vezes") | +| **Action GIFs** | `/hug`, `/kiss`, `/slap`, `/pat` and 23 more: an anime GIF of you doing it to someone, who can return it with a button. Done to the bot, it answers in character; asked ("dá um abraço no Bruno"), it does them itself. Counts per pair ("Ana já abraçou Bruno 5 vezes") | | **Persistent Memory** | The bot remembers: atomic facts about the server and its members, auto-injected into every conversation, with inline LLM writes, pinning, dedupe, full audit history and admin control. Each memory records who said it — a fact about someone told by someone else is shown as a report ("segundo Fulano") | All AI responses are in **Brazilian Portuguese**. @@ -234,12 +234,13 @@ A recap of the server over a period (`semana` = 7 days, default; `mes`; `ano`; o | Kind | Commands | Button | |---|---|---| -| Affection | `/hug`, `/kiss`, `/pat`, `/cuddle`, `/highfive`, `/handhold`, `/feed` | Retribuir | -| Playful | `/lick`, `/poke`, `/bite`, `/bonk`, `/tickle` | Devolver | -| Rough | `/slap`, `/punch`, `/kick` | Revidar | +| Affection | `/hug`, `/kiss`, `/peck`, `/blowkiss`, `/pat` (headpat), `/cuddle`, `/nuzzle`, `/lappillow`, `/handhold`, `/handshake`, `/highfive`, `/brofist`, `/wave`, `/cheers`, `/feed` | Retribuir | +| Playful | `/wink`, `/stare`, `/lick`, `/poke`, `/pinch`, `/tickle`, `/bite`, `/bonk` | Devolver | +| Rough | `/slap`, `/punch`, `/kick`, `/yeet` | Revidar | - **Doing it back:** the button under the GIF works for its target only, once, for 10 minutes; it posts the same action the other way ("… de volta!"), without a button of its own -- **GIFs:** [nekos.best](https://nekos.best) first (it also names the anime), then [otakugifs.xyz](https://otakugifs.xyz) (the only one with `lick`); only GIFs on those hosts are posted. Each GIF fetched is remembered (50 per action, `ACTIONS_DB_PATH`), so when both APIs are down an earlier one is reused; with none, the action goes out as text. nekos.best refuses requests without a User-Agent naming the app and a contact: by default the bot's name and invite link, or `ACTIONS_USER_AGENT` +- **GIFs:** each action's sources in order — [nekos.best](https://nekos.best) (it also names the anime) and [otakugifs.xyz](https://otakugifs.xyz) (`blowkiss` falls back to its `airkiss`; `lick`, `nuzzle`, `brofist`, `cheers` and `pinch` exist only there; `peck`, `lappillow`, `handshake`, `highfive`, `feed`, `bonk`, `kick` and `yeet` only on nekos.best). Only GIFs on those hosts are posted. nekos.best refuses requests without a User-Agent naming the app and a contact: by default the bot's name and invite link, or `ACTIONS_USER_AGENT` +- **When no API answers:** every distinct GIF the APIs return is recorded (`ACTIONS_DB_PATH`, no limit), and its file is downloaded once in the background into `ACTIONS_GIFS_DIR`, named by its SHA-256 so identical GIFs are kept once (two downloads at a time; a failed one is retried the next time that GIF is served; only real GIFs up to 10 MiB, Discord's upload limit). When every source fails, a stored file is uploaded with the message and the embed shows it (`attachment://hug.gif`), so nothing has to be hosted; without files, a stored URL is reused; with neither, the action goes out as text. A GIF averaged about 0.9 MB in testing, so a full set of a few thousand GIFs is a few GB. `ACTIONS_STORE_GIFS=false` keeps only the URLs. nekos.best's terms allow caching its responses for private use only and forbid rehosting, so storing and re-uploading its GIFs is the operator's call - **Doing it to the bot:** after the GIF, the bot answers in character, like a mention — a few words, a reaction on the GIF, doing it back with `send_action_gif`, or nothing. It costs the person one turn of their `CHAT_USER_BUDGET` (over it, the GIF stands alone), and replying to the answer continues the conversation. Not in channels where `respond` is `off`; `ACTIONS_BOT_REPLY=false` turns it off - **The bot doing it:** the `send_action_gif` tool (chat profile) — when asked ("dá um abraço no Bruno", "bate nele") or when it fits its personality, at most once per answer; the GIF goes out before the answer, with a button for the person to do it back. `ACTIONS_TOOL_ENABLED=false` removes it - **Yourself:** affection actions come from the bot instead ("Ninguém merece fazer isso sozinho: **QuillBot** abraçou @Ana!"); the others are refused @@ -515,7 +516,8 @@ QuillBot/ ├── settings.db # /config settings ├── persona.db # Personality sections + history ├── conversations.db # Conversations (handles, triggers, episode state) - ├── actions.db # Action counts per pair, recent GIF URLs + ├── actions.db # Action counts per pair, every GIF URL seen and its stored file + ├── action_gifs/ # Stored GIF files (.gif), uploaded when no GIF API answers ├── lore.db # Legacy lore encyclopedia (kept as migration source) └── history/ # Per-guild history stores ``` @@ -734,7 +736,9 @@ cp .env.example .env # if available, otherwise create .env manually | Variable | Default | Description | |---|---|---| | `ACTIONS_ENABLED` | `true` | `/hug`, `/kiss`, `/slap`… and the `send_action_gif` tool | -| `ACTIONS_DB_PATH` | `data/actions.db` | Counts per pair and recent GIF URLs | +| `ACTIONS_DB_PATH` | `data/actions.db` | Counts per pair and every GIF URL seen | +| `ACTIONS_STORE_GIFS` | `true` | Keep a copy of every distinct GIF, uploaded as an attachment when no GIF API answers | +| `ACTIONS_GIFS_DIR` | `data/action_gifs` | Where those copies go | | `ACTIONS_PING_TARGET` | `true` | Notify the person on the receiving end | | `ACTIONS_COOLDOWN_SECONDS` | `5` | Between two actions of one person (all commands together) | | `ACTIONS_BOT_REPLY` | `true` | Doing an action to the bot gets an answer in character (one chat turn) | @@ -815,7 +819,7 @@ Cog load order doesn't matter: the router decides who sees a message, not the or docker compose up --build -d ``` -- Uses `python:3.11-slim`, persists `data/` via volume mount, reads config from `.env`. +- Uses `python:3.11-slim`, persists `data/` via volume mount, reads config from `.env`. `data/` (databases, stored action GIFs) is in `.dockerignore`, so it never goes into the build or the image. --- @@ -835,7 +839,7 @@ ruff check . # lint (rules configured in pyproject.toml) | File | Covers | |---|---| -| `test_actions.py` | Action GIFs: providers in order and fallbacks (recent GIF, then text), refused hosts, counts, wording, the return button (target only, once, back the other way), pings, cooldown and self-actions, the bot answering actions done to it (and returns of its own), the `send_action_gif` tool, the engine's answer starting a conversation | +| `test_actions.py` | Action GIFs: providers in order and fallbacks (stored file uploaded as an attachment, stored URL, text), every distinct GIF kept, files saved once per content and retried after a failed download, non-GIFs and oversized files refused, refused hosts, counts, wording, the return button (target only, once, back the other way), pings, cooldown and self-actions, the bot answering actions done to it (and returns of its own), the `send_action_gif` tool, the engine's answer starting a conversation | | `test_api_logger.py` | Request logging for aiohttp/httpx/httpx2, redaction, body capture, inbound interactions (runs in its own process) | | `test_attribution.py` | Author tags on every question, speaker changes marked in the tag (verbatim and compact replay), the conversation block naming who speaks now, byte-identical replay of per-turn blocks, memory block labels and person-memory rules | | `test_channel_context_images.py` | Images from automatically fetched channel context | diff --git a/SETUP.md b/SETUP.md index 7541b82..536fb46 100644 --- a/SETUP.md +++ b/SETUP.md @@ -216,7 +216,7 @@ Every message goes through one router (`core/router.py`): passive observers (his | `/resumo` | Summarize what happened in a channel | Yes | | `/wrapped` | Server recap: who talked most, channels, emojis… | Optional** | | `/config` | Server and channel settings (Manage Server) | No | -| `/hug`, `/kiss`, `/slap`… | Anime GIF of you doing it to someone (15 actions) | No*** | +| `/hug`, `/kiss`, `/slap`… | Anime GIF of you doing it to someone (27 actions) | No*** | | `/persona` | The bot's personality on this server (editing needs Manage Server) | No | | `/memory`, `/monitor`, `/schedule` | Memories, standing triggers, scheduled tasks | Yes | | `/analyze` | Analyze a server log with AI (mclo.gs, pastebin, or file) | Yes | diff --git a/cogs/actions.py b/cogs/actions.py index 8861a26..c86c965 100644 --- a/cogs/actions.py +++ b/cogs/actions.py @@ -28,7 +28,9 @@ ACTIONS_COOLDOWN_SECONDS, ACTIONS_DB_PATH, ACTIONS_ENABLED, + ACTIONS_GIFS_DIR, ACTIONS_PING_TARGET, + ACTIONS_STORE_GIFS, ACTIONS_TOOL_ENABLED, ACTIONS_USER_AGENT, ) @@ -156,6 +158,8 @@ async def cog_unload(self) -> None: self.bot.tree.remove_command(command.name) self._commands.clear() self.services.tools.unregister(TOOL_NAME) + if self.gifs is not None: + self.gifs.close() if self.session is not None: await self.session.close() @@ -172,7 +176,9 @@ def picker(self) -> GifPicker: """The GIF picker, made on first use: the bot only knows its own id once logged in.""" if self.gifs is None: self.session = aiohttp.ClientSession(timeout=_HTTP_TIMEOUT, headers={'User-Agent': self.user_agent()}) - self.gifs = GifPicker(self.session, self.store) + self.gifs = GifPicker( + self.session, self.store, files_dir=ACTIONS_GIFS_DIR if ACTIONS_STORE_GIFS else None, + ) return self.gifs def make_command(self, action: Action) -> app_commands.Command: @@ -252,6 +258,9 @@ async def perform( kwargs: dict[str, Any] = {'content': content, 'allowed_mentions': self._mentions(target)} if embed is not None: kwargs['embed'] = embed + file = action_gifs.attachment(action, gif) # a stored copy: no API answered + if file is not None: + kwargs['file'] = file view = None if not returned and not getattr(target, 'bot', False): view = kwargs['view'] = ReturnView(self, action, actor=actor, target=target) diff --git a/config.py b/config.py index af05d02..f7bf4e3 100644 --- a/config.py +++ b/config.py @@ -313,8 +313,11 @@ def _is_openrouter_url(url: str) -> bool: # --- Action GIFs (/hug, /kiss, /slap…: an anime GIF of someone doing it to someone) --- ACTIONS_ENABLED: Final[bool] = _flag('ACTIONS_ENABLED') -# Action counts per pair and the GIF URLs seen lately (reused when the GIF APIs are down). +# Action counts per pair and every GIF URL the APIs returned. ACTIONS_DB_PATH: Final[str] = os.getenv('ACTIONS_DB_PATH', 'data/actions.db') +# Keep a copy of every distinct GIF, uploaded as an attachment when no GIF API answers. +ACTIONS_STORE_GIFS: Final[bool] = _flag('ACTIONS_STORE_GIFS') +ACTIONS_GIFS_DIR: Final[str] = os.getenv('ACTIONS_GIFS_DIR', 'data/action_gifs') # Whether the person on the receiving end gets a notification. ACTIONS_PING_TARGET: Final[bool] = _flag('ACTIONS_PING_TARGET') # Seconds between two action commands of one person. diff --git a/core/action_gifs.py b/core/action_gifs.py index 79a12f5..1e3e5f8 100644 --- a/core/action_gifs.py +++ b/core/action_gifs.py @@ -5,17 +5,19 @@ bot does the action itself. GIFs come from free anime GIF APIs, tried in each action's order: nekos.best -(which also names the anime) and otakugifs.xyz. Every GIF fetched is -remembered per action (``RECENT_GIFS`` of them), so when the APIs are down an -earlier one is reused; with none at all, the action goes out as text. How many -times each person did each action to each other person is counted in the -same SQLite file. +(which also names the anime) and otakugifs.xyz. Every distinct GIF they return +is recorded, and its file is downloaded once in the background (identical +files are kept once). When no API answers, a stored file is uploaded as an +attachment; without files, a stored URL is reused; with neither, the action +goes out as text. How many times each person did each action to each other +person is counted in the same SQLite file. """ from __future__ import annotations import asyncio import datetime +import hashlib import logging import os import random @@ -38,12 +40,16 @@ NEKOS = 'nekos.best' OTAKU = 'otakugifs' -# GIFs kept per action for when the APIs are down. -RECENT_GIFS = 50 # Only GIFs hosted by the APIs themselves are posted: an embed shows whatever URL it gets. _ALLOWED_HOSTS = ('nekos.best', 'otakugifs.xyz') _NEKOS_URL = 'https://nekos.best/api/v2/{category}' _OTAKU_URL = 'https://api.otakugifs.xyz/gif' +# Stored files must fit Discord's upload limit on servers without boosts (10 MiB). +MAX_FILE_BYTES = 10 * 1024 * 1024 +_DOWNLOAD_TIMEOUT = aiohttp.ClientTimeout(total=60) +_GIF_MAGIC = (b'GIF87a', b'GIF89a') +# Downloads at once: a CDN refused some of six parallel ones in testing (HTTP 428). +_PARALLEL_DOWNLOADS = 2 AFFECTION = 'carinho' PLAYFUL = 'brincadeira' @@ -72,27 +78,55 @@ def return_label(self) -> str: def color(self) -> int: return _COLORS[self.kind] + @property + def attachment_name(self) -> str: + """The file name a stored GIF is uploaded under.""" + return f'{self.key}.gif' + def _both(category: str) -> tuple[tuple[str, str], ...]: return ((NEKOS, category), (OTAKU, category)) +def _nekos_only(category: str) -> tuple[tuple[str, str], ...]: + return ((NEKOS, category),) + + +def _otaku_only(category: str) -> tuple[tuple[str, str], ...]: + return ((OTAKU, category),) + + ACTIONS: dict[str, Action] = {a.key: a for a in ( Action('hug', '🤗', 'abraçou', 'Dê um abraço em alguém', AFFECTION, _both('hug')), Action('kiss', '😘', 'beijou', 'Dê um beijo em alguém', AFFECTION, _both('kiss')), - Action('slap', '🖐️', 'deu um tapa em', 'Dê um tapa em alguém', ROUGH, _both('slap')), - Action('lick', '👅', 'lambeu', 'Lamba alguém', PLAYFUL, ((OTAKU, 'lick'),)), + Action('peck', '😚', 'deu um selinho em', 'Dê um selinho em alguém', AFFECTION, _nekos_only('peck')), + Action( + 'blowkiss', '💋', 'mandou um beijo para', 'Mande um beijo para alguém', AFFECTION, + ((NEKOS, 'blowkiss'), (OTAKU, 'airkiss')), + ), Action('pat', '🫶', 'fez cafuné em', 'Faça cafuné em alguém', AFFECTION, _both('pat')), Action('cuddle', '🥰', 'se aconchegou em', 'Aconchegue-se em alguém', AFFECTION, _both('cuddle')), + Action('nuzzle', '😊', 'deu um cheirinho em', 'Dê um cheirinho em alguém', AFFECTION, _otaku_only('nuzzle')), + Action('lappillow', '😴', 'deitou no colo de', 'Deite no colo de alguém', AFFECTION, _nekos_only('lappillow')), + Action('handhold', '💞', 'segurou a mão de', 'Segure a mão de alguém', AFFECTION, _both('handhold')), + Action('handshake', '🤝', 'apertou a mão de', 'Aperte a mão de alguém', AFFECTION, _nekos_only('handshake')), + Action('highfive', '🙌', 'bateu um toca aqui com', 'Bata um toca aqui com alguém', AFFECTION, _nekos_only('highfive')), + Action('brofist', '🤜', 'bateu um soquinho com', 'Bata um soquinho com alguém', AFFECTION, _otaku_only('brofist')), + Action('wave', '👋', 'acenou para', 'Acene para alguém', AFFECTION, _both('wave')), + Action('cheers', '🍻', 'brindou com', 'Brinde com alguém', AFFECTION, _otaku_only('cheers')), + Action('feed', '🍙', 'deu comida para', 'Dê comida para alguém', AFFECTION, _nekos_only('feed')), + Action('wink', '😉', 'piscou para', 'Pisque para alguém', PLAYFUL, _both('wink')), + Action('stare', '👀', 'encarou', 'Encare alguém', PLAYFUL, _both('stare')), + Action('lick', '👅', 'lambeu', 'Lamba alguém', PLAYFUL, _otaku_only('lick')), Action('poke', '👉', 'cutucou', 'Cutuque alguém', PLAYFUL, _both('poke')), + Action('pinch', '🤏', 'beliscou', 'Belisque alguém', PLAYFUL, _otaku_only('pinch')), + Action('tickle', '🤭', 'fez cócegas em', 'Faça cócegas em alguém', PLAYFUL, _both('tickle')), Action('bite', '😬', 'mordeu', 'Morda alguém', PLAYFUL, _both('bite')), - Action('bonk', '🔨', 'deu um bonk em', 'Dê um bonk em alguém', PLAYFUL, ((NEKOS, 'bonk'),)), + Action('bonk', '🔨', 'deu um bonk em', 'Dê um bonk em alguém', PLAYFUL, _nekos_only('bonk')), + Action('slap', '🖐️', 'deu um tapa em', 'Dê um tapa em alguém', ROUGH, _both('slap')), Action('punch', '👊', 'deu um soco em', 'Dê um soco em alguém', ROUGH, _both('punch')), - Action('kick', '🦵', 'chutou', 'Chute alguém', ROUGH, ((NEKOS, 'kick'),)), - Action('tickle', '🤭', 'fez cócegas em', 'Faça cócegas em alguém', PLAYFUL, _both('tickle')), - Action('highfive', '🙌', 'bateu um toca aqui com', 'Bata um toca aqui com alguém', AFFECTION, ((NEKOS, 'highfive'),)), - Action('handhold', '🤝', 'segurou a mão de', 'Segure a mão de alguém', AFFECTION, _both('handhold')), - Action('feed', '🍙', 'deu comida para', 'Dê comida para alguém', AFFECTION, ((NEKOS, 'feed'),)), + Action('kick', '🦵', 'chutou', 'Chute alguém', ROUGH, _nekos_only('kick')), + Action('yeet', '🚀', 'arremessou', 'Arremesse alguém', ROUGH, _nekos_only('yeet')), )} @@ -104,6 +138,8 @@ def _both(category: str) -> tuple[tuple[str, str], ...]: class Gif: url: str anime: str = '' + # A stored copy to upload as an attachment (the APIs didn't answer). + path: str = '' def allowed_url(url: Any) -> bool: @@ -141,12 +177,37 @@ async def _otaku(session: aiohttp.ClientSession, category: str) -> Gif | None: PROVIDERS = {NEKOS: _nekos, OTAKU: _otaku} +def file_path(files_dir: str, sha: str) -> str: + return os.path.join(files_dir, f'{sha}.gif') + + +def _write_file(files_dir: str, sha: str, data: bytes) -> None: + os.makedirs(files_dir, exist_ok=True) + path = file_path(files_dir, sha) + if os.path.exists(path): + return + tmp = f'{path}.{os.getpid()}.tmp' + with open(tmp, 'wb') as f: + f.write(data) + os.replace(tmp, path) + + class GifPicker: - """A GIF for an action: each of its sources in order, then a recent one.""" + """A GIF for an action: its sources in order, then a stored file, then a stored URL. - def __init__(self, session: aiohttp.ClientSession, store: ActionStore): + Every GIF a source returns is recorded; with *files_dir*, its file is + downloaded in the background the first time it shows up (and again the + next time it's served, if that failed), so that when no source answers + one can be uploaded as an attachment. + """ + + def __init__(self, session: aiohttp.ClientSession, store: ActionStore, *, files_dir: str | None = None): self.session = session self.store = store + self.files_dir = files_dir + self._saving: set[str] = set() + self._tasks: set[asyncio.Task] = set() + self._downloads = asyncio.Semaphore(_PARALLEL_DOWNLOADS) async def pick(self, action: Action) -> Gif | None: for provider, category in action.sources: @@ -156,25 +217,100 @@ async def pick(self, action: Action) -> Gif | None: logger.warning('[actions] %s failed for %s: %r', provider, category, e) continue if gif is not None: - await asyncio.to_thread(self.store.remember_gif, action.key, gif) + file_missing = await asyncio.to_thread(self.store.remember_gif, action.key, gif) + if file_missing: + self._save_later(action.key, gif.url) return gif logger.info('[actions] %s had no GIF for %s', provider, category) + gif = await asyncio.to_thread(self._stored_file, action.key) + if gif is not None: + logger.info('[actions] no API answered for %s: uploading a stored GIF', action.key) + return gif gif = await asyncio.to_thread(self.store.recent_gif, action.key) if gif is None: logger.warning('[actions] no GIF for %s: sending it as text', action.key) return gif + def _stored_file(self, action_key: str) -> Gif | None: + """A stored GIF of *action_key* whose file is on disk, at random.""" + if not self.files_dir: + return None + rows = self.store.stored_files(action_key) + random.shuffle(rows) + for url, anime, sha in rows: + path = file_path(self.files_dir, sha) + if os.path.isfile(path): + return Gif(url, anime, path) + self.store.forget_file(sha) # deleted from disk: downloaded again next time it's served + return None + + # --- saving files --- + + def _save_later(self, action_key: str, url: str) -> None: + if not self.files_dir or url in self._saving: + return + self._saving.add(url) + task = asyncio.get_running_loop().create_task(self._save(action_key, url)) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + + async def _save(self, action_key: str, url: str) -> None: + assert self.files_dir is not None + try: + async with self._downloads: + data = await self._download(url) + if data is None: + return + sha = hashlib.sha256(data).hexdigest() + await asyncio.to_thread(_write_file, self.files_dir, sha, data) + await asyncio.to_thread(self.store.set_file, action_key, url, sha) + except Exception as e: + logger.warning('[actions] could not save %s: %r', url, e) + finally: + self._saving.discard(url) + + async def _download(self, url: str) -> bytes | None: + """The GIF at *url*, or ``None`` when it's too big to upload or not a GIF.""" + async with self.session.get(url, timeout=_DOWNLOAD_TIMEOUT) as resp: + if resp.status != 200: + raise ProviderError(f'HTTP {resp.status}') + if (resp.content_length or 0) > MAX_FILE_BYTES: + logger.info('[actions] %s is over %d bytes; not stored', url, MAX_FILE_BYTES) + return None + data = bytearray() + async for chunk in resp.content.iter_chunked(1 << 16): + data += chunk + if len(data) > MAX_FILE_BYTES: + logger.info('[actions] %s is over %d bytes; not stored', url, MAX_FILE_BYTES) + return None + if bytes(data[:6]) not in _GIF_MAGIC: + logger.info('[actions] %s is not a GIF; not stored', url) + return None + return bytes(data) + + async def drain(self) -> None: + """Wait for the downloads in progress.""" + while self._tasks: + await asyncio.gather(*list(self._tasks), return_exceptions=True) + + def close(self) -> None: + for task in list(self._tasks): + task.cancel() + # --------------------------------------------------------------------------- -# Counts and recent GIFs +# Counts and stored GIFs # --------------------------------------------------------------------------- class ActionStore: - """SQLite (``ACTIONS_DB_PATH``): action counts per pair and recent GIF URLs.""" + """SQLite (``ACTIONS_DB_PATH``): action counts per pair, and every GIF seen per action. - def __init__(self, path: str, *, recent: int = RECENT_GIFS): + A GIF row keeps its URL, the anime it's from and, once downloaded, the + SHA-256 of its file (files are named by it, so identical GIFs share one). + """ + + def __init__(self, path: str): self.path = path - self.recent = recent self._lock = threading.Lock() def _connect(self) -> sqlite3.Connection: @@ -202,8 +338,12 @@ def load(self) -> None: url TEXT NOT NULL, anime TEXT NOT NULL DEFAULT '', seen_at REAL NOT NULL, + file TEXT NOT NULL DEFAULT '', PRIMARY KEY (action, url) )""") + columns = {row[1] for row in con.execute('PRAGMA table_info(action_gifs)')} + if 'file' not in columns: # tables made before files were stored + con.execute("ALTER TABLE action_gifs ADD COLUMN file TEXT NOT NULL DEFAULT ''") con.commit() finally: con.close() @@ -229,26 +369,54 @@ def bump(self, guild_id: int, actor_id: int, target_id: int, action: str) -> int con.close() return int(row[0]) if row else 1 - def remember_gif(self, action: str, gif: Gif) -> None: - """Keep *gif* among *action*'s newest ``recent`` GIFs.""" + def remember_gif(self, action: str, gif: Gif) -> bool: + """Record *gif* for *action* (every distinct URL is kept); returns whether it has no file yet.""" with self._lock: con = self._connect() try: con.execute( - 'INSERT OR REPLACE INTO action_gifs (action, url, anime, seen_at) VALUES (?,?,?,?)', + 'INSERT INTO action_gifs (action, url, anime, seen_at) VALUES (?,?,?,?) ' + 'ON CONFLICT (action, url) DO UPDATE SET seen_at = excluded.seen_at, ' + "anime = CASE WHEN excluded.anime != '' THEN excluded.anime ELSE anime END", (action, gif.url, gif.anime, time.time()), ) - con.execute( - 'DELETE FROM action_gifs WHERE action=? AND url NOT IN ' - '(SELECT url FROM action_gifs WHERE action=? ORDER BY seen_at DESC LIMIT ?)', - (action, action, self.recent), - ) + con.commit() + row = con.execute('SELECT file FROM action_gifs WHERE action=? AND url=?', (action, gif.url)).fetchone() + finally: + con.close() + return not (row and row[0]) + + def set_file(self, action: str, url: str, sha: str) -> None: + with self._lock: + con = self._connect() + try: + con.execute('UPDATE action_gifs SET file=? WHERE action=? AND url=?', (sha, action, url)) + con.commit() + finally: + con.close() + + def forget_file(self, sha: str) -> None: + """The file *sha* is gone: its GIFs count as not downloaded.""" + with self._lock: + con = self._connect() + try: + con.execute("UPDATE action_gifs SET file='' WHERE file=?", (sha,)) con.commit() finally: con.close() + def stored_files(self, action: str) -> list[tuple[str, str, str]]: + """``(url, anime, sha)`` of *action*'s downloaded GIFs.""" + con = self._connect() + try: + return con.execute( + "SELECT url, anime, file FROM action_gifs WHERE action=? AND file != ''", (action,), + ).fetchall() + finally: + con.close() + def recent_gif(self, action: str) -> Gif | None: - """One of *action*'s remembered GIFs, at random.""" + """One of *action*'s recorded GIF URLs, at random.""" con = self._connect() try: rows = con.execute('SELECT url, anime FROM action_gifs WHERE action=?', (action,)).fetchall() @@ -293,11 +461,19 @@ def render( if gif is None: return f'{content}\n-# {counted}', None embed = discord.Embed(color=action.color) - embed.set_image(url=gif.url) + # A stored copy goes up with the message (see ``attachment``); the embed shows it. + embed.set_image(url=f'attachment://{action.attachment_name}' if gif.path else gif.url) embed.set_footer(text=f'{counted} · Anime: {gif.anime}' if gif.anime else counted) return content, embed +def attachment(action: Action, gif: Gif | None) -> discord.File | None: + """The file to upload with the message when *gif* is a stored copy.""" + if gif is None or not gif.path: + return None + return discord.File(gif.path, filename=action.attachment_name) + + def action_question(action: Action, actor: Any, *, returned: bool = False, can_send: bool = True) -> str: """The turn the bot answers when someone does *action* to it (``/hug @bot``).""" did = 'devolveu o que você fez com' if returned else 'usou' diff --git a/tests/test_actions.py b/tests/test_actions.py index 0a98ea4..8e72704 100644 --- a/tests/test_actions.py +++ b/tests/test_actions.py @@ -1,6 +1,7 @@ """Action GIFs: /hug, /slap…, their providers and fallbacks, counts, the return button, the bot answering actions done to it, and the send_action_gif tool.""" +import os from types import SimpleNamespace as NS import discord @@ -26,10 +27,22 @@ # Fakes # --------------------------------------------------------------------------- +GIF_BYTES = b'GIF89a' + b'\x00' * 100 + + class _Resp: - def __init__(self, status, data): + def __init__(self, status, data, body=b''): self.status = status self.data = data + self.body = body + self.content_length = len(body) if body else None + self.content = NS(iter_chunked=self._chunks) + + def _chunks(self, size): + async def gen(): + for i in range(0, len(self.body), size): + yield self.body[i:i + size] + return gen() async def __aenter__(self): if isinstance(self.data, Exception): @@ -44,13 +57,20 @@ async def json(self, content_type=None): class FakeSession: - """``aiohttp.ClientSession.get`` answering per host: (status, json) or an exception.""" + """``aiohttp.ClientSession.get``: API calls answer per host with (status, json) or an + exception; GIF downloads answer from *files* (url -> bytes).""" - def __init__(self, **by_host): + def __init__(self, files=None, **by_host): self.by_host = by_host + self.files = files or {} self.calls = [] + self.downloads = [] - def get(self, url, params=None): + def get(self, url, params=None, timeout=None): + if url in self.files: + self.downloads.append(url) + body = self.files[url] + return _Resp(0, body) if isinstance(body, Exception) else _Resp(200, None, body) self.calls.append((url, params)) host = 'otaku' if 'otakugifs' in url else 'nekos' status, data = self.by_host.get(host, (500, None)) @@ -131,14 +151,14 @@ def get_partial_message(self, mid): return NS(id=mid, channel=self, guild=self.guild) -def make_cog(tmp_path, *, session=None, chat=None): +def make_cog(tmp_path, *, session=None, chat=None, files_dir=None): services = make_services(tmp_path) services.chat = chat bot = NS(services=services, user=BOT_MEMBER, tree=None) cog = actions_mod.Actions(bot) cog.store = ActionStore(str(tmp_path / 'actions.db')) cog.store.load() - cog.gifs = GifPicker(session or FakeSession(nekos=nekos_ok(), otaku=otaku_ok()), cog.store) + cog.gifs = GifPicker(session or FakeSession(nekos=nekos_ok(), otaku=otaku_ok()), cog.store, files_dir=files_dir) guild = Guild(members=[ASKER, OTHER, BOT_MEMBER, OTHER_BOT]) guild.me = BOT_MEMBER channel = ActionChannel(guild) @@ -191,18 +211,116 @@ async def test_gifs_from_other_hosts_are_refused(tmp_path): check('look-alike host refused', not action_gifs.allowed_url('https://notnekos.best/x.gif')) -def test_store_counts_per_pair_and_keeps_recent_gifs(tmp_path): - store = ActionStore(str(tmp_path / 'a.db'), recent=3) +def test_store_counts_per_pair_and_keeps_every_gif(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) store.load() check('first', store.bump(1, 222, 333, 'hug') == 1) check('second', store.bump(1, 222, 333, 'hug') == 2) check('other direction apart', store.bump(1, 333, 222, 'hug') == 1) check('other action apart', store.bump(1, 222, 333, 'slap') == 1) check('other server apart', store.bump(2, 222, 333, 'hug') == 1) - for i in range(5): + for i in range(80): store.remember_gif('hug', Gif(f'https://nekos.best/{i}.gif')) - urls = {store.recent_gif('hug').url for _ in range(40)} - check('only the newest are kept', urls <= {f'https://nekos.best/{i}.gif' for i in (2, 3, 4)} and urls, urls) + store.remember_gif('hug', Gif('https://nekos.best/0.gif', 'K-On!')) + urls = {store.recent_gif('hug').url for _ in range(2000)} + check('no cap: all 80 kept, once each', len(urls) == 80, len(urls)) + con = store._connect() + anime = con.execute('SELECT anime FROM action_gifs WHERE url=?', ('https://nekos.best/0.gif',)).fetchone()[0] + con.close() + check('anime filled in later', anime == 'K-On!', anime) + + +async def test_every_distinct_gif_file_is_saved_once(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + files_dir = str(tmp_path / 'gifs') + other = 'https://cdn.otakugifs.xyz/gifs/hug/same.gif' + session = FakeSession(files={NEKOS_GIF: GIF_BYTES, other: GIF_BYTES}, nekos=nekos_ok(), otaku=otaku_ok(url=other)) + picker = GifPicker(session, store, files_dir=files_dir) + gif = await picker.pick(ACTIONS['hug']) + check('the API GIF is used as is', gif.url == NEKOS_GIF and not gif.path) + await picker.drain() + check('its file was saved, named by its hash', len(os.listdir(files_dir)) == 1 and session.downloads == [NEKOS_GIF], session.downloads) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('a GIF already saved is not downloaded again', session.downloads == [NEKOS_GIF], session.downloads) + session.by_host['nekos'] = (503, None) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('a new URL with the same bytes shares the file', session.downloads == [NEKOS_GIF, other] and len(os.listdir(files_dir)) == 1) + + +async def test_failed_download_is_retried_when_served_again(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + files_dir = str(tmp_path / 'gifs') + session = FakeSession(files={NEKOS_GIF: OSError('428')}, nekos=nekos_ok()) + picker = GifPicker(session, store, files_dir=files_dir) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('nothing saved yet', store.stored_files('hug') == []) + session.files[NEKOS_GIF] = GIF_BYTES + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('saved on the next serve', len(store.stored_files('hug')) == 1 and len(session.downloads) == 2, session.downloads) + + +async def test_apis_down_upload_a_stored_file(tmp_path): + cog, guild, channel = make_cog(tmp_path, files_dir=str(tmp_path / 'gifs'), + session=FakeSession(files={NEKOS_GIF: GIF_BYTES}, nekos=nekos_ok())) + await cog.perform(ACTIONS['hug'], actor=ASKER, target=OTHER, guild=guild, channel=channel, send=Sender()) + await cog.gifs.drain() + cog.gifs.session.by_host['nekos'] = (0, OSError('down')) + cog.gifs.session.by_host['otaku'] = (0, OSError('down')) + send = Sender() + await cog.perform(ACTIONS['hug'], actor=ASKER, target=OTHER, guild=guild, channel=channel, send=send) + kwargs = send.sent[0].kwargs + check('uploaded as an attachment', isinstance(kwargs.get('file'), discord.File) and kwargs['file'].filename == 'hug.gif', kwargs) + check('shown in the embed from the attachment', kwargs['embed'].image.url == 'attachment://hug.gif', kwargs['embed'].image.url) + check('footer keeps the anime', kwargs['embed'].footer.text.endswith('· Anime: Sword Art Online'), kwargs['embed'].footer.text) + kwargs['file'].close() + + +async def test_stored_file_gone_falls_back_to_the_url(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + files_dir = str(tmp_path / 'gifs') + session = FakeSession(files={NEKOS_GIF: GIF_BYTES}, nekos=nekos_ok()) + picker = GifPicker(session, store, files_dir=files_dir) + await picker.pick(ACTIONS['hug']) + await picker.drain() + for name in os.listdir(files_dir): + os.remove(os.path.join(files_dir, name)) + session.by_host['nekos'] = (503, None) + gif = await picker.pick(ACTIONS['hug']) + check('the URL instead', gif == Gif(NEKOS_GIF, 'Sword Art Online'), gif) + check('marked to download again', store.stored_files('hug') == []) + + +async def test_non_gifs_and_big_files_are_not_stored(tmp_path, monkeypatch): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + files_dir = str(tmp_path / 'gifs') + picker = GifPicker(FakeSession(files={NEKOS_GIF: b'blocked'}, nekos=nekos_ok()), store, files_dir=files_dir) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('not a GIF', not os.path.exists(files_dir) or not os.listdir(files_dir)) + monkeypatch.setattr(action_gifs, 'MAX_FILE_BYTES', 50) + picker = GifPicker(FakeSession(files={NEKOS_GIF: GIF_BYTES}, nekos=nekos_ok()), store, files_dir=files_dir) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('over the upload limit', not os.path.exists(files_dir) or not os.listdir(files_dir)) + check('still recorded as a URL', store.recent_gif('hug').url == NEKOS_GIF) + + +async def test_no_files_without_a_directory(tmp_path): + store = ActionStore(str(tmp_path / 'a.db')) + store.load() + session = FakeSession(files={NEKOS_GIF: GIF_BYTES}, nekos=nekos_ok()) + picker = GifPicker(session, store) + await picker.pick(ACTIONS['hug']) + await picker.drain() + check('ACTIONS_STORE_GIFS=false downloads nothing', session.downloads == []) # --------------------------------------------------------------------------- @@ -225,11 +343,15 @@ def test_render_with_and_without_a_gif(): def test_every_action_has_a_source_and_a_return_label(): - check('fifteen actions', len(ACTIONS) == 15, list(ACTIONS)) + check('twenty-seven actions', len(ACTIONS) == 27, list(ACTIONS)) for action in ACTIONS.values(): check(f'{action.key} sources', action.sources and all(p in action_gifs.PROVIDERS for p, _ in action.sources)) check('labels by kind', (ACTIONS['hug'].return_label, ACTIONS['slap'].return_label, ACTIONS['poke'].return_label) == ('Retribuir', 'Revidar', 'Devolver')) + check('blowkiss falls back to airkiss', ACTIONS['blowkiss'].sources == (('nekos.best', 'blowkiss'), ('otakugifs', 'airkiss'))) + names = [a.key for a in ACTIONS.values()] + check('valid, distinct command names', len(set(names)) == len(names) and all(n.isascii() and n.islower() and len(n) <= 32 for n in names)) + check('descriptions fit', all(len(f'{a.emoji} {a.description}') <= 100 for a in ACTIONS.values())) def test_find_member():