feat(bot): hardening + auto-responder, query commands, quiet hours

Reply-bot overhaul on top of the trigger/reply auto-reply:

Robustness
- single botTriggerMatches() shared by DM/channel paths; named constants
  (BOT_REPLY_COOLDOWN_MS / BOT_SCRATCH) replace magic numbers.
- per-contact DM throttle (8-entry ring) so a second sender isn't starved
  while one contact is on cooldown.
- channel anti-loop: skip only when an incoming message equals our own reply
  (was: any reply containing the trigger word — which silently killed channel
  replies for the common "trigger word in reply" setup).

Features
- away / reply-to-all: a lone "*" trigger matches every message.
- independent DM vs channel triggers (bot_trigger / bot_trigger_ch); "*" works
  on the channel too, bounded by cooldown + echo guard.
- query commands: a DM or monitored-channel message is scanned for "!word"
  tokens — !ping/!batt/!loc/!time/!temp/!hops/!status/!help — merged into one
  combined reply. DM = per-contact throttle, ignores quiet hours; channel =
  broadcast, per-channel cooldown, respects quiet hours. !hops uses
  getPathHashCount() (0 = direct).
- quiet hours (bot_quiet_start/end, local, wraps midnight) silence push replies.
- reply counter shown in the BotScreen header.

UI / storage
- BotScreen: 9 rows, scrolling list (no more cramming), field I/O via
  fieldBuf()/fieldCap().
- prefs bot_commands_enabled / bot_quiet_start / bot_quiet_end / bot_trigger_ch
  persisted; schema 0xC0DE000A → 0xC0DE000C with clamping + migration
  (bot_trigger_ch seeded from bot_trigger on upgrade).
- docs: tools_screen bot section rewritten; FEATURES.md refreshed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MarekZegare4
2026-06-15 11:57:27 +02:00
parent 8c0ccaed73
commit 8bd6fbf1cb
8 changed files with 410 additions and 100 deletions

View File

