@elizaos/plugin-telegram 1.0.0-beta.8 → 1.0.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/README.md CHANGED
@@ -22,6 +22,25 @@ Here are the available configuration options for the `character.json` file:
22
22
  | `messageTrackingLimit` | Integer | `100` | Sets the maximum number of messages to track in memory for each chat. |
23
23
  | `templates` | Object | `{}` | Allows customization of response templates for different message scenarios. |
24
24
 
25
+ ## Error 409: Conflict in Multiple Agents Environment
26
+
27
+ When you encounter this error in your logs:
28
+
29
+ ```
30
+ error: 409: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
31
+ ```
32
+
33
+ This indicates a fundamental architectural limitation with the Telegram Bot API. The Telegram API strictly enforces that only one active connection can exist per bot token at any given time. This is by design to ensure reliable message delivery and prevent message duplication or loss.
34
+
35
+ In ElizaOS multi-agent environments, this error commonly occurs when:
36
+
37
+ 1. **Multiple Agents Using Same Token**: Two or more agents (such as "Eliza" and another character) each have the `@elizaos/plugin-telegram` plugin enabled in their configuration
38
+ 2. **Simultaneous Initialization**: Each agent independently attempts to initialize its own Telegram service during startup
39
+ 3. **Token Collision**: All agents use the same `TELEGRAM_BOT_TOKEN` from your environment configuration
40
+ 4. **Connection Rejection**: When a second agent tries to establish a connection while another is already active, Telegram rejects it with a 409 error
41
+
42
+ This is not a bug in ElizaOS or the Telegram plugin, but rather a result of using a shared resource (the bot token) that can only accept one connection at a time.
43
+
25
44
  ## Example `<charactername>.character.json`
26
45
 
27
46
  Below is an example configuration file with all options:
@@ -85,3 +104,40 @@ npm run dev
85
104
  ```bash
86
105
  bun start --character="characters/your-character.json"
87
106
  ```
