@theokit/gateway-telegram 0.8.0 → 0.10.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/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 2831ca3: Report `capabilities.maxMessageChars` from the splitter limit, and `capabilities.threads` (true for Discord, Telegram and Slack).
8
+
9
+ ## 0.9.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 9c832b2: Add `AdapterCapabilities` and `BasePlatformAdapter.capabilities` (edit, attachment kinds, typing, reactions, threads, max length), derived by default. Telegram reports `image` and `audio` attachments.
14
+ - 0bc525c: Add a `requireMention` option: when true, group messages reach the handler only if they mention the bot, reply to it or are slash commands, on both the polled and the `deliver()` paths. Default false.
15
+ - 56bb1d8: Declare whether a channel's sender id is authenticated with `senderIdentity`.
16
+
3
17
  ## 0.8.0
4
18
 
5
19
  ### Minor Changes
package/README.md CHANGED
@@ -90,6 +90,16 @@ shows OGG/Opus, MP3 and M4A as a voice bubble; other audio is delivered as a fil
90
90
  Attachments need `@theokit/gateway` 0.13.0 or later: an older core's `ctx.reply` does not carry
91
91
  them to the adapter, so install both together.
92
92
 
93
+ ## Group messages: `requireMention`
94
+
95
+ With `requireMention: true`, a group or supergroup message reaches the handler only if it mentions
96
+ the bot (`@username`, any case), replies to one of the bot's messages, or starts with `/`. Private
97
+ chats always pass. The gate applies to polled updates and to events given to `deliver()` (webhook).
98
+ It uses the identity grammy holds after `connect()`; a group message that arrives before it is
99
+ known is dropped with one stderr line. The default is `false` here, so existing bots keep
100
+ answering every message (the other adapters default to `true`). In `telegramChannel` config,
101
+ `requireMention` must be a boolean.
102
+
93
103
  ## Channel descriptor
94
104
 
95
105
  `telegramChannel` describes this channel as data, for `createChannels` in `@theokit/gateway`:
@@ -111,6 +121,12 @@ refuses a token that is not a string or is empty, and an `allowedUsers` that is
111
121
  strings, with this package's `ConfigurationError` (also a `GatewayConfigurationError`), so
112
122
  `createChannels` lists that channel in `rejected` too.
113
123
 
124
+ ## Capabilities
125
+
126
+ `adapter.capabilities` reports `edit`, `typing` and `reactions` as `true` and
127
+ `attachments: ["image", "audio"]`. It also reports `maxMessageChars: 4096` (the splitter limit)
128
+ and `threads: true`. See `@theokit/gateway` for the field meanings.
129
+
114
130
  ## Helpers
115
131
 
116
132
  - `shouldRespondInChat(ctx, policy)` — group-chat policy (DM = always reply, group = only on `@mention` or reply-to-bot or slash command). Register as a `pre_inbound` hook.
package/dist/index.cjs CHANGED
@@ -5,6 +5,30 @@ var grammy = require('grammy');
5
5
 
6
6
  // src/adapter.ts
7
7
 
8
+ // src/group-policy.ts
9
+ function shouldRespond(input, policy) {
10
+ if (input.chatType === "private") return true;
11
+ if (input.text.startsWith("/")) return true;
12
+ if (input.replyToFromId !== void 0 && input.replyToFromId === policy.botId) return true;
13
+ return input.text.toLowerCase().includes(`@${policy.botUsername.toLowerCase()}`);
14
+ }
15
+ function shouldRespondInChat(ctx, policy) {
16
+ const chat = ctx.chat;
17
+ if (chat === void 0) return false;
18
+ return shouldRespond(
19
+ {
20
+ chatType: chat.type,
21
+ text: ctx.message?.text ?? ctx.message?.caption ?? "",
22
+ replyToFromId: ctx.message?.reply_to_message?.from?.id
23
+ },
24
+ policy
25
+ );
26
+ }
27
+ function stripBotMention(text, botUsername) {
28
+ const regex = new RegExp(`@${botUsername}`, "gi");
29
+ return text.replace(regex, "").trim();
30
+ }
31
+
8
32
  // src/parse-inbound.ts
