@elizaos/plugin-telegram 1.0.4 → 1.0.9

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.
@@ -0,0 +1,219 @@
1
+ import { type Content, type IAgentRuntime, Service, type TargetInfo } from '@elizaos/core';
2
+ import { MessageManager } from './messageManager';
3
+ /**
4
+ * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.
5
+ * This service handles all Telegram-specific functionality including:
6
+ * - Initializing and managing the Telegram bot
7
+ * - Setting up middleware for preprocessing messages
8
+ * - Handling message and reaction events
9
+ * - Synchronizing Telegram chats, users, and entities with the agent runtime
10
+ * - Managing forum topics as separate rooms
11
+ *
12
+ * @extends Service
13
+ */
14
+ export declare class TelegramService extends Service {
15
+ static serviceType: string;
16
+ capabilityDescription: string;
17
+ private bot;
18
+ messageManager: MessageManager | null;
19
+ private options;
20
+ private knownChats;
21
+ private syncedEntityIds;
22
+ /**
23
+ * Constructor for TelegramService class.
24
+ * @param {IAgentRuntime} runtime - The runtime object for the agent.
25
+ */
26
+ constructor(runtime: IAgentRuntime);
27
+ /**
28
+ * Starts the Telegram service for the given runtime.
29
+ *
30
+ * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.
31
+ * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.
32
+ */
33
+ static start(runtime: IAgentRuntime): Promise<TelegramService>;
34
+ /**
35
+ * Stops the agent runtime.
36
+ * @param {IAgentRuntime} runtime - The agent runtime to stop
37
+ */
38
+ static stop(runtime: IAgentRuntime): Promise<void>;
39
+ /**
40
+ * Asynchronously stops the bot.
41
+ *
42
+ * @returns A Promise that resolves once the bot has stopped.
43
+ */
44
+ stop(): Promise<void>;
45
+ /**
46
+ * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.
47
+ * @returns {Promise<void>} A Promise that resolves when the initialization is complete.
48
+ */
49
+ private initializeBot;
50
+ /**
51
+ * Sets up the middleware chain for preprocessing messages before they reach handlers.
52
+ * This critical method establishes a sequential processing pipeline that:
53
+ *
54
+ * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings
55
+ * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed
56
+ * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management
57
+ * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities
58
+ *
59
+ * The middleware chain runs in sequence for each message, with each step potentially
60
+ * enriching the context or stopping processing if conditions aren't met.
61
+ * This preprocessing is essential for maintaining consistent state before message handlers execute.
62
+ *
63
+ * @private
64
+ */
65
+ private setupMiddlewares;
66
+ /**
67
+ * Authorization middleware - checks if chat is allowed to interact with the bot
68
+ * based on the TELEGRAM_ALLOWED_CHATS configuration.
69
+ *
70
+ * @param {Context} ctx - The context of the incoming update
71
+ * @param {Function} next - The function to call to proceed to the next middleware
72
+ * @returns {Promise<void>}
73
+ * @private
74
+ */
75
+ private authorizationMiddleware;
76
+ /**
77
+ * Chat and entity management middleware - handles new chats, forum topics, and entity synchronization.
78
+ * This middleware implements decision logic to determine which operations are needed based on
79
+ * the chat type and whether we've seen this chat before.
80
+ *
81
+ * @param {Context} ctx - The context of the incoming update
82
+ * @param {Function} next - The function to call to proceed to the next middleware
83
+ * @returns {Promise<void>}
84
+ * @private
85
+ */
86
+ private chatAndEntityMiddleware;
87
+ /**
88
+ * Process an existing chat based on chat type and message properties.
89
+ * Different chat types require different processing steps.
90
+ *
91
+ * @param {Context} ctx - The context of the incoming update
92
+ * @returns {Promise<void>}
93
+ * @private
94
+ */
95
+ private processExistingChat;
96
+ /**
97
+ * Sets up message and reaction handlers for the bot.
98
+ * Configures event handlers to process incoming messages and reactions.
99
+ *
100
+ * @private
101
+ */
102
+ private setupMessageHandlers;
103
+ /**
104
+ * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.
105
+ * @param {Context} ctx - The context of the incoming update.
106
+ * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.
107
+ */
108
+ private isGroupAuthorized;
109
+ /**
110
+ * Synchronizes an entity from a message context with the runtime system.
111
+ * This method handles three cases:
112
+ * 1. Message sender - most common case
113
+ * 2. New chat member - when a user joins the chat
114
+ * 3. Left chat member - when a user leaves the chat
115
+ *
116
+ * @param {Context} ctx - The context of the incoming update
117
+ * @returns {Promise<void>}
118
+ * @private
119
+ */
120
+ private syncEntity;
121
+ /**
122
+ * Synchronizes the message sender entity with the runtime system.
123
+ * This is the most common entity sync case.
124
+ *
125
+ * @param {Context} ctx - The context of the incoming update
126
+ * @param {UUID} worldId - The ID of the world
127
+ * @param {UUID} roomId - The ID of the room
128
+ * @param {string} chatId - The ID of the chat
129
+ * @returns {Promise<void>}
130
+ * @private
131
+ */
132
+ private syncMessageSender;
133
+ /**
134
+ * Synchronizes a new chat member entity with the runtime system.
135
+ * Triggered when a user joins the chat.
136
+ *
137
+ * @param {Context} ctx - The context of the incoming update
138
+ * @param {UUID} worldId - The ID of the world
139
+ * @param {UUID} roomId - The ID of the room
140
+ * @param {string} chatId - The ID of the chat
141
+ * @returns {Promise<void>}
142
+ * @private
143
+ */
144
+ private syncNewChatMember;
145
+ /**
146
+ * Updates entity status when a user leaves the chat.
147
+ *
148
+ * @param {Context} ctx - The context of the incoming update
149
+ * @returns {Promise<void>}
150
+ * @private
151
+ */
152
+ private syncLeftChatMember;
153
+ /**
154
+ * Handles forum topics by creating appropriate rooms in the runtime system.
155
+ * This enables proper conversation management for Telegram's forum feature.
156
+ *
157
+ * @param {Context} ctx - The context of the incoming update
158
+ * @returns {Promise<void>}
159
+ * @private
160
+ */
161
+ private handleForumTopic;
162
+ /**
163
+ * Builds entity for message sender
164
+ */
165
+ private buildMsgSenderEntity;
166
+ /**
167
+ * Handles new chat discovery and emits WORLD_JOINED event.
168
+ * This is a critical function that ensures new chats are properly
169
+ * registered in the runtime system and appropriate events are emitted.
170
+ *
171
+ * @param {Context} ctx - The context of the incoming update
172
+ * @returns {Promise<void>}
173
+ * @private
174
+ */
175
+ private handleNewChat;
176
+ /**
177
+ * Processes entities in batches to prevent overwhelming the system.
178
+ *
179
+ * @param {Entity[]} entities - The entities to process
180
+ * @param {UUID} roomId - The ID of the room to connect entities to
181
+ * @param {string} channelId - The channel ID
182
+ * @param {string} serverId - The server ID
183
+ * @param {ChannelType} roomType - The type of the room
184
+ * @param {UUID} worldId - The ID of the world
185
+ * @returns {Promise<void>}
186
+ * @private
187
+ */
188
+ private batchProcessEntities;
189
+ /**
190
+ * Gets chat title and channel type based on Telegram chat type.
191
+ * Maps Telegram-specific chat types to standardized system types.
192
+ *
193
+ * @param {any} chat - The Telegram chat object
194
+ * @returns {Object} Object containing chatTitle and channelType
195
+ * @private
196
+ */
197
+ private getChatTypeInfo;
198
+ /**
199
+ * Builds standardized entity representations from Telegram chat data.
200
+ * Transforms Telegram-specific user data into system-standard Entity objects.
201
+ *
202
+ * @param {any} chat - The Telegram chat object
203
+ * @returns {Promise<Entity[]>} Array of standardized Entity objects
204
+ * @private
205
+ */
206
+ private buildStandardizedEntities;
207
+ /**
208
+ * Extracts and builds the room object for a forum topic from a message context.
209
+ * This refactored method can be used both in middleware and when handling new chats.
210
+ *
211
+ * @param {Context} ctx - The context of the incoming update
212
+ * @param {UUID} worldId - The ID of the world the topic belongs to
213
+ * @returns {Promise<Room | null>} A Promise that resolves with the room or null if not a topic
214
+ * @private
215
+ */
216
+ private buildForumTopicRoom;
217
+ static registerSendHandlers(runtime: IAgentRuntime, serviceInstance: TelegramService): void;
218
+ handleSendMessage(runtime: IAgentRuntime, target: TargetInfo, content: Content): Promise<void>;
219
+ }
@@ -0,0 +1,52 @@
1
+ import { type IAgentRuntime, type TestSuite } from '@elizaos/core';
2
+ import type { Context } from 'telegraf';
3
+ /**
4
+ * Represents a test suite for testing Telegram functionality.
5
+ *
6
+ * This test suite includes methods to initialize and validate a Telegram bot connection,
7
+ * send basic text messages to a Telegram chat, send text messages with image attachments,
8
+ * handle and process incoming Telegram messages, and process and validate image attachments
9
+ * in incoming messages.
10
+ *
11
+ * @implements {TestSuite}
12
+ */
13
+ export declare class TelegramTestSuite implements TestSuite {
14
+ name: string;
15
+ private telegramClient;
16
+ private bot;
17
+ private messageManager;
18
+ tests: {
19
+ name: string;
20
+ fn: (runtime: IAgentRuntime) => Promise<void>;
21
+ }[];
22
+ /**
23
+ * Constructor for initializing a set of test cases for a Telegram bot.
24
+ *
25
+ * @constructor
26
+ * @property {Array<Object>} tests - An array of test cases with name and corresponding test functions.
27
+ * @property {string} tests.name - The name of the test case.
28
+ * @property {function} tests.fn - The test function to be executed.
29
+ */
30
+ constructor();
31
+ /**
32
+ * Retrieves the Telegram test chat ID from environment variables.
33
+ *
34
+ * Reference on getting the Telegram chat ID:
35
+ * https://stackoverflow.com/a/32572159
36
+ */
37
+ /**
38
+ * Validates the chat ID by checking if it is set in the runtime settings or environment variables.
39
+ * If not set, an error is thrown with a message instructing to provide a valid chat ID.
40
+ * @param {IAgentRuntime} runtime - The runtime object that provides access to the settings and environment variables.
41
+ * @throws {Error} If TELEGRAM_TEST_CHAT_ID is not set in the runtime settings or environment variables.
42
+ * @returns {string} The validated chat ID.
43
+ */
44
+ validateChatId(runtime: IAgentRuntime): any;
45
+ getChatInfo(runtime: IAgentRuntime): Promise<Context['chat']>;
46
+ testCreatingTelegramBot(runtime: IAgentRuntime): Promise<void>;
47
+ testSendingTextMessage(runtime: IAgentRuntime): Promise<void>;
48
+ testSendingMessageWithAttachment(runtime: IAgentRuntime): Promise<void>;
49
+ testHandlingMessage(runtime: IAgentRuntime): Promise<void>;
50
+ testProcessingImages(runtime: IAgentRuntime): Promise<void>;
51
+ getFileId(chatId: string, imageUrl: string): Promise<string>;
52
+ }
@@ -0,0 +1,99 @@
1
+ import type { Content, EntityPayload, MessagePayload, WorldPayload } from '@elizaos/core';
2
+ import type { Chat, Message, ReactionType } from '@telegraf/types';
3
+ import type { Context } from 'telegraf';
4
+ /**
5
+ * Extention of the core Content type just for Telegram
6
+ */
7
+ export interface TelegramContent extends Content {
8
+ /** Array of buttons */
9
+ buttons?: Button[];
10
+ }
11
+ /**
12
+ * Represents a flexible button configuration
13
+ */
14
+ export type Button = {
15
+ /** The type of button */
16
+ kind: 'login' | 'url';
17
+ /** The text to display on the button */
18
+ text: string;
19
+ /** The URL or endpoint the button should link to */
20
+ url: string;
21
+ };
22
+ /**
23
+ * Telegram-specific event types
24
+ */
25
+ export declare enum TelegramEventTypes {
26
+ WORLD_JOINED = "TELEGRAM_WORLD_JOINED",
27
+ WORLD_CONNECTED = "TELEGRAM_WORLD_CONNECTED",
28
+ WORLD_LEFT = "TELEGRAM_WORLD_LEFT",
29
+ ENTITY_JOINED = "TELEGRAM_ENTITY_JOINED",
30
+ ENTITY_LEFT = "TELEGRAM_ENTITY_LEFT",
31
+ ENTITY_UPDATED = "TELEGRAM_ENTITY_UPDATED",
32
+ MESSAGE_RECEIVED = "TELEGRAM_MESSAGE_RECEIVED",
33
+ MESSAGE_SENT = "TELEGRAM_MESSAGE_SENT",
34
+ REACTION_RECEIVED = "TELEGRAM_REACTION_RECEIVED",
35
+ INTERACTION_RECEIVED = "TELEGRAM_INTERACTION_RECEIVED",
36
+ SLASH_START = "TELEGRAM_SLASH_START"
37
+ }
38
+ /**
39
+ * Telegram-specific event payload map
40
+ */
41
+ export interface TelegramEventPayloadMap {
42
+ [TelegramEventTypes.MESSAGE_RECEIVED]: TelegramMessageReceivedPayload;
43
+ [TelegramEventTypes.MESSAGE_SENT]: TelegramMessageSentPayload;
44
+ [TelegramEventTypes.REACTION_RECEIVED]: TelegramReactionReceivedPayload;
45
+ [TelegramEventTypes.WORLD_JOINED]: TelegramWorldPayload;
46
+ [TelegramEventTypes.WORLD_CONNECTED]: TelegramWorldPayload;
47
+ [TelegramEventTypes.WORLD_LEFT]: TelegramWorldPayload;
48
+ [TelegramEventTypes.SLASH_START]: {
49
+ ctx: Context;
50
+ };
51
+ [TelegramEventTypes.ENTITY_JOINED]: TelegramEntityPayload;
52
+ [TelegramEventTypes.ENTITY_LEFT]: TelegramEntityPayload;
53
+ [TelegramEventTypes.ENTITY_UPDATED]: TelegramEntityPayload;
54
+ [TelegramEventTypes.INTERACTION_RECEIVED]: TelegramReactionReceivedPayload;
55
+ }
56
+ /**
57
+ * Telegram-specific message received payload
58
+ */
59
+ export interface TelegramMessageReceivedPayload extends MessagePayload {
60
+ /** The original Telegram context */
61
+ ctx: Context;
62
+ /** The original Telegram message */
63
+ originalMessage: Message;
64
+ }
65
+ /**
66
+ * Telegram-specific message sent payload
67
+ */
68
+ export interface TelegramMessageSentPayload extends MessagePayload {
69
+ /** The original Telegram messages */
70
+ originalMessages: Message[];
71
+ /** The chat ID where the message was sent */
72
+ chatId: number | string;
73
+ }
74
+ /**
75
+ * Telegram-specific reaction received payload
76
+ */
77
+ export interface TelegramReactionReceivedPayload extends TelegramMessageReceivedPayload {
78
+ /** The reaction type as a string */
79
+ reactionString: string;
80
+ /** The original reaction object */
81
+ originalReaction: ReactionType;
82
+ }
83
+ /**
84
+ * Telegram-specific world payload
85
+ */
86
+ export interface TelegramWorldPayload extends WorldPayload {
87
+ chat: Chat;
88
+ botUsername?: string;
89
+ }
90
+ /**
91
+ * Telegram-specific entity payload
92
+ */
93
+ export interface TelegramEntityPayload extends EntityPayload {
94
+ telegramUser: {
95
+ id: number;
96
+ username?: string;
97
+ first_name?: string;
98
+ };
99
+ }
@@ -0,0 +1,29 @@
1
+ import { InlineKeyboardButton } from '@telegraf/types';
2
+ import { Button } from './types';
3
+ /**
4
+ * This function converts standard markdown to Telegram MarkdownV2.
5
+ *
6
+ * In addition to processing code blocks, inline code, links, bold, strikethrough, and italic,
7
+ * it converts any header lines (those starting with one or more `#`) to bold text.
8
+ *
9
+ * Note: This solution uses a sequence of regex‐replacements and placeholders.
10
+ * It makes assumptions about non–nested formatting and does not cover every edge case.
11
+ */
12
+ export declare function convertMarkdownToTelegram(markdown: string): string;
13
+ /**
14
+ * Splits a message into chunks that fit within Telegram's message length limit
15
+ */
16
+ /**
17
+ * Splits a text message into chunks based on a maximum length for each chunk.
18
+ *
19
+ * @param {string} text - The text message to split.
20
+ * @param {number} maxLength - The maximum length for each chunk (default is 4096).
21
+ * @returns {string[]} An array containing the text message split into chunks.
22
+ */
23
+ export declare function splitMessage(text: string, maxLength?: number): string[];
24
+ /**
25
+ * Converts Eliza buttons into Telegram buttons
26
+ * @param {Button[]} buttons - The buttons from Eliza content
27
+ * @returns {InlineKeyboardButton[]} Array of Telegram buttons
28
+ */
29
+ export declare function convertToTelegramButtons(buttons?: Button[] | null): InlineKeyboardButton[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elizaos/plugin-telegram",
3
- "version": "1.0.4",
3
+ "version": "1.0.9",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -18,8 +18,9 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@elizaos/core": "^1.0.0",
21
+ "@elizaos/core": "^1.0.19",
22
22
  "@telegraf/types": "7.1.0",
23
+ "@types/node": "^24.0.10",
23
24
  "strip-literal": "^3.0.0",
24
25
  "telegraf": "4.16.3",
25
26
  "type-detect": "^4.1.0",
@@ -31,7 +32,7 @@
31
32
  "vitest": "1.6.1"
32
33
  },
33
34
  "scripts": {
34
- "build": "tsup",
35
+ "build": "tsup && tsc",
35
36
  "dev": "tsup --watch",
36
37
  "test": "vitest run",
37
38
  "test:watch": "vitest",