@mastra/telegram 0.1.0 → 0.1.1-alpha.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.md CHANGED
@@ -1,10 +1,12 @@
1
1
  Portions of this software are licensed as follows:
2
2
 
3
- - All content that resides under any directory named "ee/" within this
3
+ - All content that resides under any directory named `ee/` within this
4
4
  repository, including but not limited to:
5
- - `packages/core/src/auth/ee/`
6
- - `packages/server/src/server/auth/ee/`
7
- is licensed under the license defined in `ee/LICENSE`.
5
+ - `@mastra/core/auth/ee`
6
+ - `@mastra/core/agent-builder/ee`
7
+ - `@mastra/editor/ee`
8
+
9
+ is licensed under the license defined in [`ee/LICENSE`](https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE).
8
10
 
9
11
  - All third-party components incorporated into the Mastra Software are
10
12
  licensed under the original license provided by the owner of the
package/README.md CHANGED
@@ -1,137 +1,49 @@
1
1
  # @mastra/telegram
2
2
 
3
- Telegram channel wrapper for Mastra a `ChannelProvider` (`@mastra/core/channels`) over **[`@chat-adapter/telegram`](https://www.npmjs.com/package/@chat-adapter/telegram)** (`^4.34.0`, aligned with the `@chat-adapter/*` version the monorepo builds against), to parity with `@mastra/slack`.
3
+ `@mastra/telegram` connects Mastra agents to Telegram through the Bot API. It handles bot installations, polling or webhook delivery, secret-token verification, commands, rich messages, and Mastra's channel lifecycle.
4
4
 
5
- The adapter already handles the Bot API transport (webhook parse, send/edit, typing, rich messages, inline keyboards). This package adds the install/lifecycle layer: a multi-bot token store, `setWebhook` + secret-token verification, `setMyCommands`, and Mastra route/stream wiring.
6
-
7
- **Shape (how Telegram differs from Slack):** no OAuth, no Ed25519, no app-factory. The BotFather token _is_ the credential — one token per bot, one bot per agent.
8
-
9
- ## Install
5
+ ## Installation
10
6
 
11
7
  ```bash
12
8
  npm install @mastra/telegram
13
- # peer: @mastra/core — channels require >= 1.22.0
14
9
  ```
15
10
 
16
11
  ## Usage
17
12
 
18
- ```ts
19
- import { Mastra } from '@mastra/core';
13
+ ```typescript
14
+ import { Agent } from '@mastra/core/agent';
15
+ import { Mastra } from '@mastra/core/mastra';
20
16
  import { TelegramProvider } from '@mastra/telegram';
21
17
 
18
+ const supportAgent = new Agent({
19
+ id: 'support',
20
+ name: 'Support agent',
21
+ instructions: 'Help users with product questions.',
22
+ model: 'openai/gpt-5-mini',
23
+ });
24
+
22
25
  const telegram = new TelegramProvider({
23
- baseUrl: 'https://your-app.example.com', // for setWebhook; auto-detected from the Mastra server if omitted
26
+ baseUrl: 'https://your-app.example.com',
24
27
  });
25
28
 
26
29
  export const mastra = new Mastra({
27
- agents: { support },
30
+ agents: { supportAgent },
28
31
  channels: { telegram },
29
32
  });
30
33
 
31
- // Paste a BotFather token to connect an agent instantly:
32
- const result = await telegram.connect('support', { botToken: process.env.TELEGRAM_BOT_TOKEN });
33
- // → { type: 'immediate', installationId: '...' }
34
- ```
35
-
36
- ## The connect flow
37
-
38
- `connect(agentId, options?)` returns a discriminated `ChannelConnectResult` — Telegram never uses OAuth:
39
-
40
- | Call | Result | Meaning |
41
- | --------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------- |
42
- | `connect(id, { botToken })` | `{ type: 'immediate' }` | Token validated via `getMe`; the bot is live. |
43
- | `connect(id)` | `{ type: 'deep_link', url: 'https://t.me/botfather' }` | No token yet — open BotFather, run `/newbot`, then call `connect` again with the token. |
44
-
45
- `connect` is idempotent per agent: a pending install upgrades to active (same id/webhook) when the token arrives, and re-connecting an already-active agent throws (disconnect first). **One bot = one agent.**
46
-
47
- ## Webhook vs polling
48
-
49
- Setting a webhook and long-polling `getUpdates` are mutually exclusive; the provider manages the switch per bot via the `mode` option:
50
-
51
- - `auto` (default) — webhook when a `baseUrl` is available, otherwise polling.
52
- - `webhook` — register `setWebhook` (requires a `baseUrl`).
53
- - `polling` — clear any webhook first, then long-poll.
54
-
55
- In polling mode the adapter's `getUpdates` loop starts automatically once the agent is wired (tune it with `longPolling`); `disconnect()` stops it.
56
-
57
- In webhook mode the provider mounts one route, `POST /telegram/events/:webhookId`, and verifies the `X-Telegram-Bot-Api-Secret-Token` header (constant-time) on **every** request before delegating to the agent. The per-bot secret is generated automatically and never travels in the URL.
58
-
59
- ## Commands
60
-
61
- Commands are published via `setMyCommands` and default to the conventional `/start` `/help` `/settings` seed. Override per agent or provider-wide:
62
-
63
- ```ts
64
34
  await telegram.connect('support', {
65
- botToken,
66
- commands: ['/ask', { command: 'summarize', description: 'Summarize a link' }],
35
+ botToken: process.env.TELEGRAM_BOT_TOKEN!,
67
36
  });
68
37
  ```
69
38
 
70
- Names are normalized to the Bot API constraints (lowercase `[a-z0-9_]`, 1-32 chars; description 1-256).
71
-
72
- ## Streaming
73
-
74
- Telegram has no native token streaming. With `streaming: true` (default) the reply is chunk-edited via `editMessageText` (4096-char cap handled by the adapter), and `typingStatus: true` (default) keeps a `sendChatAction` indicator alive. Set either to `false` to disable.
75
-
76
- ## Configuration
77
-
78
- `new TelegramProvider(config)`:
79
-
80
- | Option | Default | Notes |
81
- | ---------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
82
- | `baseUrl` | Mastra server config | Public HTTPS base for `setWebhook`. |
83
- | `storage` | Mastra channels storage, else in-memory | Installation persistence (`ChannelsStorage`). |
84
- | `encryptionKey` | `MASTRA_ENCRYPTION_KEY` env | Encrypts `botToken`/`secretToken` at rest with AES-256-GCM when set; otherwise they are stored in plaintext. |
85
- | `apiBaseUrl` | `https://api.telegram.org` | Override for a self-hosted Bot API server. |
86
- | `mode` | `auto` | `auto` \| `webhook` \| `polling`. |
87
- | `allowedUpdates` | message, edited_message, channel_post, callback_query, message_reaction | Passed to `setWebhook`. |
88
- | `longPolling` | adapter defaults | Poll-loop tuning (`timeout`, `limit`, `retryDelayMs`…) for polling mode. |
89
- | `commands` | `/start /help /settings` | Default command seed. |
90
- | `commandScope` | Telegram default | `BotCommandScope` for `setMyCommands`. |
91
- | `streaming` | `true` | Post-and-edit reply streaming. |
92
- | `typingStatus` | `true` | Typing keepalive. |
93
- | `toolDisplay` | `'text'` | How tool calls render. Telegram has no Block Kit, so `'cards'`/`'grouped'`/`'timeline'` degrade to text. |
94
- | `waitUntil` | — | Keep serverless invocations alive (Vercel/Lambda). |
95
-
96
- ### AgentChannels passthrough
97
-
98
- These forward to the agent's `AgentChannels` (the same curated subset `@mastra/slack` exposes); each falls back to anything the agent author already configured:
39
+ ## Documentation
99
40
 
100
- | Option | Notes |
101
- | --------------------------------- | ------------------------------------------------------------------------ |
102
- | `handlers` | Override `onDirectMessage` / `onMention` / `onSubscribedMessage`. |
103
- | `inlineMedia` | Which media types are sent inline to the model (Telegram photos, PDFs…). |
104
- | `inlineLinks` | Promote URLs in messages to file parts. |
105
- | `tools` | Expose reaction tools (`add_reaction`/`remove_reaction`). Default on. |
106
- | `state` | State adapter for dedup, locking, subscriptions. |
107
- | `threadContext` | Fetch recent messages when joining a thread mid-conversation. |
108
- | `chatOptions` | Passthrough to the underlying Chat SDK. |
109
- | `resolveResourceId` | Choose memory ownership for a thread. |
110
- | `cors` / `formatError` / `logger` | Webhook-route CORS, error rendering, adapter logger. |
111
- | `resolveWaitUntil` | Resolve `waitUntil` from the request context. |
112
- | `onInstall` | Called after an agent connects and the install is persisted. |
41
+ - [`TelegramProvider` reference](https://mastra.ai/reference/channels/telegram-provider)
113
42
 
114
- ## Formatting & interactivity
43
+ ## Changelog
115
44
 
116
- Message rendering is owned by the adapter, not this provider so there is no double-escaping to worry about:
117
-
118
- - **MarkdownV2** — the adapter emits `parse_mode: MarkdownV2` with context-aware escaping. Return `{ raw: '…' }` from a card to ship a pre-escaped string yourself.
119
- - **Inline keyboards** — supported via the adapter's card buttons. Telegram caps `callback_data` at **64 bytes**, so keep button ids/values short; rich elements beyond buttons render as fallback text.
120
- - **Reactions** — enabled through `tools` (`add_reaction`/`remove_reaction`); `message_reaction` updates are requested by default.
121
-
122
- ## Module format
123
-
124
- Dual **ESM + CJS**. `@chat-adapter/telegram` is ESM-only (its `exports` declares only an `import` condition), and tsup externalises `dependencies` by default — so the adapter is kept external in the ESM build (lean, deduped) but bundled into the CJS output via `noExternal`. Both `import` and `require('@mastra/telegram')` therefore work. See `tsup.config.ts` for why this intentionally differs from `channels/slack`.
125
-
126
- ## Development
127
-
128
- ```bash
129
- pnpm install
130
- pnpm --filter @mastra/telegram typecheck
131
- pnpm --filter @mastra/telegram test # vitest, undici-mocked Bot API
132
- pnpm --filter @mastra/telegram build # tsup → dist
133
- ```
45
+ See the [package changelog](https://github.com/mastra-ai/mastra/blob/main/channels/telegram/CHANGELOG.md) for version history and release notes.
134
46
 
135
- ## License
47
+ ## Support
136
48
 
137
- Apache-2.0
49
+ We have an [open community Discord](https://discord.gg/mastra-ai). Come and say hello and let us know if you have any questions or need any help getting things running.