Files
meshcore-bot/modules/commands/magic8_command.py
T
agessaman fc63039a48 fix: address Codex review of tonight's work
Correctness:

- {path_distance} was always blank in production. The resolution code that
  builds repeater_info dropped latitude/longitude in every branch, so the
  calculator could never find a coordinate. My tests passed hand-built
  dicts straight to the calculator and never exercised the builder, which
  is why they stayed green. Coordinates are now carried through all four
  construction sites, and the new tests drive _lookup_repeater_names via
  its lookup_func hook so the real builder runs.

- The #80 route guard was defeated two ways in the channel handler. When
  the RF data was an uncorrelated fallback, control fell through to the
  raw-hex and routing_info fallbacks below, which took the route from the
  unrelated packet anyway; the guard had actually made that path
  reachable. message.routing_info was also assigned unconditionally, and
  the path command reads it. "Not attributable" is now a terminal branch
  and the routing_info hand-off checks provenance.

- Same fix was incomplete for DMs: routing_info was captured and turned
  into path_info before the provenance check ran, so the later check only
  declined to overwrite an already-wrong value. Guarded at the source.

- Rendering could transmit for real. Capture only intercepts
  send_response, but advert calls send_advert() directly and
  send_response_chunked never checked capture_sink. Chunked sends are now
  captured, and rendering is opt-in via BaseCommand.render_safe (default
  False) instead of a denylist that cannot be complete. This also closes
  the DM-only leak: schedule is not marked safe, so {cmd:schedule} can no
  longer broadcast configuration to a channel.

- Multi-part rendered output was rejoined into one oversized send.
  Scheduled messages are now split to the RF body budget and sent through
  send_channel_messages_chunked, on character boundaries so multi-byte
  text is not corrupted.

- _last_path_distance_km is instance state that was only set on success,
  so an invalid path request could show the previous request's distance.
  Reset at the start of every execute().

- Stale-contact retries were only counted on non-OK results, so timeouts
  and exceptions left a contact eligible forever and could recreate the
  storm. All failed attempts count now.

Web viewer:

- A failed config reload was reported as a successful save. The API and
  UI now distinguish "saved and active" from "saved, restart needed".

- Preview count was unbounded; clamped to 1-20.

- update_ini_values is a read-modify-replace with no locking, so two
  concurrent viewer saves could lose one. Serialised behind a lock.
2026-08-22 00:16:03 -07:00

101 lines
3.4 KiB
Python

#!/usr/bin/env python3
"""
Magic 8-ball command for the MeshCore Bot
Handles the 'magic8' keyword response
"""
import random
from typing import Optional
from ..models import MeshMessage
from .base_command import BaseCommand
magic8_responses = ["It is certain.","It is decidedly so.","Without a doubt.","Yes definitely.","You may rely on it.","As I see it, yes.","Most likely.","Outlook good.","Yes.","Signs point to yes.","Reply hazy, try again.","Ask again later.","Better not tell you now.","Cannot predict now.","Concentrate and ask again.","Don't count on it.","My reply is no.","My sources say no.","Outlook not so good.","Very doubtful."]
def magic8():
answer=magic8_responses[random.randint(0,len(magic8_responses)-1)]
return answer
class Magic8Command(BaseCommand):
"""Handles the magic8 command.
Emulates a Magic 8-Ball, providing a random "fortune" response to a user's question.
"""
# Plugin metadata
# Read-only informational output; safe for scheduled {cmd:...} rendering.
render_safe = True
name = "magic8"
keywords = ['magic8']
description = "Emulates the classic Magic 8-ball toy'"
category = "games"
# Documentation
short_description = "Ask the Magic 8-Ball a yes/no question"
usage = "magic8 <question>"
examples = ["magic8 Will it rain tomorrow?"]
def __init__(self, bot):
"""Initialize the magic8 command.
Args:
bot: The bot instance.
"""
super().__init__(bot)
self.magic8_enabled = self.get_config_value('Magic8_Command', 'enabled', fallback=True, value_type='bool')
def can_execute(self, message: MeshMessage, skip_channel_check: bool = False) -> bool:
"""Check if this command can be executed with the given message.
Args:
message: The message triggering the command.
Returns:
bool: True if command is enabled and checks pass, False otherwise.
"""
if not self.magic8_enabled:
return False
return super().can_execute(message)
def get_help_text(self) -> str:
"""Get help text for the magic8 command.
Returns:
str: The help text for this command.
"""
return self.translate('commands.magic8.description')
def get_response_format(self) -> Optional[str]:
"""Get the response format from config.
Returns:
Optional[str]: The format string for the response, or None if not configured.
"""
if self.bot.config.has_section('Keywords'):
format_str = self.bot.config.get('Keywords', 'magic8', fallback=None)
return self._strip_quotes_from_config(format_str) if format_str else None
return None
async def execute(self, message: MeshMessage) -> bool:
"""Execute the magic8 command.
Selects a random response and sends it to the user.
Args:
message: The message that triggered the command.
Returns:
bool: True if executed successfully, False otherwise.
"""
answer = magic8()
# Format response with sender mention for channel messages, without for DMs
if message.is_dm:
response = f"🎱 {answer}"
else:
sender = message.sender_id or "Unknown"
response = f"🎱 @[{sender}] {answer}"
return await self.send_response(message, response)