9
33
  function buildEvent(chat, msg, from, raw) {
10
34
  let channelType;
@@ -465,12 +489,31 @@ function mapSendError(err) {
465
489
  }
466
490
 
467
491
  // src/adapter.ts
492
+ function isObj(v) {
493
+ return typeof v === "object" && v !== null;
494
+ }
495
+ function policyInput(event) {
496
+ const raw = event.telegram?.raw;
497
+ const msg = isObj(raw) && isObj(raw.message) ? raw.message : void 0;
498
+ const replyTo = msg !== void 0 && isObj(msg.reply_to_message) ? msg.reply_to_message : void 0;
499
+ const from = replyTo !== void 0 && isObj(replyTo.from) ? replyTo.from : void 0;
500
+ return {
501
+ chatType: event.channel.type === "dm" ? "private" : "group",
502
+ text: event.text,
503
+ replyToFromId: typeof from?.id === "number" ? from.id : void 0
504
+ };
505
+ }
468
506
  var TelegramAdapter = class extends gateway.BasePlatformAdapter {
507
+ get capabilities() {
508
+ return { ...super.capabilities, maxMessageChars: TELEGRAM_MAX_MESSAGE, threads: true };
509
+ }
469
510
  platform = "telegram";
470
511
  bot;
471
512
  allowedUsers;
472
513
  handler;
473
514
  inbound;
515
+ requireMention;
516
+ warnedNoIdentity = false;
474
517
  connected = false;
475
518
  startPromise;
476
519
  constructor(opts) {
@@ -478,6 +521,7 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
478
521
  this.bot = new grammy.Bot(opts.token);
479
522
  this.allowedUsers = new Set(opts.allowedUsers ?? []);
480
523
  this.inbound = opts.inbound ?? "polling";
524
+ this.requireMention = opts.requireMention === true;
481
525
  this.bot.on("message", async (ctx) => this.handleInbound(ctx));
482
526
  this.bot.catch((err) => {
483
527
  process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
@@ -566,6 +610,8 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
566
610
  }
567
611
  /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
568
612
  supportsAttachments = true;
613
+ /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
614
+ attachmentKinds = ["image", "audio"];
569
615
  /** Telegram edits a sent message's text through `editMessageText`. */
570
616
  supportsEdit = true;
571
617
  /**
@@ -661,8 +707,29 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
661
707
  }
662
708
  const event = normalizeEvent(ctx);
663
709
  if (event === void 0) return;
710
+ if (!this.passesMentionGate(event)) return;
664
711
  await this.dispatchEvent(await this.withVoice(ctx, event));
665
712
  }
713
+ /** The `requireMention` gate, shared by the polled and webhook paths. */
714
+ passesMentionGate(event) {
715
+ if (!this.requireMention || event.channel.type === "dm") return true;
716
+ let me;
717
+ try {
718
+ me = this.bot.botInfo;
719
+ } catch {
720
+ me = void 0;
721
+ }
722
+ if (me?.username === void 0) {
723
+ if (!this.warnedNoIdentity) {
724
+ this.warnedNoIdentity = true;
725
+ process.stderr.write(
726
+ "[telegram] requireMention: bot identity not known yet; dropping group message\n"
727
+ );
728
+ }
729
+ return false;
730
+ }
731
+ return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });
732
+ }
666
733
  /**
667
734
  * The event with the voice note's audio when the message has one (B-715, ADR D1).
668
735
  *
@@ -708,6 +775,7 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
708
775
  * named as the handler's failure rather than the platform's, and delivery continues.
709
776
  */
710
777
  async deliver(event) {
778
+ if (!this.passesMentionGate(event)) return "ok";
711
779
  return this.runHandler(this.handler, event);
712
780
  }
713
781
  };
@@ -772,6 +840,12 @@ function readAllowedUsers(config) {
772
840
  }
773
841
  return value;
774
842
  }
843
+ function readRequireMention(config) {
844
+ const value = config.requireMention;
845
+ if (value === void 0 || value === null) return void 0;
846
+ if (typeof value !== "boolean") throw invalid("requireMention", "a boolean");
847
+ return value;
848
+ }
775
849
  var CONFIG = [
776
850
  {
777
851
  key: "token",
@@ -784,37 +858,31 @@ var CONFIG = [
784
858
  required: false,
785
859
  secret: false,
786
860
  description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
861
+ },
862
+ {
863
+ key: "requireMention",
864
+ required: false,
865
+ secret: false,
866
+ description: "When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false."
787
867
  }
788
868
  ];
789
869
  var telegramChannel = {
790
870
  platform: "telegram",
791
871
  transport: "socket",
872
+ senderIdentity: "authenticated",
792
873
  config: CONFIG,
793
874
  create(config) {
794
875
  const token = readToken(config);
795
876
  const allowedUsers = readAllowedUsers(config);
796
- return new TelegramAdapter(allowedUsers === void 0 ? { token } : { token, allowedUsers });
877
+ const requireMention = readRequireMention(config);
878
+ return new TelegramAdapter({
879
+ token,
880
+ ...allowedUsers === void 0 ? {} : { allowedUsers },
881
+ ...requireMention === void 0 ? {} : { requireMention }
882
+ });
797
883
  }
798
884
  };
799
885
 
800
- // src/group-policy.ts
801
- function shouldRespondInChat(ctx, policy) {
802
- const chat = ctx.chat;
803
- if (chat === void 0) return false;
804
- if (chat.type === "private") return true;
805
- const text = ctx.message?.text ?? ctx.message?.caption ?? "";
806
- if (text.startsWith("/")) return true;
807
- const replyTo = ctx.message?.reply_to_message;
808
- if (replyTo?.from?.id === policy.botId) return true;
809
- const mentionTag = `@${policy.botUsername.toLowerCase()}`;
810
- if (text.toLowerCase().includes(mentionTag)) return true;
811
- return false;
812
- }
813
- function stripBotMention(text, botUsername) {
814
- const regex = new RegExp(`@${botUsername}`, "gi");
815
- return text.replace(regex, "").trim();
816
- }
817
-
818
886
  exports.ConfigurationError = ConfigurationError;
819
887
  exports.TelegramAdapter = TelegramAdapter;
820
888
  exports.parseInbound = parseInbound;