@@ -493,14 +493,9 @@ Tools Stats:
Read-only. UP/DOWN switches between metrics. Bottom shows current value as text.
### Auto-reply trigger words with sensor placeholders
### Auto-reply query commands with live data
Bot already has a single trigger word. Extend to a small table of (trigger, reply-with-placeholder) pairs:
- "temp?" → replies with `{temp}`
- "loc?" → replies with `{loc}`
- "batt?" → replies with `{batt}`
Stored in NodePrefs as fixed-size table (say 4 pairs × 16 B). UI: edit pairs in Tools Auto-Reply Bot.
Realised as a **command bot** rather than a trigger/reply table: with **Commands** ON, a DM is scanned for `!word` tokens and answered with live node data via `expandMsg``!batt`/`!loc`/`!time`/`!temp`/`!status`/`!ping`/`!help`, plus `!hops` (per-message hop count via `getPathHashCount()`, `direct` if heard directly). Multiple commands in one message are merged into a single ` | `-joined reply (one transmission/throttle/counter tick) via the shared `botScanCommands`. Works in DMs (per-contact throttle, ignores quiet hours — a pull) and on the bot's **monitored channel** (broadcast: per-channel cooldown, respects quiet hours). Toggled independently of the trigger bot. See [`MyMeshBot.h`](examples/companion_radio/MyMeshBot.h) `tryBotCommand` / `tryBotChannelCommand` / `botCommandReply`.
### ✅ Lock-screen unread count
@@ -774,7 +769,7 @@ Pub-key line is skipped entirely when `max_chars < 4` instead of feeding a negat
### 📋 `expandMsg` GPS validity test treats (0, 0) as invalid
[`MyMeshBot.h:23, 60`](examples/companion_radio/MyMeshBot.h#L23)
[`MyMeshBot.h:95, 132, 182`](examples/companion_radio/MyMeshBot.h#L95)
```cpp
sensors.node_lat != 0.0 || sensors.node_lon != 0.0 // proxy for "valid GPS"
@@ -798,9 +793,9 @@ Safe today (CAPACITY=512 fits), fragile if CAPACITY grows past 65535.
### 📋 Bot `strstr` on truncated 199-char buffer
[`MyMeshBot.h:14-17`](examples/companion_radio/MyMeshBot.h#L14-L17)
[`MyMeshBot.h:22-25`](examples/companion_radio/MyMeshBot.h#L22-L25)
Trigger word near the end of a >199-character message will not match.
Trigger word near the end of a >199-character message will not match. Matching is now centralised in `botTriggerMatches()` (single `BOT_SCRATCH`-sized buffer), so a fix would land in one place.
### ✅ `strncpy("?", buf, sizeof(buf))` replaced with `strcpy`

View File

@@ -252,11 +252,38 @@ When the bot is enabled it listens to DMs by default. Channel monitoring is an o
| Setting | Description |
| ------------- | -------------------------------------------------------------------------------- |
| Bot | ON / OFF — enables DM listening |
| Channel mode | ON / OFF — additionally monitors a selected channel |
| Channel | Which channel to monitor (only relevant when channel mode is ON) |
| Trigger | Word or phrase that activates the reply (shared by both modes, case-insensitive) |
| DM reply | Reply text for DMs; supports `{time}` and `{loc}` placeholders |
| Channel reply | Reply text for channel messages; supports `{time}` and `{loc}` placeholders |
| Enable | ON / OFF — enables DM listening |
| Channel | OFF, or which channel to additionally monitor (cycles through your channels) |
| Trigger DM | Word or phrase that activates the DM reply (case-insensitive). A lone `*` means **reply to every DM** (away mode) and is shown as `(any msg)`. |
| Reply DM | Reply text for DMs; supports `{time}`, `{loc}` and sensor placeholders |
| Trigger Ch | Independent trigger for the monitored channel. `*` means **reply to every channel message** — bounded by the per-channel cooldown, but use sparingly on a busy channel. |
| Reply Ch | Reply text for channel messages; supports the same placeholders |
| Commands | ON / OFF — answer `!` query commands (see below) |
| Quiet from/to | Local-time window during which auto-replies stay silent; set both equal (`OFF`) to disable |
A 10-second cooldown prevents repeated replies in quick succession.
The DM and channel triggers are independent, so you can run e.g. an away-message (`*`) in DMs while the channel reacts only to a specific keyword (or vice-versa).
The header shows a running count of auto-replies sent since boot.
**Throttle.** Auto-replies are rate-limited **per contact** (10 s), so a second sender is never starved while one contact is on cooldown. The channel bot keeps a single 10 s cooldown and won't echo a message identical to its own reply (so two bots running the same reply text on one channel can't ping-pong); the cooldown caps any residual back-and-forth.
**Quiet hours** suppress the push (trigger) replies between the configured local hours; a window where *from* is later than *to* wraps past midnight. Commands are a pull (explicitly requested), so they answer even during quiet hours.
### Commands
With **Commands** ON, a DM beginning with `!` is answered with live node data, independent of the trigger:
| Command | Reply |
| --------- | --------------------------------------- |
| `!ping` | `pong` |
| `!batt` | battery voltage |
| `!loc` | GPS coordinates (or `no GPS`) |
| `!time` | local time `HH:MM` |
| `!temp` | temperature (or `n/a` if no sensor) |
| `!hops` | how many hops the command message took to reach the node (`direct` if heard directly) |
| `!status` | combined battery / location / time |
| `!help` | list of available commands |
Several commands can be combined in one message — `!batt !time !hops` is answered with a single `4.10V | 14:30 | 3 hops` reply (one transmission). A message with no recognised command falls through to the trigger bot.
Commands also work on the **monitored channel** (the one selected for channel mode) — anyone there can query the node. Channel replies are broadcast to everyone, so unlike DM commands they respect quiet hours and use the shared per-channel cooldown. DM commands use the per-contact throttle.

View File

@@ -325,6 +325,15 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
rd(&_prefs.rx_powersave, sizeof(_prefs.rx_powersave));
rd(&_prefs.tx_apc, sizeof(_prefs.tx_apc));
rd(&_prefs.dm_resend_count, sizeof(_prefs.dm_resend_count));
rd(&_prefs.bot_commands_enabled, sizeof(_prefs.bot_commands_enabled));
rd(&_prefs.bot_quiet_start, sizeof(_prefs.bot_quiet_start));
rd(&_prefs.bot_quiet_end, sizeof(_prefs.bot_quiet_end));
rd(_prefs.bot_trigger_ch, sizeof(_prefs.bot_trigger_ch));
// → 0xC0DE000B: append bot_commands_enabled + quiet-hours. Older files leave
// stray bytes here; clamp so upgraders fall back to off / no quiet hours.
if (_prefs.bot_commands_enabled > 1) _prefs.bot_commands_enabled = 0;
if (_prefs.bot_quiet_start > 23) _prefs.bot_quiet_start = 0;
if (_prefs.bot_quiet_end > 23) _prefs.bot_quiet_end = 0;
// These fields were appended over successive schema bumps; an older file
// can leave stray bytes here, so clamp out-of-range values back to defaults.
// Values for notif_melody_ad: 0=built-in, 1=melody1, 2=melody2, 3=none.
@@ -366,6 +375,11 @@ void DataStore::loadPrefsInt(const char *filename, NodePrefs& _prefs, double& no
// upgraders fall back to built-in advert sound + metric + speed + All.
// → 0xC0DE0009: append tx_apc after rx_powersave. Clamped above, so
// upgraders fall back to APC off (fixed tx power).
// → 0xC0DE000C: split out a per-channel trigger (was shared with the DM
// trigger). Pre-0x0C files have no bot_trigger_ch; seed it from bot_trigger
// so an existing channel bot keeps reacting to the same word after upgrade.
if (_prefs.bot_trigger_ch[0] == '\0')
strncpy(_prefs.bot_trigger_ch, _prefs.bot_trigger, sizeof(_prefs.bot_trigger_ch) - 1);
}
file.close();
@@ -461,6 +475,10 @@ void DataStore::savePrefs(const NodePrefs& _prefs, double node_lat, double node_
file.write((uint8_t *)&_prefs.rx_powersave, sizeof(_prefs.rx_powersave));
file.write((uint8_t *)&_prefs.tx_apc, sizeof(_prefs.tx_apc));
file.write((uint8_t *)&_prefs.dm_resend_count, sizeof(_prefs.dm_resend_count));
file.write((uint8_t *)&_prefs.bot_commands_enabled, sizeof(_prefs.bot_commands_enabled));
file.write((uint8_t *)&_prefs.bot_quiet_start, sizeof(_prefs.bot_quiet_start));
file.write((uint8_t *)&_prefs.bot_quiet_end, sizeof(_prefs.bot_quiet_end));
file.write((uint8_t *)_prefs.bot_trigger_ch, sizeof(_prefs.bot_trigger_ch));
// Tail sentinel — must be last. See NodePrefs::SCHEMA_SENTINEL.
uint32_t sentinel = NodePrefs::SCHEMA_SENTINEL;

View File

@@ -569,7 +569,13 @@ void MyMesh::onMessageRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t
markConnectionActive(from); // in case this is from a server, and we have a connection
queueMessage(from, TXT_TYPE_PLAIN, pkt, sender_timestamp, NULL, 0, text);
tryBotReplyDM(from, text);
// hop count of the received message. getPathHashCount() (low 6 bits of path_len)
// is the number of repeaters traversed — the same value the mesh uses for flood
// retransmit priority. 0 = heard directly. (Raw path_len is a size/count
// bitfield for transport packets, so it must not be used directly.)
uint8_t hops = pkt ? pkt->getPathHashCount() : 0;
if (!tryBotCommand(from, text, hops)) // commands take priority; fall through to trigger reply
tryBotReplyDM(from, text);
}
void MyMesh::onCommandDataRecv(const ContactInfo &from, mesh::Packet *pkt, uint32_t sender_timestamp,
@@ -639,7 +645,9 @@ void MyMesh::onChannelMessageRecv(const mesh::GroupChannel &channel, mesh::Packe
if (_ui) _ui->newMsg(path_len, channel_name, text, offline_queue_len, 0);
#endif
tryBotReplyChannel(channel_idx, text);
// hop count for !hops (see onMessageRecv); not the wire path_len above.
if (!tryBotChannelCommand(channel_idx, text, pkt->getPathHashCount())) // commands take priority
tryBotReplyChannel(channel_idx, text);
}
void MyMesh::onChannelDataRecv(const mesh::GroupChannel &channel, mesh::Packet *pkt, uint16_t data_type,
@@ -1217,8 +1225,9 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
_last_relay_seq = 0;
offline_queue_len = 0;
app_target_ver = 0;
_bot_last_dm_reply_ms = 0;
_bot_last_ch_reply_ms = 0;
memset(_bot_dm_log, 0, sizeof(_bot_dm_log));
_bot_reply_count = 0;
_next_auto_advert_ms = 0;
clearPendingReqs();
next_ack_idx = 0;
@@ -1262,6 +1271,10 @@ MyMesh::MyMesh(mesh::Radio &radio, mesh::RNG &rng, mesh::RTCClock &rtc, SimpleMe
_prefs.bot_trigger[0] = '\0';
_prefs.bot_reply_dm[0] = '\0';
_prefs.bot_reply_ch[0] = '\0';
_prefs.bot_trigger_ch[0] = '\0';
_prefs.bot_commands_enabled = 0;
_prefs.bot_quiet_start = 0;
_prefs.bot_quiet_end = 0; // start==end → quiet hours disabled
_prefs.dm_show_all = 1; // show all contacts by default
_prefs.dm_resend_count = 2; // auto-resend on-device DMs twice by default
memset(_prefs.dm_notif, 0, sizeof(_prefs.dm_notif));

View File

@@ -245,9 +245,20 @@ public:
// To check if there is pending work
bool hasPendingWork() const;
// Number of auto-replies sent since boot (DM + channel). Shown on BotScreen.
uint16_t botReplyCount() const { return _bot_reply_count; }
private:
void tryBotReplyDM(const ContactInfo& from, const char* text);
void tryBotReplyChannel(uint8_t channel_idx, const char* text);
bool tryBotCommand(const ContactInfo& from, const char* text, uint8_t hops); // DM commands
bool tryBotChannelCommand(uint8_t channel_idx, const char* text, uint8_t hops); // channel commands
bool botCommandReply(const char* cmd, uint8_t hops, uint32_t ts, char* out, int out_len); // one command → reply text
int botScanCommands(const char* body, uint8_t hops, uint32_t ts, char* out, int out_len); // scan "!word"s → combined reply, returns count
bool botTriggerMatches(const char* trigger, const char* body, bool allow_wildcard) const;
bool botInQuietHours() const; // true when auto-replies should stay silent
bool botDmAllowed(const uint8_t* pubkey); // per-contact DM throttle: ok to reply?
void botDmRecord(const uint8_t* pubkey); // remember we just replied to this contact
void writeOKFrame();
void writeErrFrame(uint8_t err_code);
@@ -320,10 +331,16 @@ private:
uint8_t *sign_data;
uint32_t sign_data_len;
unsigned long dirty_contacts_expiry;
unsigned long _bot_last_dm_reply_ms;
unsigned long _bot_last_ch_reply_ms;
unsigned long _next_auto_advert_ms;
// Per-contact DM reply throttle: a small ring of the most recent recipients so
// one chatty contact can't be spammed while a different sender is still served.
struct BotReplyLog { uint8_t key[4]; unsigned long t_ms; bool used; };
static const int BOT_DM_LOG_SIZE = 8;
BotReplyLog _bot_dm_log[BOT_DM_LOG_SIZE];
uint16_t _bot_reply_count; // total auto-replies sent since boot
TransportKey send_scope;
uint8_t cmd_frame[MAX_FRAME_SIZE + 1];

View File

@@ -2,26 +2,93 @@
// Bot logic — not part of upstream MyMesh.cpp.
// Included at the bottom of MyMesh.cpp after all class definitions.
// Minimum gap between two auto-replies to the same contact (DM) or on the bot
// channel. Guards against floods and, with botTriggerMatches()'s loop check,
// against bot↔bot ping-pong on a shared channel.
static const unsigned long BOT_REPLY_COOLDOWN_MS = 10000UL;
// Scratch buffer size for trigger matching / reply expansion. Covers the full
// incoming message (MAX_TEXT_LEN ~160) plus the 140-byte reply templates.
static const int BOT_SCRATCH = 200;
// Case-insensitive (ASCII) substring test: does `body` contain `trigger`? A lone
// "*" trigger means "match everything" (away / reply-to-all mode); honoured only
// where allow_wildcard is set. DM and channel each pass their own trigger string.
bool MyMesh::botTriggerMatches(const char* trigger, const char* body, bool allow_wildcard) const {
if (!trigger[0]) return false; // empty trigger would match everything
if (trigger[0] == '*' && trigger[1] == '\0')
return allow_wildcard;
char low[BOT_SCRATCH];
size_t n = strlen(body);
if (n >= sizeof(low)) n = sizeof(low) - 1;
for (size_t i = 0; i < n; i++) low[i] = (char)tolower((uint8_t)body[i]);
low[n] = '\0';
char low_trigger[64];
size_t tlen = strnlen(trigger, sizeof(low_trigger) - 1);
for (size_t i = 0; i < tlen; i++) low_trigger[i] = (char)tolower((uint8_t)trigger[i]);
low_trigger[tlen] = '\0';
return strstr(low, low_trigger) != NULL;
}
// Per-contact DM throttle: true if enough time has passed (or we've never
// replied) to this contact. Only the first 4 key bytes are compared — ample to
// tell local contacts apart.
bool MyMesh::botDmAllowed(const uint8_t* pubkey) {
unsigned long now = millis();
for (int i = 0; i < BOT_DM_LOG_SIZE; i++) {
if (_bot_dm_log[i].used && memcmp(_bot_dm_log[i].key, pubkey, 4) == 0)
return now - _bot_dm_log[i].t_ms > BOT_REPLY_COOLDOWN_MS;
}
return true;
}
void MyMesh::botDmRecord(const uint8_t* pubkey) {
unsigned long now = millis();
for (int i = 0; i < BOT_DM_LOG_SIZE; i++) { // refresh existing entry
if (_bot_dm_log[i].used && memcmp(_bot_dm_log[i].key, pubkey, 4) == 0) {
_bot_dm_log[i].t_ms = now;
return;
}
}
int target = -1; // else take a free slot...
for (int i = 0; i < BOT_DM_LOG_SIZE; i++)
if (!_bot_dm_log[i].used) { target = i; break; }
if (target < 0) { // ...or evict the oldest
target = 0;
for (int i = 1; i < BOT_DM_LOG_SIZE; i++)
if (_bot_dm_log[i].t_ms < _bot_dm_log[target].t_ms) target = i;
}
memcpy(_bot_dm_log[target].key, pubkey, 4);
_bot_dm_log[target].t_ms = now;
_bot_dm_log[target].used = true;
}
// Quiet hours: when the local hour is inside [start, end) the auto-reply paths
// stay silent (commands are explicitly requested, so they ignore this). A zero-
// width window (start == end) disables the feature; a window where start > end
// wraps past midnight.
bool MyMesh::botInQuietHours() const {
if (_prefs.bot_quiet_start == _prefs.bot_quiet_end) return false; // disabled
uint32_t utc = getRTCClock()->getCurrentTime();
if (utc < 1000000000UL) return false; // clock not set — don't suppress
uint32_t local = utc + (int32_t)_prefs.tz_offset_hours * 3600;
int h = (int)((local / 3600) % 24);
int s = _prefs.bot_quiet_start, e = _prefs.bot_quiet_end;
return (s < e) ? (h >= s && h < e) // same-day window
: (h >= s || h < e); // overnight window
}
void MyMesh::tryBotReplyDM(const ContactInfo& from, const char* text) {
if (from.type != ADV_TYPE_CHAT) return;
if (!(_prefs.bot_enabled && _prefs.bot_trigger[0] && _prefs.bot_reply_dm[0] &&
millis() - _bot_last_dm_reply_ms > 10000UL))
return;
// Lower-case both body and trigger for case-insensitive matching.
char low[200];
size_t n = strlen(text);
if (n >= sizeof(low)) n = sizeof(low) - 1;
for (size_t i = 0; i < n; i++) low[i] = (char)tolower((uint8_t)text[i]);
low[n] = '\0';
char low_trigger[sizeof(_prefs.bot_trigger)];
size_t tlen = strnlen(_prefs.bot_trigger, sizeof(low_trigger) - 1);
for (size_t i = 0; i < tlen; i++) low_trigger[i] = (char)tolower((uint8_t)_prefs.bot_trigger[i]);
low_trigger[tlen] = '\0';
if (!strstr(low, low_trigger)) return;
if (!(_prefs.bot_enabled && _prefs.bot_reply_dm[0])) return;
if (botInQuietHours()) return;
if (!botTriggerMatches(_prefs.bot_trigger, text, true)) return; // wildcard "*" allowed
if (!botDmAllowed(from.id.pub_key)) return; // already answered this contact recently
uint32_t ts = getRTCClock()->getCurrentTime();
char expanded[200];
char expanded[BOT_SCRATCH];
expandMsg(_prefs.bot_reply_dm, expanded, sizeof(expanded),
sensors.node_lat, sensors.node_lon,
sensors.node_lat != 0.0 || sensors.node_lon != 0.0,
@@ -29,7 +96,8 @@ void MyMesh::tryBotReplyDM(const ContactInfo& from, const char* text) {
&sensors, (float)board.getBattMilliVolts() / 1000.0f);
uint32_t expected_ack, est_timeout;
if (sendMessage(from, ts, 0, expanded, expected_ack, est_timeout) != MSG_SEND_FAILED) {
_bot_last_dm_reply_ms = millis();
botDmRecord(from.id.pub_key);
_bot_reply_count++;
#ifdef DISPLAY_CLASS
if (_ui) _ui->addDMMsg(from.id.pub_key, true, expanded);
#endif
@@ -37,40 +105,37 @@ void MyMesh::tryBotReplyDM(const ContactInfo& from, const char* text) {
}
void MyMesh::tryBotReplyChannel(uint8_t channel_idx, const char* text) {
if (!(_prefs.bot_enabled && _prefs.bot_channel_enabled && _prefs.bot_trigger[0] && _prefs.bot_reply_ch[0] &&
if (!(_prefs.bot_enabled && _prefs.bot_channel_enabled && _prefs.bot_reply_ch[0] &&
channel_idx == _prefs.bot_channel_idx &&
millis() - _bot_last_ch_reply_ms > 10000UL))
millis() - _bot_last_ch_reply_ms > BOT_REPLY_COOLDOWN_MS))
return;
if (botInQuietHours()) return;
// Skip "sender_name: " prefix so the trigger is only matched against the message body.
const char* msg = text;
const char* sep = strstr(text, ": ");
if (sep) msg = sep + 2;
char low[200];
size_t n = strlen(msg);
if (n >= sizeof(low)) n = sizeof(low) - 1;
for (size_t i = 0; i < n; i++) low[i] = (char)tolower((uint8_t)msg[i]);
low[n] = '\0';
char low_trigger[sizeof(_prefs.bot_trigger)];
size_t tlen = strnlen(_prefs.bot_trigger, sizeof(low_trigger) - 1);
for (size_t i = 0; i < tlen; i++) low_trigger[i] = (char)tolower((uint8_t)_prefs.bot_trigger[i]);
low_trigger[tlen] = '\0';
if (!strstr(low, low_trigger)) return;
if (!botTriggerMatches(_prefs.bot_trigger_ch, msg, true)) return; // own trigger; "*" = any msg
ChannelDetails ch;
if (!getChannel(channel_idx, ch)) return;
uint32_t ts = getRTCClock()->getCurrentTime();
char expanded[200];
char expanded[BOT_SCRATCH];
expandMsg(_prefs.bot_reply_ch, expanded, sizeof(expanded),
sensors.node_lat, sensors.node_lon,
sensors.node_lat != 0.0 || sensors.node_lon != 0.0,
ts, _prefs.tz_offset_hours,
&sensors, (float)board.getBattMilliVolts() / 1000.0f);
// Anti-loop: don't echo a message identical to our own reply (e.g. another bot
// on the channel sending the same text), which would ping-pong forever. The
// per-channel cooldown caps any residual back-and-forth between mismatched bots.
if (strcmp(msg, expanded) == 0) return;
int rlen = strlen(expanded);
if (sendGroupMessage(ts, ch.channel, _prefs.node_name, expanded, rlen)) {
_bot_last_ch_reply_ms = millis();
_bot_reply_count++;
#ifdef DISPLAY_CLASS
if (_ui) {
char with_sender[240]; // node_name(32) + ": "(2) + expanded(200) + margin
@@ -80,3 +145,127 @@ void MyMesh::tryBotReplyChannel(uint8_t channel_idx, const char* text) {
#endif
}
}
// Builds the reply text for a single command word into out. Returns false for an
// unknown command. !hops is dynamic (per received message); the rest expand a
// static template via expandMsg's placeholders.
bool MyMesh::botCommandReply(const char* cmd, uint8_t hops, uint32_t ts, char* out, int out_len) {
if (!strcmp(cmd, "hops")) {
if (hops == 0) strncpy(out, "direct", out_len); // heard directly (0 repeaters)
else snprintf(out, out_len, "%u hops", (unsigned)hops);
out[out_len - 1] = '\0';
return true;
}
const char* tmpl = nullptr;
if (!strcmp(cmd, "ping")) tmpl = "pong";
else if (!strcmp(cmd, "batt")) tmpl = "{batt}";
else if (!strcmp(cmd, "loc")) tmpl = "{loc}";
else if (!strcmp(cmd, "time")) tmpl = "{time}";
else if (!strcmp(cmd, "temp")) tmpl = "{temp}";
else if (!strcmp(cmd, "status")) tmpl = "batt {batt} loc {loc} at {time}";
else if (!strcmp(cmd, "help")) tmpl = "cmds: !ping !batt !loc !time !temp !hops !status";
else return false; // unknown — let the trigger bot try
expandMsg(tmpl, out, out_len,
sensors.node_lat, sensors.node_lon,
sensors.node_lat != 0.0 || sensors.node_lon != 0.0,
ts, _prefs.tz_offset_hours,
&sensors, (float)board.getBattMilliVolts() / 1000.0f);
if (strchr(out, '{')) strcpy(out, "n/a"); // requested sensor not present
return true;
}
// Scans body for any number of space-separated "!word" tokens, building a single
// combined reply (segments joined by " | ") into out. Returns how many commands
// were recognised. Shared by the DM and channel command paths.
int MyMesh::botScanCommands(const char* body, uint8_t hops, uint32_t ts, char* out, int out_len) {
int oi = 0;
int matched = 0;
for (const char* p = body; *p; ) {
while (*p == ' ') p++; // skip whitespace
if (*p != '!') { // not a command token
while (*p && *p != ' ') p++;
continue;
}
p++; // step past '!'
char cmd[16];
int ci = 0;
while (*p && *p != ' ' && ci < (int)sizeof(cmd) - 1)
cmd[ci++] = (char)tolower((uint8_t)*p++);
cmd[ci] = '\0';
while (*p && *p != ' ') p++; // consume any overflow of this token
if (!cmd[0]) continue;
char seg[64];
if (!botCommandReply(cmd, hops, ts, seg, sizeof(seg))) continue; // unknown
if (matched > 0 && oi + 3 < out_len) { // " | " separator
out[oi++] = ' '; out[oi++] = '|'; out[oi++] = ' ';
}
int sl = strlen(seg);
if (oi + sl >= out_len) sl = out_len - 1 - oi;
if (sl > 0) { memcpy(out + oi, seg, sl); oi += sl; }
matched++;
}
out[oi] = '\0';
return matched;
}
// DM query commands. The reply is a pull, not a push, so it ignores quiet hours;
// the per-contact throttle still applies. Returns true when at least one command
// was found (replied or throttled), so the caller skips the trigger-reply path.
bool MyMesh::tryBotCommand(const ContactInfo& from, const char* text, uint8_t hops) {
if (!_prefs.bot_commands_enabled) return false;
if (from.type != ADV_TYPE_CHAT) return false;
uint32_t ts = getRTCClock()->getCurrentTime();
char out[BOT_SCRATCH];
if (botScanCommands(text, hops, ts, out, sizeof(out)) == 0) return false; // no commands
if (!botDmAllowed(from.id.pub_key)) return true; // throttled
uint32_t expected_ack, est_timeout;
if (sendMessage(from, ts, 0, out, expected_ack, est_timeout) != MSG_SEND_FAILED) {
botDmRecord(from.id.pub_key);
_bot_reply_count++;
#ifdef DISPLAY_CLASS
if (_ui) _ui->addDMMsg(from.id.pub_key, true, out);
#endif
}
return true;
}
// Channel query commands — only on the bot's monitored channel. The reply is
// broadcast to everyone on the channel, so unlike DM commands it respects quiet
// hours and uses the global per-channel cooldown (shared with the trigger reply).
bool MyMesh::tryBotChannelCommand(uint8_t channel_idx, const char* text, uint8_t hops) {
if (!(_prefs.bot_commands_enabled && _prefs.bot_channel_enabled &&
channel_idx == _prefs.bot_channel_idx))
return false;
// Skip "sender_name: " prefix so commands are read from the message body only.
const char* msg = text;
const char* sep = strstr(text, ": ");
if (sep) msg = sep + 2;
uint32_t ts = getRTCClock()->getCurrentTime();
char out[BOT_SCRATCH];
if (botScanCommands(msg, hops, ts, out, sizeof(out)) == 0) return false; // no commands
if (botInQuietHours()) return true; // quiet hours
if (millis() - _bot_last_ch_reply_ms <= BOT_REPLY_COOLDOWN_MS) return true; // throttled
ChannelDetails ch;
if (!getChannel(channel_idx, ch)) return true;
int rlen = strlen(out);
if (sendGroupMessage(ts, ch.channel, _prefs.node_name, out, rlen)) {
_bot_last_ch_reply_ms = millis();
_bot_reply_count++;
#ifdef DISPLAY_CLASS
if (_ui) {
char with_sender[240];
snprintf(with_sender, sizeof(with_sender), "%s: %s", _prefs.node_name, out);
_ui->addChannelMsg(channel_idx, with_sender);
}
#endif
}
return true;
}

View File

@@ -57,9 +57,13 @@ struct NodePrefs { // persisted to file
uint8_t bot_enabled; // 0=disabled, 1=DM bot active (responds to all DMs)
uint8_t bot_channel_enabled; // 0=disabled, 1=channel bot active for bot_channel_idx
uint8_t bot_channel_idx; // channel index for channel bot
char bot_trigger[64]; // trigger phrase (case-insensitive contains match)
char bot_trigger[64]; // DM trigger phrase (case-insensitive contains; "*" = any DM)
char bot_reply_dm[140]; // auto-reply text for DM
char bot_reply_ch[140]; // auto-reply text for channel
char bot_trigger_ch[64]; // channel trigger phrase (independent of DM; "*" = any channel msg)
uint8_t bot_commands_enabled; // 0=off, 1=answer !ping/!batt/!loc/!time/!help DM commands
uint8_t bot_quiet_start; // quiet-hours start hour, local 0-23 (start==end → disabled)
uint8_t bot_quiet_end; // quiet-hours end hour, local 0-23
uint8_t clock_hide_seconds; // 0=show HH:MM:SS/refresh 1s (default), 1=hide/refresh 60s
uint8_t clock_12h; // 0=24h (default), 1=12h with AM/PM
uint8_t buzzer_auto; // 0=manual (default), 1=auto-mute when BT connected
@@ -140,7 +144,7 @@ struct NodePrefs { // persisted to file
// adding/removing/reordering fields in DataStore::savePrefs/loadPrefsInt so
// older saves are detected on load and skipped (zero-init defaults kept).
// High 24 bits identify the file format; low byte is the schema revision.
static const uint32_t SCHEMA_SENTINEL = 0xC0DE000A;
static const uint32_t SCHEMA_SENTINEL = 0xC0DE000C;
// Bit-index for each home page. Used by page_order (entries store bit+1) and
// by home_pages_mask. Single source of truth — both HomeScreen::pageBit/bitToPage

View File

@@ -6,14 +6,17 @@ class BotScreen : public UIScreen {
UITask* _task;
NodePrefs* _prefs;
// Items: 0=Enable(DM), 1=Channel, 2=Trigger, 3=Reply DM, 4=Reply Ch
static const int ITEM_COUNT = 5;
// Items: 0=Enable(DM), 1=Channel, 2=Trigger DM, 3=Reply DM, 4=Trigger Ch,
// 5=Reply Ch, 6=Commands, 7=Quiet from, 8=Quiet to
static const int ITEM_COUNT = 9;
int _sel;
int _scroll; // index of first visible item
int _visible; // items fitting on screen; updated each render, used by handleInput
bool _dirty;
// keyboard state (reused for trigger and reply fields)
int _kb_field; // -1=off, 2=trigger, 3=reply DM, 4=reply Ch
int _kb_field; // -1=off, else the item index being edited (2..5)
KeyboardWidget* _kb;
// channel cache (refreshed on enter)
@@ -29,6 +32,12 @@ class BotScreen : public UIScreen {
}
}
// Keep the selected row inside the visible window (_visible set by render()).
void scrollToSel() {
if (_sel < _scroll) _scroll = _sel;
else if (_sel >= _scroll + _visible) _scroll = _sel - _visible + 1;
}
// Returns index into _channel_indices[] for current bot_channel_idx, or -1 if not found/disabled.
int currentChannelListIdx() const {
if (!_prefs->bot_channel_enabled) return -1;
@@ -42,6 +51,8 @@ public:
void enter() {
_sel = 0;
_scroll = 0;
_visible = 1;
_kb_field = -1;
_dirty = false;
refreshChannels();
@@ -55,18 +66,30 @@ public:
return _kb->render(display);
}
int avail_h = display.height() - display.listStart();
int item_h = display.lineStep();
if (item_h * ITEM_COUNT > avail_h) item_h = avail_h / ITEM_COUNT;
int start_y = display.listStart();
int val_x = display.valCol();
_visible = display.listVisible(item_h);
if (_visible < 1) _visible = 1;
display.drawTextCentered(display.width() / 2, 0, "AUTO-REPLY BOT");
// reply counter, right-aligned in the header
uint16_t sent = the_mesh.botReplyCount();
if (sent > 0) {
char cbuf[12];
snprintf(cbuf, sizeof(cbuf), "%u", (unsigned)sent);
int cw = display.getTextWidth(cbuf);
display.setCursor(display.width() - cw - 1, 0);
display.print(cbuf);
}
display.fillRect(0, display.headerH() - 1, display.width(), display.sepH());
static const char* labels[] = { "Enable", "Channel", "Trigger", "Reply DM", "Reply Ch" };
for (int i = 0; i < ITEM_COUNT; i++) {
int y = start_y + i * item_h;
static const char* labels[] = { "Enable", "Channel", "Trigger DM", "Reply DM",
"Trigger Ch", "Reply Ch", "Commands",
"Quiet from", "Quiet to" };
for (int vi = 0; vi < _visible && (_scroll + vi) < ITEM_COUNT; vi++) {
int i = _scroll + vi;
int y = start_y + vi * item_h;
bool sel = (i == _sel);
display.drawSelectionRow(0, y - 1, display.width(), item_h, sel);
display.setCursor(2, y);
@@ -85,18 +108,31 @@ public:
else
display.print("?");
}
} else if (i == 2) {
const char* tr = _prefs->bot_trigger;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, tr[0] ? tr : "(none)");
} else if (i == 3) {
const char* rp = _prefs->bot_reply_dm;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, rp[0] ? rp : "(none)");
} else {
const char* rp = _prefs->bot_reply_ch;
} else if (i == 2 || i == 4) {
const char* tr = (i == 2) ? _prefs->bot_trigger : _prefs->bot_trigger_ch;
const char* shown = !tr[0] ? "(none)"
: (tr[0] == '*' && !tr[1]) ? "(any msg)" // wildcard / away mode
: tr;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, shown);
} else if (i == 3 || i == 5) {
const char* rp = (i == 3) ? _prefs->bot_reply_dm : _prefs->bot_reply_ch;
display.drawTextEllipsized(val_x, y, display.width() - val_x - 1, rp[0] ? rp : "(none)");
} else if (i == 6) {
display.print(_prefs->bot_commands_enabled ? "ON" : "OFF");
} else { // i == 7 (quiet from) or i == 8 (quiet to)
bool off = (_prefs->bot_quiet_start == _prefs->bot_quiet_end);
if (off) {
display.print("OFF");
} else {
char hb[8];
snprintf(hb, sizeof(hb), "%02d:00", i == 7 ? _prefs->bot_quiet_start : _prefs->bot_quiet_end);
display.print(hb);
}
}
display.setColor(DisplayDriver::LIGHT);
}
display.drawScrollArrows(start_y, start_y + (_visible - 1) * item_h,
_scroll > 0, _scroll + _visible < ITEM_COUNT);
return 2000;
}
@@ -111,16 +147,9 @@ public:
if (_kb_field >= 0) {
auto res = _kb->handleInput(c);
if (res == KeyboardWidget::DONE) {
if (_kb_field == 2) {
strncpy(_prefs->bot_trigger, _kb->buf, sizeof(_prefs->bot_trigger) - 1);
_prefs->bot_trigger[sizeof(_prefs->bot_trigger) - 1] = '\0';
} else if (_kb_field == 3) {
strncpy(_prefs->bot_reply_dm, _kb->buf, sizeof(_prefs->bot_reply_dm) - 1);
_prefs->bot_reply_dm[sizeof(_prefs->bot_reply_dm) - 1] = '\0';
} else {
strncpy(_prefs->bot_reply_ch, _kb->buf, sizeof(_prefs->bot_reply_ch) - 1);
_prefs->bot_reply_ch[sizeof(_prefs->bot_reply_ch) - 1] = '\0';
}
char* dst = fieldBuf(_kb_field);
int cap = fieldCap(_kb_field);
if (dst) { strncpy(dst, _kb->buf, cap - 1); dst[cap - 1] = '\0'; }
_dirty = true;
_kb_field = -1;
} else if (res == KeyboardWidget::CANCELLED) {
@@ -134,8 +163,8 @@ public:
_task->gotoToolsScreen();
return true;
}
if (up && _sel > 0) { _sel--; return true; }
if (down && _sel < ITEM_COUNT - 1) { _sel++; return true; }
if (up && _sel > 0) { _sel--; scrollToSel(); return true; }
if (down && _sel < ITEM_COUNT - 1) { _sel++; scrollToSel(); return true; }
if (_sel == 0 && (enter || left || right)) {
_prefs->bot_enabled ^= 1;
@@ -165,28 +194,46 @@ public:
return true;
}
}
if ((_sel == 2 || _sel == 3 || _sel == 4) && enter) {
if (_sel == 6 && (enter || left || right)) {
_prefs->bot_commands_enabled ^= 1;
_dirty = true;
return true;
}
if ((_sel == 7 || _sel == 8) && (left || right)) {
uint8_t& h = (_sel == 7) ? _prefs->bot_quiet_start : _prefs->bot_quiet_end;
h = right ? (h + 1) % 24 : (h + 23) % 24;
_dirty = true;
return true;
}
if ((_sel == 2 || _sel == 3 || _sel == 4 || _sel == 5) && enter) {
_kb_field = _sel;
const char* initial;
int max;
if (_sel == 2) {
initial = _prefs->bot_trigger;
max = sizeof(_prefs->bot_trigger) - 1;
} else if (_sel == 3) {
initial = _prefs->bot_reply_dm;
max = sizeof(_prefs->bot_reply_dm) - 1;
} else {
initial = _prefs->bot_reply_ch;
max = sizeof(_prefs->bot_reply_ch) - 1;
}
_kb->begin(initial, max);
if (_sel == 2) {
_kb->clearPlaceholders(); // trigger is literal text — placeholders never match incoming msgs
} else {
kbAddSensorPlaceholders(*_kb, &sensors);
}
_kb->begin(fieldBuf(_sel), fieldCap(_sel) - 1);
bool is_trigger = (_sel == 2 || _sel == 4);
if (is_trigger) _kb->clearPlaceholders(); // trigger is literal — placeholders never match
else kbAddSensorPlaceholders(*_kb, &sensors);
return true;
}
return false;
}
private:
// Maps a keyboard-editable item index to its backing string + capacity.
char* fieldBuf(int item) {
switch (item) {
case 2: return _prefs->bot_trigger;
case 3: return _prefs->bot_reply_dm;
case 4: return _prefs->bot_trigger_ch;
case 5: return _prefs->bot_reply_ch;
default: return nullptr;
}
}
int fieldCap(int item) {
switch (item) {
case 2: return sizeof(_prefs->bot_trigger);
case 3: return sizeof(_prefs->bot_reply_dm);
case 4: return sizeof(_prefs->bot_trigger_ch);
case 5: return sizeof(_prefs->bot_reply_ch);
default: return 0;
}
}
};