@mirid-dev/sendkit-core 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +36 -2
- package/dist/index.d.ts +45 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +73 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -4
- package/src/index.ts +2 -0
- package/src/operations.ts +65 -0
- package/src/schemas.ts +72 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ky-Ling
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mirid-dev/sendkit-core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Telegram messaging operations and [zod](https://zod.dev) schemas shared by the SendKit CLI and MCP servers.
|
|
4
|
+
|
|
5
|
+
Requires Node.js 20 or later. ESM only.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @mirid-dev/sendkit-core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { sendTelegramMessage } from '@mirid-dev/sendkit-core'
|
|
17
|
+
|
|
18
|
+
const result = await sendTelegramMessage({
|
|
19
|
+
botToken: process.env.TELEGRAM_BOT_TOKEN!,
|
|
20
|
+
chatId: '123456789',
|
|
21
|
+
message: 'Hello from SendKit',
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
console.log(result.messageId, result.chatId, result.sentAt)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`sendTelegramMessage` validates its input, calls the Telegram Bot API `sendMessage` method with a 10-second timeout, and resolves to `{ messageId, chatId, sentAt }`. `chatId` comes back numeric even when you pass an `@channelusername`. Errors never include the bot token.
|
|
28
|
+
|
|
29
|
+
## Exports
|
|
30
|
+
|
|
31
|
+
- `sendTelegramMessage(options)`
|
|
32
|
+
- Schemas: `telegramMessageInputSchema` (`chatId`, `message`), `telegramMessageOptionsSchema` (adds `botToken`), `telegramMessageOutputSchema`, `telegramSendMessageRequestSchema`, `telegramSendMessageResponseSchema`
|
|
33
|
+
- Types: `TelegramMessageInput`, `TelegramMessageOptions`, `TelegramMessageOutput`
|
|
34
|
+
|
|
35
|
+
## License
|
|
36
|
+
|
|
37
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export declare const telegramMessageInputSchema: z.ZodObject<{
|
|
3
|
+
chatId: z.ZodString;
|
|
4
|
+
message: z.ZodString;
|
|
5
|
+
}, z.core.$strip>;
|
|
6
|
+
export declare const telegramMessageOptionsSchema: z.ZodObject<{
|
|
7
|
+
chatId: z.ZodString;
|
|
8
|
+
message: z.ZodString;
|
|
9
|
+
botToken: z.ZodString;
|
|
10
|
+
}, z.core.$strip>;
|
|
11
|
+
export declare const telegramSendMessageRequestSchema: z.ZodObject<{
|
|
12
|
+
chat_id: z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>;
|
|
13
|
+
text: z.ZodString;
|
|
14
|
+
parse_mode: z.ZodOptional<z.ZodEnum<{
|
|
15
|
+
HTML: "HTML";
|
|
16
|
+
Markdown: "Markdown";
|
|
17
|
+
MarkdownV2: "MarkdownV2";
|
|
18
|
+
}>>;
|
|
19
|
+
disable_notification: z.ZodOptional<z.ZodBoolean>;
|
|
20
|
+
protect_content: z.ZodOptional<z.ZodBoolean>;
|
|
21
|
+
}, z.core.$strip>;
|
|
22
|
+
export declare const telegramSendMessageResponseSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
23
|
+
ok: z.ZodLiteral<true>;
|
|
24
|
+
result: z.ZodObject<{
|
|
25
|
+
message_id: z.ZodNumber;
|
|
26
|
+
date: z.ZodNumber;
|
|
27
|
+
chat: z.ZodObject<{
|
|
28
|
+
id: z.ZodNumber;
|
|
29
|
+
}, z.core.$strip>;
|
|
30
|
+
}, z.core.$strip>;
|
|
31
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
32
|
+
ok: z.ZodLiteral<false>;
|
|
33
|
+
error_code: z.ZodOptional<z.ZodNumber>;
|
|
34
|
+
description: z.ZodOptional<z.ZodString>;
|
|
35
|
+
}, z.core.$strip>], "ok">;
|
|
36
|
+
export declare const telegramMessageOutputSchema: z.ZodObject<{
|
|
37
|
+
messageId: z.ZodNumber;
|
|
38
|
+
chatId: z.ZodNumber;
|
|
39
|
+
sentAt: z.ZodDate;
|
|
40
|
+
}, z.core.$strip>;
|
|
41
|
+
export type TelegramMessageInput = z.infer<typeof telegramMessageInputSchema>;
|
|
42
|
+
export type TelegramMessageOptions = z.infer<typeof telegramMessageOptionsSchema>;
|
|
43
|
+
export type TelegramMessageOutput = z.infer<typeof telegramMessageOutputSchema>;
|
|
44
|
+
export declare function sendTelegramMessage(input: z.input<typeof telegramMessageOptionsSchema>): Promise<TelegramMessageOutput>;
|
|
45
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/schemas.ts","../src/operations.ts"],"mappings":";qBAca,4BAA0B,EAAA;;;GASrC,EAAA,KAAA;qBAEW,8BAA4B,EAAA;;;;GAOvC,EAAA,KAAA;qBAGW,kCAAgC,EAAA;;;;;;;;;;GAM3C,EAAA,KAAA;qBAGW,mCAAiC,EAAA,uBAAA,EAAA;;;;;;;;;;;;;GAgB5C,EAAA,KAAA;qBAEW,6BAA2B,EAAA;;;;GAKtC,EAAA,KAAA;YAEU,uBAAuB,EAAE,aAAa;YACtC,yBAAyB,EAAE,aAAa;YACxC,wBAAwB,EAAE,aAAa;wBC5D7B,oBACpB,OAAO,EAAE,aAAa,gCACrB,QAAQ"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
// src/schemas.ts
|
|
3
|
+
const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;
|
|
4
|
+
const telegramChatIdSchema = z.string().trim().refine((chatId) => /^-?\d+$/.test(chatId) || /^@\w{5,}$/.test(chatId), "Use a numeric chat ID or @channelusername");
|
|
5
|
+
const telegramMessageInputSchema = z.object({
|
|
6
|
+
chatId: telegramChatIdSchema,
|
|
7
|
+
message: z.string().refine((message) => message.trim().length > 0, "Message cannot be empty").refine((message) => message.length <= TELEGRAM_MAX_MESSAGE_LENGTH, `Telegram allows at most ${TELEGRAM_MAX_MESSAGE_LENGTH} characters`)
|
|
8
|
+
});
|
|
9
|
+
const telegramMessageOptionsSchema = telegramMessageInputSchema.extend({ botToken: z.string().trim().min(1, "Telegram bot token is required").regex(/^\d+:[\w-]+$/, "Expected a token like 123456789:ABC-DEF..., without the \"bot\" prefix") });
|
|
10
|
+
const telegramSendMessageRequestSchema = z.object({
|
|
11
|
+
chat_id: z.union([z.string(), z.number().int()]),
|
|
12
|
+
text: z.string().min(1).max(TELEGRAM_MAX_MESSAGE_LENGTH),
|
|
13
|
+
parse_mode: z.enum([
|
|
14
|
+
"MarkdownV2",
|
|
15
|
+
"HTML",
|
|
16
|
+
"Markdown"
|
|
17
|
+
]).optional(),
|
|
18
|
+
disable_notification: z.boolean().optional(),
|
|
19
|
+
protect_content: z.boolean().optional()
|
|
20
|
+
});
|
|
21
|
+
const telegramSendMessageResponseSchema = z.discriminatedUnion("ok", [z.object({
|
|
22
|
+
ok: z.literal(true),
|
|
23
|
+
result: z.object({
|
|
24
|
+
message_id: z.number().int(),
|
|
25
|
+
date: z.number().int(),
|
|
26
|
+
chat: z.object({ id: z.number().int() })
|
|
27
|
+
})
|
|
28
|
+
}), z.object({
|
|
29
|
+
ok: z.literal(false),
|
|
30
|
+
error_code: z.number().int().optional(),
|
|
31
|
+
description: z.string().optional()
|
|
32
|
+
})]);
|
|
33
|
+
const telegramMessageOutputSchema = z.object({
|
|
34
|
+
messageId: z.number().int(),
|
|
35
|
+
chatId: z.number().int(),
|
|
36
|
+
sentAt: z.date()
|
|
37
|
+
});
|
|
38
|
+
// src/operations.ts
|
|
39
|
+
const TELEGRAM_REQUEST_TIMEOUT_MS = 1e4;
|
|
40
|
+
async function sendTelegramMessage(input) {
|
|
41
|
+
const { chatId, message, botToken } = telegramMessageOptionsSchema.parse(input);
|
|
42
|
+
const requestBody = telegramSendMessageRequestSchema.parse({
|
|
43
|
+
chat_id: chatId,
|
|
44
|
+
text: message
|
|
45
|
+
});
|
|
46
|
+
let response;
|
|
47
|
+
try {
|
|
48
|
+
response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
|
|
49
|
+
method: "POST",
|
|
50
|
+
headers: { "Content-Type": "application/json" },
|
|
51
|
+
body: JSON.stringify(requestBody),
|
|
52
|
+
signal: AbortSignal.timeout(TELEGRAM_REQUEST_TIMEOUT_MS)
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
56
|
+
throw new Error(`Could not reach Telegram: ${reason.replaceAll(botToken, "<redacted>")}`, { cause: error });
|
|
57
|
+
}
|
|
58
|
+
const parsedResponse = telegramSendMessageResponseSchema.safeParse(await response.json().catch(() => null));
|
|
59
|
+
if (!parsedResponse.success) {
|
|
60
|
+
const hint = response.ok ? "; the message may still have been sent" : "";
|
|
61
|
+
throw new Error(`Unexpected response from Telegram (HTTP ${response.status})${hint}`);
|
|
62
|
+
}
|
|
63
|
+
const data = parsedResponse.data;
|
|
64
|
+
if (!data.ok) throw new Error(`Telegram API error (${response.status}): ${data.description || response.statusText || "Unknown error"}`);
|
|
65
|
+
return telegramMessageOutputSchema.parse({
|
|
66
|
+
messageId: data.result.message_id,
|
|
67
|
+
chatId: data.result.chat.id,
|
|
68
|
+
sentAt: /* @__PURE__ */ new Date(data.result.date * 1e3)
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
export { sendTelegramMessage, telegramMessageInputSchema, telegramMessageOptionsSchema, telegramMessageOutputSchema, telegramSendMessageRequestSchema, telegramSendMessageResponseSchema };
|
|
72
|
+
|
|
73
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/schemas.ts","../src/operations.ts"],"sourcesContent":["import { z } from 'zod'\n\n// Telegram rejects message text longer than this\nconst TELEGRAM_MAX_MESSAGE_LENGTH = 4096\n\n// Numeric ID (negative for groups) or a public @channelusername\nconst telegramChatIdSchema = z\n .string()\n .trim()\n .refine(\n (chatId) => /^-?\\d+$/.test(chatId) || /^@\\w{5,}$/.test(chatId),\n 'Use a numeric chat ID or @channelusername',\n )\n\nexport const telegramMessageInputSchema = z.object({\n chatId: telegramChatIdSchema,\n message: z\n .string()\n .refine((message) => message.trim().length > 0, 'Message cannot be empty')\n .refine(\n (message) => message.length <= TELEGRAM_MAX_MESSAGE_LENGTH,\n `Telegram allows at most ${TELEGRAM_MAX_MESSAGE_LENGTH} characters`,\n ),\n})\n\nexport const telegramMessageOptionsSchema = telegramMessageInputSchema.extend({\n botToken: z\n .string()\n .trim()\n .min(1, 'Telegram bot token is required')\n // Tokens look like 123456789:AAH...; a copied \"bot\" prefix would otherwise surface as a 404\n .regex(/^\\d+:[\\w-]+$/, 'Expected a token like 123456789:ABC-DEF..., without the \"bot\" prefix'),\n})\n\n// Body of POST /bot<token>/sendMessage, in Telegram's snake_case\nexport const telegramSendMessageRequestSchema = z.object({\n chat_id: z.union([z.string(), z.number().int()]),\n text: z.string().min(1).max(TELEGRAM_MAX_MESSAGE_LENGTH),\n parse_mode: z.enum(['MarkdownV2', 'HTML', 'Markdown']).optional(),\n disable_notification: z.boolean().optional(),\n protect_content: z.boolean().optional(),\n})\n\n// Telegram returns a JSON body with `ok` and `description` even on 4xx errors\nexport const telegramSendMessageResponseSchema = z.discriminatedUnion('ok', [\n z.object({\n ok: z.literal(true),\n result: z.object({\n message_id: z.number().int(),\n date: z.number().int(),\n chat: z.object({\n id: z.number().int(),\n }),\n }),\n }),\n z.object({\n ok: z.literal(false),\n error_code: z.number().int().optional(),\n description: z.string().optional(),\n }),\n])\n\nexport const telegramMessageOutputSchema = z.object({\n messageId: z.number().int(),\n // Always numeric: Telegram resolves @channelusername to the chat's ID\n chatId: z.number().int(),\n sentAt: z.date(),\n})\n\nexport type TelegramMessageInput = z.infer<typeof telegramMessageInputSchema>\nexport type TelegramMessageOptions = z.infer<typeof telegramMessageOptionsSchema>\nexport type TelegramMessageOutput = z.infer<typeof telegramMessageOutputSchema>\n","import { z } from 'zod'\nimport {\n telegramMessageOutputSchema,\n telegramMessageOptionsSchema,\n telegramSendMessageRequestSchema,\n telegramSendMessageResponseSchema,\n type TelegramMessageOutput,\n} from './schemas'\n\nconst TELEGRAM_REQUEST_TIMEOUT_MS = 10_000\n\nexport async function sendTelegramMessage(\n input: z.input<typeof telegramMessageOptionsSchema>,\n): Promise<TelegramMessageOutput> {\n const { chatId, message, botToken } = telegramMessageOptionsSchema.parse(input)\n\n const requestBody = telegramSendMessageRequestSchema.parse({\n chat_id: chatId,\n text: message,\n })\n\n let response: Response\n\n try {\n response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(requestBody),\n signal: AbortSignal.timeout(TELEGRAM_REQUEST_TIMEOUT_MS),\n })\n } catch (error) {\n // Don't rethrow the original error: the request URL contains the bot token\n const reason = error instanceof Error ? error.message : String(error)\n throw new Error(`Could not reach Telegram: ${reason.replaceAll(botToken, '<redacted>')}`, {\n cause: error,\n })\n }\n\n // Telegram returns a JSON body even on 4xx errors, but a proxy or outage page may not\n const parsedResponse = telegramSendMessageResponseSchema.safeParse(\n await response.json().catch(() => null),\n )\n\n if (!parsedResponse.success) {\n // A 2xx we can't read may still mean the message went out, so warn before the caller resends\n const hint = response.ok ? '; the message may still have been sent' : ''\n throw new Error(`Unexpected response from Telegram (HTTP ${response.status})${hint}`)\n }\n\n const data = parsedResponse.data\n\n if (!data.ok) {\n throw new Error(\n `Telegram API error (${response.status}): ${data.description || response.statusText || 'Unknown error'}`,\n )\n }\n\n return telegramMessageOutputSchema.parse({\n messageId: data.result.message_id,\n chatId: data.result.chat.id,\n sentAt: new Date(data.result.date * 1000),\n })\n}\n"],"mappings":";;AAGA,MAAM,8BAA8B;AAGpC,MAAM,uBAAuB,EAC1B,OAAO,CAAC,CACR,KAAK,CAAC,CACN,QACE,WAAW,UAAU,KAAK,MAAM,KAAK,YAAY,KAAK,MAAM,GAC7D,2CACF;AAEF,MAAa,6BAA6B,E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core",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Core Telegram messaging operations and zod schemas for SendKit",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Ky-Ling/sendkit.git",
|
|
9
|
+
"directory": "packages/core"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"dist",
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"source": "./src/index.ts",
|
|
22
|
+
"types": "./dist/index.d.ts",
|
|
23
|
+
"import": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsdown",
|
|
31
|
+
"pack:dry": "bun run build && bun pm pack --dry-run",
|
|
32
|
+
"prepublishOnly": "bun run build"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"zod": "^4.6.7"
|
|
36
|
+
},
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=20"
|
|
39
|
+
}
|
|
40
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import {
|
|
3
|
+
telegramMessageOutputSchema,
|
|
4
|
+
telegramMessageOptionsSchema,
|
|
5
|
+
telegramSendMessageRequestSchema,
|
|
6
|
+
telegramSendMessageResponseSchema,
|
|
7
|
+
type TelegramMessageOutput,
|
|
8
|
+
} from './schemas'
|
|
9
|
+
|
|
10
|
+
const TELEGRAM_REQUEST_TIMEOUT_MS = 10_000
|
|
11
|
+
|
|
12
|
+
export async function sendTelegramMessage(
|
|
13
|
+
input: z.input<typeof telegramMessageOptionsSchema>,
|
|
14
|
+
): Promise<TelegramMessageOutput> {
|
|
15
|
+
const { chatId, message, botToken } = telegramMessageOptionsSchema.parse(input)
|
|
16
|
+
|
|
17
|
+
const requestBody = telegramSendMessageRequestSchema.parse({
|
|
18
|
+
chat_id: chatId,
|
|
19
|
+
text: message,
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
let response: Response
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: {
|
|
28
|
+
'Content-Type': 'application/json',
|
|
29
|
+
},
|
|
30
|
+
body: JSON.stringify(requestBody),
|
|
31
|
+
signal: AbortSignal.timeout(TELEGRAM_REQUEST_TIMEOUT_MS),
|
|
32
|
+
})
|
|
33
|
+
} catch (error) {
|
|
34
|
+
// Don't rethrow the original error: the request URL contains the bot token
|
|
35
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
36
|
+
throw new Error(`Could not reach Telegram: ${reason.replaceAll(botToken, '<redacted>')}`, {
|
|
37
|
+
cause: error,
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Telegram returns a JSON body even on 4xx errors, but a proxy or outage page may not
|
|
42
|
+
const parsedResponse = telegramSendMessageResponseSchema.safeParse(
|
|
43
|
+
await response.json().catch(() => null),
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
if (!parsedResponse.success) {
|
|
47
|
+
// A 2xx we can't read may still mean the message went out, so warn before the caller resends
|
|
48
|
+
const hint = response.ok ? '; the message may still have been sent' : ''
|
|
49
|
+
throw new Error(`Unexpected response from Telegram (HTTP ${response.status})${hint}`)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const data = parsedResponse.data
|
|
53
|
+
|
|
54
|
+
if (!data.ok) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Telegram API error (${response.status}): ${data.description || response.statusText || 'Unknown error'}`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return telegramMessageOutputSchema.parse({
|
|
61
|
+
messageId: data.result.message_id,
|
|
62
|
+
chatId: data.result.chat.id,
|
|
63
|
+
sentAt: new Date(data.result.date * 1000),
|
|
64
|
+
})
|
|
65
|
+
}
|
package/src/schemas.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
// Telegram rejects message text longer than this
|
|
4
|
+
const TELEGRAM_MAX_MESSAGE_LENGTH = 4096
|
|
5
|
+
|
|
6
|
+
// Numeric ID (negative for groups) or a public @channelusername
|
|
7
|
+
const telegramChatIdSchema = z
|
|
8
|
+
.string()
|
|
9
|
+
.trim()
|
|
10
|
+
.refine(
|
|
11
|
+
(chatId) => /^-?\d+$/.test(chatId) || /^@\w{5,}$/.test(chatId),
|
|
12
|
+
'Use a numeric chat ID or @channelusername',
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
export const telegramMessageInputSchema = z.object({
|
|
16
|
+
chatId: telegramChatIdSchema,
|
|
17
|
+
message: z
|
|
18
|
+
.string()
|
|
19
|
+
.refine((message) => message.trim().length > 0, 'Message cannot be empty')
|
|
20
|
+
.refine(
|
|
21
|
+
(message) => message.length <= TELEGRAM_MAX_MESSAGE_LENGTH,
|
|
22
|
+
`Telegram allows at most ${TELEGRAM_MAX_MESSAGE_LENGTH} characters`,
|
|
23
|
+
),
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
export const telegramMessageOptionsSchema = telegramMessageInputSchema.extend({
|
|
27
|
+
botToken: z
|
|
28
|
+
.string()
|
|
29
|
+
.trim()
|
|
30
|
+
.min(1, 'Telegram bot token is required')
|
|
31
|
+
// Tokens look like 123456789:AAH...; a copied "bot" prefix would otherwise surface as a 404
|
|
32
|
+
.regex(/^\d+:[\w-]+$/, 'Expected a token like 123456789:ABC-DEF..., without the "bot" prefix'),
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
// Body of POST /bot<token>/sendMessage, in Telegram's snake_case
|
|
36
|
+
export const telegramSendMessageRequestSchema = z.object({
|
|
37
|
+
chat_id: z.union([z.string(), z.number().int()]),
|
|
38
|
+
text: z.string().min(1).max(TELEGRAM_MAX_MESSAGE_LENGTH),
|
|
39
|
+
parse_mode: z.enum(['MarkdownV2', 'HTML', 'Markdown']).optional(),
|
|
40
|
+
disable_notification: z.boolean().optional(),
|
|
41
|
+
protect_content: z.boolean().optional(),
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
// Telegram returns a JSON body with `ok` and `description` even on 4xx errors
|
|
45
|
+
export const telegramSendMessageResponseSchema = z.discriminatedUnion('ok', [
|
|
46
|
+
z.object({
|
|
47
|
+
ok: z.literal(true),
|
|
48
|
+
result: z.object({
|
|
49
|
+
message_id: z.number().int(),
|
|
50
|
+
date: z.number().int(),
|
|
51
|
+
chat: z.object({
|
|
52
|
+
id: z.number().int(),
|
|
53
|
+
}),
|
|
54
|
+
}),
|
|
55
|
+
}),
|
|
56
|
+
z.object({
|
|
57
|
+
ok: z.literal(false),
|
|
58
|
+
error_code: z.number().int().optional(),
|
|
59
|
+
description: z.string().optional(),
|
|
60
|
+
}),
|
|
61
|
+
])
|
|
62
|
+
|
|
63
|
+
export const telegramMessageOutputSchema = z.object({
|
|
64
|
+
messageId: z.number().int(),
|
|
65
|
+
// Always numeric: Telegram resolves @channelusername to the chat's ID
|
|
66
|
+
chatId: z.number().int(),
|
|
67
|
+
sentAt: z.date(),
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
export type TelegramMessageInput = z.infer<typeof telegramMessageInputSchema>
|
|
71
|
+
export type TelegramMessageOptions = z.infer<typeof telegramMessageOptionsSchema>
|
|
72
|
+
export type TelegramMessageOutput = z.infer<typeof telegramMessageOutputSchema>
|