@kadaliao/dsh-bots 0.7.1 → 0.9.0

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.
@@ -15,6 +15,22 @@
15
15
  * and the other unrecoverable close codes (4010–4013) are fatal: no reconnects.
16
16
  * - The token never appears in log lines, thrown errors or status details.
17
17
  *
18
+ * Threads: `threadId` on a message is the thread channel it was posted in
19
+ * (then equal to `chatId`, which is always the channel the message is in), or
20
+ * else the root of the reply chain it answers: the root this connector has
21
+ * seen for the referenced message, else the message that one answered (both
22
+ * in the event; no extra API calls), else the referenced message itself. A
23
+ * message that answers nothing outside a thread has none. Thread channels are
24
+ * known from the guild's thread list and thread events.
25
+ * `send(chatId, …, {threadId})` posts to that thread channel when it is one
26
+ * (or is `chatId`); otherwise it answers the reply chain's root, so the
27
+ * message joins the chain. The root is quoted once: not again while the bot's
28
+ * own last message in the channel is already in that chain, as the later parts
29
+ * of one reply are. With `replyTo` as well, the first part quotes `replyTo`
30
+ * instead (inside the thread channel, or in the chain). Every part the bot
31
+ * sends is remembered as part of its chain, so a reply to any of them reports
32
+ * the same root.
33
+ *
18
34
  * @module @kadaliao/dsh-bots/lib/channels/discord
19
35
  */
20
36
 
@@ -47,8 +63,25 @@ const FATAL_CLOSE = {
47
63
  };
48
64
  /** The session is gone: start a new one instead of resuming. */
49
65
  const REIDENTIFY_CLOSE = new Set([4007, 4009]);
66
+ /** Channel types of threads: announcement, public, private. */
67
+ const THREAD_TYPES = new Set([10, 11, 12]);
50
68
 
51
69
  const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
70
+ /** Snowflake `a` is later than `b` (any other ids compare as strings). */
71
+ const later = (a, b) => (/^\d{1,25}$/.test(a) && /^\d{1,25}$/.test(b) ? BigInt(a) > BigInt(b) : a > b);
72
+ /** Keep `key` → `value` in an insertion-ordered map of at most `max` entries. */
73
+ function remember(map, key, value, max) {
74
+ map.delete(key);
75
+ map.set(key, value);
76
+ if (map.size > max) map.delete(map.keys().next().value);
77
+ }
78
+
79
+ /** The id of the message `m` replies to (not a forward or a crosspost), or ''. */
80
+ function repliedTo(m) {
81
+ const ref = m?.message_reference;
82
+ if (ref && (ref.type ?? 0) === 0 && ref.message_id) return String(ref.message_id);
83
+ return !ref && m?.type === 19 && m.referenced_message?.id ? String(m.referenced_message.id) : '';
84
+ }
52
85
 
53
86
  /**
54
87
  * Reconnect delay for the n-th consecutive failure (0-based): doubles from 1 s,
@@ -67,8 +100,10 @@ export function backoffDelay(attempt, random = Math.random) {
67
100
  * @param {object} d the event payload
68
101
  * @param {string} botId the bot's own user id
69
102
  * @param {string[]} [botRoleIds] the bot's managed role in this guild (people often @ the role by mistake)
103
+ * @param {{inThread?: boolean, rootOf?: (messageId: string) => string | undefined}} [thread]
104
+ * whether `d.channel_id` is a thread channel, and the known reply-chain root of a message
70
105
  */
