@theokit/gateway-telegram 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.
package/dist/index.js CHANGED
@@ -3,6 +3,30 @@ import { Bot, GrammyError, HttpError, InputFile } from 'grammy';
3
3
 
4
4
  // src/adapter.ts
5
5
 
6
+ // src/group-policy.ts
7
+ function shouldRespond(input, policy) {
8
+ if (input.chatType === "private") return true;
9
+ if (input.text.startsWith("/")) return true;
10
+ if (input.replyToFromId !== void 0 && input.replyToFromId === policy.botId) return true;
11
+ return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);
12
+ }
13
+ function shouldRespondInChat(ctx, policy) {
14
+ const chat = ctx.chat;
15
+ if (chat === void 0) return false;
16
+ return shouldRespond(
17
+ {
18
+ chatType: chat.type,
19
+ text: ctx.message?.text ?? ctx.message?.caption ?? "",
20
+ replyToFromId: ctx.message?.reply_to_message?.from?.id
21
+ },
22
+ policy
23
+ );
24
+ }
25
+ function stripBotMention(text, botUsername) {
26
+ const regex = new RegExp(`@${botUsername}`, "gi");
27
+ return text.replace(regex, "").trim();
28
+ }
29
+
6
30
  // src/parse-inbound.ts
7
31
  function buildEvent(chat, msg, from, raw) {
8
32
  let channelType;
@@ -330,7 +354,7 @@ async function sendPhotos(api, out) {
330
354
  let lastId = await sendEachAttachment(api, chatId, out, shared);
331
355
  if (out.text.length > CAPTION_LIMIT) {
332
356
  for (const chunk of splitForTelegram(out.text)) {
333
- lastId = (await api.sendMessage(chatId, chunk, shared)).message_id;
357
+ lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts))).message_id;
334
358
  }
335
359
  }
336
360
  return { ok: true, messageId: String(lastId) };
@@ -344,12 +368,29 @@ async function sendEachAttachment(api, chatId, out, shared) {
344
368
  let lastId = 0;
345
369
  for (const [index, attachment] of attachments.entries()) {
346
370
  const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
347
- const file = new InputFile(attachment.data, attachment.filename);
348
- const msg = attachment.kind === "audio" ? await api.sendVoice(chatId, file, options) : await api.sendPhoto(chatId, file, options);
371
+ const msg = await withPlainFallback(options, (opts) => {
372
+ const file = new InputFile(attachment.data, attachment.filename);
373
+ return attachment.kind === "audio" ? api.sendVoice(chatId, file, opts) : api.sendPhoto(chatId, file, opts);
374
+ });
349
375
  lastId = msg.message_id;
350
376
  }
351
377
  return lastId;
352
378
  }
379
+ async function withPlainFallback(options, send) {
380
+ try {
381
+ return await send(options);
382
+ } catch (err) {
383
+ if (options.parse_mode === void 0) throw err;
384
+ const mapped = mapSendError(err);
385
+ if (mapped.ok || mapped.error?.code !== "markdown_error") throw err;
386
+ process.stderr.write(
387
+ `[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text
388
+ `
389
+ );
390
+ const { parse_mode: _dropped, ...plain } = options;
391
+ return send(plain);
392
+ }
393
+ }
353
394
  function captionOf(text) {
354
395
  return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
355
396
  }
@@ -446,17 +487,36 @@ function mapSendError(err) {
446
487
  }
447
488
 
448
489
  // src/adapter.ts
490
+ function isObj(v) {
491
+ return typeof v === "object" && v !== null;
492
+ }
493
+ function policyInput(event) {
494
+ const raw = event.telegram?.raw;
495
+ const msg = isObj(raw) && isObj(raw.message) ? raw.message : void 0;
496
+ const replyTo = msg !== void 0 && isObj(msg.reply_to_message) ? msg.reply_to_message : void 0;
497
+ const from = replyTo !== void 0 && isObj(replyTo.from) ? replyTo.from : void 0;
498
+ return {
499
+ chatType: event.channel.type === "dm" ? "private" : "group",
500
+ text: event.text,
501
+ replyToFromId: typeof from?.id === "number" ? from.id : void 0
502
+ };
503
+ }
449
504
  var TelegramAdapter = class extends BasePlatformAdapter {
450
505
  platform = "telegram";
451
506
  bot;
452
507
  allowedUsers;
453
508
  handler;
509
+ inbound;
510
+ requireMention;
511
+ warnedNoIdentity = false;
454
512
  connected = false;
455
513
  startPromise;
456
514
  constructor(opts) {
457
515
  super();
458
516
  this.bot = new Bot(opts.token);
459
517
  this.allowedUsers = new Set(opts.allowedUsers ?? []);
518
+ this.inbound = opts.inbound ?? "polling";
519
+ this.requireMention = opts.requireMention === true;
460
520
  this.bot.on("message", async (ctx) => this.handleInbound(ctx));
461
521
  this.bot.catch((err) => {
462
522
  process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
@@ -483,16 +543,18 @@ var TelegramAdapter = class extends BasePlatformAdapter {
483
543
  `);
484
544
  return false;
485
545
  }
486
- this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
487
- process.stderr.write(`[telegram] polling stopped: ${err.message}
546
+ if (this.inbound === "polling")
547
+ this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
548
+ process.stderr.write(`[telegram] polling stopped: ${err.message}
488
549
  `);
489
- });
550
+ });
490
551
  this.connected = true;
491
552
  return true;
492
553
  }
