@elizaos/plugin-telegram 1.6.3 → 1.6.4
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/dist/index.js +51 -34
- package/dist/index.js.map +1 -1
- package/dist/service.d.ts +0 -1
- package/dist/tests.d.ts +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -611,7 +611,6 @@ Type: ${document.mime_type || "unknown"}`
|
|
|
611
611
|
name: ctx.from.first_name,
|
|
612
612
|
source: "telegram",
|
|
613
613
|
channelId: telegramRoomid,
|
|
614
|
-
serverId: void 0,
|
|
615
614
|
type: channelType,
|
|
616
615
|
worldId: createUniqueUuid(this.runtime, roomId),
|
|
617
616
|
worldName: telegramRoomid
|
|
@@ -684,13 +683,20 @@ Type: ${document.mime_type || "unknown"}`
|
|
|
684
683
|
return [];
|
|
685
684
|
}
|
|
686
685
|
};
|
|
687
|
-
if (
|
|
686
|
+
if (this.runtime.hasElizaOS()) {
|
|
687
|
+
await this.runtime.elizaOS.handleMessage(this.runtime.agentId, memory, {
|
|
688
|
+
onResponse: async (content) => {
|
|
689
|
+
await callback(content);
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
} else if (this.runtime.messageService) {
|
|
693
|
+
await this.runtime.messageService.handleMessage(this.runtime, memory, callback);
|
|
694
|
+
} else {
|
|
688
695
|
logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId }, "Message service is not available");
|
|
689
696
|
throw new Error(
|
|
690
697
|
"Message service is not initialized. Ensure the message service is properly configured."
|
|
691
698
|
);
|
|
692
699
|
}
|
|
693
|
-
await this.runtime.messageService.handleMessage(this.runtime, memory, callback);
|
|
694
700
|
} catch (error) {
|
|
695
701
|
logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId: ctx.chat?.id, messageId: ctx.message?.message_id, from: ctx.from?.username || ctx.from?.id, error: error instanceof Error ? error.message : String(error) }, "Error handling Telegram message");
|
|
696
702
|
throw error;
|
|
@@ -822,18 +828,23 @@ Type: ${document.mime_type || "unknown"}`
|
|
|
822
828
|
await this.runtime.createMemory(memory, "messages");
|
|
823
829
|
memories.push(memory);
|
|
824
830
|
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
831
|
+
if (memories.length > 0) {
|
|
832
|
+
this.runtime.emitEvent(EventType.MESSAGE_SENT, {
|
|
833
|
+
runtime: this.runtime,
|
|
834
|
+
message: memories[0],
|
|
835
|
+
source: "telegram"
|
|
836
|
+
});
|
|
837
|
+
}
|
|
838
|
+
this.runtime.emitEvent(
|
|
839
|
+
"TELEGRAM_MESSAGE_SENT" /* MESSAGE_SENT */,
|
|
840
|
+
{
|
|
841
|
+
runtime: this.runtime,
|
|
842
|
+
source: "telegram",
|
|
843
|
+
originalMessages: sentMessages,
|
|
844
|
+
chatId,
|
|
845
|
+
message: memories[0]
|
|
846
|
+
}
|
|
847
|
+
);
|
|
837
848
|
return sentMessages;
|
|
838
849
|
} catch (error) {
|
|
839
850
|
logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, "Error sending message to Telegram");
|
|
@@ -942,10 +953,14 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
942
953
|
*/
|
|
943
954
|
async initializeBot() {
|
|
944
955
|
this.bot?.start((ctx) => {
|
|
945
|
-
this.runtime.emitEvent(
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
956
|
+
this.runtime.emitEvent(
|
|
957
|
+
"TELEGRAM_SLASH_START" /* SLASH_START */,
|
|
958
|
+
{
|
|
959
|
+
ctx,
|
|
960
|
+
runtime: this.runtime,
|
|
961
|
+
source: "telegram"
|
|
962
|
+
}
|
|
963
|
+
);
|
|
949
964
|
});
|
|
950
965
|
this.bot?.launch({
|
|
951
966
|
dropPendingUpdates: true,
|
|
@@ -1122,7 +1137,6 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
1122
1137
|
name: ctx.from.first_name || ctx.from.username || "Unknown User",
|
|
1123
1138
|
source: "telegram",
|
|
1124
1139
|
channelId: chatId,
|
|
1125
|
-
serverId: chatId,
|
|
1126
1140
|
type: ChannelType2.GROUP,
|
|
1127
1141
|
worldId
|
|
1128
1142
|
});
|
|
@@ -1154,18 +1168,24 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
1154
1168
|
name: newMember.first_name || newMember.username || "Unknown User",
|
|
1155
1169
|
source: "telegram",
|
|
1156
1170
|
channelId: chatId,
|
|
1157
|
-
serverId: chatId,
|
|
1158
1171
|
type: ChannelType2.GROUP,
|
|
1159
1172
|
worldId
|
|
1160
1173
|
});
|
|
1161
1174
|
this.syncedEntityIds.add(entityId);
|
|
1162
|
-
this.runtime.emitEvent(
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1175
|
+
this.runtime.emitEvent(
|
|
1176
|
+
"TELEGRAM_ENTITY_JOINED" /* ENTITY_JOINED */,
|
|
1177
|
+
{
|
|
1178
|
+
runtime: this.runtime,
|
|
1179
|
+
entityId,
|
|
1180
|
+
worldId,
|
|
1181
|
+
source: "telegram",
|
|
1182
|
+
telegramUser: {
|
|
1183
|
+
id: newMember.id,
|
|
1184
|
+
username: newMember.username,
|
|
1185
|
+
first_name: newMember.first_name
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
);
|
|
1169
1189
|
}
|
|
1170
1190
|
}
|
|
1171
1191
|
/**
|
|
@@ -1313,7 +1333,6 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
1313
1333
|
entities,
|
|
1314
1334
|
generalRoom.id,
|
|
1315
1335
|
generalRoom.channelId,
|
|
1316
|
-
generalRoom.serverId,
|
|
1317
1336
|
generalRoom.type,
|
|
1318
1337
|
worldId
|
|
1319
1338
|
);
|
|
@@ -1343,13 +1362,12 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
1343
1362
|
* @param {Entity[]} entities - The entities to process
|
|
1344
1363
|
* @param {UUID} roomId - The ID of the room to connect entities to
|
|
1345
1364
|
* @param {string} channelId - The channel ID
|
|
1346
|
-
* @param {string} serverId - The server ID
|
|
1347
1365
|
* @param {ChannelType} roomType - The type of the room
|
|
1348
1366
|
* @param {UUID} worldId - The ID of the world
|
|
1349
1367
|
* @returns {Promise<void>}
|
|
1350
1368
|
* @private
|
|
1351
1369
|
*/
|
|
1352
|
-
async batchProcessEntities(entities, roomId, channelId,
|
|
1370
|
+
async batchProcessEntities(entities, roomId, channelId, roomType, worldId) {
|
|
1353
1371
|
const batchSize = 50;
|
|
1354
1372
|
for (let i = 0; i < entities.length; i += batchSize) {
|
|
1355
1373
|
const entityBatch = entities.slice(i, i + batchSize);
|
|
@@ -1366,7 +1384,6 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
1366
1384
|
userId: telegramMetadata?.id,
|
|
1367
1385
|
source: "telegram",
|
|
1368
1386
|
channelId,
|
|
1369
|
-
serverId,
|
|
1370
1387
|
type: roomType,
|
|
1371
1388
|
worldId
|
|
1372
1389
|
});
|
|
@@ -1630,7 +1647,7 @@ var TelegramTestSuite = class {
|
|
|
1630
1647
|
*/
|
|
1631
1648
|
validateChatId(runtime) {
|
|
1632
1649
|
const testChatId = runtime.getSetting("TELEGRAM_TEST_CHAT_ID") || process.env.TELEGRAM_TEST_CHAT_ID;
|
|
1633
|
-
if (!testChatId) {
|
|
1650
|
+
if (!testChatId || typeof testChatId === "boolean") {
|
|
1634
1651
|
throw new Error(
|
|
1635
1652
|
"TELEGRAM_TEST_CHAT_ID is not set. Please provide a valid chat ID in the environment variables."
|
|
1636
1653
|
);
|
|
@@ -1740,7 +1757,7 @@ var TelegramTestSuite = class {
|
|
|
1740
1757
|
if (!this.bot) throw new Error("Bot not initialized.");
|
|
1741
1758
|
if (!this.messageManager) throw new Error("MessageManager not initialized.");
|
|
1742
1759
|
const chatId = this.validateChatId(runtime);
|
|
1743
|
-
const fileId = await this.getFileId(chatId, TEST_IMAGE_URL);
|
|
1760
|
+
const fileId = await this.getFileId(String(chatId), TEST_IMAGE_URL);
|
|
1744
1761
|
const mockMessage = {
|
|
1745
1762
|
message_id: 12345,
|
|
1746
1763
|
chat: { id: chatId, type: "private" },
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/service.ts","../src/messageManager.ts","../src/utils.ts","../src/tests.ts","../src/index.ts"],"sourcesContent":["export const MESSAGE_CONSTANTS = {\n MAX_MESSAGES: 50,\n RECENT_MESSAGE_COUNT: 5,\n CHAT_HISTORY_COUNT: 10,\n DEFAULT_SIMILARITY_THRESHOLD: 0.6,\n DEFAULT_SIMILARITY_THRESHOLD_FOLLOW_UPS: 0.4,\n INTEREST_DECAY_TIME: 5 * 60 * 1000, // 5 minutes\n PARTIAL_INTEREST_DECAY: 3 * 60 * 1000, // 3 minutes\n} as const;\n\nexport const TELEGRAM_SERVICE_NAME = 'telegram';\n","import {\n ChannelType,\n type Content,\n type Entity,\n EventType,\n type IAgentRuntime,\n Role,\n type Room,\n Service,\n type TargetInfo,\n type UUID,\n type World,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport { type Context, Telegraf } from 'telegraf';\nimport { type ChatMemberOwner, type ChatMemberAdministrator, type User } from 'telegraf/types';\nimport { TELEGRAM_SERVICE_NAME } from './constants';\nimport { MessageManager } from './messageManager';\nimport { TelegramEventTypes, type TelegramWorldPayload } from './types';\n\n/**\n * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.\n * This service handles all Telegram-specific functionality including:\n * - Initializing and managing the Telegram bot\n * - Setting up middleware for preprocessing messages\n * - Handling message and reaction events\n * - Synchronizing Telegram chats, users, and entities with the agent runtime\n * - Managing forum topics as separate rooms\n *\n * @extends Service\n */\nexport class TelegramService extends Service {\n static serviceType = TELEGRAM_SERVICE_NAME;\n capabilityDescription = 'The agent is able to send and receive messages on telegram';\n private bot: Telegraf<Context> | null;\n public messageManager: MessageManager | null;\n private options;\n private knownChats: Map<string, any> = new Map();\n private syncedEntityIds: Set<string> = new Set<string>();\n\n /**\n * Constructor for TelegramService class.\n * @param {IAgentRuntime} runtime - The runtime object for the agent.\n */\n constructor(runtime: IAgentRuntime) {\n super(runtime);\n logger.debug({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Constructing TelegramService');\n\n // Check if Telegram bot token is available and valid\n const botToken = runtime.getSetting('TELEGRAM_BOT_TOKEN') as string;\n if (!botToken || botToken.trim() === '') {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Bot token not provided, Telegram functionality unavailable');\n this.bot = null;\n this.messageManager = null;\n return;\n }\n\n this.options = {\n telegram: {\n apiRoot:\n runtime.getSetting('TELEGRAM_API_ROOT') ||\n process.env.TELEGRAM_API_ROOT ||\n 'https://api.telegram.org',\n },\n };\n\n try {\n this.bot = new Telegraf(botToken, this.options);\n this.messageManager = new MessageManager(this.bot, this.runtime);\n logger.debug({ src: 'plugin:telegram', agentId: runtime.agentId }, 'TelegramService constructor completed');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Failed to initialize Telegram bot');\n this.bot = null;\n this.messageManager = null;\n }\n }\n\n /**\n * Starts the Telegram service for the given runtime.\n *\n * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.\n * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.\n */\n static async start(runtime: IAgentRuntime): Promise<TelegramService> {\n // Remove validateTelegramConfig call to allow service to start without token\n\n const service = new TelegramService(runtime);\n\n // If bot is not initialized (no token), return the service without further initialization\n if (!service.bot) {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Service started without bot functionality');\n return service;\n }\n\n const maxRetries = 5;\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, agentName: runtime.character.name }, 'Starting Telegram bot');\n await service.initializeBot();\n\n // Set up middlewares before message handlers to ensure proper preprocessing\n service.setupMiddlewares();\n\n // Set up message handlers after middlewares\n service.setupMessageHandlers();\n\n // Wait for bot to be ready by testing getMe()\n await service.bot!.telegram.getMe();\n\n logger.success({ src: 'plugin:telegram', agentId: runtime.agentId, agentName: runtime.character.name }, 'Telegram bot started successfully');\n return service;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, attempt: retryCount + 1, error: lastError.message }, 'Initialization attempt failed');\n retryCount++;\n\n if (retryCount < maxRetries) {\n const delay = 2 ** retryCount * 1000; // Exponential backoff\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, delaySeconds: delay / 1000 }, 'Retrying initialization');\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, maxRetries, error: lastError?.message }, 'Initialization failed after all attempts');\n\n // Return the service even if initialization failed, to prevent server crash\n return service;\n }\n\n /**\n * Stops the agent runtime.\n * @param {IAgentRuntime} runtime - The agent runtime to stop\n */\n static async stop(runtime: IAgentRuntime) {\n // Implement shutdown if necessary\n const tgClient = runtime.getService(TELEGRAM_SERVICE_NAME);\n if (tgClient) {\n await tgClient.stop();\n }\n }\n\n /**\n * Asynchronously stops the bot.\n *\n * @returns A Promise that resolves once the bot has stopped.\n */\n async stop(): Promise<void> {\n this.bot?.stop();\n }\n\n /**\n * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.\n * @returns {Promise<void>} A Promise that resolves when the initialization is complete.\n */\n private async initializeBot(): Promise<void> {\n this.bot?.start((ctx) => {\n this.runtime.emitEvent([TelegramEventTypes.SLASH_START], {\n // we don't need this\n ctx,\n });\n });\n this.bot?.launch({\n dropPendingUpdates: true,\n allowedUpdates: ['message', 'message_reaction'],\n });\n\n // Get bot info for identification purposes\n const botInfo = await this.bot!.telegram.getMe();\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, botId: botInfo.id, botUsername: botInfo.username }, 'Bot info retrieved');\n\n // Handle sigint and sigterm signals to gracefully stop the bot\n process.once('SIGINT', () => this.bot?.stop('SIGINT'));\n process.once('SIGTERM', () => this.bot?.stop('SIGTERM'));\n }\n\n /**\n * Sets up the middleware chain for preprocessing messages before they reach handlers.\n * This critical method establishes a sequential processing pipeline that:\n *\n * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings\n * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed\n * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management\n * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities\n *\n * The middleware chain runs in sequence for each message, with each step potentially\n * enriching the context or stopping processing if conditions aren't met.\n * This preprocessing is essential for maintaining consistent state before message handlers execute.\n *\n * @private\n */\n private setupMiddlewares(): void {\n // Register the authorization middleware\n this.bot?.use(this.authorizationMiddleware.bind(this));\n\n // Register the chat and entity management middleware\n this.bot?.use(this.chatAndEntityMiddleware.bind(this));\n }\n\n /**\n * Authorization middleware - checks if chat is allowed to interact with the bot\n * based on the TELEGRAM_ALLOWED_CHATS configuration.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {Function} next - The function to call to proceed to the next middleware\n * @returns {Promise<void>}\n * @private\n */\n private async authorizationMiddleware(ctx: Context, next: Function): Promise<void> {\n if (!(await this.isGroupAuthorized(ctx))) {\n // Skip further processing if chat is not authorized\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: ctx.chat?.id }, 'Chat not authorized, skipping');\n return;\n }\n await next();\n }\n\n /**\n * Chat and entity management middleware - handles new chats, forum topics, and entity synchronization.\n * This middleware implements decision logic to determine which operations are needed based on\n * the chat type and whether we've seen this chat before.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {Function} next - The function to call to proceed to the next middleware\n * @returns {Promise<void>}\n * @private\n */\n private async chatAndEntityMiddleware(ctx: Context, next: Function): Promise<void> {\n if (!ctx.chat) return next();\n\n const chatId = ctx.chat.id.toString();\n\n // If we haven't seen this chat before, process it as a new chat\n if (!this.knownChats.has(chatId)) {\n // Process the new chat - creates world, room, topic room (if applicable) and entities\n await this.handleNewChat(ctx);\n // Skip entity synchronization for new chats and proceed to the next middleware\n return next();\n }\n\n // For existing chats, determine the required operations based on chat type\n await this.processExistingChat(ctx);\n\n await next();\n }\n\n /**\n * Process an existing chat based on chat type and message properties.\n * Different chat types require different processing steps.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async processExistingChat(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n\n // Handle forum topics for supergroups with forums\n if (chat.type === 'supergroup' && chat.is_forum && ctx.message?.message_thread_id) {\n try {\n await this.handleForumTopic(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, 'Error handling forum topic');\n }\n }\n\n // For non-private chats, synchronize entity information\n if (ctx.from && ctx.chat.type !== 'private') {\n await this.syncEntity(ctx);\n }\n }\n\n /**\n * Sets up message and reaction handlers for the bot.\n * Configures event handlers to process incoming messages and reactions.\n *\n * @private\n */\n private setupMessageHandlers(): void {\n // Regular message handler\n this.bot?.on('message', async (ctx) => {\n try {\n // Message handling is now simplified since all preprocessing is done by middleware\n await this.messageManager!.handleMessage(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling message');\n }\n });\n\n // Reaction handler\n this.bot?.on('message_reaction', async (ctx) => {\n try {\n await this.messageManager!.handleReaction(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling reaction');\n }\n });\n }\n\n /**\n * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.\n * @param {Context} ctx - The context of the incoming update.\n * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.\n */\n private async isGroupAuthorized(ctx: Context): Promise<boolean> {\n const chatId = ctx.chat?.id.toString();\n if (!chatId) return false;\n\n const allowedChats = this.runtime.getSetting('TELEGRAM_ALLOWED_CHATS');\n if (!allowedChats) {\n return true;\n }\n\n try {\n const allowedChatsList = JSON.parse(allowedChats as string);\n return allowedChatsList.includes(chatId);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error parsing TELEGRAM_ALLOWED_CHATS');\n return false;\n }\n }\n\n /**\n * Synchronizes an entity from a message context with the runtime system.\n * This method handles three cases:\n * 1. Message sender - most common case\n * 2. New chat member - when a user joins the chat\n * 3. Left chat member - when a user leaves the chat\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async syncEntity(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n const roomId = createUniqueUuid(\n this.runtime,\n ctx.message?.message_thread_id\n ? `${ctx.chat.id}-${ctx.message.message_thread_id}`\n : ctx.chat.id.toString()\n ) as UUID;\n\n // Handle all three entity sync cases separately for clarity\n await this.syncMessageSender(ctx, worldId, roomId, chatId);\n await this.syncNewChatMember(ctx, worldId, roomId, chatId);\n await this.syncLeftChatMember(ctx);\n }\n\n /**\n * Synchronizes the message sender entity with the runtime system.\n * This is the most common entity sync case.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world\n * @param {UUID} roomId - The ID of the room\n * @param {string} chatId - The ID of the chat\n * @returns {Promise<void>}\n * @private\n */\n private async syncMessageSender(\n ctx: Context,\n worldId: UUID,\n roomId: UUID,\n chatId: string\n ): Promise<void> {\n // Handle message sender\n if (ctx.from && !this.syncedEntityIds.has(ctx.from.id.toString())) {\n const telegramId = ctx.from.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n await this.runtime.ensureConnection({\n entityId,\n roomId: roomId,\n userName: ctx.from.username,\n userId: telegramId as UUID,\n name: ctx.from.first_name || ctx.from.username || 'Unknown User',\n source: 'telegram',\n channelId: chatId,\n serverId: chatId,\n type: ChannelType.GROUP,\n worldId: worldId,\n });\n\n this.syncedEntityIds.add(entityId);\n }\n }\n\n /**\n * Synchronizes a new chat member entity with the runtime system.\n * Triggered when a user joins the chat.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world\n * @param {UUID} roomId - The ID of the room\n * @param {string} chatId - The ID of the chat\n * @returns {Promise<void>}\n * @private\n */\n private async syncNewChatMember(\n ctx: Context,\n worldId: UUID,\n roomId: UUID,\n chatId: string\n ): Promise<void> {\n // Handle new chat member\n if (ctx.message && 'new_chat_member' in ctx.message) {\n const newMember = ctx.message.new_chat_member as any;\n const telegramId = newMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n // Skip if we've already synced this entity\n if (this.syncedEntityIds.has(telegramId)) return;\n\n // We call ensure connection here for this user.\n await this.runtime.ensureConnection({\n entityId,\n roomId: roomId,\n userName: newMember.username,\n userId: telegramId,\n name: newMember.first_name || newMember.username || 'Unknown User',\n source: 'telegram',\n channelId: chatId,\n serverId: chatId,\n type: ChannelType.GROUP,\n worldId: worldId,\n });\n\n this.syncedEntityIds.add(entityId);\n\n this.runtime.emitEvent([TelegramEventTypes.ENTITY_JOINED], {\n runtime: this.runtime,\n entityId,\n worldId,\n newMember,\n ctx,\n });\n }\n }\n\n /**\n * Updates entity status when a user leaves the chat.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async syncLeftChatMember(ctx: Context): Promise<void> {\n // Handle left chat member\n if (ctx.message && 'left_chat_member' in ctx.message) {\n const leftMember = ctx.message.left_chat_member as any;\n const telegramId = leftMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n const existingEntity = await this.runtime.getEntityById(entityId);\n if (existingEntity) {\n existingEntity.metadata = {\n ...existingEntity.metadata,\n status: 'INACTIVE',\n leftAt: Date.now(),\n };\n await this.runtime.updateEntity(existingEntity);\n }\n }\n }\n\n /**\n * Handles forum topics by creating appropriate rooms in the runtime system.\n * This enables proper conversation management for Telegram's forum feature.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async handleForumTopic(ctx: Context): Promise<void> {\n if (!ctx.chat || !ctx.message?.message_thread_id) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n\n const room = await this.buildForumTopicRoom(ctx, worldId);\n if (!room) return;\n\n await this.runtime.ensureRoomExists(room);\n }\n\n /**\n * Builds entity for message sender\n */\n private buildMsgSenderEntity(from: User): Entity | null {\n if (!from) return null;\n\n const userId = createUniqueUuid(this.runtime, from.id.toString()) as UUID;\n const telegramId = from.id.toString();\n\n return {\n id: userId,\n agentId: this.runtime.agentId,\n names: [from.first_name || from.username || 'Unknown User'],\n metadata: {\n telegram: {\n id: telegramId,\n username: from.username,\n name: from.first_name || from.username || 'Unknown User',\n },\n },\n };\n }\n\n /**\n * Handles new chat discovery and emits WORLD_JOINED event.\n * This is a critical function that ensures new chats are properly\n * registered in the runtime system and appropriate events are emitted.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async handleNewChat(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n\n // Mark this chat as known\n this.knownChats.set(chatId, chat);\n\n // Get chat title and channel type\n const { chatTitle, channelType } = this.getChatTypeInfo(chat);\n\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n\n const existingWorld = await this.runtime.getWorld(worldId);\n if (existingWorld) {\n return;\n }\n\n const userId = ctx.from\n ? (createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID)\n : null;\n\n // Fetch admin information for proper role assignment\n let admins: (ChatMemberOwner | ChatMemberAdministrator)[] = [];\n let owner: ChatMemberOwner | null = null;\n if (chat.type === 'group' || chat.type === 'supergroup' || chat.type === 'channel') {\n try {\n const chatAdmins = await ctx.getChatAdministrators();\n admins = chatAdmins;\n const foundOwner = admins.find(\n (admin): admin is ChatMemberOwner => admin.status === 'creator'\n );\n owner = foundOwner || null;\n } catch (error) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Could not get chat administrators');\n }\n }\n\n let ownerId = userId;\n\n if (owner) {\n ownerId = createUniqueUuid(this.runtime, String(owner.user.id)) as UUID;\n }\n\n // Build world representation\n const world: World = {\n id: worldId,\n name: chatTitle,\n agentId: this.runtime.agentId,\n serverId: chatId,\n metadata: {\n source: 'telegram',\n ...(ownerId && { ownership: { ownerId } }),\n roles: ownerId\n ? {\n [ownerId]: Role.OWNER,\n }\n : {},\n chatType: chat.type,\n isForumEnabled: chat.type === 'supergroup' && chat.is_forum,\n },\n };\n\n // Directly ensure world exists instead of using syncTelegram\n await this.runtime.ensureWorldExists(world);\n\n // Create the main room for the chat\n const generalRoom: Room = {\n id: createUniqueUuid(this.runtime, chatId) as UUID,\n name: chatTitle,\n source: 'telegram',\n type: channelType,\n channelId: chatId,\n serverId: chatId,\n worldId,\n };\n\n // Directly ensure room exists instead of using syncTelegram\n await this.runtime.ensureRoomExists(generalRoom);\n\n // Prepare the rooms array starting with the main room\n const rooms = [generalRoom];\n\n // If this is a message in a forum topic, add the topic room as well\n if (chat.type === 'supergroup' && chat.is_forum && ctx.message?.message_thread_id) {\n const topicRoom = await this.buildForumTopicRoom(ctx, worldId);\n if (topicRoom) {\n rooms.push(topicRoom);\n await this.runtime.ensureRoomExists(topicRoom);\n }\n }\n\n // Build entities from chat\n const entities = await this.buildStandardizedEntities(chat);\n\n // Add sender if not already in entities\n if (ctx.from) {\n const senderEntity = this.buildMsgSenderEntity(ctx.from);\n if (senderEntity && senderEntity.id && !entities.some((e) => e.id === senderEntity.id)) {\n entities.push(senderEntity);\n this.syncedEntityIds.add(senderEntity.id);\n }\n }\n\n // Use the new batch processing method for entities\n await this.batchProcessEntities(\n entities,\n generalRoom.id!,\n generalRoom.channelId!,\n generalRoom.serverId!,\n generalRoom.type,\n worldId\n );\n\n // Create payload for world events\n const telegramWorldPayload: TelegramWorldPayload = {\n runtime: this.runtime,\n world,\n rooms,\n entities,\n source: 'telegram',\n chat,\n botUsername: this.bot?.botInfo?.username,\n };\n\n // Emit telegram-specific world joined event\n if (chat.type !== 'private') {\n await this.runtime.emitEvent(TelegramEventTypes.WORLD_JOINED, telegramWorldPayload);\n }\n\n // Finally emit the standard WORLD_JOINED event\n await this.runtime.emitEvent(EventType.WORLD_JOINED, {\n runtime: this.runtime,\n world,\n rooms,\n entities,\n source: 'telegram',\n });\n }\n\n /**\n * Processes entities in batches to prevent overwhelming the system.\n *\n * @param {Entity[]} entities - The entities to process\n * @param {UUID} roomId - The ID of the room to connect entities to\n * @param {string} channelId - The channel ID\n * @param {string} serverId - The server ID\n * @param {ChannelType} roomType - The type of the room\n * @param {UUID} worldId - The ID of the world\n * @returns {Promise<void>}\n * @private\n */\n private async batchProcessEntities(\n entities: Entity[],\n roomId: UUID,\n channelId: string,\n serverId: string,\n roomType: ChannelType,\n worldId: UUID\n ): Promise<void> {\n const batchSize = 50;\n\n for (let i = 0; i < entities.length; i += batchSize) {\n const entityBatch = entities.slice(i, i + batchSize);\n\n // Process each entity in the batch concurrently\n await Promise.all(\n entityBatch.map(async (entity: Entity) => {\n try {\n if (entity.id) {\n const telegramMetadata = entity.metadata?.telegram as\n | {\n username?: string;\n name?: string;\n id?: string;\n }\n | undefined;\n\n await this.runtime.ensureConnection({\n entityId: entity.id,\n roomId: roomId,\n userName: telegramMetadata?.username,\n name: telegramMetadata?.name,\n userId: telegramMetadata?.id as UUID,\n source: 'telegram',\n channelId: channelId,\n serverId: serverId,\n type: roomType,\n worldId: worldId,\n });\n } else {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, entityNames: entity.names }, 'Skipping entity sync due to missing ID');\n }\n } catch (err) {\n const telegramMetadata = entity.metadata?.telegram as\n | {\n username?: string;\n }\n | undefined;\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, username: telegramMetadata?.username, error: err instanceof Error ? err.message : String(err) }, 'Failed to sync user');\n }\n })\n );\n\n // Add a small delay between batches if not the last batch\n if (i + batchSize < entities.length) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n }\n }\n\n /**\n * Gets chat title and channel type based on Telegram chat type.\n * Maps Telegram-specific chat types to standardized system types.\n *\n * @param {any} chat - The Telegram chat object\n * @returns {Object} Object containing chatTitle and channelType\n * @private\n */\n private getChatTypeInfo(chat: any): { chatTitle: string; channelType: ChannelType } {\n let chatTitle: string;\n let channelType: ChannelType;\n\n switch (chat.type) {\n case 'private':\n chatTitle = `Chat with ${chat.first_name || 'Unknown User'}`;\n channelType = ChannelType.DM;\n break;\n case 'group':\n chatTitle = chat.title || 'Unknown Group';\n channelType = ChannelType.GROUP;\n break;\n case 'supergroup':\n chatTitle = chat.title || 'Unknown Supergroup';\n channelType = ChannelType.GROUP;\n break;\n case 'channel':\n chatTitle = chat.title || 'Unknown Channel';\n channelType = ChannelType.FEED;\n break;\n default:\n chatTitle = 'Unknown Chat';\n channelType = ChannelType.GROUP;\n }\n\n return { chatTitle, channelType };\n }\n\n /**\n * Builds standardized entity representations from Telegram chat data.\n * Transforms Telegram-specific user data into system-standard Entity objects.\n *\n * @param {any} chat - The Telegram chat object\n * @returns {Promise<Entity[]>} Array of standardized Entity objects\n * @private\n */\n private async buildStandardizedEntities(chat: any): Promise<Entity[]> {\n const entities: Entity[] = [];\n\n try {\n // For private chats, add the user\n if (chat.type === 'private' && chat.id) {\n const userId = createUniqueUuid(this.runtime, chat.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [chat.first_name || 'Unknown User'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: chat.id.toString(),\n username: chat.username || 'unknown',\n name: chat.first_name || 'Unknown User',\n },\n source: 'telegram',\n },\n });\n this.syncedEntityIds.add(userId);\n } else if (chat.type === 'group' || chat.type === 'supergroup') {\n // For groups and supergroups, try to get member information\n try {\n // Get chat administrators (this is what's available through the Bot API)\n const admins = await this.bot?.telegram.getChatAdministrators(chat.id);\n\n if (admins && admins.length > 0) {\n for (const admin of admins) {\n const userId = createUniqueUuid(this.runtime, admin.user.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [admin.user.first_name || admin.user.username || 'Unknown Admin'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: admin.user.id.toString(),\n username: admin.user.username || 'unknown',\n name: admin.user.first_name || 'Unknown Admin',\n isAdmin: true,\n adminTitle:\n admin.custom_title || (admin.status === 'creator' ? 'Owner' : 'Admin'),\n },\n source: 'telegram',\n roles: [admin.status === 'creator' ? Role.OWNER : Role.ADMIN],\n },\n });\n this.syncedEntityIds.add(userId);\n }\n }\n } catch (error) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, 'Could not fetch administrators');\n }\n }\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error building standardized entities');\n }\n\n return entities;\n }\n\n /**\n * Extracts and builds the room object for a forum topic from a message context.\n * This refactored method can be used both in middleware and when handling new chats.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world the topic belongs to\n * @returns {Promise<Room | null>} A Promise that resolves with the room or null if not a topic\n * @private\n */\n private async buildForumTopicRoom(ctx: Context, worldId: UUID): Promise<Room | null> {\n if (!ctx.chat || !ctx.message?.message_thread_id) return null;\n if (ctx.chat.type !== 'supergroup' || !ctx.chat.is_forum) return null;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const threadId = ctx.message.message_thread_id.toString();\n const roomId = createUniqueUuid(this.runtime, `${chatId}-${threadId}`) as UUID;\n\n try {\n // Ensure the message object is fully initialized\n const replyMessage = JSON.parse(JSON.stringify(ctx.message));\n\n // Default topic name\n let topicName = `Topic #${threadId}`;\n\n // Check if forum_topic_created exists directly in the message\n if (\n replyMessage &&\n typeof replyMessage === 'object' &&\n 'forum_topic_created' in replyMessage &&\n replyMessage.forum_topic_created\n ) {\n const topicCreated = replyMessage.forum_topic_created;\n if (topicCreated && typeof topicCreated === 'object' && 'name' in topicCreated) {\n topicName = topicCreated.name;\n }\n }\n // Check if forum_topic_created exists in reply_to_message\n else if (\n replyMessage &&\n typeof replyMessage === 'object' &&\n 'reply_to_message' in replyMessage &&\n replyMessage.reply_to_message &&\n typeof replyMessage.reply_to_message === 'object' &&\n 'forum_topic_created' in replyMessage.reply_to_message &&\n replyMessage.reply_to_message.forum_topic_created\n ) {\n const topicCreated = replyMessage.reply_to_message.forum_topic_created;\n if (topicCreated && typeof topicCreated === 'object' && 'name' in topicCreated) {\n topicName = topicCreated.name;\n }\n }\n\n // Create a room for this topic\n const room: Room = {\n id: roomId,\n name: topicName,\n source: 'telegram',\n type: ChannelType.GROUP,\n channelId: `${chatId}-${threadId}`,\n serverId: chatId,\n worldId,\n metadata: {\n threadId: threadId,\n isForumTopic: true,\n parentChatId: chatId,\n },\n };\n\n return room;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, threadId, error: error instanceof Error ? error.message : String(error) }, 'Error building forum topic room');\n return null;\n }\n }\n\n static registerSendHandlers(runtime: IAgentRuntime, serviceInstance: TelegramService) {\n if (serviceInstance && serviceInstance.bot) {\n runtime.registerSendHandler(\n 'telegram',\n serviceInstance.handleSendMessage.bind(serviceInstance)\n );\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Registered send handler');\n } else {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Cannot register send handler, bot not initialized');\n }\n }\n\n async handleSendMessage(\n runtime: IAgentRuntime,\n target: TargetInfo,\n content: Content\n ): Promise<void> {\n // Check if bot and messageManager are available\n if (!this.bot || !this.messageManager) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Bot not initialized, cannot send messages');\n throw new Error('Telegram bot is not initialized. Please provide TELEGRAM_BOT_TOKEN.');\n }\n\n let chatId: number | string | undefined;\n\n // Determine the target chat ID\n if (target.channelId) {\n // Use channelId directly if provided (might be string like chat_id-thread_id or just chat_id)\n // We might need to parse this depending on how room IDs are stored vs Telegram IDs\n chatId = target.channelId;\n } else if (target.roomId) {\n // Fallback: Try to use roomId if channelId isn't available\n // This assumes roomId maps directly to Telegram chat ID or requires lookup\n // Placeholder - requires logic to map roomId -> telegram chat ID if different\n const room = await runtime.getRoom(target.roomId);\n chatId = room?.channelId; // Assuming channelId on Room IS the telegram ID\n if (!chatId)\n throw new Error(`Could not resolve Telegram chat ID from roomId ${target.roomId}`);\n } else if (target.entityId) {\n // TODO: Need robust way to map entityId (runtime UUID) to Telegram User ID (number)\n // This might involve checking entity metadata.\n // For now, this part is non-functional without that mapping.\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, entityId: target.entityId }, 'Sending DMs via entityId not implemented');\n throw new Error('Sending DMs via entityId is not yet supported for Telegram.');\n // Example placeholder: const telegramUserId = await getTelegramIdFromEntity(runtime, target.entityId);\n // chatId = telegramUserId;\n } else {\n throw new Error('Telegram SendHandler requires channelId, roomId, or entityId.');\n }\n\n if (!chatId) {\n throw new Error(\n `Could not determine target Telegram chat ID for target: ${JSON.stringify(target)}`\n );\n }\n\n try {\n // Use existing MessageManager method, pass chatId and content\n // Assuming sendMessage handles splitting, markdown, etc.\n await this.messageManager.sendMessage(chatId, content);\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, chatId }, 'Message sent');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending message');\n throw error;\n }\n }\n}\n","import {\n ChannelType,\n type Content,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Media,\n type Memory,\n ModelType,\n ServiceType,\n type UUID,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport type { Chat, Message, ReactionType, Update, Document } from '@telegraf/types';\nimport type { Context, NarrowedContext, Telegraf } from 'telegraf';\nimport { Markup } from 'telegraf';\nimport {\n type TelegramContent,\n TelegramEventTypes,\n type TelegramMessageSentPayload,\n type TelegramReactionReceivedPayload,\n} from './types';\nimport { convertToTelegramButtons, convertMarkdownToTelegram, cleanText } from './utils';\nimport fs from 'fs';\n\n/**\n * Interface for structured document processing results.\n */\ninterface DocumentProcessingResult {\n title: string;\n fullText: string;\n formattedDescription: string;\n fileName: string;\n mimeType: string | undefined;\n fileSize: number | undefined;\n error?: string;\n}\n\n/**\n * Enum representing different types of media.\n * @enum { string }\n * @readonly\n */\nexport enum MediaType {\n PHOTO = 'photo',\n VIDEO = 'video',\n DOCUMENT = 'document',\n AUDIO = 'audio',\n ANIMATION = 'animation',\n}\n\nconst MAX_MESSAGE_LENGTH = 4096; // Telegram's max message length\n\nconst getChannelType = (chat: Chat): ChannelType => {\n // Use a switch statement for clarity and exhaustive checks\n switch (chat.type) {\n case 'private':\n return ChannelType.DM;\n case 'group':\n case 'supergroup':\n case 'channel':\n return ChannelType.GROUP;\n default:\n throw new Error(`Unrecognized Telegram chat type: ${(chat as any).type}`);\n }\n};\n\n/**\n * Class representing a message manager.\n * @class\n */\nexport class MessageManager {\n public bot: Telegraf<Context>;\n protected runtime: IAgentRuntime;\n\n /**\n * Constructor for creating a new instance of a BotAgent.\n *\n * @param {Telegraf<Context>} bot - The Telegraf instance used for interacting with the bot platform.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n */\n constructor(bot: Telegraf<Context>, runtime: IAgentRuntime) {\n this.bot = bot;\n this.runtime = runtime;\n }\n\n /**\n * Process an image from a Telegram message to extract the image URL and description.\n *\n * @param {Message} message - The Telegram message object containing the image.\n * @returns {Promise<{ description: string } | null>} The description of the processed image or null if no image found.\n */\n async processImage(message: Message): Promise<{ description: string } | null> {\n try {\n let imageUrl: string | null = null;\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, messageId: message.message_id }, 'Processing image from message');\n\n if ('photo' in message && message.photo?.length > 0) {\n const photo = message.photo[message.photo.length - 1];\n const fileLink = await this.bot.telegram.getFileLink(photo.file_id);\n imageUrl = fileLink.toString();\n } else if (\n 'document' in message &&\n message.document?.mime_type?.startsWith('image/') &&\n !message.document?.mime_type?.startsWith('application/pdf')\n ) {\n const fileLink = await this.bot.telegram.getFileLink(message.document.file_id);\n imageUrl = fileLink.toString();\n }\n\n if (imageUrl) {\n const { title, description } = await this.runtime.useModel(\n ModelType.IMAGE_DESCRIPTION,\n imageUrl\n );\n return { description: `[Image: ${title}\\n${description}]` };\n }\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing image');\n }\n\n return null;\n }\n\n /**\n * Process a document from a Telegram message to extract the document URL and description.\n * Handles PDFs and other document types by converting them to text when possible.\n *\n * @param {Message} message - The Telegram message object containing the document.\n * @returns {Promise<{ description: string } | null>} The description of the processed document or null if no document found.\n */\n async processDocument(message: Message): Promise<DocumentProcessingResult | null> {\n try {\n if (!('document' in message) || !message.document) {\n return null;\n }\n\n const document = message.document;\n const fileLink = await this.bot.telegram.getFileLink(document.file_id);\n const documentUrl = fileLink.toString();\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, mimeType: document.mime_type, fileSize: document.file_size }, 'Processing document');\n\n // Centralized document processing based on MIME type\n const documentProcessor = this.getDocumentProcessor(document.mime_type);\n if (documentProcessor) {\n return await documentProcessor(document, documentUrl);\n }\n\n // Generic fallback for unsupported types\n return {\n title: `Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[Document: ${document.file_name || 'Unknown Document'}\\nType: ${document.mime_type || 'unknown'}\\nSize: ${document.file_size || 0} bytes]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');\n return null;\n }\n }\n\n /**\n * Get the appropriate document processor based on MIME type.\n */\n private getDocumentProcessor(\n mimeType?: string\n ): ((document: Document, url: string) => Promise<DocumentProcessingResult>) | null {\n if (!mimeType) return null;\n\n const processors = {\n 'application/pdf': this.processPdfDocument.bind(this),\n 'text/': this.processTextDocument.bind(this), // covers text/plain, text/csv, text/markdown, etc.\n 'application/json': this.processTextDocument.bind(this),\n };\n\n for (const [pattern, processor] of Object.entries(processors)) {\n if (mimeType.startsWith(pattern)) {\n return processor;\n }\n }\n\n return null;\n }\n\n /**\n * Process PDF documents by converting them to text.\n */\n private async processPdfDocument(\n document: Document,\n documentUrl: string\n ): Promise<DocumentProcessingResult> {\n try {\n const pdfService = this.runtime.getService(ServiceType.PDF) as any;\n if (!pdfService) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'PDF service not available, using fallback');\n return {\n title: `PDF Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nUnable to extract text content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n\n const response = await fetch(documentUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch PDF: ${response.status}`);\n }\n\n const pdfBuffer = await response.arrayBuffer();\n const text = await pdfService.convertPdfToText(Buffer.from(pdfBuffer));\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'PDF processed successfully');\n return {\n title: document.file_name || 'Unknown Document',\n fullText: text,\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nText extracted successfully: ${text.length} characters]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing PDF document');\n return {\n title: `PDF Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nError: Unable to extract text content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n }\n\n /**\n * Process text documents by fetching their content.\n */\n private async processTextDocument(\n document: Document,\n documentUrl: string\n ): Promise<DocumentProcessingResult> {\n try {\n const response = await fetch(documentUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch text document: ${response.status}`);\n }\n\n const text = await response.text();\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'Text document processed successfully');\n return {\n title: document.file_name || 'Unknown Document',\n fullText: text,\n formattedDescription: `[Text Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nText extracted successfully: ${text.length} characters]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing text document');\n return {\n title: `Text Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[Text Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nError: Unable to read content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n }\n\n /**\n * Processes the message content, documents, and images to generate\n * processed content and media attachments.\n *\n * @param {Message} message The message to process\n * @returns {Promise<{ processedContent: string; attachments: Media[] }>} Processed content and media attachments\n */\n async processMessage(\n message: Message\n ): Promise<{ processedContent: string; attachments: Media[] }> {\n let processedContent = '';\n let attachments: Media[] = [];\n\n // Get message text\n if ('text' in message && message.text) {\n processedContent = message.text;\n } else if ('caption' in message && message.caption) {\n processedContent = message.caption as string;\n }\n\n // Process documents\n if ('document' in message && message.document) {\n const document = message.document;\n const documentInfo = await this.processDocument(message);\n\n if (documentInfo) {\n try {\n const fileLink = await this.bot.telegram.getFileLink(document.file_id);\n\n // Use structured data directly instead of regex parsing\n const title = documentInfo.title;\n const fullText = documentInfo.fullText;\n\n // Add document content to processedContent so agent can access it\n if (fullText) {\n const documentContent = `\\n\\n--- DOCUMENT CONTENT ---\\nTitle: ${title}\\n\\nFull Content:\\n${fullText}\\n--- END DOCUMENT ---\\n\\n`;\n processedContent += documentContent;\n }\n\n attachments.push({\n id: document.file_id,\n url: fileLink.toString(),\n title: title,\n source: document.mime_type?.startsWith('application/pdf') ? 'PDF' : 'Document',\n description: documentInfo.formattedDescription,\n text: fullText,\n });\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName }, 'Document processed successfully');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');\n // Add a fallback attachment even if processing failed\n attachments.push({\n id: document.file_id,\n url: '',\n title: `Document: ${documentInfo.fileName}`,\n source: 'Document',\n description: `Document processing failed: ${documentInfo.fileName}`,\n text: `Document: ${documentInfo.fileName}\\nSize: ${documentInfo.fileSize || 0} bytes\\nType: ${documentInfo.mimeType || 'unknown'}`,\n });\n }\n } else {\n // Add a basic attachment even if documentInfo is null\n attachments.push({\n id: document.file_id,\n url: '',\n title: `Document: ${document.file_name || 'Unknown Document'}`,\n source: 'Document',\n description: `Document: ${document.file_name || 'Unknown Document'}`,\n text: `Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nType: ${document.mime_type || 'unknown'}`,\n });\n }\n }\n\n // Process images\n if ('photo' in message && message.photo?.length > 0) {\n const imageInfo = await this.processImage(message);\n if (imageInfo) {\n const photo = message.photo[message.photo.length - 1];\n const fileLink = await this.bot.telegram.getFileLink(photo.file_id);\n attachments.push({\n id: photo.file_id,\n url: fileLink.toString(),\n title: 'Image Attachment',\n source: 'Image',\n description: imageInfo.description,\n text: imageInfo.description,\n });\n }\n }\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, hasContent: !!processedContent, attachmentsCount: attachments.length }, 'Message processed');\n\n return { processedContent, attachments };\n }\n\n /**\n * Sends a message in chunks, handling attachments and splitting the message if necessary\n *\n * @param {Context} ctx - The context object representing the current state of the bot\n * @param {TelegramContent} content - The content of the message to be sent\n * @param {number} [replyToMessageId] - The ID of the message to reply to, if any\n * @returns {Promise<Message.TextMessage[]>} - An array of TextMessage objects representing the messages sent\n */\n async sendMessageInChunks(\n ctx: Context,\n content: TelegramContent,\n replyToMessageId?: number\n ): Promise<Message.TextMessage[]> {\n if (content.attachments && content.attachments.length > 0) {\n content.attachments.map(async (attachment: Media) => {\n const typeMap: { [key: string]: MediaType } = {\n 'image/gif': MediaType.ANIMATION,\n image: MediaType.PHOTO,\n doc: MediaType.DOCUMENT,\n video: MediaType.VIDEO,\n audio: MediaType.AUDIO,\n };\n\n let mediaType: MediaType | undefined = undefined;\n\n for (const prefix in typeMap) {\n if (attachment.contentType?.startsWith(prefix)) {\n mediaType = typeMap[prefix];\n break;\n }\n }\n\n if (!mediaType) {\n throw new Error(\n `Unsupported Telegram attachment content type: ${attachment.contentType}`\n );\n }\n\n await this.sendMedia(ctx, attachment.url, mediaType, attachment.description);\n });\n return [];\n } else {\n const chunks = this.splitMessage(content.text ?? '');\n const sentMessages: Message.TextMessage[] = [];\n\n const telegramButtons = convertToTelegramButtons(content.buttons ?? []);\n\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks: ctx.chat is undefined');\n return [];\n }\n await ctx.telegram.sendChatAction(ctx.chat.id, 'typing');\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = convertMarkdownToTelegram(chunks[i]);\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks loop: ctx.chat is undefined');\n continue;\n }\n const sentMessage = (await ctx.telegram.sendMessage(ctx.chat.id, chunk, {\n reply_parameters:\n i === 0 && replyToMessageId ? { message_id: replyToMessageId } : undefined,\n parse_mode: 'MarkdownV2',\n ...Markup.inlineKeyboard(telegramButtons),\n })) as Message.TextMessage;\n\n sentMessages.push(sentMessage);\n }\n\n return sentMessages;\n }\n }\n\n /**\n * Sends media to a chat using the Telegram API.\n *\n * @param {Context} ctx - The context object containing information about the current chat.\n * @param {string} mediaPath - The path to the media to be sent, either a URL or a local file path.\n * @param {MediaType} type - The type of media being sent (PHOTO, VIDEO, DOCUMENT, AUDIO, or ANIMATION).\n * @param {string} [caption] - Optional caption for the media being sent.\n *\n * @returns {Promise<void>} A Promise that resolves when the media is successfully sent.\n */\n async sendMedia(\n ctx: Context,\n mediaPath: string,\n type: MediaType,\n caption?: string\n ): Promise<void> {\n try {\n const isUrl = /^(http|https):\\/\\//.test(mediaPath);\n const sendFunctionMap: Record<MediaType, Function> = {\n [MediaType.PHOTO]: ctx.telegram.sendPhoto.bind(ctx.telegram),\n [MediaType.VIDEO]: ctx.telegram.sendVideo.bind(ctx.telegram),\n [MediaType.DOCUMENT]: ctx.telegram.sendDocument.bind(ctx.telegram),\n [MediaType.AUDIO]: ctx.telegram.sendAudio.bind(ctx.telegram),\n [MediaType.ANIMATION]: ctx.telegram.sendAnimation.bind(ctx.telegram),\n };\n\n const sendFunction = sendFunctionMap[type];\n\n if (!sendFunction) {\n throw new Error(`Unsupported media type: ${type}`);\n }\n\n if (!ctx.chat) {\n throw new Error('sendMedia: ctx.chat is undefined');\n }\n\n if (isUrl) {\n // Handle HTTP URLs\n await sendFunction(ctx.chat.id, mediaPath, { caption });\n } else {\n // Handle local file paths\n if (!fs.existsSync(mediaPath)) {\n throw new Error(`File not found at path: ${mediaPath}`);\n }\n\n const fileStream = fs.createReadStream(mediaPath);\n\n try {\n if (!ctx.chat) {\n throw new Error('sendMedia (file): ctx.chat is undefined');\n }\n await sendFunction(ctx.chat.id, { source: fileStream }, { caption });\n } finally {\n fileStream.destroy();\n }\n }\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath }, 'Media sent successfully');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath, error: error instanceof Error ? error.message : String(error) }, 'Failed to send media');\n throw error;\n }\n }\n\n /**\n * Splits a given text into an array of strings based on the maximum message length.\n *\n * @param {string} text - The text to split into chunks.\n * @returns {string[]} An array of strings with each element representing a chunk of the original text.\n */\n private splitMessage(text: string): string[] {\n const chunks: string[] = [];\n if (!text) return chunks;\n let currentChunk = '';\n\n const lines = text.split('\\n');\n for (const line of lines) {\n if (currentChunk.length + line.length + 1 <= MAX_MESSAGE_LENGTH) {\n currentChunk += (currentChunk ? '\\n' : '') + line;\n } else {\n if (currentChunk) chunks.push(currentChunk);\n currentChunk = line;\n }\n }\n\n if (currentChunk) chunks.push(currentChunk);\n return chunks;\n }\n\n /**\n * Handle incoming messages from Telegram and process them accordingly.\n * @param {Context} ctx - The context object containing information about the message.\n * @returns {Promise<void>}\n */\n public async handleMessage(ctx: Context): Promise<void> {\n // Type guard to ensure message exists\n if (!ctx.message || !ctx.from) return;\n\n const message = ctx.message as Message.TextMessage;\n\n try {\n // Convert IDs to UUIDs\n const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID;\n\n const threadId =\n 'is_topic_message' in message && message.is_topic_message\n ? message.message_thread_id?.toString()\n : undefined;\n\n // Add null check for ctx.chat\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'handleMessage: ctx.chat is undefined');\n return;\n }\n // Generate room ID based on whether this is in a forum topic\n const telegramRoomid = threadId ? `${ctx.chat.id}-${threadId}` : ctx.chat.id.toString();\n const roomId = createUniqueUuid(this.runtime, telegramRoomid) as UUID;\n\n // Get message ID (unique to channel)\n const messageId = createUniqueUuid(this.runtime, message?.message_id?.toString());\n\n // Process message content and attachments\n const { processedContent, attachments } = await this.processMessage(message);\n\n // Clean processedContent and attachments to avoid NULL characters\n const cleanedContent = cleanText(processedContent);\n const cleanedAttachments = attachments.map((att) => ({\n ...att,\n text: cleanText(att.text),\n description: cleanText(att.description),\n title: cleanText(att.title),\n }));\n\n if (!cleanedContent && cleanedAttachments.length === 0) {\n return;\n }\n\n // Get chat type and determine channel type\n const chat = message.chat as Chat;\n const channelType = getChannelType(chat);\n\n const sourceId = createUniqueUuid(this.runtime, '' + chat.id);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: ctx.from.username,\n name: ctx.from.first_name,\n source: 'telegram',\n channelId: telegramRoomid,\n serverId: undefined,\n type: channelType,\n worldId: createUniqueUuid(this.runtime, roomId) as UUID,\n worldName: telegramRoomid,\n });\n\n // Create the memory object\n const memory: Memory = {\n id: messageId,\n entityId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n text: cleanedContent || ' ',\n attachments: cleanedAttachments,\n source: 'telegram',\n channelType: channelType,\n inReplyTo:\n 'reply_to_message' in message && message.reply_to_message\n ? createUniqueUuid(this.runtime, message.reply_to_message.message_id.toString())\n : undefined,\n },\n metadata: {\n entityName: ctx.from.first_name,\n entityUserName: ctx.from.username,\n fromBot: ctx.from.is_bot,\n // include very technical/exact reference to this user for security reasons\n // don't remove or change this, spartan needs this\n fromId: chat.id,\n sourceId,\n // why message? all Memories contain content (which is basically a message)\n // what are the other types? see MemoryType\n type: 'message', // MemoryType.MESSAGE\n // scope: `shared`, `private`, or `room`\n },\n createdAt: message.date * 1000,\n };\n\n // Create callback for handling responses\n const callback: HandlerCallback = async (content: Content, _files?: string[]) => {\n try {\n // If response is from reasoning do not send it.\n if (!content.text) return [];\n\n let sentMessages: boolean | Message.TextMessage[] = false;\n // channelType target === 'telegram'\n if (content?.channelType === 'DM') {\n sentMessages = [];\n if (ctx.from) {\n // FIXME split on 4096 chars\n const res = await this.bot.telegram.sendMessage(ctx.from.id, content.text);\n sentMessages.push(res);\n }\n } else {\n sentMessages = await this.sendMessageInChunks(ctx, content, message.message_id);\n }\n\n if (!Array.isArray(sentMessages)) return [];\n\n const memories: Memory[] = [];\n for (let i = 0; i < sentMessages.length; i++) {\n const sentMessage = sentMessages[i];\n\n const responseMemory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n source: 'telegram',\n text: sentMessage.text,\n inReplyTo: messageId,\n channelType: channelType,\n },\n createdAt: sentMessage.date * 1000,\n };\n\n await this.runtime.createMemory(responseMemory, 'messages');\n memories.push(responseMemory);\n }\n\n return memories;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in message callback');\n return [];\n }\n };\n\n // Call the message handler directly instead of emitting events\n // This provides a clearer, more traceable flow for message processing\n if (!this.runtime.messageService) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'Message service is not available');\n throw new Error(\n 'Message service is not initialized. Ensure the message service is properly configured.'\n );\n }\n await this.runtime.messageService.handleMessage(this.runtime, memory, callback);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: ctx.chat?.id, messageId: ctx.message?.message_id, from: ctx.from?.username || ctx.from?.id, error: error instanceof Error ? error.message : String(error) }, 'Error handling Telegram message');\n throw error;\n }\n }\n\n /**\n * Handles the reaction event triggered by a user reacting to a message.\n * @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update\n * @returns {Promise<void>} A Promise that resolves when the reaction handling is complete\n */\n public async handleReaction(\n ctx: NarrowedContext<Context<Update>, Update.MessageReactionUpdate>\n ): Promise<void> {\n // Ensure we have the necessary data\n if (!ctx.update.message_reaction || !ctx.from) return;\n\n const reaction = ctx.update.message_reaction;\n const reactedToMessageId = reaction.message_id;\n\n const originalMessagePlaceholder: Partial<Message> = {\n message_id: reactedToMessageId,\n chat: reaction.chat,\n from: ctx.from,\n date: Math.floor(Date.now() / 1000),\n };\n\n const reactionType = reaction.new_reaction[0].type;\n const reactionEmoji = (reaction.new_reaction[0] as ReactionType).type; // Assuming ReactionType has 'type' for emoji\n\n try {\n const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID;\n const roomId = createUniqueUuid(this.runtime, ctx.chat.id.toString());\n\n const reactionId = createUniqueUuid(\n this.runtime,\n `${reaction.message_id}-${ctx.from.id}-${Date.now()}`\n );\n\n // Create reaction memory\n const memory: Memory = {\n id: reactionId,\n entityId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n channelType: getChannelType(reaction.chat as Chat),\n text: `Reacted with: ${reactionType === 'emoji' ? reactionEmoji : reactionType}`,\n source: 'telegram',\n inReplyTo: createUniqueUuid(this.runtime, reaction.message_id.toString()),\n },\n createdAt: Date.now(),\n };\n\n // Create callback for handling reaction responses\n const callback: HandlerCallback = async (content: Content) => {\n try {\n // Add null check for content.text\n const replyText = content.text ?? '';\n const sentMessage = await ctx.reply(replyText);\n const responseMemory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n inReplyTo: reactionId,\n },\n createdAt: sentMessage.date * 1000,\n };\n return [responseMemory];\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in reaction callback');\n return [];\n }\n };\n\n // Let the bootstrap plugin handle the reaction\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n ctx,\n originalMessage: originalMessagePlaceholder as Message, // Cast needed due to placeholder\n reactionString: reactionType === 'emoji' ? reactionEmoji : reactionType,\n originalReaction: reaction.new_reaction[0] as ReactionType,\n } as TelegramReactionReceivedPayload);\n\n // Also emit the platform-specific event\n this.runtime.emitEvent(TelegramEventTypes.REACTION_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n ctx,\n originalMessage: originalMessagePlaceholder as Message, // Cast needed due to placeholder\n reactionString: reactionType === 'emoji' ? reactionEmoji : reactionType,\n originalReaction: reaction.new_reaction[0] as ReactionType,\n } as TelegramReactionReceivedPayload);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling reaction');\n }\n }\n\n /**\n * Sends a message to a Telegram chat and emits appropriate events\n * @param {number | string} chatId - The Telegram chat ID to send the message to\n * @param {Content} content - The content to send\n * @param {number} [replyToMessageId] - Optional message ID to reply to\n * @returns {Promise<Message.TextMessage[]>} The sent messages\n */\n public async sendMessage(\n chatId: number | string,\n content: Content,\n replyToMessageId?: number\n ): Promise<Message.TextMessage[]> {\n try {\n // Create a context-like object for sending\n const ctx = {\n chat: { id: chatId },\n telegram: this.bot.telegram,\n };\n\n const sentMessages = await this.sendMessageInChunks(\n ctx as Context,\n content,\n replyToMessageId\n );\n\n if (!sentMessages?.length) return [];\n\n // Create group ID\n const roomId = createUniqueUuid(this.runtime, chatId.toString());\n\n // Create memories for the sent messages\n const memories: Memory[] = [];\n for (const sentMessage of sentMessages) {\n const memory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n text: sentMessage.text,\n source: 'telegram',\n channelType: getChannelType({\n id: typeof chatId === 'string' ? Number.parseInt(chatId, 10) : chatId,\n type: 'private', // Default to private, will be overridden if in context\n } as Chat),\n },\n createdAt: sentMessage.date * 1000,\n };\n\n await this.runtime.createMemory(memory, 'messages');\n memories.push(memory);\n }\n\n // Emit both generic and platform-specific message sent events\n this.runtime.emitEvent(EventType.MESSAGE_SENT, {\n runtime: this.runtime,\n message: {\n content: content,\n },\n roomId,\n source: 'telegram',\n });\n\n // Also emit platform-specific event\n this.runtime.emitEvent(TelegramEventTypes.MESSAGE_SENT, {\n originalMessages: sentMessages,\n chatId,\n } as TelegramMessageSentPayload);\n\n return sentMessages;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending message to Telegram');\n return [];\n }\n }\n}\n","import { Markup } from 'telegraf';\nimport type { Button } from './types';\nimport type { InlineKeyboardButton } from '@telegraf/types';\nimport { logger } from '@elizaos/core';\n\n// A list of Telegram MarkdownV2 reserved characters that must be escaped\nconst TELEGRAM_RESERVED_REGEX = /([_*[\\]()~`>#+\\-=|{}.!\\\\])/g;\n\n/**\n * Escapes plain text for Telegram MarkdownV2.\n * (Any character in 1–126 that is reserved is prefixed with a backslash.)\n */\nfunction escapePlainText(text: string): string {\n if (!text) return '';\n return text.replace(TELEGRAM_RESERVED_REGEX, '\\\\$1');\n}\n\n/**\n * Escapes plain text line‐by–line while preserving any leading blockquote markers.\n */\nfunction escapePlainTextPreservingBlockquote(text: string): string {\n if (!text) return '';\n return text\n .split('\\n')\n .map((line) => {\n // If the line begins with one or more \">\" (and optional space),\n // leave that part unescaped.\n const match = line.match(/^(>+\\s?)(.*)$/);\n if (match) {\n return match[1] + escapePlainText(match[2]);\n }\n return escapePlainText(line);\n })\n .join('\\n');\n}\n\n/**\n * Escapes code inside inline or pre-formatted code blocks.\n * Telegram requires that inside code blocks all ` and \\ characters are escaped.\n */\nfunction escapeCode(text: string): string {\n if (!text) return '';\n return text.replace(/([`\\\\])/g, '\\\\$1');\n}\n\n/**\n * Escapes a URL for inline links:\n * inside the URL, only \")\" and \"\\\" need to be escaped.\n */\nfunction escapeUrl(url: string): string {\n if (!url) return '';\n return url.replace(/([)\\\\])/g, '\\\\$1');\n}\n\n/**\n * This function converts standard markdown to Telegram MarkdownV2.\n *\n * In addition to processing code blocks, inline code, links, bold, strikethrough, and italic,\n * it converts any header lines (those starting with one or more `#`) to bold text.\n *\n * Note: This solution uses a sequence of regex‐replacements and placeholders.\n * It makes assumptions about non–nested formatting and does not cover every edge case.\n */\nexport function convertMarkdownToTelegram(markdown: string): string {\n // We will temporarily replace recognized markdown tokens with placeholders.\n // Each placeholder is a string like \"\\u0000{index}\\u0000\".\n const replacements: string[] = [];\n function storeReplacement(formatted: string): string {\n const placeholder = `\\u0000${replacements.length}\\u0000`;\n replacements.push(formatted);\n return placeholder;\n }\n\n let converted = markdown;\n\n // 1. Fenced code blocks (```...```)\n // Matches an optional language (letters only) and then any content until the closing ```\n converted = converted.replace(/```(\\w+)?\\n([\\s\\S]*?)```/g, (_match, lang, code) => {\n const escapedCode = escapeCode(code);\n const formatted = '```' + (lang || '') + '\\n' + escapedCode + '```';\n return storeReplacement(formatted);\n });\n\n // 2. Inline code (`...`)\n converted = converted.replace(/`([^`]+)`/g, (_match, code) => {\n const escapedCode = escapeCode(code);\n const formatted = '`' + escapedCode + '`';\n return storeReplacement(formatted);\n });\n\n // 3. Links: [link text](url)\n converted = converted.replace(\n /$begin:math:display$([^$end:math:display$]+)]$begin:math:text$([^)]+)$end:math:text$/g,\n (_match, text, url) => {\n // For link text we escape as plain text.\n const formattedText = escapePlainText(text);\n const escapedURL = escapeUrl(url);\n const formatted = `[${formattedText}](${escapedURL})`;\n return storeReplacement(formatted);\n }\n );\n\n // 4. Bold text: standard markdown bold **text**\n // Telegram bold is delimited by single asterisks: *text*\n converted = converted.replace(/\\*\\*([^*]+)\\*\\*/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `*${formattedContent}*`;\n return storeReplacement(formatted);\n });\n\n // 5. Strikethrough: standard markdown uses ~~text~~,\n // while Telegram uses ~text~\n converted = converted.replace(/~~([^~]+)~~/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `~${formattedContent}~`;\n return storeReplacement(formatted);\n });\n\n // 6. Italic text:\n // Standard markdown italic can be written as either *text* or _text_.\n // In Telegram MarkdownV2 italic must be delimited by underscores.\n // Process asterisk-based italic first.\n // (Using negative lookbehind/lookahead to avoid matching bold **)\n converted = converted.replace(/(?<!\\*)\\*([^*\\n]+)\\*(?!\\*)/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `_${formattedContent}_`;\n return storeReplacement(formatted);\n });\n // Then underscore-based italic.\n converted = converted.replace(/_([^_\\n]+)_/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `_${formattedContent}_`;\n return storeReplacement(formatted);\n });\n\n // 7. Headers: Convert markdown headers (lines starting with '#' characters)\n // to bold text. This avoids unescaped '#' characters (which crash Telegram)\n // by removing them and wrapping the rest of the line in bold markers.\n converted = converted.replace(/^(#{1,6})\\s*(.*)$/gm, (_match, _hashes, headerContent: string) => {\n // Remove any trailing whitespace and escape the header text.\n const formatted = `*${escapePlainText(headerContent.trim())}*`;\n return storeReplacement(formatted);\n });\n\n // Define the placeholder marker as a string constant\n const NULL_CHAR = String.fromCharCode(0);\n const PLACEHOLDER_PATTERN = new RegExp(`(${NULL_CHAR}\\\\d+${NULL_CHAR})`, 'g');\n const PLACEHOLDER_TEST = new RegExp(`^${NULL_CHAR}\\\\d+${NULL_CHAR}$`);\n const PLACEHOLDER_REPLACE = new RegExp(`${NULL_CHAR}(\\\\d+)${NULL_CHAR}`, 'g');\n\n const finalEscaped = converted\n .split(PLACEHOLDER_PATTERN)\n .map((segment) => {\n // If the segment is a placeholder (matches the pattern), leave it untouched.\n if (PLACEHOLDER_TEST.test(segment)) {\n return segment;\n } else {\n // Otherwise, escape it while preserving any leading blockquote markers.\n return escapePlainTextPreservingBlockquote(segment);\n }\n })\n .join('');\n\n // Finally, substitute back all placeholders with their preformatted content.\n const finalResult = finalEscaped.replace(PLACEHOLDER_REPLACE, (_, index) => {\n return replacements[parseInt(index)];\n });\n\n return finalResult;\n}\n\n/**\n * Splits a message into chunks that fit within Telegram's message length limit\n */\n/**\n * Splits a text message into chunks based on a maximum length for each chunk.\n *\n * @param {string} text - The text message to split.\n * @param {number} maxLength - The maximum length for each chunk (default is 4096).\n * @returns {string[]} An array containing the text message split into chunks.\n */\nexport function splitMessage(text: string, maxLength = 4096): string[] {\n const chunks: string[] = [];\n if (!text) return chunks;\n let currentChunk = '';\n\n const lines = text.split('\\n');\n for (const line of lines) {\n if (currentChunk.length + line.length + 1 <= maxLength) {\n currentChunk += (currentChunk ? '\\n' : '') + line;\n } else {\n if (currentChunk) chunks.push(currentChunk);\n currentChunk = line;\n }\n }\n\n if (currentChunk) chunks.push(currentChunk);\n return chunks;\n}\n\n/**\n * Converts Eliza buttons into Telegram buttons\n * @param {Button[]} buttons - The buttons from Eliza content\n * @returns {InlineKeyboardButton[]} Array of Telegram buttons\n */\nexport function convertToTelegramButtons(buttons?: Button[] | null): InlineKeyboardButton[] {\n if (!buttons) return [];\n const telegramButtons: InlineKeyboardButton[] = [];\n\n for (const button of buttons) {\n // Validate button has required properties\n if (!button || !button.text || !button.url) {\n logger.warn({ button }, 'Invalid button configuration, skipping');\n continue;\n }\n\n let telegramButton: InlineKeyboardButton;\n switch (button.kind) {\n case 'login':\n telegramButton = Markup.button.login(button.text, button.url);\n break;\n case 'url':\n telegramButton = Markup.button.url(button.text, button.url);\n break;\n default:\n logger.warn({ src: 'plugin:telegram', buttonKind: button.kind }, 'Unknown button kind, treating as URL button');\n telegramButton = Markup.button.url(button.text, button.url);\n break;\n }\n\n telegramButtons.push(telegramButton);\n }\n\n return telegramButtons;\n}\n\n/**\n * Clean text by removing all NULL (\\u0000) characters\n * @param {string | undefined | null} text - The text to clean\n * @returns {string} The cleaned text\n */\nexport function cleanText(text: string | undefined | null): string {\n if (!text) return '';\n // Avoid control char in regex literal; lint-friendly\n return text.split('\\u0000').join('');\n}\n","import { type IAgentRuntime, type TestSuite, logger } from '@elizaos/core';\nimport type { Chat, User } from '@telegraf/types';\nimport type { Telegraf } from 'telegraf';\nimport type { Context } from 'telegraf';\nimport type { MessageManager } from './messageManager';\nimport type { TelegramService } from './service';\nimport type { TelegramContent } from './types';\n\nconst TEST_IMAGE_URL =\n 'https://github.com/elizaOS/awesome-eliza/blob/main/assets/eliza-logo.jpg?raw=true';\n\n/**\n * Represents a test suite for testing Telegram functionality.\n *\n * This test suite includes methods to initialize and validate a Telegram bot connection,\n * send basic text messages to a Telegram chat, send text messages with image attachments,\n * handle and process incoming Telegram messages, and process and validate image attachments\n * in incoming messages.\n *\n * @implements {TestSuite}\n */\n\nexport class TelegramTestSuite implements TestSuite {\n name = 'telegram';\n private telegramClient: TelegramService | null = null;\n private bot: Telegraf<Context> | null = null;\n private messageManager: MessageManager | null = null;\n tests: { name: string; fn: (runtime: IAgentRuntime) => Promise<void> }[];\n\n /**\n * Constructor for initializing a set of test cases for a Telegram bot.\n *\n * @constructor\n * @property {Array<Object>} tests - An array of test cases with name and corresponding test functions.\n * @property {string} tests.name - The name of the test case.\n * @property {function} tests.fn - The test function to be executed.\n */\n constructor() {\n this.tests = [\n {\n name: 'Initialize and Validate Telegram Bot Connection',\n fn: this.testCreatingTelegramBot.bind(this),\n },\n {\n name: 'Send Basic Text Message to Telegram Chat',\n fn: this.testSendingTextMessage.bind(this),\n },\n {\n name: 'Send Text Message with an Image Attachment',\n fn: this.testSendingMessageWithAttachment.bind(this),\n },\n {\n name: 'Handle and Process Incoming Telegram Messages',\n fn: this.testHandlingMessage.bind(this),\n },\n {\n name: 'Process and Validate Image Attachments in Incoming Messages',\n fn: this.testProcessingImages.bind(this),\n },\n ];\n }\n\n /**\n * Retrieves the Telegram test chat ID from environment variables.\n *\n * Reference on getting the Telegram chat ID:\n * https://stackoverflow.com/a/32572159\n */\n /**\n * Validates the chat ID by checking if it is set in the runtime settings or environment variables.\n * If not set, an error is thrown with a message instructing to provide a valid chat ID.\n * @param {IAgentRuntime} runtime - The runtime object that provides access to the settings and environment variables.\n * @throws {Error} If TELEGRAM_TEST_CHAT_ID is not set in the runtime settings or environment variables.\n * @returns {string} The validated chat ID.\n */\n validateChatId(runtime: IAgentRuntime) {\n const testChatId =\n runtime.getSetting('TELEGRAM_TEST_CHAT_ID') || process.env.TELEGRAM_TEST_CHAT_ID;\n if (!testChatId) {\n throw new Error(\n 'TELEGRAM_TEST_CHAT_ID is not set. Please provide a valid chat ID in the environment variables.'\n );\n }\n return testChatId;\n }\n\n async getChatInfo(runtime: IAgentRuntime): Promise<Context['chat']> {\n try {\n const chatId = this.validateChatId(runtime);\n if (!this.bot) {\n throw new Error('Bot is not initialized.');\n }\n const chat = await this.bot.telegram.getChat(chatId);\n logger.debug({ src: 'plugin:telegram', chatId }, 'Fetched real chat');\n return chat;\n } catch (error) {\n throw new Error(`Error fetching real Telegram chat: ${error}`);\n }\n }\n\n async testCreatingTelegramBot(runtime: IAgentRuntime) {\n this.telegramClient = runtime.getService('telegram') as TelegramService;\n if (!this.telegramClient || !this.telegramClient.messageManager) {\n throw new Error(\n 'Telegram service or message manager not initialized - check TELEGRAM_BOT_TOKEN'\n );\n }\n this.bot = this.telegramClient.messageManager.bot;\n this.messageManager = this.telegramClient.messageManager;\n logger.debug({ src: 'plugin:telegram' }, 'Telegram bot initialized successfully');\n }\n\n async testSendingTextMessage(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n\n const chatId = this.validateChatId(runtime);\n await this.bot.telegram.sendMessage(chatId, 'Testing Telegram message!');\n logger.debug({ src: 'plugin:telegram', chatId }, 'Message sent successfully');\n } catch (error) {\n throw new Error(`Error sending Telegram message: ${error}`);\n }\n }\n\n async testSendingMessageWithAttachment(runtime: IAgentRuntime) {\n try {\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n if (!this.bot) throw new Error('Bot not initialized.');\n\n const chat = await this.getChatInfo(runtime);\n const mockContext: Partial<Context> = {\n chat,\n from: { id: 123, username: 'TestUser' } as User,\n telegram: this.bot.telegram,\n };\n\n const messageContent = {\n text: 'Here is an image attachment:',\n attachments: [\n {\n id: '123',\n title: 'Sample Image',\n source: TEST_IMAGE_URL,\n text: 'Sample Image',\n url: TEST_IMAGE_URL,\n contentType: 'image/png',\n description: 'Sample Image',\n },\n ],\n };\n\n await this.messageManager.sendMessageInChunks(\n mockContext as Context,\n messageContent as TelegramContent\n );\n\n logger.success({ src: 'plugin:telegram' }, 'Message with image attachment sent successfully');\n } catch (error) {\n throw new Error(`Error sending Telegram message with attachment: ${error}`);\n }\n }\n\n async testHandlingMessage(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n\n const chat = await this.getChatInfo(runtime);\n const mockContext: Partial<Context> = {\n chat,\n from: {\n id: 123,\n username: 'TestUser',\n is_bot: false,\n first_name: 'Test',\n last_name: 'User',\n } as User,\n message: {\n message_id: undefined,\n text: `@${this.bot.botInfo?.username}! Hello!`,\n date: Math.floor(Date.now() / 1000),\n chat,\n } as any,\n telegram: this.bot.telegram,\n };\n\n try {\n await this.messageManager.handleMessage(mockContext as Context);\n } catch (error) {\n throw new Error(`Error handling Telegram message: ${error}`);\n }\n } catch (error) {\n throw new Error(`Error handling Telegram message: ${error}`);\n }\n }\n\n async testProcessingImages(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n\n const chatId = this.validateChatId(runtime);\n const fileId = await this.getFileId(chatId, TEST_IMAGE_URL);\n\n const mockMessage = {\n message_id: 12345,\n chat: { id: chatId, type: 'private' } as Chat,\n date: Math.floor(Date.now() / 1000),\n photo: [\n {\n file_id: fileId,\n file_unique_id: `unique_${fileId}`,\n width: 100,\n height: 100,\n },\n ],\n text: `@${this.bot.botInfo?.username}!`,\n };\n\n const result = await this.messageManager.processImage(mockMessage as any);\n if (!result || !result.description) {\n throw new Error('Error processing Telegram image or description not found');\n }\n const { description } = result;\n logger.debug({ src: 'plugin:telegram', description }, 'Processing Telegram image successfully');\n } catch (error) {\n throw new Error(`Error processing Telegram image: ${error}`);\n }\n }\n\n async getFileId(chatId: string, imageUrl: string) {\n try {\n if (!this.bot) {\n throw new Error('Bot is not initialized.');\n }\n const message = await this.bot.telegram.sendPhoto(chatId, imageUrl);\n if (!message.photo || message.photo.length === 0) {\n throw new Error('No photo received in the message response.');\n }\n return message.photo[message.photo.length - 1].file_id;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending image');\n throw error;\n }\n }\n}\n","import type { Plugin } from '@elizaos/core';\nimport { TELEGRAM_SERVICE_NAME } from './constants';\nimport { TelegramService } from './service';\nimport { TelegramTestSuite } from './tests';\nimport { MessageManager } from './messageManager';\n\nconst telegramPlugin: Plugin = {\n name: TELEGRAM_SERVICE_NAME,\n description: 'Telegram client plugin',\n services: [TelegramService],\n tests: [new TelegramTestSuite()],\n};\n\nexport { TelegramService, MessageManager };\nexport default telegramPlugin;\n"],"mappings":";AAAO,IAAM,oBAAoB;AAAA,EAC/B,cAAc;AAAA,EACd,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,8BAA8B;AAAA,EAC9B,yCAAyC;AAAA,EACzC,qBAAqB,IAAI,KAAK;AAAA;AAAA,EAC9B,wBAAwB,IAAI,KAAK;AAAA;AACnC;AAEO,IAAM,wBAAwB;;;ACVrC;AAAA,EACE,eAAAA;AAAA,EAGA,aAAAC;AAAA,EAEA;AAAA,EAEA;AAAA,EAIA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;AACP,SAAuB,gBAAgB;;;ACfvC;A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A,QACF;AAAA,QACA,MAAM,IAAI,KAAK,IAAI,SAAS,QAAQ;AAAA,MACtC;AAEA,YAAM,SAAS,MAAM,KAAK,eAAe,aAAa,WAAkB;AACxE,UAAI,CAAC,UAAU,CAAC,OAAO,aAAa;AAClC,cAAM,IAAI,MAAM,0DAA0D;AAAA,MAC5E;AACA,YAAM,EAAE,YAAY,IAAI;AACxB,MAAAA,QAAO,MAAM,EAAE,KAAK,mBAAmB,YAAY,GAAG,wCAAwC;AAAA,IAChG,SAAS,OAAO;AACd,YAAM,IAAI,MAAM,oCAAoC,KAAK,EAAE;AAAA,IAC7D;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,QAAgB,UAAkB;AAChD,QAAI;AACF,UAAI,CAAC,KAAK,KAAK;AACb,cAAM,IAAI,MAAM,yBAAyB;AAAA,MAC3C;AACA,YAAM,UAAU,MAAM,KAAK,IAAI,SAAS,UAAU,QAAQ,QAAQ;AAClE,UAAI,CAAC,QAAQ,SAAS,QAAQ,MAAM,WAAW,GAAG;AAChD,cAAM,IAAI,MAAM,4CAA4C;AAAA,MAC9D;AACA,aAAO,QAAQ,MAAM,QAAQ,MAAM,SAAS,CAAC,EAAE;AAAA,IACjD,SAAS,OAAO;AACd,MAAAA,QAAO,MAAM,EAAE,KAAK,mBAAmB,QAAQ,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,GAAG,qBAAqB;AACrI,YAAM;AAAA,IACR;AAAA,EACF;AACF;;;AC/OA,IAAM,iBAAyB;AAAA,EAC7B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU,CAAC,eAAe;AAAA,EAC1B,OAAO,CAAC,IAAI,kBAAkB,CAAC;AACjC;AAGA,IAAO,gBAAQ;","names":["ChannelType","EventType","createUniqueUuid","logger","logger","Markup","logger","Markup","logger","createUniqueUuid","ChannelType","EventType","logger"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/service.ts","../src/messageManager.ts","../src/utils.ts","../src/tests.ts","../src/index.ts"],"sourcesContent":["export const MESSAGE_CONSTANTS = {\n MAX_MESSAGES: 50,\n RECENT_MESSAGE_COUNT: 5,\n CHAT_HISTORY_COUNT: 10,\n DEFAULT_SIMILARITY_THRESHOLD: 0.6,\n DEFAULT_SIMILARITY_THRESHOLD_FOLLOW_UPS: 0.4,\n INTEREST_DECAY_TIME: 5 * 60 * 1000, // 5 minutes\n PARTIAL_INTEREST_DECAY: 3 * 60 * 1000, // 3 minutes\n} as const;\n\nexport const TELEGRAM_SERVICE_NAME = 'telegram';\n","import {\n ChannelType,\n type Content,\n type Entity,\n EventType,\n type IAgentRuntime,\n Role,\n type Room,\n Service,\n type TargetInfo,\n type UUID,\n type World,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport { type Context, Telegraf } from 'telegraf';\nimport { type ChatMemberOwner, type ChatMemberAdministrator, type User } from 'telegraf/types';\nimport { TELEGRAM_SERVICE_NAME } from './constants';\nimport { MessageManager } from './messageManager';\nimport { TelegramEventTypes, type TelegramWorldPayload } from './types';\n\n/**\n * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.\n * This service handles all Telegram-specific functionality including:\n * - Initializing and managing the Telegram bot\n * - Setting up middleware for preprocessing messages\n * - Handling message and reaction events\n * - Synchronizing Telegram chats, users, and entities with the agent runtime\n * - Managing forum topics as separate rooms\n *\n * @extends Service\n */\nexport class TelegramService extends Service {\n static serviceType = TELEGRAM_SERVICE_NAME;\n capabilityDescription = 'The agent is able to send and receive messages on telegram';\n private bot: Telegraf<Context> | null;\n public messageManager: MessageManager | null;\n private options;\n private knownChats: Map<string, any> = new Map();\n private syncedEntityIds: Set<string> = new Set<string>();\n\n /**\n * Constructor for TelegramService class.\n * @param {IAgentRuntime} runtime - The runtime object for the agent.\n */\n constructor(runtime: IAgentRuntime) {\n super(runtime);\n logger.debug({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Constructing TelegramService');\n\n // Check if Telegram bot token is available and valid\n const botToken = runtime.getSetting('TELEGRAM_BOT_TOKEN') as string;\n if (!botToken || botToken.trim() === '') {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Bot token not provided, Telegram functionality unavailable');\n this.bot = null;\n this.messageManager = null;\n return;\n }\n\n this.options = {\n telegram: {\n apiRoot:\n runtime.getSetting('TELEGRAM_API_ROOT') ||\n process.env.TELEGRAM_API_ROOT ||\n 'https://api.telegram.org',\n },\n };\n\n try {\n this.bot = new Telegraf(botToken, this.options);\n this.messageManager = new MessageManager(this.bot, this.runtime);\n logger.debug({ src: 'plugin:telegram', agentId: runtime.agentId }, 'TelegramService constructor completed');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Failed to initialize Telegram bot');\n this.bot = null;\n this.messageManager = null;\n }\n }\n\n /**\n * Starts the Telegram service for the given runtime.\n *\n * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.\n * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.\n */\n static async start(runtime: IAgentRuntime): Promise<TelegramService> {\n // Remove validateTelegramConfig call to allow service to start without token\n\n const service = new TelegramService(runtime);\n\n // If bot is not initialized (no token), return the service without further initialization\n if (!service.bot) {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Service started without bot functionality');\n return service;\n }\n\n const maxRetries = 5;\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, agentName: runtime.character.name }, 'Starting Telegram bot');\n await service.initializeBot();\n\n // Set up middlewares before message handlers to ensure proper preprocessing\n service.setupMiddlewares();\n\n // Set up message handlers after middlewares\n service.setupMessageHandlers();\n\n // Wait for bot to be ready by testing getMe()\n await service.bot!.telegram.getMe();\n\n logger.success({ src: 'plugin:telegram', agentId: runtime.agentId, agentName: runtime.character.name }, 'Telegram bot started successfully');\n return service;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, attempt: retryCount + 1, error: lastError.message }, 'Initialization attempt failed');\n retryCount++;\n\n if (retryCount < maxRetries) {\n const delay = 2 ** retryCount * 1000; // Exponential backoff\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, delaySeconds: delay / 1000 }, 'Retrying initialization');\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, maxRetries, error: lastError?.message }, 'Initialization failed after all attempts');\n\n // Return the service even if initialization failed, to prevent server crash\n return service;\n }\n\n /**\n * Stops the agent runtime.\n * @param {IAgentRuntime} runtime - The agent runtime to stop\n */\n static async stop(runtime: IAgentRuntime) {\n // Implement shutdown if necessary\n const tgClient = runtime.getService(TELEGRAM_SERVICE_NAME);\n if (tgClient) {\n await tgClient.stop();\n }\n }\n\n /**\n * Asynchronously stops the bot.\n *\n * @returns A Promise that resolves once the bot has stopped.\n */\n async stop(): Promise<void> {\n this.bot?.stop();\n }\n\n /**\n * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.\n * @returns {Promise<void>} A Promise that resolves when the initialization is complete.\n */\n private async initializeBot(): Promise<void> {\n this.bot?.start((ctx) => {\n this.runtime.emitEvent(\n TelegramEventTypes.SLASH_START as string,\n {\n ctx,\n runtime: this.runtime,\n source: 'telegram',\n } as any\n );\n });\n this.bot?.launch({\n dropPendingUpdates: true,\n allowedUpdates: ['message', 'message_reaction'],\n });\n\n // Get bot info for identification purposes\n const botInfo = await this.bot!.telegram.getMe();\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, botId: botInfo.id, botUsername: botInfo.username }, 'Bot info retrieved');\n\n // Handle sigint and sigterm signals to gracefully stop the bot\n process.once('SIGINT', () => this.bot?.stop('SIGINT'));\n process.once('SIGTERM', () => this.bot?.stop('SIGTERM'));\n }\n\n /**\n * Sets up the middleware chain for preprocessing messages before they reach handlers.\n * This critical method establishes a sequential processing pipeline that:\n *\n * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings\n * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed\n * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management\n * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities\n *\n * The middleware chain runs in sequence for each message, with each step potentially\n * enriching the context or stopping processing if conditions aren't met.\n * This preprocessing is essential for maintaining consistent state before message handlers execute.\n *\n * @private\n */\n private setupMiddlewares(): void {\n // Register the authorization middleware\n this.bot?.use(this.authorizationMiddleware.bind(this));\n\n // Register the chat and entity management middleware\n this.bot?.use(this.chatAndEntityMiddleware.bind(this));\n }\n\n /**\n * Authorization middleware - checks if chat is allowed to interact with the bot\n * based on the TELEGRAM_ALLOWED_CHATS configuration.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {Function} next - The function to call to proceed to the next middleware\n * @returns {Promise<void>}\n * @private\n */\n private async authorizationMiddleware(ctx: Context, next: Function): Promise<void> {\n if (!(await this.isGroupAuthorized(ctx))) {\n // Skip further processing if chat is not authorized\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: ctx.chat?.id }, 'Chat not authorized, skipping');\n return;\n }\n await next();\n }\n\n /**\n * Chat and entity management middleware - handles new chats, forum topics, and entity synchronization.\n * This middleware implements decision logic to determine which operations are needed based on\n * the chat type and whether we've seen this chat before.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {Function} next - The function to call to proceed to the next middleware\n * @returns {Promise<void>}\n * @private\n */\n private async chatAndEntityMiddleware(ctx: Context, next: Function): Promise<void> {\n if (!ctx.chat) return next();\n\n const chatId = ctx.chat.id.toString();\n\n // If we haven't seen this chat before, process it as a new chat\n if (!this.knownChats.has(chatId)) {\n // Process the new chat - creates world, room, topic room (if applicable) and entities\n await this.handleNewChat(ctx);\n // Skip entity synchronization for new chats and proceed to the next middleware\n return next();\n }\n\n // For existing chats, determine the required operations based on chat type\n await this.processExistingChat(ctx);\n\n await next();\n }\n\n /**\n * Process an existing chat based on chat type and message properties.\n * Different chat types require different processing steps.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async processExistingChat(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n\n // Handle forum topics for supergroups with forums\n if (chat.type === 'supergroup' && chat.is_forum && ctx.message?.message_thread_id) {\n try {\n await this.handleForumTopic(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, 'Error handling forum topic');\n }\n }\n\n // For non-private chats, synchronize entity information\n if (ctx.from && ctx.chat.type !== 'private') {\n await this.syncEntity(ctx);\n }\n }\n\n /**\n * Sets up message and reaction handlers for the bot.\n * Configures event handlers to process incoming messages and reactions.\n *\n * @private\n */\n private setupMessageHandlers(): void {\n // Regular message handler\n this.bot?.on('message', async (ctx) => {\n try {\n // Message handling is now simplified since all preprocessing is done by middleware\n await this.messageManager!.handleMessage(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling message');\n }\n });\n\n // Reaction handler\n this.bot?.on('message_reaction', async (ctx) => {\n try {\n await this.messageManager!.handleReaction(ctx);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling reaction');\n }\n });\n }\n\n /**\n * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.\n * @param {Context} ctx - The context of the incoming update.\n * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.\n */\n private async isGroupAuthorized(ctx: Context): Promise<boolean> {\n const chatId = ctx.chat?.id.toString();\n if (!chatId) return false;\n\n const allowedChats = this.runtime.getSetting('TELEGRAM_ALLOWED_CHATS');\n if (!allowedChats) {\n return true;\n }\n\n try {\n const allowedChatsList = JSON.parse(allowedChats as string);\n return allowedChatsList.includes(chatId);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error parsing TELEGRAM_ALLOWED_CHATS');\n return false;\n }\n }\n\n /**\n * Synchronizes an entity from a message context with the runtime system.\n * This method handles three cases:\n * 1. Message sender - most common case\n * 2. New chat member - when a user joins the chat\n * 3. Left chat member - when a user leaves the chat\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async syncEntity(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n const roomId = createUniqueUuid(\n this.runtime,\n ctx.message?.message_thread_id\n ? `${ctx.chat.id}-${ctx.message.message_thread_id}`\n : ctx.chat.id.toString()\n ) as UUID;\n\n // Handle all three entity sync cases separately for clarity\n await this.syncMessageSender(ctx, worldId, roomId, chatId);\n await this.syncNewChatMember(ctx, worldId, roomId, chatId);\n await this.syncLeftChatMember(ctx);\n }\n\n /**\n * Synchronizes the message sender entity with the runtime system.\n * This is the most common entity sync case.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world\n * @param {UUID} roomId - The ID of the room\n * @param {string} chatId - The ID of the chat\n * @returns {Promise<void>}\n * @private\n */\n private async syncMessageSender(\n ctx: Context,\n worldId: UUID,\n roomId: UUID,\n chatId: string\n ): Promise<void> {\n // Handle message sender\n if (ctx.from && !this.syncedEntityIds.has(ctx.from.id.toString())) {\n const telegramId = ctx.from.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n await this.runtime.ensureConnection({\n entityId,\n roomId: roomId,\n userName: ctx.from.username,\n userId: telegramId as UUID,\n name: ctx.from.first_name || ctx.from.username || 'Unknown User',\n source: 'telegram',\n channelId: chatId,\n type: ChannelType.GROUP,\n worldId: worldId,\n });\n\n this.syncedEntityIds.add(entityId);\n }\n }\n\n /**\n * Synchronizes a new chat member entity with the runtime system.\n * Triggered when a user joins the chat.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world\n * @param {UUID} roomId - The ID of the room\n * @param {string} chatId - The ID of the chat\n * @returns {Promise<void>}\n * @private\n */\n private async syncNewChatMember(\n ctx: Context,\n worldId: UUID,\n roomId: UUID,\n chatId: string\n ): Promise<void> {\n // Handle new chat member\n if (ctx.message && 'new_chat_member' in ctx.message) {\n const newMember = ctx.message.new_chat_member as any;\n const telegramId = newMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n // Skip if we've already synced this entity\n if (this.syncedEntityIds.has(telegramId)) return;\n\n // We call ensure connection here for this user.\n await this.runtime.ensureConnection({\n entityId,\n roomId: roomId,\n userName: newMember.username,\n userId: telegramId as UUID,\n name: newMember.first_name || newMember.username || 'Unknown User',\n source: 'telegram',\n channelId: chatId,\n type: ChannelType.GROUP,\n worldId: worldId,\n });\n\n this.syncedEntityIds.add(entityId);\n\n this.runtime.emitEvent(\n TelegramEventTypes.ENTITY_JOINED as string,\n {\n runtime: this.runtime,\n entityId,\n worldId,\n source: 'telegram',\n telegramUser: {\n id: newMember.id,\n username: newMember.username,\n first_name: newMember.first_name,\n },\n } as any\n );\n }\n }\n\n /**\n * Updates entity status when a user leaves the chat.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async syncLeftChatMember(ctx: Context): Promise<void> {\n // Handle left chat member\n if (ctx.message && 'left_chat_member' in ctx.message) {\n const leftMember = ctx.message.left_chat_member as any;\n const telegramId = leftMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n const existingEntity = await this.runtime.getEntityById(entityId);\n if (existingEntity) {\n existingEntity.metadata = {\n ...existingEntity.metadata,\n status: 'INACTIVE',\n leftAt: Date.now(),\n };\n await this.runtime.updateEntity(existingEntity);\n }\n }\n }\n\n /**\n * Handles forum topics by creating appropriate rooms in the runtime system.\n * This enables proper conversation management for Telegram's forum feature.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async handleForumTopic(ctx: Context): Promise<void> {\n if (!ctx.chat || !ctx.message?.message_thread_id) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n\n const room = await this.buildForumTopicRoom(ctx, worldId);\n if (!room) return;\n\n await this.runtime.ensureRoomExists(room);\n }\n\n /**\n * Builds entity for message sender\n */\n private buildMsgSenderEntity(from: User): Entity | null {\n if (!from) return null;\n\n const userId = createUniqueUuid(this.runtime, from.id.toString()) as UUID;\n const telegramId = from.id.toString();\n\n return {\n id: userId,\n agentId: this.runtime.agentId,\n names: [from.first_name || from.username || 'Unknown User'],\n metadata: {\n telegram: {\n id: telegramId,\n username: from.username,\n name: from.first_name || from.username || 'Unknown User',\n },\n },\n };\n }\n\n /**\n * Handles new chat discovery and emits WORLD_JOINED event.\n * This is a critical function that ensures new chats are properly\n * registered in the runtime system and appropriate events are emitted.\n *\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n * @private\n */\n private async handleNewChat(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n\n // Mark this chat as known\n this.knownChats.set(chatId, chat);\n\n // Get chat title and channel type\n const { chatTitle, channelType } = this.getChatTypeInfo(chat);\n\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n\n const existingWorld = await this.runtime.getWorld(worldId);\n if (existingWorld) {\n return;\n }\n\n const userId = ctx.from\n ? (createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID)\n : null;\n\n // Fetch admin information for proper role assignment\n let admins: (ChatMemberOwner | ChatMemberAdministrator)[] = [];\n let owner: ChatMemberOwner | null = null;\n if (chat.type === 'group' || chat.type === 'supergroup' || chat.type === 'channel') {\n try {\n const chatAdmins = await ctx.getChatAdministrators();\n admins = chatAdmins;\n const foundOwner = admins.find(\n (admin): admin is ChatMemberOwner => admin.status === 'creator'\n );\n owner = foundOwner || null;\n } catch (error) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Could not get chat administrators');\n }\n }\n\n let ownerId = userId;\n\n if (owner) {\n ownerId = createUniqueUuid(this.runtime, String(owner.user.id)) as UUID;\n }\n\n // Build world representation\n const world: World = {\n id: worldId,\n name: chatTitle,\n agentId: this.runtime.agentId,\n serverId: chatId as UUID,\n metadata: {\n source: 'telegram',\n ...(ownerId && { ownership: { ownerId } }),\n roles: ownerId\n ? {\n [ownerId]: Role.OWNER,\n }\n : {},\n chatType: chat.type,\n isForumEnabled: chat.type === 'supergroup' && chat.is_forum,\n },\n };\n\n // Directly ensure world exists instead of using syncTelegram\n await this.runtime.ensureWorldExists(world);\n\n // Create the main room for the chat\n const generalRoom: Room = {\n id: createUniqueUuid(this.runtime, chatId) as UUID,\n name: chatTitle,\n source: 'telegram',\n type: channelType,\n channelId: chatId,\n serverId: chatId as UUID,\n worldId,\n };\n\n // Directly ensure room exists instead of using syncTelegram\n await this.runtime.ensureRoomExists(generalRoom);\n\n // Prepare the rooms array starting with the main room\n const rooms = [generalRoom];\n\n // If this is a message in a forum topic, add the topic room as well\n if (chat.type === 'supergroup' && chat.is_forum && ctx.message?.message_thread_id) {\n const topicRoom = await this.buildForumTopicRoom(ctx, worldId);\n if (topicRoom) {\n rooms.push(topicRoom);\n await this.runtime.ensureRoomExists(topicRoom);\n }\n }\n\n // Build entities from chat\n const entities = await this.buildStandardizedEntities(chat);\n\n // Add sender if not already in entities\n if (ctx.from) {\n const senderEntity = this.buildMsgSenderEntity(ctx.from);\n if (senderEntity && senderEntity.id && !entities.some((e) => e.id === senderEntity.id)) {\n entities.push(senderEntity);\n this.syncedEntityIds.add(senderEntity.id);\n }\n }\n\n // Use the new batch processing method for entities\n await this.batchProcessEntities(\n entities,\n generalRoom.id!,\n generalRoom.channelId!,\n generalRoom.type,\n worldId\n );\n\n // Create payload for world events\n const telegramWorldPayload: TelegramWorldPayload = {\n runtime: this.runtime,\n world,\n rooms,\n entities,\n source: 'telegram',\n chat,\n botUsername: this.bot?.botInfo?.username,\n };\n\n // Emit telegram-specific world joined event\n if (chat.type !== 'private') {\n await this.runtime.emitEvent(TelegramEventTypes.WORLD_JOINED, telegramWorldPayload);\n }\n\n // Finally emit the standard WORLD_JOINED event\n await this.runtime.emitEvent(EventType.WORLD_JOINED, {\n runtime: this.runtime,\n world,\n rooms,\n entities,\n source: 'telegram',\n });\n }\n\n /**\n * Processes entities in batches to prevent overwhelming the system.\n *\n * @param {Entity[]} entities - The entities to process\n * @param {UUID} roomId - The ID of the room to connect entities to\n * @param {string} channelId - The channel ID\n * @param {ChannelType} roomType - The type of the room\n * @param {UUID} worldId - The ID of the world\n * @returns {Promise<void>}\n * @private\n */\n private async batchProcessEntities(\n entities: Entity[],\n roomId: UUID,\n channelId: string,\n roomType: ChannelType,\n worldId: UUID\n ): Promise<void> {\n const batchSize = 50;\n\n for (let i = 0; i < entities.length; i += batchSize) {\n const entityBatch = entities.slice(i, i + batchSize);\n\n // Process each entity in the batch concurrently\n await Promise.all(\n entityBatch.map(async (entity: Entity) => {\n try {\n if (entity.id) {\n const telegramMetadata = entity.metadata?.telegram as\n | {\n username?: string;\n name?: string;\n id?: string;\n }\n | undefined;\n\n await this.runtime.ensureConnection({\n entityId: entity.id,\n roomId: roomId,\n userName: telegramMetadata?.username,\n name: telegramMetadata?.name,\n userId: telegramMetadata?.id as UUID,\n source: 'telegram',\n channelId: channelId,\n type: roomType,\n worldId: worldId,\n });\n } else {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, entityNames: entity.names }, 'Skipping entity sync due to missing ID');\n }\n } catch (err) {\n const telegramMetadata = entity.metadata?.telegram as\n | {\n username?: string;\n }\n | undefined;\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, username: telegramMetadata?.username, error: err instanceof Error ? err.message : String(err) }, 'Failed to sync user');\n }\n })\n );\n\n // Add a small delay between batches if not the last batch\n if (i + batchSize < entities.length) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n }\n }\n }\n\n /**\n * Gets chat title and channel type based on Telegram chat type.\n * Maps Telegram-specific chat types to standardized system types.\n *\n * @param {any} chat - The Telegram chat object\n * @returns {Object} Object containing chatTitle and channelType\n * @private\n */\n private getChatTypeInfo(chat: any): { chatTitle: string; channelType: ChannelType } {\n let chatTitle: string;\n let channelType: ChannelType;\n\n switch (chat.type) {\n case 'private':\n chatTitle = `Chat with ${chat.first_name || 'Unknown User'}`;\n channelType = ChannelType.DM;\n break;\n case 'group':\n chatTitle = chat.title || 'Unknown Group';\n channelType = ChannelType.GROUP;\n break;\n case 'supergroup':\n chatTitle = chat.title || 'Unknown Supergroup';\n channelType = ChannelType.GROUP;\n break;\n case 'channel':\n chatTitle = chat.title || 'Unknown Channel';\n channelType = ChannelType.FEED;\n break;\n default:\n chatTitle = 'Unknown Chat';\n channelType = ChannelType.GROUP;\n }\n\n return { chatTitle, channelType };\n }\n\n /**\n * Builds standardized entity representations from Telegram chat data.\n * Transforms Telegram-specific user data into system-standard Entity objects.\n *\n * @param {any} chat - The Telegram chat object\n * @returns {Promise<Entity[]>} Array of standardized Entity objects\n * @private\n */\n private async buildStandardizedEntities(chat: any): Promise<Entity[]> {\n const entities: Entity[] = [];\n\n try {\n // For private chats, add the user\n if (chat.type === 'private' && chat.id) {\n const userId = createUniqueUuid(this.runtime, chat.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [chat.first_name || 'Unknown User'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: chat.id.toString(),\n username: chat.username || 'unknown',\n name: chat.first_name || 'Unknown User',\n },\n source: 'telegram',\n },\n });\n this.syncedEntityIds.add(userId);\n } else if (chat.type === 'group' || chat.type === 'supergroup') {\n // For groups and supergroups, try to get member information\n try {\n // Get chat administrators (this is what's available through the Bot API)\n const admins = await this.bot?.telegram.getChatAdministrators(chat.id);\n\n if (admins && admins.length > 0) {\n for (const admin of admins) {\n const userId = createUniqueUuid(this.runtime, admin.user.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [admin.user.first_name || admin.user.username || 'Unknown Admin'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: admin.user.id.toString(),\n username: admin.user.username || 'unknown',\n name: admin.user.first_name || 'Unknown Admin',\n isAdmin: true,\n adminTitle:\n admin.custom_title || (admin.status === 'creator' ? 'Owner' : 'Admin'),\n },\n source: 'telegram',\n roles: [admin.status === 'creator' ? Role.OWNER : Role.ADMIN],\n },\n });\n this.syncedEntityIds.add(userId);\n }\n }\n } catch (error) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, 'Could not fetch administrators');\n }\n }\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error building standardized entities');\n }\n\n return entities;\n }\n\n /**\n * Extracts and builds the room object for a forum topic from a message context.\n * This refactored method can be used both in middleware and when handling new chats.\n *\n * @param {Context} ctx - The context of the incoming update\n * @param {UUID} worldId - The ID of the world the topic belongs to\n * @returns {Promise<Room | null>} A Promise that resolves with the room or null if not a topic\n * @private\n */\n private async buildForumTopicRoom(ctx: Context, worldId: UUID): Promise<Room | null> {\n if (!ctx.chat || !ctx.message?.message_thread_id) return null;\n if (ctx.chat.type !== 'supergroup' || !ctx.chat.is_forum) return null;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const threadId = ctx.message.message_thread_id.toString();\n const roomId = createUniqueUuid(this.runtime, `${chatId}-${threadId}`) as UUID;\n\n try {\n // Ensure the message object is fully initialized\n const replyMessage = JSON.parse(JSON.stringify(ctx.message));\n\n // Default topic name\n let topicName = `Topic #${threadId}`;\n\n // Check if forum_topic_created exists directly in the message\n if (\n replyMessage &&\n typeof replyMessage === 'object' &&\n 'forum_topic_created' in replyMessage &&\n replyMessage.forum_topic_created\n ) {\n const topicCreated = replyMessage.forum_topic_created;\n if (topicCreated && typeof topicCreated === 'object' && 'name' in topicCreated) {\n topicName = topicCreated.name;\n }\n }\n // Check if forum_topic_created exists in reply_to_message\n else if (\n replyMessage &&\n typeof replyMessage === 'object' &&\n 'reply_to_message' in replyMessage &&\n replyMessage.reply_to_message &&\n typeof replyMessage.reply_to_message === 'object' &&\n 'forum_topic_created' in replyMessage.reply_to_message &&\n replyMessage.reply_to_message.forum_topic_created\n ) {\n const topicCreated = replyMessage.reply_to_message.forum_topic_created;\n if (topicCreated && typeof topicCreated === 'object' && 'name' in topicCreated) {\n topicName = topicCreated.name;\n }\n }\n\n // Create a room for this topic\n const room: Room = {\n id: roomId,\n name: topicName,\n source: 'telegram',\n type: ChannelType.GROUP,\n channelId: `${chatId}-${threadId}`,\n serverId: chatId as UUID,\n worldId,\n metadata: {\n threadId: threadId,\n isForumTopic: true,\n parentChatId: chatId,\n },\n };\n\n return room;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, threadId, error: error instanceof Error ? error.message : String(error) }, 'Error building forum topic room');\n return null;\n }\n }\n\n static registerSendHandlers(runtime: IAgentRuntime, serviceInstance: TelegramService) {\n if (serviceInstance && serviceInstance.bot) {\n runtime.registerSendHandler(\n 'telegram',\n serviceInstance.handleSendMessage.bind(serviceInstance)\n );\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Registered send handler');\n } else {\n logger.warn({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Cannot register send handler, bot not initialized');\n }\n }\n\n async handleSendMessage(\n runtime: IAgentRuntime,\n target: TargetInfo,\n content: Content\n ): Promise<void> {\n // Check if bot and messageManager are available\n if (!this.bot || !this.messageManager) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId }, 'Bot not initialized, cannot send messages');\n throw new Error('Telegram bot is not initialized. Please provide TELEGRAM_BOT_TOKEN.');\n }\n\n let chatId: number | string | undefined;\n\n // Determine the target chat ID\n if (target.channelId) {\n // Use channelId directly if provided (might be string like chat_id-thread_id or just chat_id)\n // We might need to parse this depending on how room IDs are stored vs Telegram IDs\n chatId = target.channelId;\n } else if (target.roomId) {\n // Fallback: Try to use roomId if channelId isn't available\n // This assumes roomId maps directly to Telegram chat ID or requires lookup\n // Placeholder - requires logic to map roomId -> telegram chat ID if different\n const room = await runtime.getRoom(target.roomId);\n chatId = room?.channelId; // Assuming channelId on Room IS the telegram ID\n if (!chatId)\n throw new Error(`Could not resolve Telegram chat ID from roomId ${target.roomId}`);\n } else if (target.entityId) {\n // TODO: Need robust way to map entityId (runtime UUID) to Telegram User ID (number)\n // This might involve checking entity metadata.\n // For now, this part is non-functional without that mapping.\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, entityId: target.entityId }, 'Sending DMs via entityId not implemented');\n throw new Error('Sending DMs via entityId is not yet supported for Telegram.');\n // Example placeholder: const telegramUserId = await getTelegramIdFromEntity(runtime, target.entityId);\n // chatId = telegramUserId;\n } else {\n throw new Error('Telegram SendHandler requires channelId, roomId, or entityId.');\n }\n\n if (!chatId) {\n throw new Error(\n `Could not determine target Telegram chat ID for target: ${JSON.stringify(target)}`\n );\n }\n\n try {\n // Use existing MessageManager method, pass chatId and content\n // Assuming sendMessage handles splitting, markdown, etc.\n await this.messageManager.sendMessage(chatId, content);\n logger.info({ src: 'plugin:telegram', agentId: runtime.agentId, chatId }, 'Message sent');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending message');\n throw error;\n }\n }\n}\n","import {\n ChannelType,\n type Content,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Media,\n type Memory,\n ModelType,\n ServiceType,\n type UUID,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport type { Chat, Message, ReactionType, Update, Document } from '@telegraf/types';\nimport type { Context, NarrowedContext, Telegraf } from 'telegraf';\nimport { Markup } from 'telegraf';\nimport {\n type TelegramContent,\n TelegramEventTypes,\n type TelegramReactionReceivedPayload,\n} from './types';\nimport { convertToTelegramButtons, convertMarkdownToTelegram, cleanText } from './utils';\nimport fs from 'fs';\n\n/**\n * Interface for structured document processing results.\n */\ninterface DocumentProcessingResult {\n title: string;\n fullText: string;\n formattedDescription: string;\n fileName: string;\n mimeType: string | undefined;\n fileSize: number | undefined;\n error?: string;\n}\n\n/**\n * Enum representing different types of media.\n * @enum { string }\n * @readonly\n */\nexport enum MediaType {\n PHOTO = 'photo',\n VIDEO = 'video',\n DOCUMENT = 'document',\n AUDIO = 'audio',\n ANIMATION = 'animation',\n}\n\nconst MAX_MESSAGE_LENGTH = 4096; // Telegram's max message length\n\nconst getChannelType = (chat: Chat): ChannelType => {\n // Use a switch statement for clarity and exhaustive checks\n switch (chat.type) {\n case 'private':\n return ChannelType.DM;\n case 'group':\n case 'supergroup':\n case 'channel':\n return ChannelType.GROUP;\n default:\n throw new Error(`Unrecognized Telegram chat type: ${(chat as any).type}`);\n }\n};\n\n/**\n * Class representing a message manager.\n * @class\n */\nexport class MessageManager {\n public bot: Telegraf<Context>;\n protected runtime: IAgentRuntime;\n\n /**\n * Constructor for creating a new instance of a BotAgent.\n *\n * @param {Telegraf<Context>} bot - The Telegraf instance used for interacting with the bot platform.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n */\n constructor(bot: Telegraf<Context>, runtime: IAgentRuntime) {\n this.bot = bot;\n this.runtime = runtime;\n }\n\n /**\n * Process an image from a Telegram message to extract the image URL and description.\n *\n * @param {Message} message - The Telegram message object containing the image.\n * @returns {Promise<{ description: string } | null>} The description of the processed image or null if no image found.\n */\n async processImage(message: Message): Promise<{ description: string } | null> {\n try {\n let imageUrl: string | null = null;\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, messageId: message.message_id }, 'Processing image from message');\n\n if ('photo' in message && message.photo?.length > 0) {\n const photo = message.photo[message.photo.length - 1];\n const fileLink = await this.bot.telegram.getFileLink(photo.file_id);\n imageUrl = fileLink.toString();\n } else if (\n 'document' in message &&\n message.document?.mime_type?.startsWith('image/') &&\n !message.document?.mime_type?.startsWith('application/pdf')\n ) {\n const fileLink = await this.bot.telegram.getFileLink(message.document.file_id);\n imageUrl = fileLink.toString();\n }\n\n if (imageUrl) {\n const { title, description } = await this.runtime.useModel(\n ModelType.IMAGE_DESCRIPTION,\n imageUrl\n );\n return { description: `[Image: ${title}\\n${description}]` };\n }\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing image');\n }\n\n return null;\n }\n\n /**\n * Process a document from a Telegram message to extract the document URL and description.\n * Handles PDFs and other document types by converting them to text when possible.\n *\n * @param {Message} message - The Telegram message object containing the document.\n * @returns {Promise<{ description: string } | null>} The description of the processed document or null if no document found.\n */\n async processDocument(message: Message): Promise<DocumentProcessingResult | null> {\n try {\n if (!('document' in message) || !message.document) {\n return null;\n }\n\n const document = message.document;\n const fileLink = await this.bot.telegram.getFileLink(document.file_id);\n const documentUrl = fileLink.toString();\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, mimeType: document.mime_type, fileSize: document.file_size }, 'Processing document');\n\n // Centralized document processing based on MIME type\n const documentProcessor = this.getDocumentProcessor(document.mime_type);\n if (documentProcessor) {\n return await documentProcessor(document, documentUrl);\n }\n\n // Generic fallback for unsupported types\n return {\n title: `Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[Document: ${document.file_name || 'Unknown Document'}\\nType: ${document.mime_type || 'unknown'}\\nSize: ${document.file_size || 0} bytes]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');\n return null;\n }\n }\n\n /**\n * Get the appropriate document processor based on MIME type.\n */\n private getDocumentProcessor(\n mimeType?: string\n ): ((document: Document, url: string) => Promise<DocumentProcessingResult>) | null {\n if (!mimeType) return null;\n\n const processors = {\n 'application/pdf': this.processPdfDocument.bind(this),\n 'text/': this.processTextDocument.bind(this), // covers text/plain, text/csv, text/markdown, etc.\n 'application/json': this.processTextDocument.bind(this),\n };\n\n for (const [pattern, processor] of Object.entries(processors)) {\n if (mimeType.startsWith(pattern)) {\n return processor;\n }\n }\n\n return null;\n }\n\n /**\n * Process PDF documents by converting them to text.\n */\n private async processPdfDocument(\n document: Document,\n documentUrl: string\n ): Promise<DocumentProcessingResult> {\n try {\n const pdfService = this.runtime.getService(ServiceType.PDF) as any;\n if (!pdfService) {\n logger.warn({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'PDF service not available, using fallback');\n return {\n title: `PDF Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nUnable to extract text content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n\n const response = await fetch(documentUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch PDF: ${response.status}`);\n }\n\n const pdfBuffer = await response.arrayBuffer();\n const text = await pdfService.convertPdfToText(Buffer.from(pdfBuffer));\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'PDF processed successfully');\n return {\n title: document.file_name || 'Unknown Document',\n fullText: text,\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nText extracted successfully: ${text.length} characters]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing PDF document');\n return {\n title: `PDF Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[PDF Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nError: Unable to extract text content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n }\n\n /**\n * Process text documents by fetching their content.\n */\n private async processTextDocument(\n document: Document,\n documentUrl: string\n ): Promise<DocumentProcessingResult> {\n try {\n const response = await fetch(documentUrl);\n if (!response.ok) {\n throw new Error(`Failed to fetch text document: ${response.status}`);\n }\n\n const text = await response.text();\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, 'Text document processed successfully');\n return {\n title: document.file_name || 'Unknown Document',\n fullText: text,\n formattedDescription: `[Text Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nText extracted successfully: ${text.length} characters]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, 'Error processing text document');\n return {\n title: `Text Document: ${document.file_name || 'Unknown Document'}`,\n fullText: '',\n formattedDescription: `[Text Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nError: Unable to read content]`,\n fileName: document.file_name || 'Unknown Document',\n mimeType: document.mime_type,\n fileSize: document.file_size,\n };\n }\n }\n\n /**\n * Processes the message content, documents, and images to generate\n * processed content and media attachments.\n *\n * @param {Message} message The message to process\n * @returns {Promise<{ processedContent: string; attachments: Media[] }>} Processed content and media attachments\n */\n async processMessage(\n message: Message\n ): Promise<{ processedContent: string; attachments: Media[] }> {\n let processedContent = '';\n let attachments: Media[] = [];\n\n // Get message text\n if ('text' in message && message.text) {\n processedContent = message.text;\n } else if ('caption' in message && message.caption) {\n processedContent = message.caption as string;\n }\n\n // Process documents\n if ('document' in message && message.document) {\n const document = message.document;\n const documentInfo = await this.processDocument(message);\n\n if (documentInfo) {\n try {\n const fileLink = await this.bot.telegram.getFileLink(document.file_id);\n\n // Use structured data directly instead of regex parsing\n const title = documentInfo.title;\n const fullText = documentInfo.fullText;\n\n // Add document content to processedContent so agent can access it\n if (fullText) {\n const documentContent = `\\n\\n--- DOCUMENT CONTENT ---\\nTitle: ${title}\\n\\nFull Content:\\n${fullText}\\n--- END DOCUMENT ---\\n\\n`;\n processedContent += documentContent;\n }\n\n attachments.push({\n id: document.file_id,\n url: fileLink.toString(),\n title: title,\n source: document.mime_type?.startsWith('application/pdf') ? 'PDF' : 'Document',\n description: documentInfo.formattedDescription,\n text: fullText,\n });\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName }, 'Document processed successfully');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, fileName: documentInfo.fileName, error: error instanceof Error ? error.message : String(error) }, 'Error processing document');\n // Add a fallback attachment even if processing failed\n attachments.push({\n id: document.file_id,\n url: '',\n title: `Document: ${documentInfo.fileName}`,\n source: 'Document',\n description: `Document processing failed: ${documentInfo.fileName}`,\n text: `Document: ${documentInfo.fileName}\\nSize: ${documentInfo.fileSize || 0} bytes\\nType: ${documentInfo.mimeType || 'unknown'}`,\n });\n }\n } else {\n // Add a basic attachment even if documentInfo is null\n attachments.push({\n id: document.file_id,\n url: '',\n title: `Document: ${document.file_name || 'Unknown Document'}`,\n source: 'Document',\n description: `Document: ${document.file_name || 'Unknown Document'}`,\n text: `Document: ${document.file_name || 'Unknown Document'}\\nSize: ${document.file_size || 0} bytes\\nType: ${document.mime_type || 'unknown'}`,\n });\n }\n }\n\n // Process images\n if ('photo' in message && message.photo?.length > 0) {\n const imageInfo = await this.processImage(message);\n if (imageInfo) {\n const photo = message.photo[message.photo.length - 1];\n const fileLink = await this.bot.telegram.getFileLink(photo.file_id);\n attachments.push({\n id: photo.file_id,\n url: fileLink.toString(),\n title: 'Image Attachment',\n source: 'Image',\n description: imageInfo.description,\n text: imageInfo.description,\n });\n }\n }\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, hasContent: !!processedContent, attachmentsCount: attachments.length }, 'Message processed');\n\n return { processedContent, attachments };\n }\n\n /**\n * Sends a message in chunks, handling attachments and splitting the message if necessary\n *\n * @param {Context} ctx - The context object representing the current state of the bot\n * @param {TelegramContent} content - The content of the message to be sent\n * @param {number} [replyToMessageId] - The ID of the message to reply to, if any\n * @returns {Promise<Message.TextMessage[]>} - An array of TextMessage objects representing the messages sent\n */\n async sendMessageInChunks(\n ctx: Context,\n content: TelegramContent,\n replyToMessageId?: number\n ): Promise<Message.TextMessage[]> {\n if (content.attachments && content.attachments.length > 0) {\n content.attachments.map(async (attachment: Media) => {\n const typeMap: { [key: string]: MediaType } = {\n 'image/gif': MediaType.ANIMATION,\n image: MediaType.PHOTO,\n doc: MediaType.DOCUMENT,\n video: MediaType.VIDEO,\n audio: MediaType.AUDIO,\n };\n\n let mediaType: MediaType | undefined = undefined;\n\n for (const prefix in typeMap) {\n if (attachment.contentType?.startsWith(prefix)) {\n mediaType = typeMap[prefix];\n break;\n }\n }\n\n if (!mediaType) {\n throw new Error(\n `Unsupported Telegram attachment content type: ${attachment.contentType}`\n );\n }\n\n await this.sendMedia(ctx, attachment.url, mediaType, attachment.description);\n });\n return [];\n } else {\n const chunks = this.splitMessage(content.text ?? '');\n const sentMessages: Message.TextMessage[] = [];\n\n const telegramButtons = convertToTelegramButtons(content.buttons ?? []);\n\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks: ctx.chat is undefined');\n return [];\n }\n await ctx.telegram.sendChatAction(ctx.chat.id, 'typing');\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = convertMarkdownToTelegram(chunks[i]);\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'sendMessageInChunks loop: ctx.chat is undefined');\n continue;\n }\n const sentMessage = (await ctx.telegram.sendMessage(ctx.chat.id, chunk, {\n reply_parameters:\n i === 0 && replyToMessageId ? { message_id: replyToMessageId } : undefined,\n parse_mode: 'MarkdownV2',\n ...Markup.inlineKeyboard(telegramButtons),\n })) as Message.TextMessage;\n\n sentMessages.push(sentMessage);\n }\n\n return sentMessages;\n }\n }\n\n /**\n * Sends media to a chat using the Telegram API.\n *\n * @param {Context} ctx - The context object containing information about the current chat.\n * @param {string} mediaPath - The path to the media to be sent, either a URL or a local file path.\n * @param {MediaType} type - The type of media being sent (PHOTO, VIDEO, DOCUMENT, AUDIO, or ANIMATION).\n * @param {string} [caption] - Optional caption for the media being sent.\n *\n * @returns {Promise<void>} A Promise that resolves when the media is successfully sent.\n */\n async sendMedia(\n ctx: Context,\n mediaPath: string,\n type: MediaType,\n caption?: string\n ): Promise<void> {\n try {\n const isUrl = /^(http|https):\\/\\//.test(mediaPath);\n const sendFunctionMap: Record<MediaType, Function> = {\n [MediaType.PHOTO]: ctx.telegram.sendPhoto.bind(ctx.telegram),\n [MediaType.VIDEO]: ctx.telegram.sendVideo.bind(ctx.telegram),\n [MediaType.DOCUMENT]: ctx.telegram.sendDocument.bind(ctx.telegram),\n [MediaType.AUDIO]: ctx.telegram.sendAudio.bind(ctx.telegram),\n [MediaType.ANIMATION]: ctx.telegram.sendAnimation.bind(ctx.telegram),\n };\n\n const sendFunction = sendFunctionMap[type];\n\n if (!sendFunction) {\n throw new Error(`Unsupported media type: ${type}`);\n }\n\n if (!ctx.chat) {\n throw new Error('sendMedia: ctx.chat is undefined');\n }\n\n if (isUrl) {\n // Handle HTTP URLs\n await sendFunction(ctx.chat.id, mediaPath, { caption });\n } else {\n // Handle local file paths\n if (!fs.existsSync(mediaPath)) {\n throw new Error(`File not found at path: ${mediaPath}`);\n }\n\n const fileStream = fs.createReadStream(mediaPath);\n\n try {\n if (!ctx.chat) {\n throw new Error('sendMedia (file): ctx.chat is undefined');\n }\n await sendFunction(ctx.chat.id, { source: fileStream }, { caption });\n } finally {\n fileStream.destroy();\n }\n }\n\n logger.debug({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath }, 'Media sent successfully');\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, mediaType: type, mediaPath, error: error instanceof Error ? error.message : String(error) }, 'Failed to send media');\n throw error;\n }\n }\n\n /**\n * Splits a given text into an array of strings based on the maximum message length.\n *\n * @param {string} text - The text to split into chunks.\n * @returns {string[]} An array of strings with each element representing a chunk of the original text.\n */\n private splitMessage(text: string): string[] {\n const chunks: string[] = [];\n if (!text) return chunks;\n let currentChunk = '';\n\n const lines = text.split('\\n');\n for (const line of lines) {\n if (currentChunk.length + line.length + 1 <= MAX_MESSAGE_LENGTH) {\n currentChunk += (currentChunk ? '\\n' : '') + line;\n } else {\n if (currentChunk) chunks.push(currentChunk);\n currentChunk = line;\n }\n }\n\n if (currentChunk) chunks.push(currentChunk);\n return chunks;\n }\n\n /**\n * Handle incoming messages from Telegram and process them accordingly.\n * @param {Context} ctx - The context object containing information about the message.\n * @returns {Promise<void>}\n */\n public async handleMessage(ctx: Context): Promise<void> {\n // Type guard to ensure message exists\n if (!ctx.message || !ctx.from) return;\n\n const message = ctx.message as Message.TextMessage;\n\n try {\n // Convert IDs to UUIDs\n const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID;\n\n const threadId =\n 'is_topic_message' in message && message.is_topic_message\n ? message.message_thread_id?.toString()\n : undefined;\n\n // Add null check for ctx.chat\n if (!ctx.chat) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'handleMessage: ctx.chat is undefined');\n return;\n }\n // Generate room ID based on whether this is in a forum topic\n const telegramRoomid = threadId ? `${ctx.chat.id}-${threadId}` : ctx.chat.id.toString();\n const roomId = createUniqueUuid(this.runtime, telegramRoomid) as UUID;\n\n // Get message ID (unique to channel)\n const messageId = createUniqueUuid(this.runtime, message?.message_id?.toString());\n\n // Process message content and attachments\n const { processedContent, attachments } = await this.processMessage(message);\n\n // Clean processedContent and attachments to avoid NULL characters\n const cleanedContent = cleanText(processedContent);\n const cleanedAttachments = attachments.map((att) => ({\n ...att,\n text: cleanText(att.text),\n description: cleanText(att.description),\n title: cleanText(att.title),\n }));\n\n if (!cleanedContent && cleanedAttachments.length === 0) {\n return;\n }\n\n // Get chat type and determine channel type\n const chat = message.chat as Chat;\n const channelType = getChannelType(chat);\n\n const sourceId = createUniqueUuid(this.runtime, '' + chat.id);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: ctx.from.username,\n name: ctx.from.first_name,\n source: 'telegram',\n channelId: telegramRoomid,\n type: channelType,\n worldId: createUniqueUuid(this.runtime, roomId) as UUID,\n worldName: telegramRoomid,\n });\n\n // Create the memory object\n const memory: Memory = {\n id: messageId,\n entityId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n text: cleanedContent || ' ',\n attachments: cleanedAttachments,\n source: 'telegram',\n channelType: channelType,\n inReplyTo:\n 'reply_to_message' in message && message.reply_to_message\n ? createUniqueUuid(this.runtime, message.reply_to_message.message_id.toString())\n : undefined,\n },\n metadata: {\n entityName: ctx.from.first_name,\n entityUserName: ctx.from.username,\n fromBot: ctx.from.is_bot,\n // include very technical/exact reference to this user for security reasons\n // don't remove or change this, spartan needs this\n fromId: chat.id,\n sourceId,\n // why message? all Memories contain content (which is basically a message)\n // what are the other types? see MemoryType\n type: 'message', // MemoryType.MESSAGE\n // scope: `shared`, `private`, or `room`\n },\n createdAt: message.date * 1000,\n };\n\n // Create callback for handling responses\n const callback: HandlerCallback = async (content: Content, _files?: string[]) => {\n try {\n // If response is from reasoning do not send it.\n if (!content.text) return [];\n\n let sentMessages: boolean | Message.TextMessage[] = false;\n // channelType target === 'telegram'\n if (content?.channelType === 'DM') {\n sentMessages = [];\n if (ctx.from) {\n // FIXME split on 4096 chars\n const res = await this.bot.telegram.sendMessage(ctx.from.id, content.text);\n sentMessages.push(res);\n }\n } else {\n sentMessages = await this.sendMessageInChunks(ctx, content, message.message_id);\n }\n\n if (!Array.isArray(sentMessages)) return [];\n\n const memories: Memory[] = [];\n for (let i = 0; i < sentMessages.length; i++) {\n const sentMessage = sentMessages[i];\n\n const responseMemory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n source: 'telegram',\n text: sentMessage.text,\n inReplyTo: messageId,\n channelType: channelType,\n },\n createdAt: sentMessage.date * 1000,\n };\n\n await this.runtime.createMemory(responseMemory, 'messages');\n memories.push(responseMemory);\n }\n\n return memories;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in message callback');\n return [];\n }\n };\n\n // Use elizaOS.handleMessage if available (unified messaging API with streaming support)\n // Falls back to direct messageService call for backward compatibility\n if (this.runtime.hasElizaOS()) {\n await this.runtime.elizaOS.handleMessage(this.runtime.agentId, memory, {\n onResponse: async (content) => {\n await callback(content);\n },\n });\n } else if (this.runtime.messageService) {\n await this.runtime.messageService.handleMessage(this.runtime, memory, callback);\n } else {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId }, 'Message service is not available');\n throw new Error(\n 'Message service is not initialized. Ensure the message service is properly configured.'\n );\n }\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId: ctx.chat?.id, messageId: ctx.message?.message_id, from: ctx.from?.username || ctx.from?.id, error: error instanceof Error ? error.message : String(error) }, 'Error handling Telegram message');\n throw error;\n }\n }\n\n /**\n * Handles the reaction event triggered by a user reacting to a message.\n * @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update\n * @returns {Promise<void>} A Promise that resolves when the reaction handling is complete\n */\n public async handleReaction(\n ctx: NarrowedContext<Context<Update>, Update.MessageReactionUpdate>\n ): Promise<void> {\n // Ensure we have the necessary data\n if (!ctx.update.message_reaction || !ctx.from) return;\n\n const reaction = ctx.update.message_reaction;\n const reactedToMessageId = reaction.message_id;\n\n const originalMessagePlaceholder: Partial<Message> = {\n message_id: reactedToMessageId,\n chat: reaction.chat,\n from: ctx.from,\n date: Math.floor(Date.now() / 1000),\n };\n\n const reactionType = reaction.new_reaction[0].type;\n const reactionEmoji = (reaction.new_reaction[0] as ReactionType).type; // Assuming ReactionType has 'type' for emoji\n\n try {\n const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID;\n const roomId = createUniqueUuid(this.runtime, ctx.chat.id.toString());\n\n const reactionId = createUniqueUuid(\n this.runtime,\n `${reaction.message_id}-${ctx.from.id}-${Date.now()}`\n );\n\n // Create reaction memory\n const memory: Memory = {\n id: reactionId,\n entityId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n channelType: getChannelType(reaction.chat as Chat),\n text: `Reacted with: ${reactionType === 'emoji' ? reactionEmoji : reactionType}`,\n source: 'telegram',\n inReplyTo: createUniqueUuid(this.runtime, reaction.message_id.toString()),\n },\n createdAt: Date.now(),\n };\n\n // Create callback for handling reaction responses\n const callback: HandlerCallback = async (content: Content) => {\n try {\n // Add null check for content.text\n const replyText = content.text ?? '';\n const sentMessage = await ctx.reply(replyText);\n const responseMemory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n inReplyTo: reactionId,\n },\n createdAt: sentMessage.date * 1000,\n };\n return [responseMemory];\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error in reaction callback');\n return [];\n }\n };\n\n // Let the bootstrap plugin handle the reaction\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n ctx,\n originalMessage: originalMessagePlaceholder as Message, // Cast needed due to placeholder\n reactionString: reactionType === 'emoji' ? reactionEmoji : reactionType,\n originalReaction: reaction.new_reaction[0] as ReactionType,\n } as TelegramReactionReceivedPayload);\n\n // Also emit the platform-specific event\n this.runtime.emitEvent(TelegramEventTypes.REACTION_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n ctx,\n originalMessage: originalMessagePlaceholder as Message, // Cast needed due to placeholder\n reactionString: reactionType === 'emoji' ? reactionEmoji : reactionType,\n originalReaction: reaction.new_reaction[0] as ReactionType,\n } as TelegramReactionReceivedPayload);\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, 'Error handling reaction');\n }\n }\n\n /**\n * Sends a message to a Telegram chat and emits appropriate events\n * @param {number | string} chatId - The Telegram chat ID to send the message to\n * @param {Content} content - The content to send\n * @param {number} [replyToMessageId] - Optional message ID to reply to\n * @returns {Promise<Message.TextMessage[]>} The sent messages\n */\n public async sendMessage(\n chatId: number | string,\n content: Content,\n replyToMessageId?: number\n ): Promise<Message.TextMessage[]> {\n try {\n // Create a context-like object for sending\n const ctx = {\n chat: { id: chatId },\n telegram: this.bot.telegram,\n };\n\n const sentMessages = await this.sendMessageInChunks(\n ctx as Context,\n content,\n replyToMessageId\n );\n\n if (!sentMessages?.length) return [];\n\n // Create group ID\n const roomId = createUniqueUuid(this.runtime, chatId.toString());\n\n // Create memories for the sent messages\n const memories: Memory[] = [];\n for (const sentMessage of sentMessages) {\n const memory: Memory = {\n id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n text: sentMessage.text,\n source: 'telegram',\n channelType: getChannelType({\n id: typeof chatId === 'string' ? Number.parseInt(chatId, 10) : chatId,\n type: 'private', // Default to private, will be overridden if in context\n } as Chat),\n },\n createdAt: sentMessage.date * 1000,\n };\n\n await this.runtime.createMemory(memory, 'messages');\n memories.push(memory);\n }\n\n // Emit both generic and platform-specific message sent events\n if (memories.length > 0) {\n this.runtime.emitEvent(EventType.MESSAGE_SENT, {\n runtime: this.runtime,\n message: memories[0],\n source: 'telegram',\n });\n }\n\n // Also emit platform-specific event\n this.runtime.emitEvent(\n TelegramEventTypes.MESSAGE_SENT as string,\n {\n runtime: this.runtime,\n source: 'telegram',\n originalMessages: sentMessages,\n chatId,\n message: memories[0],\n } as any\n );\n\n return sentMessages;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending message to Telegram');\n return [];\n }\n }\n}\n","import { Markup } from 'telegraf';\nimport type { Button } from './types';\nimport type { InlineKeyboardButton } from '@telegraf/types';\nimport { logger } from '@elizaos/core';\n\n// A list of Telegram MarkdownV2 reserved characters that must be escaped\nconst TELEGRAM_RESERVED_REGEX = /([_*[\\]()~`>#+\\-=|{}.!\\\\])/g;\n\n/**\n * Escapes plain text for Telegram MarkdownV2.\n * (Any character in 1–126 that is reserved is prefixed with a backslash.)\n */\nfunction escapePlainText(text: string): string {\n if (!text) return '';\n return text.replace(TELEGRAM_RESERVED_REGEX, '\\\\$1');\n}\n\n/**\n * Escapes plain text line‐by–line while preserving any leading blockquote markers.\n */\nfunction escapePlainTextPreservingBlockquote(text: string): string {\n if (!text) return '';\n return text\n .split('\\n')\n .map((line) => {\n // If the line begins with one or more \">\" (and optional space),\n // leave that part unescaped.\n const match = line.match(/^(>+\\s?)(.*)$/);\n if (match) {\n return match[1] + escapePlainText(match[2]);\n }\n return escapePlainText(line);\n })\n .join('\\n');\n}\n\n/**\n * Escapes code inside inline or pre-formatted code blocks.\n * Telegram requires that inside code blocks all ` and \\ characters are escaped.\n */\nfunction escapeCode(text: string): string {\n if (!text) return '';\n return text.replace(/([`\\\\])/g, '\\\\$1');\n}\n\n/**\n * Escapes a URL for inline links:\n * inside the URL, only \")\" and \"\\\" need to be escaped.\n */\nfunction escapeUrl(url: string): string {\n if (!url) return '';\n return url.replace(/([)\\\\])/g, '\\\\$1');\n}\n\n/**\n * This function converts standard markdown to Telegram MarkdownV2.\n *\n * In addition to processing code blocks, inline code, links, bold, strikethrough, and italic,\n * it converts any header lines (those starting with one or more `#`) to bold text.\n *\n * Note: This solution uses a sequence of regex‐replacements and placeholders.\n * It makes assumptions about non–nested formatting and does not cover every edge case.\n */\nexport function convertMarkdownToTelegram(markdown: string): string {\n // We will temporarily replace recognized markdown tokens with placeholders.\n // Each placeholder is a string like \"\\u0000{index}\\u0000\".\n const replacements: string[] = [];\n function storeReplacement(formatted: string): string {\n const placeholder = `\\u0000${replacements.length}\\u0000`;\n replacements.push(formatted);\n return placeholder;\n }\n\n let converted = markdown;\n\n // 1. Fenced code blocks (```...```)\n // Matches an optional language (letters only) and then any content until the closing ```\n converted = converted.replace(/```(\\w+)?\\n([\\s\\S]*?)```/g, (_match, lang, code) => {\n const escapedCode = escapeCode(code);\n const formatted = '```' + (lang || '') + '\\n' + escapedCode + '```';\n return storeReplacement(formatted);\n });\n\n // 2. Inline code (`...`)\n converted = converted.replace(/`([^`]+)`/g, (_match, code) => {\n const escapedCode = escapeCode(code);\n const formatted = '`' + escapedCode + '`';\n return storeReplacement(formatted);\n });\n\n // 3. Links: [link text](url)\n converted = converted.replace(\n /$begin:math:display$([^$end:math:display$]+)]$begin:math:text$([^)]+)$end:math:text$/g,\n (_match, text, url) => {\n // For link text we escape as plain text.\n const formattedText = escapePlainText(text);\n const escapedURL = escapeUrl(url);\n const formatted = `[${formattedText}](${escapedURL})`;\n return storeReplacement(formatted);\n }\n );\n\n // 4. Bold text: standard markdown bold **text**\n // Telegram bold is delimited by single asterisks: *text*\n converted = converted.replace(/\\*\\*([^*]+)\\*\\*/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `*${formattedContent}*`;\n return storeReplacement(formatted);\n });\n\n // 5. Strikethrough: standard markdown uses ~~text~~,\n // while Telegram uses ~text~\n converted = converted.replace(/~~([^~]+)~~/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `~${formattedContent}~`;\n return storeReplacement(formatted);\n });\n\n // 6. Italic text:\n // Standard markdown italic can be written as either *text* or _text_.\n // In Telegram MarkdownV2 italic must be delimited by underscores.\n // Process asterisk-based italic first.\n // (Using negative lookbehind/lookahead to avoid matching bold **)\n converted = converted.replace(/(?<!\\*)\\*([^*\\n]+)\\*(?!\\*)/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `_${formattedContent}_`;\n return storeReplacement(formatted);\n });\n // Then underscore-based italic.\n converted = converted.replace(/_([^_\\n]+)_/g, (_match, content) => {\n const formattedContent = escapePlainText(content);\n const formatted = `_${formattedContent}_`;\n return storeReplacement(formatted);\n });\n\n // 7. Headers: Convert markdown headers (lines starting with '#' characters)\n // to bold text. This avoids unescaped '#' characters (which crash Telegram)\n // by removing them and wrapping the rest of the line in bold markers.\n converted = converted.replace(/^(#{1,6})\\s*(.*)$/gm, (_match, _hashes, headerContent: string) => {\n // Remove any trailing whitespace and escape the header text.\n const formatted = `*${escapePlainText(headerContent.trim())}*`;\n return storeReplacement(formatted);\n });\n\n // Define the placeholder marker as a string constant\n const NULL_CHAR = String.fromCharCode(0);\n const PLACEHOLDER_PATTERN = new RegExp(`(${NULL_CHAR}\\\\d+${NULL_CHAR})`, 'g');\n const PLACEHOLDER_TEST = new RegExp(`^${NULL_CHAR}\\\\d+${NULL_CHAR}$`);\n const PLACEHOLDER_REPLACE = new RegExp(`${NULL_CHAR}(\\\\d+)${NULL_CHAR}`, 'g');\n\n const finalEscaped = converted\n .split(PLACEHOLDER_PATTERN)\n .map((segment) => {\n // If the segment is a placeholder (matches the pattern), leave it untouched.\n if (PLACEHOLDER_TEST.test(segment)) {\n return segment;\n } else {\n // Otherwise, escape it while preserving any leading blockquote markers.\n return escapePlainTextPreservingBlockquote(segment);\n }\n })\n .join('');\n\n // Finally, substitute back all placeholders with their preformatted content.\n const finalResult = finalEscaped.replace(PLACEHOLDER_REPLACE, (_, index) => {\n return replacements[parseInt(index)];\n });\n\n return finalResult;\n}\n\n/**\n * Splits a message into chunks that fit within Telegram's message length limit\n */\n/**\n * Splits a text message into chunks based on a maximum length for each chunk.\n *\n * @param {string} text - The text message to split.\n * @param {number} maxLength - The maximum length for each chunk (default is 4096).\n * @returns {string[]} An array containing the text message split into chunks.\n */\nexport function splitMessage(text: string, maxLength = 4096): string[] {\n const chunks: string[] = [];\n if (!text) return chunks;\n let currentChunk = '';\n\n const lines = text.split('\\n');\n for (const line of lines) {\n if (currentChunk.length + line.length + 1 <= maxLength) {\n currentChunk += (currentChunk ? '\\n' : '') + line;\n } else {\n if (currentChunk) chunks.push(currentChunk);\n currentChunk = line;\n }\n }\n\n if (currentChunk) chunks.push(currentChunk);\n return chunks;\n}\n\n/**\n * Converts Eliza buttons into Telegram buttons\n * @param {Button[]} buttons - The buttons from Eliza content\n * @returns {InlineKeyboardButton[]} Array of Telegram buttons\n */\nexport function convertToTelegramButtons(buttons?: Button[] | null): InlineKeyboardButton[] {\n if (!buttons) return [];\n const telegramButtons: InlineKeyboardButton[] = [];\n\n for (const button of buttons) {\n // Validate button has required properties\n if (!button || !button.text || !button.url) {\n logger.warn({ button }, 'Invalid button configuration, skipping');\n continue;\n }\n\n let telegramButton: InlineKeyboardButton;\n switch (button.kind) {\n case 'login':\n telegramButton = Markup.button.login(button.text, button.url);\n break;\n case 'url':\n telegramButton = Markup.button.url(button.text, button.url);\n break;\n default:\n logger.warn({ src: 'plugin:telegram', buttonKind: button.kind }, 'Unknown button kind, treating as URL button');\n telegramButton = Markup.button.url(button.text, button.url);\n break;\n }\n\n telegramButtons.push(telegramButton);\n }\n\n return telegramButtons;\n}\n\n/**\n * Clean text by removing all NULL (\\u0000) characters\n * @param {string | undefined | null} text - The text to clean\n * @returns {string} The cleaned text\n */\nexport function cleanText(text: string | undefined | null): string {\n if (!text) return '';\n // Avoid control char in regex literal; lint-friendly\n return text.split('\\u0000').join('');\n}\n","import { type IAgentRuntime, type TestSuite, logger } from '@elizaos/core';\nimport type { Chat, User } from '@telegraf/types';\nimport type { Telegraf } from 'telegraf';\nimport type { Context } from 'telegraf';\nimport type { MessageManager } from './messageManager';\nimport type { TelegramService } from './service';\nimport type { TelegramContent } from './types';\n\nconst TEST_IMAGE_URL =\n 'https://github.com/elizaOS/awesome-eliza/blob/main/assets/eliza-logo.jpg?raw=true';\n\n/**\n * Represents a test suite for testing Telegram functionality.\n *\n * This test suite includes methods to initialize and validate a Telegram bot connection,\n * send basic text messages to a Telegram chat, send text messages with image attachments,\n * handle and process incoming Telegram messages, and process and validate image attachments\n * in incoming messages.\n *\n * @implements {TestSuite}\n */\n\nexport class TelegramTestSuite implements TestSuite {\n name = 'telegram';\n private telegramClient: TelegramService | null = null;\n private bot: Telegraf<Context> | null = null;\n private messageManager: MessageManager | null = null;\n tests: { name: string; fn: (runtime: IAgentRuntime) => Promise<void> }[];\n\n /**\n * Constructor for initializing a set of test cases for a Telegram bot.\n *\n * @constructor\n * @property {Array<Object>} tests - An array of test cases with name and corresponding test functions.\n * @property {string} tests.name - The name of the test case.\n * @property {function} tests.fn - The test function to be executed.\n */\n constructor() {\n this.tests = [\n {\n name: 'Initialize and Validate Telegram Bot Connection',\n fn: this.testCreatingTelegramBot.bind(this),\n },\n {\n name: 'Send Basic Text Message to Telegram Chat',\n fn: this.testSendingTextMessage.bind(this),\n },\n {\n name: 'Send Text Message with an Image Attachment',\n fn: this.testSendingMessageWithAttachment.bind(this),\n },\n {\n name: 'Handle and Process Incoming Telegram Messages',\n fn: this.testHandlingMessage.bind(this),\n },\n {\n name: 'Process and Validate Image Attachments in Incoming Messages',\n fn: this.testProcessingImages.bind(this),\n },\n ];\n }\n\n /**\n * Retrieves the Telegram test chat ID from environment variables.\n *\n * Reference on getting the Telegram chat ID:\n * https://stackoverflow.com/a/32572159\n */\n /**\n * Validates the chat ID by checking if it is set in the runtime settings or environment variables.\n * If not set, an error is thrown with a message instructing to provide a valid chat ID.\n * @param {IAgentRuntime} runtime - The runtime object that provides access to the settings and environment variables.\n * @throws {Error} If TELEGRAM_TEST_CHAT_ID is not set in the runtime settings or environment variables.\n * @returns {string} The validated chat ID.\n */\n validateChatId(runtime: IAgentRuntime): string | number {\n const testChatId =\n runtime.getSetting('TELEGRAM_TEST_CHAT_ID') || process.env.TELEGRAM_TEST_CHAT_ID;\n if (!testChatId || typeof testChatId === 'boolean') {\n throw new Error(\n 'TELEGRAM_TEST_CHAT_ID is not set. Please provide a valid chat ID in the environment variables.'\n );\n }\n return testChatId;\n }\n\n async getChatInfo(runtime: IAgentRuntime): Promise<Context['chat']> {\n try {\n const chatId = this.validateChatId(runtime);\n if (!this.bot) {\n throw new Error('Bot is not initialized.');\n }\n const chat = await this.bot.telegram.getChat(chatId);\n logger.debug({ src: 'plugin:telegram', chatId }, 'Fetched real chat');\n return chat;\n } catch (error) {\n throw new Error(`Error fetching real Telegram chat: ${error}`);\n }\n }\n\n async testCreatingTelegramBot(runtime: IAgentRuntime) {\n this.telegramClient = runtime.getService('telegram') as TelegramService;\n if (!this.telegramClient || !this.telegramClient.messageManager) {\n throw new Error(\n 'Telegram service or message manager not initialized - check TELEGRAM_BOT_TOKEN'\n );\n }\n this.bot = this.telegramClient.messageManager.bot;\n this.messageManager = this.telegramClient.messageManager;\n logger.debug({ src: 'plugin:telegram' }, 'Telegram bot initialized successfully');\n }\n\n async testSendingTextMessage(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n\n const chatId = this.validateChatId(runtime);\n await this.bot.telegram.sendMessage(chatId, 'Testing Telegram message!');\n logger.debug({ src: 'plugin:telegram', chatId }, 'Message sent successfully');\n } catch (error) {\n throw new Error(`Error sending Telegram message: ${error}`);\n }\n }\n\n async testSendingMessageWithAttachment(runtime: IAgentRuntime) {\n try {\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n if (!this.bot) throw new Error('Bot not initialized.');\n\n const chat = await this.getChatInfo(runtime);\n const mockContext: Partial<Context> = {\n chat,\n from: { id: 123, username: 'TestUser' } as User,\n telegram: this.bot.telegram,\n };\n\n const messageContent = {\n text: 'Here is an image attachment:',\n attachments: [\n {\n id: '123',\n title: 'Sample Image',\n source: TEST_IMAGE_URL,\n text: 'Sample Image',\n url: TEST_IMAGE_URL,\n contentType: 'image/png',\n description: 'Sample Image',\n },\n ],\n };\n\n await this.messageManager.sendMessageInChunks(\n mockContext as Context,\n messageContent as TelegramContent\n );\n\n logger.success({ src: 'plugin:telegram' }, 'Message with image attachment sent successfully');\n } catch (error) {\n throw new Error(`Error sending Telegram message with attachment: ${error}`);\n }\n }\n\n async testHandlingMessage(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n\n const chat = await this.getChatInfo(runtime);\n const mockContext: Partial<Context> = {\n chat,\n from: {\n id: 123,\n username: 'TestUser',\n is_bot: false,\n first_name: 'Test',\n last_name: 'User',\n } as User,\n message: {\n message_id: undefined,\n text: `@${this.bot.botInfo?.username}! Hello!`,\n date: Math.floor(Date.now() / 1000),\n chat,\n } as any,\n telegram: this.bot.telegram,\n };\n\n try {\n await this.messageManager.handleMessage(mockContext as Context);\n } catch (error) {\n throw new Error(`Error handling Telegram message: ${error}`);\n }\n } catch (error) {\n throw new Error(`Error handling Telegram message: ${error}`);\n }\n }\n\n async testProcessingImages(runtime: IAgentRuntime) {\n try {\n if (!this.bot) throw new Error('Bot not initialized.');\n if (!this.messageManager) throw new Error('MessageManager not initialized.');\n\n const chatId = this.validateChatId(runtime);\n const fileId = await this.getFileId(String(chatId), TEST_IMAGE_URL);\n\n const mockMessage = {\n message_id: 12345,\n chat: { id: chatId, type: 'private' } as Chat,\n date: Math.floor(Date.now() / 1000),\n photo: [\n {\n file_id: fileId,\n file_unique_id: `unique_${fileId}`,\n width: 100,\n height: 100,\n },\n ],\n text: `@${this.bot.botInfo?.username}!`,\n };\n\n const result = await this.messageManager.processImage(mockMessage as any);\n if (!result || !result.description) {\n throw new Error('Error processing Telegram image or description not found');\n }\n const { description } = result;\n logger.debug({ src: 'plugin:telegram', description }, 'Processing Telegram image successfully');\n } catch (error) {\n throw new Error(`Error processing Telegram image: ${error}`);\n }\n }\n\n async getFileId(chatId: string, imageUrl: string) {\n try {\n if (!this.bot) {\n throw new Error('Bot is not initialized.');\n }\n const message = await this.bot.telegram.sendPhoto(chatId, imageUrl);\n if (!message.photo || message.photo.length === 0) {\n throw new Error('No photo received in the message response.');\n }\n return message.photo[message.photo.length - 1].file_id;\n } catch (error) {\n logger.error({ src: 'plugin:telegram', chatId, error: error instanceof Error ? error.message : String(error) }, 'Error sending image');\n throw error;\n }\n }\n}\n","import type { Plugin } from '@elizaos/core';\nimport { TELEGRAM_SERVICE_NAME } from './constants';\nimport { TelegramService } from './service';\nimport { TelegramTestSuite } from './tests';\nimport { MessageManager } from './messageManager';\n\nconst telegramPlugin: Plugin = {\n name: TELEGRAM_SERVICE_NAME,\n description: 'Telegram client plugin',\n services: [TelegramService],\n tests: [new TelegramTestSuite()],\n};\n\nexport { TelegramService, MessageManager };\nexport default telegramPlugin;\n"],"mappings":";AAAO,IAAM,oBAAoB;AAAA,EAC/B,cAAc;AAAA,EACd,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,EACpB,8BAA8B;AAAA,EAC9B,yCAAyC;AAAA,EACzC,qBAAqB,IAAI,KAAK;AAAA;AAAA,EAC9B,wBAAwB,IAAI,KAAK;AAAA;AACnC;AAEO,IAAM,wBAAwB;;;ACVrC;AAAA,EACE,eAAAA;AAAA,EAGA,aAAAC;AAAA,EAEA;AAAA,EAEA;AAAA,EAIA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;AACP,SAAuB,gBAAgB;;;ACfvC;AAAA,EACE;AAAA,EAEA;AAAA,EAKA;AAAA,EACA;AAAA,EAEA;AAAA,EACA,UAAAC;AAAA,OACK;AAGP,SAAS,UAAAC,eAAc;;;AChBvB,SAAS,cAAc;AAGvB,SAAS,cAAc;AAGvB,IAAM,0BAA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,CAAC,IAAI,kBAAkB,CAAC;AACjC;AAGA,IAAO,gBAAQ;","names":["ChannelType","EventType","createUniqueUuid","logger","logger","Markup","logger","Markup","logger","createUniqueUuid","ChannelType","EventType","logger"]}
|
package/dist/service.d.ts
CHANGED
|
@@ -179,7 +179,6 @@ export declare class TelegramService extends Service {
|
|
|
179
179
|
* @param {Entity[]} entities - The entities to process
|
|
180
180
|
* @param {UUID} roomId - The ID of the room to connect entities to
|
|
181
181
|
* @param {string} channelId - The channel ID
|
|
182
|
-
* @param {string} serverId - The server ID
|
|
183
182
|
* @param {ChannelType} roomType - The type of the room
|
|
184
183
|
* @param {UUID} worldId - The ID of the world
|
|
185
184
|
* @returns {Promise<void>}
|
package/dist/tests.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export declare class TelegramTestSuite implements TestSuite {
|
|
|
41
41
|
* @throws {Error} If TELEGRAM_TEST_CHAT_ID is not set in the runtime settings or environment variables.
|
|
42
42
|
* @returns {string} The validated chat ID.
|
|
43
43
|
*/
|
|
44
|
-
validateChatId(runtime: IAgentRuntime):
|
|
44
|
+
validateChatId(runtime: IAgentRuntime): string | number;
|
|
45
45
|
getChatInfo(runtime: IAgentRuntime): Promise<Context['chat']>;
|
|
46
46
|
testCreatingTelegramBot(runtime: IAgentRuntime): Promise<void>;
|
|
47
47
|
testSendingTextMessage(runtime: IAgentRuntime): Promise<void>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elizaos/plugin-telegram",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.4",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@elizaos/core": "^1.
|
|
21
|
+
"@elizaos/core": "^1.7.2",
|
|
22
22
|
"@telegraf/types": "7.1.0",
|
|
23
23
|
"@types/node": "^24.0.10",
|
|
24
24
|
"strip-literal": "^3.0.0",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"typescript": "^5.8.3"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
|
-
"@elizaos/config": "^1.
|
|
30
|
+
"@elizaos/config": "^1.7.2",
|
|
31
31
|
"@eslint/js": "^9.17.0",
|
|
32
32
|
"@typescript-eslint/eslint-plugin": "^8.22.0",
|
|
33
33
|
"@typescript-eslint/parser": "^8.22.0",
|