107
+
108
+ ## Utilizing Telegram Buttons
109
+
110
+ To send a message with native Telegram buttons, include an array of buttons in the message content. The following action demonstrates how to initiate a login flow using a Telegram button.
111
+
112
+ ```typescript
113
+ export const initAuthHandshakeAction: Action = {
114
+ name: 'INIT_AUTH_HANDSHAKE',
115
+ description: 'Initiates the identity linking and authentication flow for new users.',
116
+ validate: async (_runtime, _message, _state) => {
117
+ return _message.content.source === 'telegram';
118
+ },
119
+ handler: async (runtime, message, _state, _options, callback): Promise<boolean> => {
120
+ try {
121
+ const user = await getUser(message.userId);
122
+ if (user) return false;
123
+
124
+ callback({
125
+ text: "Let's get you set up with a new account",
126
+ buttons: [
127
+ {
128
+ text: '🔑 Authenticate with Telegram',
129
+ url: `${FRONTEND_URL}/integrations/telegram`,
130
+ kind: 'login',
131
+ },
132
+ ],
133
+ }).catch((error) => {
134
+ console.error('Error sending callback:', error);
135
+ });
136
+
137
+ return true;
138
+ } catch (error) {
139
+ ...
140
+ }
141
+ },
142
+ };
143
+ ```
@@ -0,0 +1,328 @@
1
+ import { Content, IAgentRuntime, Service, TargetInfo, Plugin } from '@elizaos/core';
2
+ import { Message, Update } from '@telegraf/types';
3
+ import { Telegraf, Context, NarrowedContext } from 'telegraf';
4
+
5
+ /**
6
+ * Extention of the core Content type just for Telegram
7
+ */
8
+ interface TelegramContent extends Content {
9
+ /** Array of buttons */
10
+ buttons?: Button[];
11
+ }
12
+ /**
13
+ * Represents a flexible button configuration
14
+ */
15
+ type Button = {
16
+ /** The type of button */
17
+ kind: 'login' | 'url';
18
+ /** The text to display on the button */
19
+ text: string;
20
+ /** The URL or endpoint the button should link to */
21
+ url: string;
22
+ };
23
+
24
+ /**
25
+ * Enum representing different types of media.
26
+ * @enum { string }
27
+ * @readonly
28
+ */
29
+ declare enum MediaType {
30
+ PHOTO = "photo",
31
+ VIDEO = "video",
32
+ DOCUMENT = "document",
33
+ AUDIO = "audio",
34
+ ANIMATION = "animation"
35
+ }
36
+ /**
37
+ * Class representing a message manager.
38
+ * @class
39
+ */
40
+ declare class MessageManager {
41
+ bot: Telegraf<Context>;
42
+ protected runtime: IAgentRuntime;
43
+ /**
44
+ * Constructor for creating a new instance of a BotAgent.
45
+ *
46
+ * @param {Telegraf<Context>} bot - The Telegraf instance used for interacting with the bot platform.
47
+ * @param {IAgentRuntime} runtime - The runtime environment for the agent.
48
+ */
49
+ constructor(bot: Telegraf<Context>, runtime: IAgentRuntime);
50
+ /**
51
+ * Process an image from a Telegram message to extract the image URL and description.
52
+ *
53
+ * @param {Message} message - The Telegram message object containing the image.
54
+ * @returns {Promise<{ description: string } | null>} The description of the processed image or null if no image found.
55
+ */
56
+ processImage(message: Message): Promise<{
57
+ description: string;
58
+ } | null>;
59
+ /**
60
+ * Sends a message in chunks, handling attachments and splitting the message if necessary
61
+ *
62
+ * @param {Context} ctx - The context object representing the current state of the bot
63
+ * @param {TelegramContent} content - The content of the message to be sent
64
+ * @param {number} [replyToMessageId] - The ID of the message to reply to, if any
65
+ * @returns {Promise<Message.TextMessage[]>} - An array of TextMessage objects representing the messages sent
66
+ */
67
+ sendMessageInChunks(ctx: Context, content: TelegramContent, replyToMessageId?: number): Promise<Message.TextMessage[]>;
68
+ /**
69
+ * Sends media to a chat using the Telegram API.
70
+ *
71
+ * @param {Context} ctx - The context object containing information about the current chat.
72
+ * @param {string} mediaPath - The path to the media to be sent, either a URL or a local file path.
73
+ * @param {MediaType} type - The type of media being sent (PHOTO, VIDEO, DOCUMENT, AUDIO, or ANIMATION).
74
+ * @param {string} [caption] - Optional caption for the media being sent.
75
+ *
76
+ * @returns {Promise<void>} A Promise that resolves when the media is successfully sent.
77
+ */
78
+ sendMedia(ctx: Context, mediaPath: string, type: MediaType, caption?: string): Promise<void>;
79
+ /**
80
+ * Splits a given text into an array of strings based on the maximum message length.
81
+ *
82
+ * @param {string} text - The text to split into chunks.
83
+ * @returns {string[]} An array of strings with each element representing a chunk of the original text.
84
+ */
85
+ private splitMessage;
86
+ /**
87
+ * Handle incoming messages from Telegram and process them accordingly.
88
+ * @param {Context} ctx - The context object containing information about the message.
89
+ * @returns {Promise<void>}
90
+ */
91
+ handleMessage(ctx: Context): Promise<void>;
92
+ /**
93
+ * Handles the reaction event triggered by a user reacting to a message.
94
+ * @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update
95
+ * @returns {Promise<void>} A Promise that resolves when the reaction handling is complete
96
+ */
97
+ handleReaction(ctx: NarrowedContext<Context<Update>, Update.MessageReactionUpdate>): Promise<void>;
98
+ /**
99
+ * Sends a message to a Telegram chat and emits appropriate events
100
+ * @param {number | string} chatId - The Telegram chat ID to send the message to
101
+ * @param {Content} content - The content to send
102
+ * @param {number} [replyToMessageId] - Optional message ID to reply to
103
+ * @returns {Promise<Message.TextMessage[]>} The sent messages
104
+ */
105
+ sendMessage(chatId: number | string, content: Content, replyToMessageId?: number): Promise<Message.TextMessage[]>;
106
+ }
107
+
108
+ /**
109
+ * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.
110
+ * This service handles all Telegram-specific functionality including:
111
+ * - Initializing and managing the Telegram bot
112
+ * - Setting up middleware for preprocessing messages
113
+ * - Handling message and reaction events
114
+ * - Synchronizing Telegram chats, users, and entities with the agent runtime
115
+ * - Managing forum topics as separate rooms
116
+ *
117
+ * @extends Service
118
+ */
119
+ declare class TelegramService extends Service {
120
+ static serviceType: string;
121
+ capabilityDescription: string;
122
+ private bot;
123
+ messageManager: MessageManager;
124
+ private options;
125
+ private knownChats;
126
+ private syncedEntityIds;
127
+ /**
128
+ * Constructor for TelegramService class.
129
+ * @param {IAgentRuntime} runtime - The runtime object for the agent.
130
+ */
131
+ constructor(runtime: IAgentRuntime);
132
+ /**
133
+ * Starts the Telegram service for the given runtime.
134
+ *
135
+ * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.
136
+ * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.
137
+ */
138
+ static start(runtime: IAgentRuntime): Promise<TelegramService>;
139
+ /**
140
+ * Stops the agent runtime.
141
+ * @param {IAgentRuntime} runtime - The agent runtime to stop
142
+ */
143
+ static stop(runtime: IAgentRuntime): Promise<void>;
144
+ /**
145
+ * Asynchronously stops the bot.
146
+ *
147
+ * @returns A Promise that resolves once the bot has stopped.
148
+ */
149
+ stop(): Promise<void>;
150
+ /**
151
+ * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.
152
+ * @returns {Promise<void>} A Promise that resolves when the initialization is complete.
153
+ */
154
+ private initializeBot;
155
+ /**
156
+ * Sets up the middleware chain for preprocessing messages before they reach handlers.
157
+ * This critical method establishes a sequential processing pipeline that:
158
+ *
159
+ * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings
160
+ * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed
161
+ * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management
162
+ * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities
163
+ *
164
+ * The middleware chain runs in sequence for each message, with each step potentially
165
+ * enriching the context or stopping processing if conditions aren't met.
166
+ * This preprocessing is essential for maintaining consistent state before message handlers execute.
167
+ *
168
+ * @private
169
+ */
170
+ private setupMiddlewares;
171
+ /**
172
+ * Authorization middleware - checks if chat is allowed to interact with the bot
173
+ * based on the TELEGRAM_ALLOWED_CHATS configuration.
174
+ *
175
+ * @param {Context} ctx - The context of the incoming update
176
+ * @param {Function} next - The function to call to proceed to the next middleware
177
+ * @returns {Promise<void>}
178
+ * @private
179
+ */
180
+ private authorizationMiddleware;
181
+ /**
182
+ * Chat and entity management middleware - handles new chats, forum topics, and entity synchronization.
183
+ * This middleware implements decision logic to determine which operations are needed based on
184
+ * the chat type and whether we've seen this chat before.
185
+ *
186
+ * @param {Context} ctx - The context of the incoming update
187
+ * @param {Function} next - The function to call to proceed to the next middleware
188
+ * @returns {Promise<void>}
189
+ * @private
190
+ */
191
+ private chatAndEntityMiddleware;
192
+ /**
193
+ * Process an existing chat based on chat type and message properties.
194
+ * Different chat types require different processing steps.
195
+ *
196
+ * @param {Context} ctx - The context of the incoming update
197
+ * @returns {Promise<void>}
198
+ * @private
199
+ */
200
+ private processExistingChat;
201
+ /**
202
+ * Sets up message and reaction handlers for the bot.
203
+ * Configures event handlers to process incoming messages and reactions.
204
+ *
205
+ * @private
206
+ */
207
+ private setupMessageHandlers;
208
+ /**
209
+ * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.
210
+ * @param {Context} ctx - The context of the incoming update.
211
+ * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.
212
+ */
213
+ private isGroupAuthorized;
214
+ /**
215
+ * Synchronizes an entity from a message context with the runtime system.
216
+ * This method handles three cases:
217
+ * 1. Message sender - most common case
218
+ * 2. New chat member - when a user joins the chat
219
+ * 3. Left chat member - when a user leaves the chat
220
+ *
221
+ * @param {Context} ctx - The context of the incoming update
222
+ * @returns {Promise<void>}
223
+ * @private
224
+ */
225
+ private syncEntity;
226
+ /**
227
+ * Synchronizes the message sender entity with the runtime system.
228
+ * This is the most common entity sync case.
229
+ *
230
+ * @param {Context} ctx - The context of the incoming update
231
+ * @param {UUID} worldId - The ID of the world
232
+ * @param {UUID} roomId - The ID of the room
233
+ * @param {string} chatId - The ID of the chat
234
+ * @returns {Promise<void>}
235
+ * @private
236
+ */
237
+ private syncMessageSender;
238
+ /**
239
+ * Synchronizes a new chat member entity with the runtime system.
240
+ * Triggered when a user joins the chat.
241
+ *
242
+ * @param {Context} ctx - The context of the incoming update
243
+ * @param {UUID} worldId - The ID of the world
244
+ * @param {UUID} roomId - The ID of the room
245
+ * @param {string} chatId - The ID of the chat
246
+ * @returns {Promise<void>}
247
+ * @private
248
+ */
249
+ private syncNewChatMember;
250
+ /**
251
+ * Updates entity status when a user leaves the chat.
252
+ *
253
+ * @param {Context} ctx - The context of the incoming update
254
+ * @returns {Promise<void>}
255
+ * @private
256
+ */
257
+ private syncLeftChatMember;
258
+ /**
259
+ * Handles forum topics by creating appropriate rooms in the runtime system.
260
+ * This enables proper conversation management for Telegram's forum feature.
261
+ *
262
+ * @param {Context} ctx - The context of the incoming update
263
+ * @returns {Promise<void>}
264
+ * @private
265
+ */
266
+ private handleForumTopic;
267
+ /**
268
+ * Builds entity for message sender
269
+ */
270
+ private buildMsgSenderEntity;
271
+ /**
272
+ * Handles new chat discovery and emits WORLD_JOINED event.
273
+ * This is a critical function that ensures new chats are properly
274
+ * registered in the runtime system and appropriate events are emitted.
275
+ *
276
+ * @param {Context} ctx - The context of the incoming update
277
+ * @returns {Promise<void>}
278
+ * @private
279
+ */
280
+ private handleNewChat;
281
+ /**
282
+ * Processes entities in batches to prevent overwhelming the system.
283
+ *
284
+ * @param {Entity[]} entities - The entities to process
285
+ * @param {UUID} roomId - The ID of the room to connect entities to
286
+ * @param {string} channelId - The channel ID
287
+ * @param {string} serverId - The server ID
288
+ * @param {ChannelType} roomType - The type of the room
289
+ * @param {UUID} worldId - The ID of the world
290
+ * @returns {Promise<void>}
291
+ * @private
292
+ */
293
+ private batchProcessEntities;
294
+ /**
295
+ * Gets chat title and channel type based on Telegram chat type.
296
+ * Maps Telegram-specific chat types to standardized system types.
297
+ *
298
+ * @param {any} chat - The Telegram chat object
299
+ * @returns {Object} Object containing chatTitle and channelType
300
+ * @private
301
+ */
302
+ private getChatTypeInfo;
303
+ /**
304
+ * Builds standardized entity representations from Telegram chat data.
305
+ * Transforms Telegram-specific user data into system-standard Entity objects.
306
+ *
307
+ * @param {any} chat - The Telegram chat object
308
+ * @returns {Promise<Entity[]>} Array of standardized Entity objects
309
+ * @private
310
+ */
311
+ private buildStandardizedEntities;
312
+ /**
313
+ * Extracts and builds the room object for a forum topic from a message context.
314
+ * This refactored method can be used both in middleware and when handling new chats.
315
+ *
316
+ * @param {Context} ctx - The context of the incoming update
317
+ * @param {UUID} worldId - The ID of the world the topic belongs to
318
+ * @returns {Promise<Room | null>} A Promise that resolves with the room or null if not a topic
319
+ * @private
320
+ */
321
+ private buildForumTopicRoom;
322
+ static registerSendHandlers(runtime: IAgentRuntime, serviceInstance: TelegramService): void;
323
+ handleSendMessage(runtime: IAgentRuntime, target: TargetInfo, content: Content): Promise<void>;
324
+ }
325
+
326
+ declare const telegramPlugin: Plugin;
327
+
328
+ export { MessageManager, TelegramService, telegramPlugin as default };