493
554
  async disconnect() {
494
555
  if (!this.connected) return;
495
556
  this.connected = false;
557
+ if (this.inbound === "webhook") return;
496
558
  try {
497
559
  await this.bot.stop();
498
560
  } catch (cause) {
@@ -526,11 +588,14 @@ var TelegramAdapter = class extends BasePlatformAdapter {
526
588
  let lastId;
527
589
  for (const chunk of chunks) {
528
590
  try {
529
- const msg = await this.bot.api.sendMessage(chatIdNum, chunk, {
530
- ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
531
- ...threadId !== void 0 ? { message_thread_id: threadId } : {},
532
- ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
533
- });
591
+ const msg = await withPlainFallback(
592
+ {
593
+ ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
594
+ ...threadId !== void 0 ? { message_thread_id: threadId } : {},
595
+ ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
596
+ },
597
+ (opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts)
598
+ );
534
599
  lastId = String(msg.message_id);
535
600
  } catch (err) {
536
601
  return mapSendError(err);
@@ -540,6 +605,8 @@ var TelegramAdapter = class extends BasePlatformAdapter {
540
605
  }
541
606
  /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
542
607
  supportsAttachments = true;
608
+ /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
609
+ attachmentKinds = ["image", "audio"];
543
610
  /** Telegram edits a sent message's text through `editMessageText`. */
544
611
  supportsEdit = true;
545
612
  /**
@@ -635,8 +702,29 @@ var TelegramAdapter = class extends BasePlatformAdapter {
635
702
  }
636
703
  const event = normalizeEvent(ctx);
637
704
  if (event === void 0) return;
705
+ if (!this.passesMentionGate(event)) return;
638
706
  await this.dispatchEvent(await this.withVoice(ctx, event));
639
707
  }
708
+ /** The `requireMention` gate, shared by the polled and webhook paths. */
709
+ passesMentionGate(event) {
710
+ if (!this.requireMention || event.channel.type === "dm") return true;
711
+ let me;
712
+ try {
713
+ me = this.bot.botInfo;
714
+ } catch {
715
+ me = void 0;
716
+ }
717
+ if (me?.username === void 0) {
718
+ if (!this.warnedNoIdentity) {
719
+ this.warnedNoIdentity = true;
720
+ process.stderr.write(
721
+ "[telegram] requireMention: bot identity not known yet; dropping group message\n"
722
+ );
723
+ }
724
+ return false;
725
+ }
726
+ return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });
727
+ }
640
728
  /**
641
729
  * The event with the voice note's audio when the message has one (B-715, ADR D1).
642
730
  *
@@ -682,6 +770,7 @@ var TelegramAdapter = class extends BasePlatformAdapter {
682
770
  * named as the handler's failure rather than the platform's, and delivery continues.
683
771
  */
684
772
  async deliver(event) {
773
+ if (!this.passesMentionGate(event)) return "ok";
685
774
  return this.runHandler(this.handler, event);
686
775
  }
687
776
  };
@@ -746,6 +835,12 @@ function readAllowedUsers(config) {
746
835
  }
747
836
  return value;
748
837
  }
838
+ function readRequireMention(config) {
839
+ const value = config.requireMention;
840
+ if (value === void 0 || value === null) return void 0;
841
+ if (typeof value !== "boolean") throw invalid("requireMention", "a boolean");
842
+ return value;
843
+ }
749
844
  var CONFIG = [
750
845
  {
751
846
  key: "token",
@@ -758,37 +853,31 @@ var CONFIG = [
758
853
  required: false,
759
854
  secret: false,
760
855
  description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
856
+ },
857
+ {
858
+ key: "requireMention",
859
+ required: false,
860
+ secret: false,
861
+ description: "When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false."
761
862
  }
762
863
  ];
763
864
  var telegramChannel = {
764
865
  platform: "telegram",
765
866
  transport: "socket",
867
+ senderIdentity: "authenticated",
766
868
  config: CONFIG,
767
869
  create(config) {
768
870
  const token = readToken(config);
769
871
  const allowedUsers = readAllowedUsers(config);
770
- return new TelegramAdapter(allowedUsers === void 0 ? { token } : { token, allowedUsers });
872
+ const requireMention = readRequireMention(config);
873
+ return new TelegramAdapter({
874
+ token,
875
+ ...allowedUsers === void 0 ? {} : { allowedUsers },
876
+ ...requireMention === void 0 ? {} : { requireMention }
877
+ });
771
878
  }
772
879
  };
773
880
 
774
- // src/group-policy.ts
775
- function shouldRespondInChat(ctx, policy) {
776
- const chat = ctx.chat;
777
- if (chat === void 0) return false;
778
- if (chat.type === "private") return true;
779
- const text = ctx.message?.text ?? ctx.message?.caption ?? "";
780
- if (text.startsWith("/")) return true;
781
- const replyTo = ctx.message?.reply_to_message;
782
- if (replyTo?.from?.id === policy.botId) return true;
783
- const mentionTag = `@${policy.botUsername.toLowerCase()}`;
784
- if (text.toLowerCase().includes(mentionTag)) return true;
785
- return false;
786
- }
787
- function stripBotMention(text, botUsername) {
788
- const regex = new RegExp(`@${botUsername}`, "gi");
789
- return text.replace(regex, "").trim();
790
- }
791
-
792
881
  export { ConfigurationError, TelegramAdapter, parseInbound, shouldRespondInChat, splitForTelegram, stripBotMention, telegramChannel };
793
882
  //# sourceMappingURL=index.js.map
794
883
  //# sourceMappingURL=index.js.map