agent-core-discord 0.8.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ """agent-core-discord — Discord bot adapter for the agent-core bus.
2
+
3
+ One DiscordEndpoint instance per Discord bot. Bridges one bot to one named
4
+ agent on the bus (1:1 mapping). See the design doc at
5
+ docs/superpowers/specs/2026-04-28-discord-endpoint-design.md for details.
6
+ """
7
+
8
+ from agent_core_discord.endpoint import DiscordEndpoint
9
+
10
+ __all__ = ["DiscordEndpoint"]
@@ -0,0 +1,73 @@
1
+ """Ack-tracking mixin for DiscordEndpoint.
2
+
3
+ Move-only extraction from endpoint.py (issue #440, Step 2 of F-B6).
4
+ Imports nothing from endpoint.py to avoid circular imports.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import logging
11
+ import time
12
+ from typing import Any
13
+
14
+ from agent_core_discord._state import _EndpointState
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ class _AcksMixin(_EndpointState):
20
+ def _track_pending_ack(self, message_id: str, emoji: str, channel_id: str) -> None:
21
+ """Record a pending ack and evict the oldest entry if we hit the cap.
22
+
23
+ When LRU eviction fires, the evicted entry's 👀 is removed from the
24
+ original message in a fire-and-forget task — we don't want bookkeeping
25
+ to slow down on_message dispatch.
26
+ """
27
+ self._pending_acks[message_id] = (emoji, channel_id, time.monotonic())
28
+ while len(self._pending_acks) > self.pending_acks_max:
29
+ old_id, (old_emoji, old_ch, _ts) = self._pending_acks.popitem(last=False)
30
+ self._awaiting_reply_ids.discard(old_id)
31
+ self._awaiting_reply_ids_timestamps.pop(old_id, None)
32
+ assert self._handle is not None
33
+ self._handle.spawn(
34
+ self._remote_remove_ack(old_id, old_emoji, old_ch),
35
+ name=f"discord-endpoint-{self.name}-evict-ack",
36
+ )
37
+
38
+ async def _remote_remove_ack(self, message_id: str, emoji: str, channel_id: str) -> None:
39
+ """Best-effort removal of an ack reaction from a Discord message."""
40
+ if self._client is None:
41
+ return
42
+ try:
43
+ channel = self._client.get_channel(channel_id)
44
+ if channel is None:
45
+ channel = await self._client.fetch_channel(channel_id)
46
+ msg = await channel.fetch_message(message_id)
47
+ if msg is None:
48
+ return
49
+ await msg.remove_reaction(emoji, self._client.user)
50
+ except Exception:
51
+ log.debug(
52
+ "discord(%s): could not remove evicted ack on message %s",
53
+ self.name,
54
+ message_id,
55
+ exc_info=True,
56
+ )
57
+
58
+ async def _clear_pending_ack(self, channel: Any, message_id: str) -> None:
59
+ mid = str(message_id)
60
+ self._awaiting_reply_ids.discard(mid)
61
+ self._awaiting_reply_ids_timestamps.pop(mid, None)
62
+ entry = self._pending_acks.pop(mid, None)
63
+ if entry is None:
64
+ return
65
+ emoji, _channel_id, _ts = entry
66
+ try:
67
+ msg = await channel.fetch_message(mid)
68
+ except Exception:
69
+ return
70
+ if msg is None:
71
+ return
72
+ with contextlib.suppress(Exception):
73
+ await msg.remove_reaction(emoji, self._client.user)
@@ -0,0 +1,18 @@
1
+ """Shared exception types for the agent_core_discord package.
2
+
3
+ Leaf module — imports nothing from other agent_core_discord modules so
4
+ that _acks.py and _lifecycle.py can import from here without creating
5
+ circular-import cycles.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+
11
+ class _ToolError(Exception):
12
+ """User-error during tool dispatch — produces an Acknowledgment with note."""
13
+
14
+
15
+ class _PersistError(Exception):
16
+ """Attachment could not be persisted (unsafe path, etc.). Neutral —
17
+ shared by the MCP tool and the inbound path; the tool layer
18
+ translates it to _ToolError."""
@@ -0,0 +1,538 @@
1
+ """Inbound-handler mixin for DiscordEndpoint.
2
+
3
+ Move-only extraction from endpoint.py (issue #441, Step 3 of F-B6).
4
+ Imports nothing from endpoint.py to avoid circular imports.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import logging
11
+ import re
12
+ import time
13
+ import uuid
14
+ from collections.abc import Callable, Coroutine
15
+ from datetime import UTC, datetime
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from agent_core.bus.envelope import Envelope, EventPayload, TextMessagePayload
20
+ from agent_core_discord._exceptions import _ToolError
21
+ from agent_core_discord._state import _EndpointState
22
+ from agent_core_discord.access import InboundContext, gate_message
23
+ from agent_core_discord.sigil import parse_sigil
24
+ from agent_core_discord.text_sanitize import scrub_surrogates
25
+
26
+ log = logging.getLogger(__name__)
27
+
28
+
29
+ def _redact_url_qs(text: str) -> str:
30
+ """Strip query strings from any URL in a message so signed Discord CDN
31
+ tokens (?ex=&is=&hm=) never reach logs or persisted envelope metadata.
32
+ """
33
+ return re.sub(r"(https?://[^\s?]+)\?\S*", r"\1?<redacted>", text)
34
+
35
+
36
+ class _HandlersMixin(_EndpointState):
37
+ def _add_listener(self, handler: Callable[..., Any], event_name: str) -> None:
38
+ """Register an event handler against the discord.py client.
39
+
40
+ Real discord.py uses `Client.add_listener(coro, name=)`. Tests use a
41
+ fake that exposes the same surface. Going through this helper lets us
42
+ switch implementations without touching call sites.
43
+ """
44
+ if hasattr(self._client, "add_listener"):
45
+ self._client.add_listener(handler, name=event_name)
46
+ else:
47
+ # Older fakes / minimal stubs: rebind the handler's name and use
48
+ # the @client.event protocol as a fallback.
49
+ handler.__name__ = event_name
50
+ self._client.event(handler)
51
+
52
+ def _remember_inbound_mapping(
53
+ self, envelope_id: str, discord_message_id: str, channel_id: str
54
+ ) -> None:
55
+ """Map a published inbound envelope id to Discord ids (LRU-capped)."""
56
+ self._inbound_envelope_discord[envelope_id] = (discord_message_id, channel_id)
57
+ while len(self._inbound_envelope_discord) > self.pending_acks_max:
58
+ self._inbound_envelope_discord.popitem(last=False)
59
+
60
+ def _record_inbound(self, envelope: Envelope) -> None:
61
+ """Cache an inbound envelope for auto-echo lookups (#83).
62
+
63
+ Stores the full envelope so _resolve_channel_id can read
64
+ metadata.discord.channel_id when an outbound's in_reply_to
65
+ matches the cached id.
66
+ """
67
+ self._recent_inbounds[envelope.id] = envelope
68
+ self._recent_inbounds.move_to_end(envelope.id)
69
+ self._recent_inbounds_timestamps[envelope.id] = time.monotonic()
70
+ while len(self._recent_inbounds) > self._recent_inbounds_max:
71
+ oldest_id, _ = self._recent_inbounds.popitem(last=False)
72
+ self._recent_inbounds_timestamps.pop(oldest_id, None)
73
+
74
+ def _resolve_channel_id(self, outbound: Envelope) -> str:
75
+ """Resolve channel_id with precedence:
76
+ 1. Explicit metadata.discord.channel_id (preserves current behavior).
77
+ 2. Fallback: in_reply_to -> _recent_inbounds lookup (auto-echo).
78
+ 3. Hard error -- refuse to guess.
79
+
80
+ Sub-causes for the failure path are logged at WARNING; the
81
+ agent-facing _ToolError message is unified.
82
+ """
83
+ # 1. Explicit always wins.
84
+ discord_meta = (outbound.metadata or {}).get("discord") or {}
85
+ if explicit := discord_meta.get("channel_id"):
86
+ return str(explicit)
87
+
88
+ # 2. Auto-echo via in_reply_to cache lookup.
89
+ if outbound.in_reply_to:
90
+ inbound = self._recent_inbounds.get(outbound.in_reply_to)
91
+ if inbound:
92
+ inbound_discord = (inbound.metadata or {}).get("discord") or {}
93
+ if cid := inbound_discord.get("channel_id"):
94
+ return str(cid)
95
+ log.warning(
96
+ "channel_id resolution failed: cached_inbound_missing_channel_id, "
97
+ "in_reply_to=%s", outbound.in_reply_to,
98
+ )
99
+ else:
100
+ log.warning(
101
+ "channel_id resolution failed: cache_miss, in_reply_to=%s",
102
+ outbound.in_reply_to,
103
+ )
104
+ else:
105
+ log.warning(
106
+ "channel_id resolution failed: no_explicit_no_in_reply_to, "
107
+ "outbound_id=%s", outbound.id,
108
+ )
109
+
110
+ raise _ToolError(
111
+ "cannot determine channel — set metadata.discord.channel_id "
112
+ "explicitly, or set in_reply_to so auto-echo can resolve."
113
+ )
114
+
115
+ async def _typing_while_pending(self, channel: Any, message_id: str) -> None:
116
+ """Hold Discord 'typing…' until this message is cleared from the awaiting set."""
117
+ typing_factory = getattr(channel, "typing", None)
118
+ if typing_factory is None:
119
+ return
120
+ try:
121
+ async with typing_factory():
122
+ while message_id in self._awaiting_reply_ids:
123
+ # TTL safety net (#84): orphan entries (no explicit cleanup
124
+ # fired, agent dismissed without reply, cache miss) evict
125
+ # after _TYPING_TTL_SECONDS. A missing timestamp means the
126
+ # entry is an orphan → evict immediately.
127
+ #
128
+ # Detect "missing" with an explicit `is None`, NOT `get(mid, 0)`
129
+ # + `monotonic() - 0 > TTL`: time.monotonic()'s epoch is
130
+ # arbitrary (~boot), so on a freshly-booted host monotonic()
131
+ # can be < TTL and `monotonic() - 0 > TTL` is False — wedging
132
+ # the orphan in the set forever (a host-uptime-dependent hang,
133
+ # surfaced on fresh CI runners).
134
+ ts = self._awaiting_reply_ids_timestamps.get(message_id)
135
+ if ts is None or time.monotonic() - ts > self._TYPING_TTL_SECONDS:
136
+ self._awaiting_reply_ids.discard(message_id)
137
+ self._awaiting_reply_ids_timestamps.pop(message_id, None)
138
+ break
139
+ # Short poll so ack clear / stop() drops the id promptly; the
140
+ # typing context manager (discord.py) keeps the indicator fresh.
141
+ await asyncio.sleep(0.2)
142
+ except asyncio.CancelledError:
143
+ raise
144
+ except Exception:
145
+ log.debug(
146
+ "discord(%s): typing loop for message %s ended",
147
+ self.name,
148
+ message_id,
149
+ exc_info=True,
150
+ )
151
+
152
+ def _make_on_message_handler(self) -> Callable[[Any], Coroutine[Any, Any, None]]:
153
+ async def on_message(message: Any) -> None:
154
+ # 1. Filter our OWN messages only — self-loops would feed the
155
+ # bot its own posts. Other bots are NOT pre-filtered here:
156
+ # the access gate's ``allowed_bot_ids`` field (added in
157
+ # PR #158 for agent_core#143) is the right layer to decide
158
+ # which other-bot authors should pass. Pre-filtering all
159
+ # bots here made ``allowed_bot_ids`` structurally
160
+ # unreachable; surfaced 2026-06-07 during the Pepper-Wren
161
+ # cross-bot rollout smoke test, where Pepper's posts in a
162
+ # shared channel never reached Wren's bus inbox.
163
+ if message.author == self._client.user:
164
+ return
165
+
166
+ # 2. Build inbound context for the access gate. ``is_bot`` is
167
+ # piped through from the discord.py Member/User flag so the
168
+ # gate can route through the allowed_bot_ids branch
169
+ # correctly (was hardcoded ``False`` before, which made the
170
+ # ``ctx.is_bot`` check in ``gate_message`` permanently dead).
171
+ is_dm = message.guild is None
172
+ ctx = InboundContext(
173
+ is_dm=is_dm,
174
+ author_id=str(message.author.id),
175
+ channel_id=str(message.channel.id),
176
+ is_bot=bool(getattr(message.author, "bot", False)),
177
+ )
178
+
179
+ # 3. Run the access gate.
180
+ if not gate_message(self._access, ctx):
181
+ log.debug(
182
+ "discord(%s): gate denied message from %s in channel %s",
183
+ self.name,
184
+ message.author.id,
185
+ message.channel.id,
186
+ )
187
+ return
188
+
189
+ # 4. Add ack reaction (best-effort) and track for later clearing.
190
+ ack_emoji = self._access.ack_reaction
191
+ if ack_emoji:
192
+ added = False
193
+ try:
194
+ await message.add_reaction(ack_emoji)
195
+ added = True
196
+ except Exception:
197
+ log.warning(
198
+ "discord(%s): add_reaction failed on message %s — skipping pending ack",
199
+ self.name,
200
+ message.id,
201
+ )
202
+ if added:
203
+ self._track_pending_ack(str(message.id), ack_emoji, str(message.channel.id))
204
+
205
+ # 5. Collect attachment metadata.
206
+ attachments: list[dict[str, Any]] = []
207
+ for att in getattr(message, "attachments", []) or []:
208
+ attachments.append(
209
+ {
210
+ "filename": att.filename,
211
+ "url": att.url,
212
+ "content_type": getattr(att, "content_type", None) or "unknown",
213
+ "size_bytes": int(getattr(att, "size", 0)),
214
+ # duration_secs is set by Discord on voice messages
215
+ # (audio/ogg); None for all other attachment types.
216
+ "duration_secs": getattr(att, "duration_secs", None),
217
+ }
218
+ )
219
+
220
+ # 6. Build and publish the envelope.
221
+ # Sigil-prefix urgency: '!' -> red, '?' -> yellow, plain -> green.
222
+ # The sigil is stripped from the published payload text. See issue #38.
223
+ urgency, text = parse_sigil(message.content or "")
224
+ text = scrub_surrogates(text)
225
+
226
+ # Mint the envelope id up front so attachment files can be grouped
227
+ # under <attachments_dir>/<envelope_id>/ and enrichment happens
228
+ # before Envelope(...) construction (avoids pydantic copy aliasing).
229
+ env_id = uuid.uuid4().hex
230
+
231
+ # 5b. Auto-download each attachment (best-effort, per-attachment).
232
+ # Failure never blocks or loses the text message: the dict
233
+ # keeps its CDN url and gains a download_error marker.
234
+ for entry in attachments:
235
+ try:
236
+ local, _nbytes = await self._persist_attachment(
237
+ url=entry["url"], subdir=env_id
238
+ )
239
+ entry["local_path"] = str(local)
240
+ except Exception as exc: # best-effort by design
241
+ entry["local_path"] = None
242
+ safe_reason = _redact_url_qs(f"{type(exc).__name__}: {exc}")
243
+ entry["download_error"] = safe_reason
244
+ log.warning(
245
+ "discord(%s): attachment download failed for %s — %s",
246
+ self.name,
247
+ entry.get("filename"),
248
+ safe_reason,
249
+ )
250
+
251
+ # 5c. Transcription pass (best-effort, per audio attachment).
252
+ # Runs only when transcribe_voice is True. Mirrors the
253
+ # download loop discipline: failures add a marker and let
254
+ # delivery continue — never block or drop the message.
255
+ if self.transcribe_voice:
256
+ for entry in attachments:
257
+ ct = entry.get("content_type", "") or ""
258
+ if not ct.startswith("audio/"):
259
+ continue
260
+ if entry.get("local_path") is None:
261
+ continue
262
+ # Duration gate: skip transcription for very long audio.
263
+ dur = entry.get("duration_secs")
264
+ if dur is not None and dur > self.transcribe_max_duration_secs:
265
+ entry["transcription_error"] = (
266
+ f"audio too long ({entry['duration_secs']:.0f}s)"
267
+ )
268
+ continue
269
+ try:
270
+ entry["transcription"] = await self._transcribe_audio(
271
+ Path(entry["local_path"])
272
+ )
273
+ except ImportError:
274
+ log.warning(
275
+ "discord(%s): faster-whisper not installed; "
276
+ "skipping voice transcription for %s",
277
+ self.name,
278
+ entry.get("filename"),
279
+ )
280
+ entry["transcription_error"] = "faster-whisper not installed"
281
+ except Exception as exc:
282
+ safe_msg = _redact_url_qs(f"{type(exc).__name__}: {exc}")
283
+ entry["transcription_error"] = safe_msg
284
+ log.warning(
285
+ "discord(%s): transcription failed for %s — %s",
286
+ self.name,
287
+ entry.get("filename"),
288
+ safe_msg,
289
+ )
290
+
291
+ # Build voice lines from successful transcriptions and append to text.
292
+ voice_lines = [
293
+ entry["transcription"]
294
+ for entry in attachments
295
+ if "transcription" in entry
296
+ ]
297
+ if voice_lines:
298
+ voice_block = "\n".join(f"[voice: {t}]" for t in voice_lines)
299
+ if text:
300
+ text = f"{text}\n{voice_block}"
301
+ else:
302
+ text = voice_block
303
+
304
+ metadata: dict[str, Any] = {
305
+ "discord": {
306
+ "channel_id": str(message.channel.id),
307
+ "message_id": str(message.id),
308
+ "guild_id": str(message.guild.id) if message.guild else "",
309
+ "author_id": str(message.author.id),
310
+ "author_display_name": getattr(message.author, "display_name", "") or "",
311
+ "is_dm": is_dm,
312
+ # is_bot piped through so downstream beings can tell "this
313
+ # is from another agent-core being" vs "this is from Jeff"
314
+ # without inspecting bot id maps. Pairs with the
315
+ # allowed_bot_ids gate (agent_core#143).
316
+ "is_bot": ctx.is_bot,
317
+ },
318
+ }
319
+ if attachments:
320
+ metadata["attachments"] = attachments
321
+
322
+ env = Envelope(
323
+ id=env_id,
324
+ correlation_id=uuid.uuid4().hex,
325
+ to=self.target,
326
+ kind="TextMessage",
327
+ payload=TextMessagePayload(text=text),
328
+ metadata=metadata,
329
+ urgency=urgency,
330
+ created_at=datetime.now(UTC),
331
+ )
332
+ assert self._handle is not None
333
+ self._remember_inbound_mapping(env.id, str(message.id), str(message.channel.id))
334
+ mid = str(message.id)
335
+ self._awaiting_reply_ids.add(mid)
336
+ self._awaiting_reply_ids_timestamps[mid] = time.monotonic()
337
+ try:
338
+ await self._handle.publish(env)
339
+ except BaseException:
340
+ self._awaiting_reply_ids.discard(mid)
341
+ self._awaiting_reply_ids_timestamps.pop(mid, None)
342
+ self._inbound_envelope_discord.pop(env.id, None)
343
+ raise
344
+ self._record_inbound(env)
345
+ self._handle.spawn(
346
+ self._typing_while_pending(message.channel, mid),
347
+ name=f"discord-{self.name}-typing-{mid}",
348
+ )
349
+
350
+ return on_message
351
+
352
+ def _channel_allowed(self, channel_id: str) -> bool:
353
+ """Return True if channel_id passes the configured channel allowlist.
354
+
355
+ Mirrors the guild-channel branch of ``gate_message()`` in access.py:
356
+ - Empty ``channels`` dict → allow all (unchanged allow-all default).
357
+ - Non-empty → allow only if ``channel_id`` is an explicit key.
358
+
359
+ Used by meta-event handlers (reaction, message lifecycle, poll vote)
360
+ that share the same channel gate but do not go through the full
361
+ ``gate_message()`` path (which also evaluates DM policy, bot-block,
362
+ and author identity — not applicable to these events).
363
+ """
364
+ if not self._access.channels:
365
+ return True
366
+ return channel_id in self._access.channels
367
+
368
+ def _make_on_reaction_add_handler(
369
+ self,
370
+ ) -> Callable[[Any, Any], Coroutine[Any, Any, None]]:
371
+ async def on_reaction_add(reaction: Any, user: Any) -> None:
372
+ # 1. Drop the bot's own reactions.
373
+ if user == self._client.user or user.bot:
374
+ return
375
+
376
+ # 2. Drop the ack emoji (the bot's own 👀, even if user reacts with same).
377
+ ack_emoji = self._access.ack_reaction
378
+ if ack_emoji and str(reaction.emoji) == ack_emoji:
379
+ return
380
+
381
+ # 3. Channel allowlist gate — same rule as on_message.
382
+ message = reaction.message
383
+ channel_id_str = str(message.channel.id)
384
+ if not self._channel_allowed(channel_id_str):
385
+ return
386
+
387
+ # 4. Build the Event envelope.
388
+ data: dict[str, Any] = {
389
+ "emoji": str(reaction.emoji),
390
+ "channel_id": channel_id_str,
391
+ "message_id": str(message.id),
392
+ "guild_id": str(message.guild.id) if message.guild else "",
393
+ "user_id": str(user.id),
394
+ "user_display_name": getattr(user, "display_name", "") or "",
395
+ }
396
+ env = Envelope(
397
+ id=uuid.uuid4().hex,
398
+ correlation_id=uuid.uuid4().hex,
399
+ to=self.target,
400
+ kind="Event",
401
+ payload=EventPayload(type="discord.reaction_add", data=data),
402
+ created_at=datetime.now(UTC),
403
+ )
404
+ assert self._handle is not None
405
+ await self._handle.publish(env)
406
+ self._record_inbound(env)
407
+
408
+ return on_reaction_add
409
+
410
+ async def _resolve_user_display_name(self, user_id: int) -> str:
411
+ """Resolve a Discord user's display name with sticky cache.
412
+
413
+ Resolution order:
414
+ 1. Local cache (``self._user_display_name_cache``) — sticky for
415
+ the lifetime of the endpoint. The whole point: a user fires
416
+ 100 votes, we fetch them once.
417
+ 2. ``client.get_user(user_id)`` — discord.py's own cache, populated
418
+ opportunistically by message / reaction events whose
419
+ dispatchers hydrate the User. Synchronous, cheap.
420
+ 3. ``client.fetch_user(user_id)`` — HTTP round-trip. Reliable but
421
+ adds latency; only paid on first encounter with the user.
422
+
423
+ Returns the empty string on any failure (uncached + fetch raises,
424
+ or no client). Failures are deliberately NOT cached so a
425
+ transient HTTP error doesn't lock the user at empty forever.
426
+ """
427
+ user_id_str = str(user_id)
428
+ cached = self._user_display_name_cache.get(user_id_str)
429
+ if cached is not None:
430
+ return cached
431
+ if self._client is None:
432
+ return ""
433
+ user = self._client.get_user(user_id)
434
+ if user is None:
435
+ try:
436
+ user = await self._client.fetch_user(user_id)
437
+ except Exception:
438
+ # discord.NotFound, HTTPException, network error, etc.
439
+ # Don't cache — try again next time.
440
+ return ""
441
+ name = str(getattr(user, "display_name", "") or "")
442
+ if name:
443
+ self._user_display_name_cache[user_id_str] = name
444
+ return name
445
+
446
+ def _make_on_raw_poll_vote_handler(
447
+ self, event_type: str
448
+ ) -> Callable[[Any], Coroutine[Any, Any, None]]:
449
+ """Build a handler for ``on_raw_poll_vote_add`` / ``on_raw_poll_vote_remove``.
450
+
451
+ Both events have identical payload shape (``RawPollVoteActionEvent``
452
+ with message_id / channel_id / user_id / guild_id / answer_id), so a
453
+ single factory parameterised by ``event_type`` covers both. We use
454
+ the *raw* variants rather than the cached ``poll_vote_add`` /
455
+ ``poll_vote_remove`` so the agent gets notified even after the
456
+ underlying message has been evicted from the client's cache.
457
+ """
458
+
459
+ async def on_raw_poll_vote(raw: Any) -> None:
460
+ # Drop the bot's own votes — same policy as on_reaction_add.
461
+ self_user = self._client.user if self._client else None
462
+ self_id = getattr(self_user, "id", None) if self_user is not None else None
463
+ if self_id is not None and str(getattr(raw, "user_id", "")) == str(self_id):
464
+ return
465
+
466
+ # Channel allowlist gate — same rule as on_message.
467
+ if not self._channel_allowed(str(raw.channel_id)):
468
+ return
469
+
470
+ # Resolve the voter's display name with a sticky local cache.
471
+ # Parity goal: ``discord.reaction_add`` Events carry
472
+ # ``user_display_name`` for free (discord.py hydrates the
473
+ # User object before dispatch). Raw poll vote events only
474
+ # carry IDs, so the handler has to resolve. First miss →
475
+ # HTTP fetch_user; subsequent votes from same user → cache
476
+ # hit. Caught on testbot 2026-05-05 round-3 verification.
477
+ user_display_name = await self._resolve_user_display_name(
478
+ int(raw.user_id)
479
+ )
480
+
481
+ data: dict[str, Any] = {
482
+ "message_id": str(raw.message_id),
483
+ "channel_id": str(raw.channel_id),
484
+ "user_id": str(raw.user_id),
485
+ "user_display_name": user_display_name,
486
+ "guild_id": str(raw.guild_id) if raw.guild_id else "",
487
+ "answer_id": int(raw.answer_id),
488
+ }
489
+ env = Envelope(
490
+ id=uuid.uuid4().hex,
491
+ correlation_id=uuid.uuid4().hex,
492
+ to=self.target,
493
+ kind="Event",
494
+ payload=EventPayload(type=event_type, data=data),
495
+ created_at=datetime.now(UTC),
496
+ )
497
+ assert self._handle is not None
498
+ await self._handle.publish(env)
499
+ self._record_inbound(env)
500
+
501
+ return on_raw_poll_vote
502
+
503
+ def _make_on_raw_message_lifecycle_handler(
504
+ self, event_type: str
505
+ ) -> Callable[[Any], Coroutine[Any, Any, None]]:
506
+ """Build a handler for ``on_raw_message_edit`` / ``on_raw_message_delete``.
507
+
508
+ Both raw events expose ``message_id``, ``channel_id``, ``guild_id``
509
+ (Optional). We deliberately don't try to surface message *content*
510
+ in the envelope — for edits, the new content lives in
511
+ ``raw.data`` (a partial gateway dict) and may not include the full
512
+ message; for deletes, there's nothing to surface anyway. Agents
513
+ that need content can refetch via ``fetch_messages``.
514
+ """
515
+
516
+ async def on_raw_message_lifecycle(raw: Any) -> None:
517
+ # Channel allowlist gate — same rule as on_message.
518
+ if not self._channel_allowed(str(raw.channel_id)):
519
+ return
520
+
521
+ data: dict[str, Any] = {
522
+ "message_id": str(raw.message_id),
523
+ "channel_id": str(raw.channel_id),
524
+ "guild_id": str(raw.guild_id) if raw.guild_id else "",
525
+ }
526
+ env = Envelope(
527
+ id=uuid.uuid4().hex,
528
+ correlation_id=uuid.uuid4().hex,
529
+ to=self.target,
530
+ kind="Event",
531
+ payload=EventPayload(type=event_type, data=data),
532
+ created_at=datetime.now(UTC),
533
+ )
534
+ assert self._handle is not None
535
+ await self._handle.publish(env)
536
+ self._record_inbound(env)
537
+
538
+ return on_raw_message_lifecycle