71
- export function normalizeMessage(d, botId, botRoleIds = []) {
106
+ export function normalizeMessage(d, botId, botRoleIds = [], { inThread = false, rootOf } = {}) {
72
107
  const author = d?.author;
73
108
  if (!author?.id || !botId) return null;
74
109
  if (author.bot || author.system || d.webhook_id || author.id === botId) return null;
@@ -86,6 +121,9 @@ export function normalizeMessage(d, botId, botRoleIds = []) {
86
121
  if (roles.length) text = text.replace(new RegExp(`<@&(?:${roles.map(escapeRe).join('|')})>\\s*`, 'g'), '');
87
122
  text = text.trim();
88
123
  if (!text) return null;
124
+ let threadId = inThread ? String(d.channel_id) : '';
125
+ const ref = threadId ? '' : repliedTo(d);
126
+ if (ref) threadId = rootOf?.(ref) || repliedTo(d.referenced_message) || ref;
89
127
  return {
90
128
  chatId: String(d.channel_id),
91
129
  messageId: String(d.id),
@@ -94,6 +132,7 @@ export function normalizeMessage(d, botId, botRoleIds = []) {
94
132
  text,
95
133
  isDirect,
96
134
  mentioned,
135
+ ...(threadId ? { threadId } : {}),
97
136
  };
98
137
  }
99
138
 
@@ -191,6 +230,7 @@ async function readJson(res) {
191
230
  * @property {boolean} isDirect a 1:1 DM with the bot
192
231
  * @property {boolean} mentioned @mentioned or replied to; always true in a DM
193
232
  * @property {string} [chatTitle] `Server #channel`, when the channel is known
233
+ * @property {string} [threadId] the thread channel (= `chatId`), or the root message of the reply chain
194
234
  */
195
235
 
196
236
  /**
@@ -306,8 +346,10 @@ export function createConnector(opts = {}) {
306
346
  let acked = true;
307
347
  let reconnectTimer = null;
308
348
  const guildNames = new Map();
309
- const channels = new Map(); // id → { guildId, name }
349
+ const channels = new Map(); // id → { guildId, name, type }
310
350
  const botRoles = new Map(); // guild id → the bot's managed role ids
351
+ const roots = new Map(); // message id → the root of the reply chain it is in (people's replies and the bot's own messages)
352
+ const latest = new Map(); // channel id → { id, root }: the newest message seen there; `root` when it is the bot's, in a chain
311
353
 
312
354
  const halted = () => stopped || dead;
313
355
  const cancel = (h) => { if (h != null) clearTimeoutImpl(h); };
@@ -471,7 +513,17 @@ export function createConnector(opts = {}) {
471
513
  }
472
514
 
473
515
  function rememberChannel(c, guildId = c?.guild_id) {
474
- if (c?.id && c.name && guildId) channels.set(c.id, { guildId, name: c.name });
516
+ if (c?.id && c.name && guildId) channels.set(c.id, { guildId, name: c.name, type: c.type });
517
+ }
518
+ const isThread = (id) => Boolean(id) && THREAD_TYPES.has(channels.get(String(id))?.type);
519
+
520
+ /** A message appeared in `channelId`: the newest there unless an older one arrives late. `mine` sent it, in chain `root`. */
521
+ function noteLatest(channelId, id, { mine = false, root = '' } = {}) {
522
+ if (!channelId || !id) return;
523
+ const cur = latest.get(channelId);
524
+ // The bot's own message, from the API's answer or its gateway echo, overwrites an equal entry.
525
+ if (cur && (mine ? later(cur.id, id) : !later(id, cur.id))) return;
526
+ remember(latest, channelId, { id, root: mine ? root : '' }, 500);
475
527
  }
476
528
  function rememberGuild(g) {
477
529
  if (!g?.id || g.unavailable) return;
@@ -494,8 +546,15 @@ export function createConnector(opts = {}) {
494
546
 
495
547
  function deliver(d) {
496
548
  if (!me) return;
497
- const msg = normalizeMessage(d, me.id, botRoles.get(d?.guild_id));
549
+ if (d?.id && d.channel_id) {
550
+ const id = String(d.id);
551
+ const mine = String(d.author?.id ?? '') === me.id;
552
+ noteLatest(String(d.channel_id), id, mine ? { mine, root: roots.get(id) ?? '' } : {});
553
+ }
554
+ const inThread = isThread(d?.channel_id);
555
+ const msg = normalizeMessage(d, me.id, botRoles.get(d?.guild_id), { inThread, rootOf: (id) => roots.get(id) });
498
556
  if (!msg) return;
557
+ if (msg.threadId && !inThread) remember(roots, msg.messageId, msg.threadId, 2000);
499
558
  const title = msg.isDirect ? undefined : titleOf(msg.chatId);
500
559
  if (title) msg.chatTitle = title;
501
560
  try {
@@ -524,6 +583,9 @@ export function createConnector(opts = {}) {
524
583
  case 'CHANNEL_UPDATE':
525
584
  case 'THREAD_CREATE':
526
585
  case 'THREAD_UPDATE': return rememberChannel(d);
586
+ case 'THREAD_LIST_SYNC':
587
+ for (const t of d?.threads ?? []) rememberChannel(t, t?.guild_id ?? d?.guild_id);
588
+ return undefined;
527
589
  case 'CHANNEL_DELETE':
528
590
  case 'THREAD_DELETE': return void channels.delete(d?.id);
529
591
  default: return undefined;
@@ -564,23 +626,41 @@ export function createConnector(opts = {}) {
564
626
  status('stopped');
565
627
  }
566
628
 
567
- /** Post `text` to a channel, split at the 2000-character limit; `replyTo` threads the first chunk under that message. */
629
+ /**
630
+ * Post `text` to a channel, split at the 2000-character limit; `replyTo`
631
+ * threads the first chunk under that message. `threadId` is a thread
632
+ * channel to post in, or the root of a reply chain in `chatId` to answer
633
+ * (quoted once; see the module notes).
634
+ */
568
635
  async function send(chatId, text, sendOpts = {}) {
569
636
  if (stopped) throw new Error('Discord connector is stopped');
570
- const path = `/channels/${encodeURIComponent(String(chatId))}/messages`;
637
+ const chat = String(chatId);
638
+ const replyTo = sendOpts?.replyTo ? String(sendOpts.replyTo) : '';
639
+ const threadId = sendOpts?.threadId ? String(sendOpts.threadId) : '';
640
+ const channel = threadId && threadId !== chat && isThread(threadId) ? threadId : chat;
641
+ const root = threadId && threadId !== channel ? threadId : '';
642
+ // The chain these messages join: the thread's root, else the one replyTo is in.
643
+ const chain = root || (replyTo && channel === chat ? roots.get(replyTo) || replyTo : '');
644
+ const path = `/channels/${encodeURIComponent(channel)}/messages`;
571
645
  const chunks = splitMessage(text);
572
646
  for (let i = 0; i < chunks.length; i += 1) {
573
647
  const body = { content: chunks[i], allowed_mentions: { parse: [] } };
574
- if (i === 0 && sendOpts?.replyTo) body.message_reference = { message_id: String(sendOpts.replyTo), fail_if_not_exists: false };
575
- await api('POST', path, body);
648
+ const quote = i === 0 && replyTo ? replyTo : root && latest.get(channel)?.root !== root ? root : '';
649
+ if (quote) body.message_reference = { message_id: quote, fail_if_not_exists: false };
650
+ const sent = await api('POST', path, body);
651
+ const id = sent?.id ? String(sent.id) : '';
652
+ if (id && chain) remember(roots, id, chain, 2000);
653
+ if (id) noteLatest(channel, id, { mine: true, root: chain });
576
654
  }
577
655
  }
578
656
 
579
- /** Show "bot is typing…" for about ten seconds. Failures are logged and ignored. */
580
- async function typing(chatId) {
657
+ /** Show "bot is typing…" for about ten seconds (in the thread channel `threadId`, if it is one). Failures are logged and ignored. */
658
+ async function typing(chatId, typingOpts = {}) {
581
659
  if (stopped) return;
660
+ const threadId = typingOpts?.threadId ? String(typingOpts.threadId) : '';
661
+ const channel = isThread(threadId) ? threadId : String(chatId);
582
662
  try {
583
- await api('POST', `/channels/${encodeURIComponent(String(chatId))}/typing`, undefined, 0);
663
+ await api('POST', `/channels/${encodeURIComponent(channel)}/typing`, undefined, 0);
584
664
  } catch (e) {
585
665
  log(`discord: typing indicator failed: ${e?.message ?? e}`);
586
666
  }
@@ -20,6 +20,18 @@
20
20
  * is only ever sent to Lark. Messages from Lark carry `source: 'Lark'`.
21
21
  * - Replies are `post` messages holding one `md` element (CommonMark + GFM),
22
22
  * hence `MARKDOWN`; in a group the first part answers the person's message.
23
+ * - Threads: `threadId` on a message is the `message_id` of the root of the
24
+ * conversation it is in: `root_id` for a reply (a reply chain, or a reply in
25
+ * a topic: Feishu points both at the root), or the message itself when it
26
+ * opens a topic (`thread_id` and no `root_id`, as in a topic group). The
27
+ * root's id, not the topic's `omt_` id, because only a message can be
28
+ * answered, and a chain the bot's reply turns into a topic keeps its root.
29
+ * A message that answers nothing and opens no topic has none.
30
+ * `send(…, {threadId})` answers that root with every part, so the parts land
31
+ * in its topic, or join its reply chain; `reply_in_thread` is not forced, so
32
+ * a chain is not turned into a topic. With `replyTo` as well, the first part
33
+ * answers `replyTo` (which stays in the same topic or chain). A recalled
34
+ * `replyTo` falls back to the root, a recalled root to the chat.
23
35
  * - Feishu delivers a message twice now and then; duplicates are dropped by
24
36
  * message_id, and `order` (the message's create_time in ms, rising within a
25
37
  * chat) feeds the hub's replay guard across restarts.
@@ -299,7 +311,8 @@ function postText(c, at) {
299
311
  * In a group, `mentioned` means the bot's own open_id is among the mentions
300
312
  * (with no open_id known yet: any bot mention), or the message replies to one
301
313
  * the bot sent. The bot's `@_user_N` placeholder is removed, other people's
302
- * become `@Name`.
314
+ * become `@Name`. `threadId` is the root message of the reply chain or topic
315
+ * the message is in (its own id when it opens a topic), absent otherwise.
303
316
  * @param {object} event the event body (`sender`, `message`)
304
317
  * @param {{botOpenId?: string, sentIds?: {has(id: string): boolean}}} [me]
305
318
  */
@@ -337,6 +350,8 @@ export function normalizeEvent(event, { botOpenId = '', sentIds } = {}) {
337
350
  const isDirect = m.chat_type === 'p2p';
338
351
  if (!isDirect && m.parent_id && sentIds?.has(String(m.parent_id))) mentioned = true;
339
352
  const created = String(m.create_time ?? '');
353
+ // A reply (in a chain or a topic) names its root; a topic's first message is its own root.
354
+ const threadId = String(m.root_id || m.parent_id || (m.thread_id ? m.message_id : ''));
340
355
  return {
341
356
  chatId: String(m.chat_id),
342
357
  messageId: String(m.message_id),
@@ -345,6 +360,7 @@ export function normalizeEvent(event, { botOpenId = '', sentIds } = {}) {
345
360
  text,
346
361
  isDirect,
347
362
  mentioned: isDirect || mentioned,
363
+ ...(threadId ? { threadId } : {}),
348
364
  };
349
365
  }
350
366
 
@@ -1117,13 +1133,17 @@ export function createConnector(opts = {}) {
1117
1133
 
1118
1134
  let sendTrouble = false;
1119
1135
 
1120
- async function deliverBody(chatId, body, replyTo) {
1136
+ /** Post `body` as an answer to the first of `replyTo` (message ids) still there, else to the chat. Ids found gone are added to `gone`. */
1137
+ async function deliverBody(chatId, body, replyTo, gone = new Set()) {
1121
1138
  let r = null;
1122
- if (replyTo) {
1139
+ for (const id of new Set(replyTo)) {
1140
+ if (!id || gone.has(id)) continue;
1123
1141
  try {
1124
- r = await api('POST', `/open-apis/im/v1/messages/${encodeURIComponent(replyTo)}/reply`, { ...body, uuid: randomUUID() }, { what: 'reply' });
1142
+ r = await api('POST', `/open-apis/im/v1/messages/${encodeURIComponent(id)}/reply`, { ...body, uuid: randomUUID() }, { what: 'reply' });
1143
+ break;
1125
1144
  } catch (e) {
1126
1145
  if (!REPLY_GONE.has(e.code)) throw e;
1146
+ gone.add(id);
1127
1147
  r = null;
1128
1148
  }
1129
1149
  }
@@ -1133,13 +1153,13 @@ export function createConnector(opts = {}) {
1133
1153
  return r;
1134
1154
  }
1135
1155
 
1136
- async function sendPart(chatId, md, replyTo) {
1156
+ async function sendPart(chatId, md, replyTo, gone) {
1137
1157
  try {
1138
- return await deliverBody(chatId, postBody(md), replyTo);
1158
+ return await deliverBody(chatId, postBody(md), replyTo, gone);
1139
1159
  } catch (e) {
1140
1160
  if (!POST_REJECTED.has(e.code)) throw e;
1141
1161
  log(`feishu: ${label()} did not take a reply as Markdown (${e.message}); sending it as plain text`);
1142
- return deliverBody(chatId, { msg_type: 'text', content: JSON.stringify({ text: toPlainText(md) }) }, replyTo);
1162
+ return deliverBody(chatId, { msg_type: 'text', content: JSON.stringify({ text: toPlainText(md) }) }, replyTo, gone);
1143
1163
  }
1144
1164
  }
1145
1165
 
@@ -1220,15 +1240,23 @@ export function createConnector(opts = {}) {
1220
1240
  return stopping;
1221
1241
  },
1222
1242
 
1223
- /** Send Markdown as `post` messages of at most TEXT_LIMIT; the first part answers `replyTo`. */
1243
+ /**
1244
+ * Send Markdown as `post` messages of at most TEXT_LIMIT; the first part
1245
+ * answers `replyTo`. With `threadId` (a root message) every part answers
1246
+ * that root (the first one `replyTo` when given), so all of it lands in
1247
+ * the root's topic or reply chain.
1248
+ */
1224
1249
  async send(chatId, text, sendOpts = {}) {
1225
1250
  if (halted()) throw new Error(`the ${label()} connector is stopped`);
1226
1251
  if (!domain) throw new Error(`the ${label()} connector is not signed in yet`);
1227
1252
  chatId = String(chatId);
1253
+ const replyTo = sendOpts?.replyTo ? String(sendOpts.replyTo) : '';
1254
+ const root = sendOpts?.threadId ? String(sendOpts.threadId) : '';
1255
+ const gone = new Set();
1228
1256
  let first = true;
1229
1257
  try {
1230
1258
  for (const part of partsOf(text)) {
1231
- await sendPart(chatId, part, first && sendOpts?.replyTo ? String(sendOpts.replyTo) : '');
1259
+ await sendPart(chatId, part, first ? [replyTo, root] : [root], gone);
1232
1260
  first = false;
1233
1261
  }
1234
1262
  if (sendTrouble) {
@@ -23,6 +23,13 @@
23
23
  * write, tables and code included) with a plain `text` fallback for
24
24
  * notifications and screen readers. In a channel they go to the thread of
25
25
  * the message they answer.
26
+ * - Threads: `threadId` on a message is the `ts` of its thread's parent
27
+ * (`thread_ts`); a top-level channel message reports its own `ts`, since
28
+ * the bot answers it in a thread under it. A DM message outside a thread
29
+ * has none. `send(…, {threadId})` posts every part into that thread
30
+ * (`thread_ts`); with `replyTo` as well, the thread `replyTo` is known to be
31
+ * in wins (Slack threads cannot quote one message). `typing(…, {threadId})`
32
+ * shows "is thinking…" under that thread.
26
33
  * - No secret appears in a log line, an error or a status.
27
34
  *
28
35
  * `apiBase` defaults to `BOTS_SLACK_API` or https://slack.com/api, so a local
@@ -168,7 +175,8 @@ export function fallbackText(md) {
168
175
  /**
169
176
  * An Events API `message` / `app_mention` event as the start of a channel
170
177
  * message, or null when it is not a person writing to the bot. `raw` is still
171
- * Slack-formatted; `thread` is the thread a reply belongs in.
178
+ * Slack-formatted; `thread` is the thread a reply belongs in; `threadId` (only
179
+ * when there is one) is the thread the message is in or starts in a channel.
172
180
  * @param {object} ev
173
181
  * @param {{userId: string, botId?: string}} me
174
182
  */
@@ -191,6 +199,8 @@ export function normalizeEvent(ev, me) {
191
199
  new RegExp(`<@${escapeRe(me.userId)}(?:\\|[^>]*)?>`).test(raw) ||
192
200
  (Boolean(ev.parent_user_id) && String(ev.parent_user_id) === me.userId);
193
201
  const profile = ev.user_profile ?? {};
202
+ // A DM is one conversation until someone replies in a thread there.
203
+ const threadId = ev.thread_ts ? String(ev.thread_ts) : isDirect ? '' : ts;
194
204
  return {
195
205
  chatId,
196
206
  messageId: ts,
@@ -200,6 +210,7 @@ export function normalizeEvent(ev, me) {
200
210
  isDirect,
201
211
  mentioned,
202
212
  thread: String(ev.thread_ts || ts),
213
+ ...(threadId ? { threadId } : {}),
203
214
  profileName: cleanName(profile.display_name || profile.real_name || profile.name || ''),
204
215
  };
205
216
  }
@@ -262,6 +273,7 @@ function retryAfterMs(headers) {
262
273
  * @property {boolean} isDirect a DM with the app
263
274
  * @property {boolean} mentioned @mentioned; always true in a DM
264
275
  * @property {string} [chatTitle] `Workspace #channel`, when Slack names it
276
+ * @property {string} [threadId] the `ts` of the thread's parent: `thread_ts`, or the message's own `ts` at the top of a channel
265
277
  */
266
278
 
267
279
  /**
@@ -476,6 +488,7 @@ export function createConnector(opts = {}) {
476
488
  isDirect: n.isDirect,
477
489
  mentioned: n.mentioned,
478
490
  ...(title ? { chatTitle: title } : {}),
491
+ ...(n.threadId ? { threadId: n.threadId } : {}),
479
492
  };
480
493
  }
481
494
 
@@ -865,28 +878,33 @@ export function createConnector(opts = {}) {
865
878
  /**
866
879
  * Post Markdown `text` to a conversation, in parts of at most 11,000
867
880
  * characters (code fences closed and reopened at a cut). With `replyTo` (a
868
- * message `ts`) every part goes to that message's thread.
881
+ * message `ts`) every part goes to that message's thread; with `threadId`
882
+ * (a thread parent's `ts`) to that thread. Given both, the thread `replyTo`
883
+ * is known to be in wins; when it is not known, `threadId` names the parent
884
+ * (Slack wants the parent's `ts`, not a reply's).
869
885
  */
870
886
  async function send(chatId, text, sendOpts = {}) {
871
887
  if (stopped) throw new Error('Slack connector is stopped');
872
888
  const channel = String(chatId);
873
889
  const replyTo = sendOpts?.replyTo ? String(sendOpts.replyTo) : '';
874
- const thread = replyTo ? roots.get(`${channel}|${replyTo}`) ?? replyTo : '';
890
+ const threadId = sendOpts?.threadId ? String(sendOpts.threadId) : '';
891
+ const thread = (replyTo && roots.get(`${channel}|${replyTo}`)) || threadId || replyTo;
875
892
  for (const part of splitMessage(text, PART_LIMIT)) await post(channel, part, thread);
876
893
  }
877
894
 
878
895
  const statusAt = new Map();
879
896
  let statusOff = false;
880
897
  /**
881
- * Show "<app> is thinking…" under the thread a channel reply will go to;
882
- * Slack clears it when the reply arrives, or after two minutes. Nothing in a
883
- * DM: a status there would turn the person's message into a thread.
898
+ * Show "<app> is thinking…" under the thread a channel reply will go to
899
+ * (`threadId`, else the thread of the channel's latest mention); Slack
900
+ * clears it when the reply arrives, or after two minutes. Nothing in a DM:
901
+ * a status there would turn the person's message into a thread.
884
902
  */
885
- async function typing(chatId) {
903
+ async function typing(chatId, typingOpts = {}) {
886
904
  if (halted() || statusOff) return;
887
905
  const channel = String(chatId);
888
906
  if (channel.startsWith('D')) return;
889
- const thread = lastThread.get(channel);
907
+ const thread = (typingOpts?.threadId ? String(typingOpts.threadId) : '') || lastThread.get(channel);
890
908
  if (!thread) return;
891
909
  const k = `${channel}|${thread}`;
892
910
  const at = statusAt.get(k);
@@ -10,6 +10,15 @@
10
10
  * `apiBase` defaults to `BOTS_TELEGRAM_API` or https://api.telegram.org, so a
11
11
  * local stand-in of the Bot API can be used for testing.
12
12
  *
13
+ * Threads: `threadId` on a message is its forum topic (`message_thread_id`),
14
+ * reported only for topic messages (`is_topic_message`: a topic of a forum
15
+ * supergroup, or of a private chat with topics turned on). The General topic,
16
+ * plain groups and private chats have none, and a reply chain is not a thread
17
+ * in Telegram. `send(…, {threadId})` and `typing(…, {threadId})` post into
18
+ * that topic (`message_thread_id`); with `replyTo` as well, the first part
19
+ * quotes that message inside the topic. A topic that is gone gets the reply
20
+ * in the chat instead.
21
+ *
13
22
  * @module @kadaliao/dsh-bots/lib/channels/telegram
14
23
  */
15
24
 
@@ -27,7 +36,12 @@ const MAX_BACKOFF_MS = 60_000;
27
36
  const TOKEN_REJECTED = 'Telegram rejected the bot token (401 Unauthorized). Copy it again from @BotFather.';
28
37
  const CONFLICT = 'Another program is using this bot token (Telegram answered 409 Conflict). Stop it, or create a separate bot with @BotFather for the team.';
29
38
 
39
+ /** What Telegram says when a message goes to a topic that no longer exists. */
40
+ const THREAD_GONE = /thread not found/i;
41
+
30
42
  const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
43
+ /** A topic id for `message_thread_id`, or null. */
44
+ const topicOf = (id) => (id != null && /^\d{1,15}$/.test(String(id)) && Number(id) > 0 ? Number(id) : null);
31
45
 
32
46
  /**
33
47
  * @param {{
@@ -157,6 +171,8 @@ export function createConnector(opts) {
157
171
  .replace(/^[ \t,,::]+/, '')
158
172
  .trim();
159
173
  const name = [from.first_name, from.last_name].filter(Boolean).join(' ').trim() || (from.username ? `@${from.username}` : String(from.id));
174
+ // Outside a topic, message_thread_id names a reply chain: not a thread here.
175
+ const topic = m.is_topic_message === true && Number.isInteger(m.message_thread_id) ? String(m.message_thread_id) : '';
160
176
  return {
161
177
  chatId: String(chat.id),
162
178
  messageId: String(m.message_id),
@@ -166,6 +182,7 @@ export function createConnector(opts) {
166
182
  isDirect,
167
183
  mentioned,
168
184
  ...(isDirect ? {} : { chatTitle: String(chat.title ?? '') }),
185
+ ...(topic ? { threadId: topic } : {}),
169
186
  };
170
187
  }
171
188
 
@@ -278,23 +295,37 @@ export function createConnector(opts) {
278
295
  return stopping;
279
296
  },
280
297
 
281
- /** Send plain text, in parts of at most TEXT_LIMIT; the first part answers `replyTo`. */
298
+ /**
299
+ * Send plain text, in parts of at most TEXT_LIMIT; the first part answers
300
+ * `replyTo`. With `threadId` (a forum topic) every part goes to that topic.
301
+ */
282
302
  async send(chatId, text, sendOpts = {}) {
283
303
  let first = true;
304
+ let topic = topicOf(sendOpts?.threadId);
284
305
  for (const part of splitText(text, TEXT_LIMIT)) {
285
306
  const replyTo = first && sendOpts?.replyTo && /^\d+$/.test(String(sendOpts.replyTo)) ? Number(sendOpts.replyTo) : null;
286
- await polite('sendMessage', {
307
+ const body = {
287
308
  chat_id: chatIdOf(chatId),
288
309
  text: part,
289
310
  ...(replyTo ? { reply_parameters: { message_id: replyTo, allow_sending_without_reply: true } } : {}),
290
- });
311
+ };
312
+ try {
313
+ await polite('sendMessage', topic ? { ...body, message_thread_id: topic } : body);
314
+ } catch (error) {
315
+ // The topic was deleted: the reply still reaches the chat.
316
+ if (!topic || error.code !== 400 || !THREAD_GONE.test(error.description ?? '')) throw error;
317
+ log(`telegram: topic ${topic} is gone; sending to the chat`);
318
+ topic = null;
319
+ await polite('sendMessage', body);
320
+ }
291
321
  first = false;
292
322
  }
293
323
  },
294
324
 
295
- /** "typing…" in the chat for about five seconds. */
296
- async typing(chatId) {
297
- await call('sendChatAction', { chat_id: chatIdOf(chatId), action: 'typing' }, 10_000);
325
+ /** "typing…" in the chat (or its topic `threadId`) for about five seconds. */
326
+ async typing(chatId, typingOpts = {}) {
327
+ const topic = topicOf(typingOpts?.threadId);
328
+ await call('sendChatAction', { chat_id: chatIdOf(chatId), ...(topic ? { message_thread_id: topic } : {}), action: 'typing' }, 10_000);
298
329
  },
299
330
  };
300
331
  }