@sedge-hq/telegram 0.0.0-stage → 0.1.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/package.json +43 -5
- package/src/bot.ts +192 -0
- package/src/format.ts +52 -0
- package/src/telegram.ts +159 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@sedge-hq/telegram",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Telegram for sedge: message your agent from anywhere, and it answers there.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/sedge-hq/sedge.git",
|
|
9
|
+
"directory": "packages/telegram"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"!src/**/*.test.ts"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./src/telegram.ts",
|
|
18
|
+
"./bot": "./src/bot.ts",
|
|
19
|
+
"./format": "./src/format.ts"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"typecheck": "tsc --noEmit",
|
|
26
|
+
"test": "bun --bun vitest run --passWithNoTests"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@sedge-hq/kit": "0.1.0",
|
|
30
|
+
"effect": "4.1.4"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@effect/vitest": "4.1.4",
|
|
34
|
+
"@sedge-hq/config": "0.0.0",
|
|
35
|
+
"@types/bun": "1.4.4",
|
|
36
|
+
"typescript": "7.0.2",
|
|
37
|
+
"vitest": "5.1.1"
|
|
38
|
+
},
|
|
39
|
+
"sedge": {
|
|
40
|
+
"plugins": [
|
|
41
|
+
"./src/telegram.ts"
|
|
42
|
+
]
|
|
43
|
+
}
|
|
44
|
+
}
|
package/src/bot.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { Effect, Schema } from 'effect';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The few Bot API calls Sedge needs, over plain fetch. Updates are decoded with Schema: they are
|
|
5
|
+
* untrusted input, and only the fields read here are kept.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const Chat = Schema.Struct({ id: Schema.Number, type: Schema.String });
|
|
9
|
+
const User = Schema.Struct({
|
|
10
|
+
id: Schema.Number,
|
|
11
|
+
first_name: Schema.optional(Schema.String),
|
|
12
|
+
username: Schema.optional(Schema.String),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
export const Message = Schema.Struct({
|
|
16
|
+
message_id: Schema.Number,
|
|
17
|
+
date: Schema.Number,
|
|
18
|
+
chat: Chat,
|
|
19
|
+
from: Schema.optional(User),
|
|
20
|
+
text: Schema.optional(Schema.String),
|
|
21
|
+
caption: Schema.optional(Schema.String),
|
|
22
|
+
});
|
|
23
|
+
export type Message = typeof Message.Type;
|
|
24
|
+
|
|
25
|
+
export const CallbackQuery = Schema.Struct({
|
|
26
|
+
id: Schema.String,
|
|
27
|
+
from: User,
|
|
28
|
+
data: Schema.optional(Schema.String),
|
|
29
|
+
message: Schema.optional(
|
|
30
|
+
Schema.Struct({
|
|
31
|
+
message_id: Schema.Number,
|
|
32
|
+
chat: Chat,
|
|
33
|
+
text: Schema.optional(Schema.String),
|
|
34
|
+
}),
|
|
35
|
+
),
|
|
36
|
+
});
|
|
37
|
+
export type CallbackQuery = typeof CallbackQuery.Type;
|
|
38
|
+
|
|
39
|
+
export const Update = Schema.Struct({
|
|
40
|
+
update_id: Schema.Number,
|
|
41
|
+
message: Schema.optional(Message),
|
|
42
|
+
callback_query: Schema.optional(CallbackQuery),
|
|
43
|
+
});
|
|
44
|
+
export type Update = typeof Update.Type;
|
|
45
|
+
|
|
46
|
+
const BotUser = Schema.Struct({ id: Schema.Number, username: Schema.optional(Schema.String) });
|
|
47
|
+
|
|
48
|
+
export class TelegramError extends Schema.TaggedError<TelegramError>()('TelegramError', {
|
|
49
|
+
method: Schema.String,
|
|
50
|
+
message: Schema.String,
|
|
51
|
+
/** Telegram's answer, when there was one. 429 asks to wait `retryAfter` seconds. */
|
|
52
|
+
status: Schema.optional(Schema.Number),
|
|
53
|
+
retryAfter: Schema.optional(Schema.Number),
|
|
54
|
+
}) {}
|
|
55
|
+
|
|
56
|
+
export interface InlineButton {
|
|
57
|
+
readonly text: string;
|
|
58
|
+
readonly callback_data: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Telegram rejects messages over 4096 characters; split on line breaks where possible. */
|
|
62
|
+
export const splitMessage = (text: string, limit = 4096): Array<string> => {
|
|
63
|
+
const chunks: Array<string> = [];
|
|
64
|
+
let rest = text;
|
|
65
|
+
while (rest.length > limit) {
|
|
66
|
+
const cut = rest.lastIndexOf('\n', limit);
|
|
67
|
+
const at = cut > limit / 2 ? cut : limit;
|
|
68
|
+
chunks.push(rest.slice(0, at));
|
|
69
|
+
rest = rest.slice(at).replace(/^\n/, '');
|
|
70
|
+
}
|
|
71
|
+
if (rest.length > 0 || chunks.length === 0) chunks.push(rest);
|
|
72
|
+
return chunks;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const makeBot = (token: string, api = 'https://api.telegram.org') => {
|
|
76
|
+
const call = <A>(
|
|
77
|
+
method: string,
|
|
78
|
+
body: Record<string, unknown>,
|
|
79
|
+
decode: (value: unknown) => A,
|
|
80
|
+
timeoutMs = 30_000,
|
|
81
|
+
) =>
|
|
82
|
+
Effect.tryPromise({
|
|
83
|
+
try: async (signal) => {
|
|
84
|
+
const response = await fetch(`${api}/bot${token}/${method}`, {
|
|
85
|
+
method: 'POST',
|
|
86
|
+
headers: { 'content-type': 'application/json' },
|
|
87
|
+
body: JSON.stringify(body),
|
|
88
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
89
|
+
});
|
|
90
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
91
|
+
ok?: boolean;
|
|
92
|
+
result?: unknown;
|
|
93
|
+
description?: string;
|
|
94
|
+
parameters?: { retry_after?: number };
|
|
95
|
+
};
|
|
96
|
+
if (!payload.ok) {
|
|
97
|
+
throw new TelegramError({
|
|
98
|
+
method,
|
|
99
|
+
message: payload.description ?? `HTTP ${response.status}`,
|
|
100
|
+
status: response.status,
|
|
101
|
+
retryAfter: payload.parameters?.retry_after,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
return decode(payload.result);
|
|
105
|
+
},
|
|
106
|
+
catch: (cause) =>
|
|
107
|
+
cause instanceof TelegramError
|
|
108
|
+
? cause
|
|
109
|
+
: new TelegramError({ method, message: String(cause) }),
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const ignore = () => undefined;
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
getMe: () => call('getMe', {}, Schema.decodeUnknownSync(BotUser)),
|
|
116
|
+
/** Long poll: Telegram holds the request up to `timeout` seconds until updates arrive. */
|
|
117
|
+
getUpdates: (offset: number | undefined, timeout = 50) =>
|
|
118
|
+
call(
|
|
119
|
+
'getUpdates',
|
|
120
|
+
{ offset, timeout, allowed_updates: ['message', 'callback_query'] },
|
|
121
|
+
(result) =>
|
|
122
|
+
(Array.isArray(result) ? result : []).flatMap((raw) => {
|
|
123
|
+
// One malformed update must not stall the stream; keep its id so the
|
|
124
|
+
// offset still moves past it.
|
|
125
|
+
try {
|
|
126
|
+
return [Schema.decodeUnknownSync(Update)(raw)];
|
|
127
|
+
} catch {
|
|
128
|
+
const id = (raw as { update_id?: unknown })?.update_id;
|
|
129
|
+
return typeof id === 'number' ? [{ update_id: id }] : [];
|
|
130
|
+
}
|
|
131
|
+
}),
|
|
132
|
+
(timeout + 10) * 1000,
|
|
133
|
+
),
|
|
134
|
+
sendMessage: (
|
|
135
|
+
chatId: number,
|
|
136
|
+
text: string,
|
|
137
|
+
buttons?: ReadonlyArray<InlineButton>,
|
|
138
|
+
parseMode?: 'HTML',
|
|
139
|
+
) =>
|
|
140
|
+
call(
|
|
141
|
+
'sendMessage',
|
|
142
|
+
{
|
|
143
|
+
chat_id: chatId,
|
|
144
|
+
text,
|
|
145
|
+
...(parseMode ? { parse_mode: parseMode } : {}),
|
|
146
|
+
link_preview_options: { is_disabled: true },
|
|
147
|
+
...(buttons ? { reply_markup: { inline_keyboard: [buttons] } } : {}),
|
|
148
|
+
},
|
|
149
|
+
Schema.decodeUnknownSync(Schema.Struct({ message_id: Schema.Number })),
|
|
150
|
+
),
|
|
151
|
+
editMessageText: (chatId: number, messageId: number, text: string) =>
|
|
152
|
+
call('editMessageText', { chat_id: chatId, message_id: messageId, text }, ignore),
|
|
153
|
+
answerCallbackQuery: (id: string, text?: string) =>
|
|
154
|
+
call('answerCallbackQuery', { callback_query_id: id, text }, ignore),
|
|
155
|
+
sendChatAction: (chatId: number, action: 'typing') =>
|
|
156
|
+
call('sendChatAction', { chat_id: chatId, action }, ignore),
|
|
157
|
+
/** Uploads a local file: as a photo when it is an image, otherwise as a document. */
|
|
158
|
+
sendFile: (chatId: number, path: string, caption?: string) =>
|
|
159
|
+
Effect.tryPromise({
|
|
160
|
+
try: async (signal) => {
|
|
161
|
+
const photo = /\.(png|jpe?g|gif|webp)$/i.test(path);
|
|
162
|
+
const form = new FormData();
|
|
163
|
+
form.append('chat_id', String(chatId));
|
|
164
|
+
form.append(photo ? 'photo' : 'document', Bun.file(path));
|
|
165
|
+
if (caption) form.append('caption', caption.slice(0, 1024));
|
|
166
|
+
const method = photo ? 'sendPhoto' : 'sendDocument';
|
|
167
|
+
const response = await fetch(`${api}/bot${token}/${method}`, {
|
|
168
|
+
method: 'POST',
|
|
169
|
+
body: form,
|
|
170
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(120_000)]),
|
|
171
|
+
});
|
|
172
|
+
const payload = (await response.json().catch(() => ({}))) as {
|
|
173
|
+
ok?: boolean;
|
|
174
|
+
description?: string;
|
|
175
|
+
};
|
|
176
|
+
if (!payload.ok) {
|
|
177
|
+
throw new TelegramError({
|
|
178
|
+
method,
|
|
179
|
+
message: payload.description ?? `HTTP ${response.status}`,
|
|
180
|
+
status: response.status,
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
catch: (cause) =>
|
|
185
|
+
cause instanceof TelegramError
|
|
186
|
+
? cause
|
|
187
|
+
: new TelegramError({ method: 'sendFile', message: String(cause) }),
|
|
188
|
+
}),
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
export type Bot = ReturnType<typeof makeBot>;
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent writes Markdown; Telegram shows it raw unless it's sent as Telegram's HTML subset.
|
|
3
|
+
* This turns the common parts (code blocks, inline code, bold, italics, links, headings, bullets)
|
|
4
|
+
* into that subset and escapes everything else, so a stray `<` can't break a message.
|
|
5
|
+
*/
|
|
6
|
+
const escape = (text: string) =>
|
|
7
|
+
text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
|
|
8
|
+
|
|
9
|
+
const inline = (text: string): string => {
|
|
10
|
+
// Inline code first, held aside so nothing inside it is formatted.
|
|
11
|
+
const codes: Array<string> = [];
|
|
12
|
+
let out = text.replace(/`([^`\n]+)`/g, (_, code: string) => {
|
|
13
|
+
codes.push(`<code>${escape(code)}</code>`);
|
|
14
|
+
return `\uE000${codes.length - 1}\uE000`;
|
|
15
|
+
});
|
|
16
|
+
out = escape(out)
|
|
17
|
+
.replace(
|
|
18
|
+
/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g,
|
|
19
|
+
(_, label: string, url: string) =>
|
|
20
|
+
`<a href="${url.replaceAll('"', '"')}">${label}</a>`,
|
|
21
|
+
)
|
|
22
|
+
.replace(/\*\*([^*\n]+)\*\*/g, '<b>$1</b>')
|
|
23
|
+
.replace(/__([^_\n]+)__/g, '<b>$1</b>')
|
|
24
|
+
.replace(/(^|[\s(])\*([^*\s][^*\n]*?)\*(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>')
|
|
25
|
+
.replace(/(^|[\s(])_([^_\s][^_\n]*?)_(?=[\s).,!?:;]|$)/g, '$1<i>$2</i>');
|
|
26
|
+
return out.replace(/\uE000(\d+)\uE000/g, (_, i: string) => codes[Number(i)]!);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const toTelegramHtml = (markdown: string): string =>
|
|
30
|
+
markdown
|
|
31
|
+
.split(/(```[^\n]*\n[\s\S]*?```)/g)
|
|
32
|
+
.map((part) => {
|
|
33
|
+
const block = /^```([^\n]*)\n([\s\S]*?)```$/.exec(part);
|
|
34
|
+
if (block) {
|
|
35
|
+
const lang = block[1]!.trim();
|
|
36
|
+
const code = escape(block[2]!.replace(/\n$/, ''));
|
|
37
|
+
return lang
|
|
38
|
+
? `<pre><code class="language-${escape(lang)}">${code}</code></pre>`
|
|
39
|
+
: `<pre>${code}</pre>`;
|
|
40
|
+
}
|
|
41
|
+
return part
|
|
42
|
+
.split('\n')
|
|
43
|
+
.map((line) => {
|
|
44
|
+
const heading = /^#{1,6}\s+(.*)$/.exec(line);
|
|
45
|
+
if (heading) return `<b>${inline(heading[1]!)}</b>`;
|
|
46
|
+
const bullet = /^(\s*)[-*+]\s+(.*)$/.exec(line);
|
|
47
|
+
if (bullet) return `${bullet[1]}• ${inline(bullet[2]!)}`;
|
|
48
|
+
return inline(line);
|
|
49
|
+
})
|
|
50
|
+
.join('\n');
|
|
51
|
+
})
|
|
52
|
+
.join('');
|
package/src/telegram.ts
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { defineChannel, type Message, type Picked, secret } from '@sedge-hq/kit';
|
|
2
|
+
import { Effect, Option, Redacted, Schema, Stream } from 'effect';
|
|
3
|
+
import { makeBot, splitMessage, type Update } from './bot';
|
|
4
|
+
import { toTelegramHtml } from './format';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Telegram as a sedge channel: you write to your bot from anywhere, sedge answers there, and what
|
|
8
|
+
* it tells you unasked arrives in the same chat.
|
|
9
|
+
*
|
|
10
|
+
* It only talks to accounts paired through an invite link (`t.me/<bot>?start=<code>`): the code is
|
|
11
|
+
* shown only on your screen, so opening the link proves the account is yours. Everyone else gets
|
|
12
|
+
* no answer at all.
|
|
13
|
+
*/
|
|
14
|
+
export default defineChannel({
|
|
15
|
+
name: 'telegram',
|
|
16
|
+
summary: 'your Telegram: message sedge from anywhere, and it answers there',
|
|
17
|
+
settings: {
|
|
18
|
+
token: secret('The bot token. Create a bot by writing /newbot to @BotFather in Telegram.'),
|
|
19
|
+
api: Schema.optional(Schema.String).annotate({
|
|
20
|
+
description: "The address of a Bot API server of your own. Default: Telegram's.",
|
|
21
|
+
}),
|
|
22
|
+
},
|
|
23
|
+
connect: (settings, kit) =>
|
|
24
|
+
Effect.gen(function* () {
|
|
25
|
+
const bot = makeBot(Redacted.value(settings.token), settings.api);
|
|
26
|
+
const me = yield* bot.getMe();
|
|
27
|
+
const stored = Option.getOrElse(yield* kit.memo.get('paired'), () => '[]');
|
|
28
|
+
const paired = new Set<number>(JSON.parse(stored) as Array<number>);
|
|
29
|
+
// In a private chat the chat id is the user's id: the user's usual conversation.
|
|
30
|
+
let home = paired.values().next().value as number | undefined;
|
|
31
|
+
const status = kit.status(
|
|
32
|
+
paired.size > 0
|
|
33
|
+
? `@${me.username} · paired`
|
|
34
|
+
: `@${me.username} · open the invite link to pair`,
|
|
35
|
+
);
|
|
36
|
+
yield* status;
|
|
37
|
+
|
|
38
|
+
const handle = (
|
|
39
|
+
update: Update,
|
|
40
|
+
): Effect.Effect<Option.Option<Message | Picked>, unknown> =>
|
|
41
|
+
Effect.gen(function* () {
|
|
42
|
+
const message = update.message;
|
|
43
|
+
if (message) {
|
|
44
|
+
// Only private chats; a group the bot is in never reaches sedge.
|
|
45
|
+
if (message.chat.type !== 'private' || !message.from) return Option.none();
|
|
46
|
+
const start = /^\/start\s+(\S+)/.exec(message.text ?? '');
|
|
47
|
+
if (start && !paired.has(message.from.id)) {
|
|
48
|
+
if (yield* kit.claim(start[1]!, String(message.from.id))) {
|
|
49
|
+
paired.add(message.from.id);
|
|
50
|
+
home = message.chat.id;
|
|
51
|
+
yield* kit.memo.set('paired', JSON.stringify([...paired]));
|
|
52
|
+
yield* bot.sendMessage(
|
|
53
|
+
message.chat.id,
|
|
54
|
+
"Paired. I'm sedge; write to me here any time.",
|
|
55
|
+
);
|
|
56
|
+
yield* status;
|
|
57
|
+
}
|
|
58
|
+
return Option.none();
|
|
59
|
+
}
|
|
60
|
+
if (!paired.has(message.from.id)) return Option.none();
|
|
61
|
+
home = message.chat.id;
|
|
62
|
+
const text = message.text ?? message.caption;
|
|
63
|
+
if (!text) {
|
|
64
|
+
yield* bot.sendMessage(
|
|
65
|
+
message.chat.id,
|
|
66
|
+
'I can only read text for now.',
|
|
67
|
+
);
|
|
68
|
+
return Option.none();
|
|
69
|
+
}
|
|
70
|
+
return Option.some<Message | Picked>({
|
|
71
|
+
_tag: 'Message',
|
|
72
|
+
from: String(message.chat.id),
|
|
73
|
+
text,
|
|
74
|
+
key: String(update.update_id),
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const query = update.callback_query;
|
|
78
|
+
if (query && paired.has(query.from.id)) {
|
|
79
|
+
yield* bot.answerCallbackQuery(query.id);
|
|
80
|
+
if (query.message?.text) {
|
|
81
|
+
yield* Effect.ignore(
|
|
82
|
+
bot.editMessageText(
|
|
83
|
+
query.message.chat.id,
|
|
84
|
+
query.message.message_id,
|
|
85
|
+
`${query.message.text}\n\n✓`,
|
|
86
|
+
),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
return Option.some<Message | Picked>({
|
|
90
|
+
_tag: 'Picked',
|
|
91
|
+
from: String(query.message?.chat.id ?? query.from.id),
|
|
92
|
+
value: query.data ?? '',
|
|
93
|
+
key: String(update.update_id),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return Option.none();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Long polling. The offset is saved at the start of the next poll, after the previous
|
|
100
|
+
// batch went through: a crash redelivers rather than drops, and sedge drops repeats.
|
|
101
|
+
let seen: number | undefined;
|
|
102
|
+
const poll = Effect.gen(function* () {
|
|
103
|
+
if (seen !== undefined) yield* kit.memo.set('offset', String(seen));
|
|
104
|
+
const offset = Number(Option.getOrElse(yield* kit.memo.get('offset'), () => '0'));
|
|
105
|
+
const updates = yield* bot.getUpdates(offset ? offset + 1 : undefined, 50);
|
|
106
|
+
const events: Array<Message | Picked> = [];
|
|
107
|
+
for (const update of updates) {
|
|
108
|
+
const event = yield* handle(update);
|
|
109
|
+
if (Option.isSome(event)) events.push(event.value);
|
|
110
|
+
seen = update.update_id;
|
|
111
|
+
}
|
|
112
|
+
return events;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
const chatFor = (to?: string): Effect.Effect<number, Error> => {
|
|
116
|
+
const chat = to !== undefined ? Number(to) : home;
|
|
117
|
+
if (chat === undefined || !paired.has(chat)) {
|
|
118
|
+
return Effect.fail(
|
|
119
|
+
new Error('Telegram is not paired yet; open the invite link first.'),
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
return Effect.succeed(chat);
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
return {
|
|
126
|
+
incoming: Stream.fromEffectRepeat(poll).pipe(
|
|
127
|
+
Stream.flatMap((events) => Stream.fromIterable(events)),
|
|
128
|
+
),
|
|
129
|
+
invite: (code) => `https://t.me/${me.username}?start=${code}`,
|
|
130
|
+
working: (to) =>
|
|
131
|
+
chatFor(to).pipe(Effect.flatMap((chat) => bot.sendChatAction(chat, 'typing'))),
|
|
132
|
+
deliver: (reply, to) =>
|
|
133
|
+
Effect.gen(function* () {
|
|
134
|
+
const chat = yield* chatFor(to);
|
|
135
|
+
const chunks = splitMessage(reply.text, 3500);
|
|
136
|
+
for (const [i, chunk] of chunks.entries()) {
|
|
137
|
+
const buttons =
|
|
138
|
+
i === chunks.length - 1 && reply.choices?.length
|
|
139
|
+
? reply.choices.map((c) => ({
|
|
140
|
+
text: c.label,
|
|
141
|
+
callback_data: c.value.slice(0, 64),
|
|
142
|
+
}))
|
|
143
|
+
: undefined;
|
|
144
|
+
// Formatted when Telegram accepts it; plain text if it rejects the markup.
|
|
145
|
+
yield* bot
|
|
146
|
+
.sendMessage(chat, toTelegramHtml(chunk), buttons, 'HTML')
|
|
147
|
+
.pipe(
|
|
148
|
+
Effect.catchIf(
|
|
149
|
+
(error) => error.status === 400,
|
|
150
|
+
() => bot.sendMessage(chat, chunk, buttons),
|
|
151
|
+
),
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
for (const file of reply.files ?? [])
|
|
155
|
+
yield* bot.sendFile(chat, file.path, file.caption);
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
}),
|
|
159
|
+
});
|
package/README.md
DELETED