@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/CHANGELOG.md +18 -0
- package/README.md +26 -2
- package/dist/index.cjs +119 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -1
- package/dist/index.d.ts +21 -1
- package/dist/index.js +119 -30
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
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
|
+
|
|
11
|
+
## 0.8.0
|
|
12
|
+
|
|
13
|
+
### Minor Changes
|
|
14
|
+
|
|
15
|
+
- 4ae0506: `TelegramAdapter` takes `inbound: "webhook"`: `connect()` checks the token without starting long polling, and `disconnect()` does not call `bot.stop()`. Updates arrive through `deliver()`. The default stays `"polling"`.
|
|
16
|
+
|
|
17
|
+
### Patch Changes
|
|
18
|
+
|
|
19
|
+
- 66646fc: A chunk (or photo caption) that Telegram refuses with a legacy Markdown parse error is now resent once as plain text, so the reply arrives and later chunks are no longer dropped.
|
|
20
|
+
|
|
3
21
|
## 0.7.1
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -10,8 +10,17 @@ Telegram platform adapter for `@theokit/gateway`. Wraps [grammy](https://grammy.
|
|
|
10
10
|
**Long polling by default.** grammY pulls updates and they reach `onInbound` once `connect()`
|
|
11
11
|
resolves.
|
|
12
12
|
|
|
13
|
-
Telegram also supports a webhook, and `theokit/server/webhook` exports `telegram()` for
|
|
14
|
-
token it sends in `X-Telegram-Bot-Api-Secret-Token`.
|
|
13
|
+
**Webhook.** Telegram also supports a webhook, and `theokit/server/webhook` exports `telegram()` for
|
|
14
|
+
the secret token it sends in `X-Telegram-Bot-Api-Secret-Token`. Set `inbound: "webhook"` so
|
|
15
|
+
`connect()` checks the token but does not start long polling (a bot with a webhook set cannot call
|
|
16
|
+
`getUpdates`), and `disconnect()` does not stop a poller. Parsed updates go to `adapter.deliver(event)`.
|
|
17
|
+
|
|
18
|
+
```typescript
|
|
19
|
+
const adapter = new TelegramAdapter({ token: process.env.TELEGRAM_BOT_TOKEN!, inbound: "webhook" });
|
|
20
|
+
// In your webhook route, after verifying the secret token:
|
|
21
|
+
await adapter.deliver(event);
|
|
22
|
+
```
|
|
23
|
+
|
|
15
24
|
## Install
|
|
16
25
|
|
|
17
26
|
```bash
|
|
@@ -81,6 +90,16 @@ shows OGG/Opus, MP3 and M4A as a voice bubble; other audio is delivered as a fil
|
|
|
81
90
|
Attachments need `@theokit/gateway` 0.13.0 or later: an older core's `ctx.reply` does not carry
|
|
82
91
|
them to the adapter, so install both together.
|
|
83
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
|
+
|
|
84
103
|
## Channel descriptor
|
|
85
104
|
|
|
86
105
|
`telegramChannel` describes this channel as data, for `createChannels` in `@theokit/gateway`:
|
|
@@ -102,6 +121,11 @@ refuses a token that is not a string or is empty, and an `allowedUsers` that is
|
|
|
102
121
|
strings, with this package's `ConfigurationError` (also a `GatewayConfigurationError`), so
|
|
103
122
|
`createChannels` lists that channel in `rejected` too.
|
|
104
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
|
+
|
|
105
129
|
## Helpers
|
|
106
130
|
|
|
107
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;
|
|
@@ -332,7 +356,7 @@ async function sendPhotos(api, out) {
|
|
|
332
356
|
let lastId = await sendEachAttachment(api, chatId, out, shared);
|
|
333
357
|
if (out.text.length > CAPTION_LIMIT) {
|
|
334
358
|
for (const chunk of splitForTelegram(out.text)) {
|
|
335
|
-
lastId = (await api.sendMessage(chatId, chunk,
|
|
359
|
+
lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts))).message_id;
|
|
336
360
|
}
|
|
337
361
|
}
|
|
338
362
|
return { ok: true, messageId: String(lastId) };
|
|
@@ -346,12 +370,29 @@ async function sendEachAttachment(api, chatId, out, shared) {
|
|
|
346
370
|
let lastId = 0;
|
|
347
371
|
for (const [index, attachment] of attachments.entries()) {
|
|
348
372
|
const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
|
|
349
|
-
const
|
|
350
|
-
|
|
373
|
+
const msg = await withPlainFallback(options, (opts) => {
|
|
374
|
+
const file = new grammy.InputFile(attachment.data, attachment.filename);
|
|
375
|
+
return attachment.kind === "audio" ? api.sendVoice(chatId, file, opts) : api.sendPhoto(chatId, file, opts);
|
|
376
|
+
});
|
|
351
377
|
lastId = msg.message_id;
|
|
352
378
|
}
|
|
353
379
|
return lastId;
|
|
354
380
|
}
|
|
381
|
+
async function withPlainFallback(options, send) {
|
|
382
|
+
try {
|
|
383
|
+
return await send(options);
|
|
384
|
+
} catch (err) {
|
|
385
|
+
if (options.parse_mode === void 0) throw err;
|
|
386
|
+
const mapped = mapSendError(err);
|
|
387
|
+
if (mapped.ok || mapped.error?.code !== "markdown_error") throw err;
|
|
388
|
+
process.stderr.write(
|
|
389
|
+
`[theokit-gateway-telegram] ${mapped.error.message}; resending as plain text
|
|
390
|
+
`
|
|
391
|
+
);
|
|
392
|
+
const { parse_mode: _dropped, ...plain } = options;
|
|
393
|
+
return send(plain);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
355
396
|
function captionOf(text) {
|
|
356
397
|
return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
|
|
357
398
|
}
|
|
@@ -448,17 +489,36 @@ function mapSendError(err) {
|
|
|
448
489
|
}
|
|
449
490
|
|
|
450
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
|
+
}
|
|
451
506
|
var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
452
507
|
platform = "telegram";
|
|
453
508
|
bot;
|
|
454
509
|
allowedUsers;
|
|
455
510
|
handler;
|
|
511
|
+
inbound;
|
|
512
|
+
requireMention;
|
|
513
|
+
warnedNoIdentity = false;
|
|
456
514
|
connected = false;
|
|
457
515
|
startPromise;
|
|
458
516
|
constructor(opts) {
|
|
459
517
|
super();
|
|
460
518
|
this.bot = new grammy.Bot(opts.token);
|
|
461
519
|
this.allowedUsers = new Set(opts.allowedUsers ?? []);
|
|
520
|
+
this.inbound = opts.inbound ?? "polling";
|
|
521
|
+
this.requireMention = opts.requireMention === true;
|
|
462
522
|
this.bot.on("message", async (ctx) => this.handleInbound(ctx));
|
|
463
523
|
this.bot.catch((err) => {
|
|
464
524
|
process.stderr.write(`[telegram] bot error: ${err.error?.message ?? err}
|
|
@@ -485,16 +545,18 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
485
545
|
`);
|
|
486
546
|
return false;
|
|
487
547
|
}
|
|
488
|
-
|
|
489
|
-
|
|
548
|
+
if (this.inbound === "polling")
|
|
549
|
+
this.startPromise = this.bot.start({ drop_pending_updates: true }).catch((err) => {
|
|
550
|
+
process.stderr.write(`[telegram] polling stopped: ${err.message}
|
|
490
551
|
`);
|
|
491
|
-
|
|
552
|
+
});
|
|
492
553
|
this.connected = true;
|
|
493
554
|
return true;
|
|
494
555
|
}
|
|
495
556
|
async disconnect() {
|
|
496
557
|
if (!this.connected) return;
|
|
497
558
|
this.connected = false;
|
|
559
|
+
if (this.inbound === "webhook") return;
|
|
498
560
|
try {
|
|
499
561
|
await this.bot.stop();
|
|
500
562
|
} catch (cause) {
|
|
@@ -528,11 +590,14 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
528
590
|
let lastId;
|
|
529
591
|
for (const chunk of chunks) {
|
|
530
592
|
try {
|
|
531
|
-
const msg = await
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
593
|
+
const msg = await withPlainFallback(
|
|
594
|
+
{
|
|
595
|
+
...parseMode !== void 0 ? { parse_mode: parseMode } : {},
|
|
596
|
+
...threadId !== void 0 ? { message_thread_id: threadId } : {},
|
|
597
|
+
...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
|
|
598
|
+
},
|
|
599
|
+
(opts) => this.bot.api.sendMessage(chatIdNum, chunk, opts)
|
|
600
|
+
);
|
|
536
601
|
lastId = String(msg.message_id);
|
|
537
602
|
} catch (err) {
|
|
538
603
|
return mapSendError(err);
|
|
@@ -542,6 +607,8 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
542
607
|
}
|
|
543
608
|
/** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
|
|
544
609
|
supportsAttachments = true;
|
|
610
|
+
/** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
|
|
611
|
+
attachmentKinds = ["image", "audio"];
|
|
545
612
|
/** Telegram edits a sent message's text through `editMessageText`. */
|
|
546
613
|
supportsEdit = true;
|
|
547
614
|
/**
|
|
@@ -637,8 +704,29 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
637
704
|
}
|
|
638
705
|
const event = normalizeEvent(ctx);
|
|
639
706
|
if (event === void 0) return;
|
|
707
|
+
if (!this.passesMentionGate(event)) return;
|
|
640
708
|
await this.dispatchEvent(await this.withVoice(ctx, event));
|
|
641
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
|
+
}
|
|
642
730
|
/**
|
|
643
731
|
* The event with the voice note's audio when the message has one (B-715, ADR D1).
|
|
644
732
|
*
|
|
@@ -684,6 +772,7 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
684
772
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
685
773
|
*/
|
|
686
774
|
async deliver(event) {
|
|
775
|
+
if (!this.passesMentionGate(event)) return "ok";
|
|
687
776
|
return this.runHandler(this.handler, event);
|
|
688
777
|
}
|
|
689
778
|
};
|
|
@@ -748,6 +837,12 @@ function readAllowedUsers(config) {
|
|
|
748
837
|
}
|
|
749
838
|
return value;
|
|
750
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
|
+
}
|
|
751
846
|
var CONFIG = [
|
|
752
847
|
{
|
|
753
848
|
key: "token",
|
|
@@ -760,37 +855,31 @@ var CONFIG = [
|
|
|
760
855
|
required: false,
|
|
761
856
|
secret: false,
|
|
762
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."
|
|
763
864
|
}
|
|
764
865
|
];
|
|
765
866
|
var telegramChannel = {
|
|
766
867
|
platform: "telegram",
|
|
767
868
|
transport: "socket",
|
|
869
|
+
senderIdentity: "authenticated",
|
|
768
870
|
config: CONFIG,
|
|
769
871
|
create(config) {
|
|
770
872
|
const token = readToken(config);
|
|
771
873
|
const allowedUsers = readAllowedUsers(config);
|
|
772
|
-
|
|
874
|
+
const requireMention = readRequireMention(config);
|
|
875
|
+
return new TelegramAdapter({
|
|
876
|
+
token,
|
|
877
|
+
...allowedUsers === void 0 ? {} : { allowedUsers },
|
|
878
|
+
...requireMention === void 0 ? {} : { requireMention }
|
|
879
|
+
});
|
|
773
880
|
}
|
|
774
881
|
};
|
|
775
882
|
|
|
776
|
-
// src/group-policy.ts
|
|
777
|
-
function shouldRespondInChat(ctx, policy) {
|
|
778
|
-
const chat = ctx.chat;
|
|
779
|
-
if (chat === void 0) return false;
|
|
780
|
-
if (chat.type === "private") return true;
|
|
781
|
-
const text = ctx.message?.text ?? ctx.message?.caption ?? "";
|
|
782
|
-
if (text.startsWith("/")) return true;
|
|
783
|
-
const replyTo = ctx.message?.reply_to_message;
|
|
784
|
-
if (replyTo?.from?.id === policy.botId) return true;
|
|
785
|
-
const mentionTag = `@${policy.botUsername.toLowerCase()}`;
|
|
786
|
-
if (text.toLowerCase().includes(mentionTag)) return true;
|
|
787
|
-
return false;
|
|
788
|
-
}
|
|
789
|
-
function stripBotMention(text, botUsername) {
|
|
790
|
-
const regex = new RegExp(`@${botUsername}`, "gi");
|
|
791
|
-
return text.replace(regex, "").trim();
|
|
792
|
-
}
|
|
793
|
-
|
|
794
883
|
exports.ConfigurationError = ConfigurationError;
|
|
795
884
|
exports.TelegramAdapter = TelegramAdapter;
|
|
796
885
|
exports.parseInbound = parseInbound;
|