@theokit/gateway-telegram 0.8.0 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 9c832b2: Add `AdapterCapabilities` and `BasePlatformAdapter.capabilities` (edit, attachment kinds, typing, reactions, threads, max length), derived by default. Telegram reports `image` and `audio` attachments.
8
+ - 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.
9
+ - 56bb1d8: Declare whether a channel's sender id is authenticated with `senderIdentity`.
10
+
3
11
  ## 0.8.0
4
12
 
5
13
  ### 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,11 @@ 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"]`. See `@theokit/gateway` for the field meanings.
128
+
114
129
  ## Helpers
115
130
 
116
131
  - `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,28 @@ 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 {
469
507
  platform = "telegram";
470
508
  bot;
471
509
  allowedUsers;
472
510
  handler;
473
511
  inbound;
512
+ requireMention;
513
+ warnedNoIdentity = false;
474
514
  connected = false;
475
515
  startPromise;
476
516
  constructor(opts) {
@@ -478,6 +518,7 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
478
518
  this.bot = new grammy.Bot(opts.token);
479
519
  this.allowedUsers = new Set(opts.allowedUsers ?? []);
480
520
  this.inbound = opts.inbound ?? "polling";
521
+ this.requireMention = opts.requireMention === true;
481
522
  this.bot.on("message", async (ctx) => this.handleInbound(ctx));
482
523
  this.bot.catch((err) => {
483
524
  process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
@@ -566,6 +607,8 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
566
607
  }
567
608
  /** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
568
609
  supportsAttachments = true;
610
+ /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
611
+ attachmentKinds = ["image", "audio"];
569
612
  /** Telegram edits a sent message's text through `editMessageText`. */
570
613
  supportsEdit = true;
571
614
  /**
@@ -661,8 +704,29 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
661
704
  }
662
705
  const event = normalizeEvent(ctx);
663
706
  if (event === void 0) return;
707
+ if (!this.passesMentionGate(event)) return;
664
708
  await this.dispatchEvent(await this.withVoice(ctx, event));
665
709
  }
710
+ /** The `requireMention` gate, shared by the polled and webhook paths. */
711
+ passesMentionGate(event) {
712
+ if (!this.requireMention || event.channel.type === "dm") return true;
713
+ let me;
714
+ try {
715
+ me = this.bot.botInfo;
716
+ } catch {
717
+ me = void 0;
718
+ }
719
+ if (me?.username === void 0) {
720
+ if (!this.warnedNoIdentity) {
721
+ this.warnedNoIdentity = true;
722
+ process.stderr.write(
723
+ "[telegram] requireMention: bot identity not known yet; dropping group message\n"
724
+ );
725
+ }
726
+ return false;
727
+ }
728
+ return shouldRespond(policyInput(event), { botUsername: me.username, botId: me.id });
729
+ }
666
730
  /**
667
731
  * The event with the voice note's audio when the message has one (B-715, ADR D1).
668
732
  *
@@ -708,6 +772,7 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
708
772
  * named as the handler's failure rather than the platform's, and delivery continues.
709
773
  */
710
774
  async deliver(event) {
775
+ if (!this.passesMentionGate(event)) return "ok";
711
776
  return this.runHandler(this.handler, event);
712
777
  }
713
778
  };
@@ -772,6 +837,12 @@ function readAllowedUsers(config) {
772
837
  }
773
838
  return value;
774
839
  }
840
+ function readRequireMention(config) {
841
+ const value = config.requireMention;
842
+ if (value === void 0 || value === null) return void 0;
843
+ if (typeof value !== "boolean") throw invalid("requireMention", "a boolean");
844
+ return value;
845
+ }
775
846
  var CONFIG = [
776
847
  {
777
848
  key: "token",
@@ -784,37 +855,31 @@ var CONFIG = [
784
855
  required: false,
785
856
  secret: false,
786
857
  description: "Telegram user ids allowed to reach the handler; absent or empty allows everyone."
858
+ },
859
+ {
860
+ key: "requireMention",
861
+ required: false,
862
+ secret: false,
863
+ description: "When true, group messages reach the handler only if they mention the bot, reply to it or are slash commands; default false."
787
864
  }
788
865
  ];
789
866
  var telegramChannel = {
790
867
  platform: "telegram",
791
868
  transport: "socket",
869
+ senderIdentity: "authenticated",
792
870
  config: CONFIG,
793
871
  create(config) {
794
872
  const token = readToken(config);
795
873
  const allowedUsers = readAllowedUsers(config);
796
- return new TelegramAdapter(allowedUsers === void 0 ? { token } : { token, allowedUsers });
874
+ const requireMention = readRequireMention(config);
875
+ return new TelegramAdapter({
876
+ token,
877
+ ...allowedUsers === void 0 ? {} : { allowedUsers },
878
+ ...requireMention === void 0 ? {} : { requireMention }
879
+ });
797
880
  }
798
881
  };
799
882
 
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
883
  exports.ConfigurationError = ConfigurationError;
819
884
  exports.TelegramAdapter = TelegramAdapter;
820
885
  exports.parseInbound = parseInbound;