@elizaos/plugin-telegram 1.0.0-alpha.63 → 1.0.0-alpha.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -3
- package/dist/index.js +86 -154
- package/dist/index.js.map +1 -1
- package/package.json +43 -40
package/README.md
CHANGED
|
@@ -80,9 +80,8 @@ Create or modify `characters/your-character.json`:
|
|
|
80
80
|
npm run dev
|
|
81
81
|
```
|
|
82
82
|
|
|
83
|
-
## Or using
|
|
83
|
+
## Or using bun:
|
|
84
84
|
|
|
85
85
|
```bash
|
|
86
|
-
|
|
86
|
+
bun start --character="characters/your-character.json"
|
|
87
87
|
```
|
|
88
|
-
|
package/dist/index.js
CHANGED
|
@@ -13,7 +13,14 @@ var MESSAGE_CONSTANTS = {
|
|
|
13
13
|
var TELEGRAM_SERVICE_NAME = "telegram";
|
|
14
14
|
|
|
15
15
|
// src/service.ts
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
ChannelType as ChannelType2,
|
|
18
|
+
EventType as EventType2,
|
|
19
|
+
Role,
|
|
20
|
+
Service,
|
|
21
|
+
createUniqueUuid as createUniqueUuid2,
|
|
22
|
+
logger as logger2
|
|
23
|
+
} from "@elizaos/core";
|
|
17
24
|
import { Telegraf } from "telegraf";
|
|
18
25
|
|
|
19
26
|
// src/environment.ts
|
|
@@ -30,10 +37,8 @@ async function validateTelegramConfig(runtime) {
|
|
|
30
37
|
} catch (error) {
|
|
31
38
|
if (error instanceof z.ZodError) {
|
|
32
39
|
const errorMessages = error.errors.map((err) => `${err.path.join(".")}: ${err.message}`).join("\n");
|
|
33
|
-
throw new Error(
|
|
34
|
-
|
|
35
|
-
${errorMessages}`
|
|
36
|
-
);
|
|
40
|
+
throw new Error(`Telegram configuration validation failed:
|
|
41
|
+
${errorMessages}`);
|
|
37
42
|
}
|
|
38
43
|
throw error;
|
|
39
44
|
}
|
|
@@ -42,7 +47,7 @@ ${errorMessages}`
|
|
|
42
47
|
// src/messageManager.ts
|
|
43
48
|
import {
|
|
44
49
|
ChannelType,
|
|
45
|
-
|
|
50
|
+
EventType,
|
|
46
51
|
ModelType,
|
|
47
52
|
createUniqueUuid,
|
|
48
53
|
logger
|
|
@@ -101,9 +106,7 @@ var MessageManager = class {
|
|
|
101
106
|
const fileLink = await this.bot.telegram.getFileLink(photo.file_id);
|
|
102
107
|
imageUrl = fileLink.toString();
|
|
103
108
|
} else if ("document" in message && ((_c = (_b = message.document) == null ? void 0 : _b.mime_type) == null ? void 0 : _c.startsWith("image/"))) {
|
|
104
|
-
const fileLink = await this.bot.telegram.getFileLink(
|
|
105
|
-
message.document.file_id
|
|
106
|
-
);
|
|
109
|
+
const fileLink = await this.bot.telegram.getFileLink(message.document.file_id);
|
|
107
110
|
imageUrl = fileLink.toString();
|
|
108
111
|
}
|
|
109
112
|
if (imageUrl) {
|
|
@@ -150,26 +153,17 @@ ${description}]` };
|
|
|
150
153
|
`Unsupported Telegram attachment content type: ${attachment.contentType}`
|
|
151
154
|
);
|
|
152
155
|
}
|
|
153
|
-
await this.sendMedia(
|
|
154
|
-
ctx,
|
|
155
|
-
attachment.url,
|
|
156
|
-
mediaType,
|
|
157
|
-
attachment.description
|
|
158
|
-
);
|
|
156
|
+
await this.sendMedia(ctx, attachment.url, mediaType, attachment.description);
|
|
159
157
|
});
|
|
160
158
|
} else {
|
|
161
159
|
const chunks = this.splitMessage(content.text);
|
|
162
160
|
const sentMessages = [];
|
|
163
161
|
for (let i = 0; i < chunks.length; i++) {
|
|
164
162
|
const chunk = escapeMarkdown(chunks[i]);
|
|
165
|
-
const sentMessage = await ctx.telegram.sendMessage(
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
reply_parameters: i === 0 && replyToMessageId ? { message_id: replyToMessageId } : void 0,
|
|
170
|
-
parse_mode: "Markdown"
|
|
171
|
-
}
|
|
172
|
-
);
|
|
163
|
+
const sentMessage = await ctx.telegram.sendMessage(ctx.chat.id, chunk, {
|
|
164
|
+
reply_parameters: i === 0 && replyToMessageId ? { message_id: replyToMessageId } : void 0,
|
|
165
|
+
parse_mode: "Markdown"
|
|
166
|
+
});
|
|
173
167
|
sentMessages.push(sentMessage);
|
|
174
168
|
}
|
|
175
169
|
return sentMessages;
|
|
@@ -216,9 +210,7 @@ ${description}]` };
|
|
|
216
210
|
`${type.charAt(0).toUpperCase() + type.slice(1)} sent successfully: ${mediaPath}`
|
|
217
211
|
);
|
|
218
212
|
} catch (error) {
|
|
219
|
-
logger.error(
|
|
220
|
-
`Failed to send ${type}. Path: ${mediaPath}. Error: ${error.message}`
|
|
221
|
-
);
|
|
213
|
+
logger.error(`Failed to send ${type}. Path: ${mediaPath}. Error: ${error.message}`);
|
|
222
214
|
logger.debug(error.stack);
|
|
223
215
|
throw error;
|
|
224
216
|
}
|
|
@@ -256,16 +248,10 @@ ${description}]` };
|
|
|
256
248
|
if (!ctx.message || !ctx.from) return;
|
|
257
249
|
const message = ctx.message;
|
|
258
250
|
try {
|
|
259
|
-
const entityId = createUniqueUuid(
|
|
260
|
-
this.runtime,
|
|
261
|
-
ctx.from.id.toString()
|
|
262
|
-
);
|
|
251
|
+
const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString());
|
|
263
252
|
const userName = ctx.from.username || ctx.from.first_name || "Unknown User";
|
|
264
253
|
const roomId = createUniqueUuid(this.runtime, (_a = ctx.chat) == null ? void 0 : _a.id.toString());
|
|
265
|
-
const messageId = createUniqueUuid(
|
|
266
|
-
this.runtime,
|
|
267
|
-
(_b = message == null ? void 0 : message.message_id) == null ? void 0 : _b.toString()
|
|
268
|
-
);
|
|
254
|
+
const messageId = createUniqueUuid(this.runtime, (_b = message == null ? void 0 : message.message_id) == null ? void 0 : _b.toString());
|
|
269
255
|
const imageInfo = await this.processImage(message);
|
|
270
256
|
let messageText = "";
|
|
271
257
|
if ("text" in message && message.text) {
|
|
@@ -314,30 +300,20 @@ ${description}]` };
|
|
|
314
300
|
text: fullText,
|
|
315
301
|
source: "telegram",
|
|
316
302
|
channelType,
|
|
317
|
-
inReplyTo: "reply_to_message" in message && message.reply_to_message ? createUniqueUuid(
|
|
318
|
-
this.runtime,
|
|
319
|
-
message.reply_to_message.message_id.toString()
|
|
320
|
-
) : void 0
|
|
303
|
+
inReplyTo: "reply_to_message" in message && message.reply_to_message ? createUniqueUuid(this.runtime, message.reply_to_message.message_id.toString()) : void 0
|
|
321
304
|
},
|
|
322
305
|
createdAt: message.date * 1e3
|
|
323
306
|
};
|
|
324
307
|
const callback = async (content, _files) => {
|
|
325
308
|
try {
|
|
326
|
-
const sentMessages = await this.sendMessageInChunks(
|
|
327
|
-
ctx,
|
|
328
|
-
content,
|
|
329
|
-
message.message_id
|
|
330
|
-
);
|
|
309
|
+
const sentMessages = await this.sendMessageInChunks(ctx, content, message.message_id);
|
|
331
310
|
if (!sentMessages) return [];
|
|
332
311
|
const memories = [];
|
|
333
312
|
for (let i = 0; i < sentMessages.length; i++) {
|
|
334
313
|
const sentMessage = sentMessages[i];
|
|
335
314
|
const _isLastMessage = i === sentMessages.length - 1;
|
|
336
315
|
const responseMemory = {
|
|
337
|
-
id: createUniqueUuid(
|
|
338
|
-
this.runtime,
|
|
339
|
-
sentMessage.message_id.toString()
|
|
340
|
-
),
|
|
316
|
+
id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),
|
|
341
317
|
entityId: this.runtime.agentId,
|
|
342
318
|
agentId: this.runtime.agentId,
|
|
343
319
|
roomId,
|
|
@@ -358,26 +334,20 @@ ${description}]` };
|
|
|
358
334
|
return [];
|
|
359
335
|
}
|
|
360
336
|
};
|
|
361
|
-
this.runtime.emitEvent(
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
"
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
callback,
|
|
376
|
-
source: "telegram",
|
|
377
|
-
ctx,
|
|
378
|
-
originalMessage: message
|
|
379
|
-
}
|
|
380
|
-
);
|
|
337
|
+
this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {
|
|
338
|
+
runtime: this.runtime,
|
|
339
|
+
message: memory,
|
|
340
|
+
callback,
|
|
341
|
+
source: "telegram"
|
|
342
|
+
});
|
|
343
|
+
this.runtime.emitEvent("TELEGRAM_MESSAGE_RECEIVED" /* MESSAGE_RECEIVED */, {
|
|
344
|
+
runtime: this.runtime,
|
|
345
|
+
message: memory,
|
|
346
|
+
callback,
|
|
347
|
+
source: "telegram",
|
|
348
|
+
ctx,
|
|
349
|
+
originalMessage: message
|
|
350
|
+
});
|
|
381
351
|
} catch (error) {
|
|
382
352
|
logger.error("Error handling Telegram message:", {
|
|
383
353
|
error,
|
|
@@ -399,10 +369,7 @@ ${description}]` };
|
|
|
399
369
|
const reactionType = reaction.new_reaction[0].type;
|
|
400
370
|
const reactionEmoji = reaction.new_reaction[0].type;
|
|
401
371
|
try {
|
|
402
|
-
const entityId = createUniqueUuid(
|
|
403
|
-
this.runtime,
|
|
404
|
-
ctx.from.id.toString()
|
|
405
|
-
);
|
|
372
|
+
const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString());
|
|
406
373
|
const roomId = createUniqueUuid(this.runtime, ctx.chat.id.toString());
|
|
407
374
|
const worldId = createUniqueUuid(this.runtime, ctx.chat.id.toString());
|
|
408
375
|
const reactionId = createUniqueUuid(
|
|
@@ -418,10 +385,7 @@ ${description}]` };
|
|
|
418
385
|
channelType: getChannelType(reaction.chat),
|
|
419
386
|
text: `Reacted with: ${reactionType === "emoji" ? reactionEmoji : reactionType}`,
|
|
420
387
|
source: "telegram",
|
|
421
|
-
inReplyTo: createUniqueUuid(
|
|
422
|
-
this.runtime,
|
|
423
|
-
reaction.message_id.toString()
|
|
424
|
-
)
|
|
388
|
+
inReplyTo: createUniqueUuid(this.runtime, reaction.message_id.toString())
|
|
425
389
|
},
|
|
426
390
|
createdAt: Date.now()
|
|
427
391
|
};
|
|
@@ -429,10 +393,7 @@ ${description}]` };
|
|
|
429
393
|
try {
|
|
430
394
|
const sentMessage = await ctx.reply(content.text);
|
|
431
395
|
const responseMemory = {
|
|
432
|
-
id: createUniqueUuid(
|
|
433
|
-
this.runtime,
|
|
434
|
-
sentMessage.message_id.toString()
|
|
435
|
-
),
|
|
396
|
+
id: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),
|
|
436
397
|
entityId: this.runtime.agentId,
|
|
437
398
|
agentId: this.runtime.agentId,
|
|
438
399
|
roomId,
|
|
@@ -448,27 +409,21 @@ ${description}]` };
|
|
|
448
409
|
return [];
|
|
449
410
|
}
|
|
450
411
|
};
|
|
451
|
-
this.runtime.emitEvent(
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
"
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
source: "telegram",
|
|
467
|
-
ctx,
|
|
468
|
-
reactionString: reactionType === "emoji" ? reactionEmoji : reactionType,
|
|
469
|
-
originalReaction: reaction.new_reaction[0]
|
|
470
|
-
}
|
|
471
|
-
);
|
|
412
|
+
this.runtime.emitEvent(EventType.REACTION_RECEIVED, {
|
|
413
|
+
runtime: this.runtime,
|
|
414
|
+
message: memory,
|
|
415
|
+
callback,
|
|
416
|
+
source: "telegram"
|
|
417
|
+
});
|
|
418
|
+
this.runtime.emitEvent("TELEGRAM_REACTION_RECEIVED" /* REACTION_RECEIVED */, {
|
|
419
|
+
runtime: this.runtime,
|
|
420
|
+
message: memory,
|
|
421
|
+
callback,
|
|
422
|
+
source: "telegram",
|
|
423
|
+
ctx,
|
|
424
|
+
reactionString: reactionType === "emoji" ? reactionEmoji : reactionType,
|
|
425
|
+
originalReaction: reaction.new_reaction[0]
|
|
426
|
+
});
|
|
472
427
|
} catch (error) {
|
|
473
428
|
logger.error("Error handling reaction:", error);
|
|
474
429
|
}
|
|
@@ -515,22 +470,16 @@ ${description}]` };
|
|
|
515
470
|
await this.runtime.createMemory(memory, "messages");
|
|
516
471
|
memories.push(memory);
|
|
517
472
|
}
|
|
518
|
-
this.runtime.emitEvent(
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
"TELEGRAM_MESSAGE_SENT" /* MESSAGE_SENT */,
|
|
529
|
-
{
|
|
530
|
-
originalMessages: sentMessages,
|
|
531
|
-
chatId
|
|
532
|
-
}
|
|
533
|
-
);
|
|
473
|
+
this.runtime.emitEvent(EventType.MESSAGE_SENT, {
|
|
474
|
+
runtime: this.runtime,
|
|
475
|
+
messages: memories,
|
|
476
|
+
roomId,
|
|
477
|
+
source: "telegram"
|
|
478
|
+
});
|
|
479
|
+
this.runtime.emitEvent("TELEGRAM_MESSAGE_SENT" /* MESSAGE_SENT */, {
|
|
480
|
+
originalMessages: sentMessages,
|
|
481
|
+
chatId
|
|
482
|
+
});
|
|
534
483
|
return sentMessages;
|
|
535
484
|
} catch (error) {
|
|
536
485
|
logger.error("Error sending message to Telegram:", error);
|
|
@@ -588,7 +537,9 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
588
537
|
return service;
|
|
589
538
|
} catch (error) {
|
|
590
539
|
lastError = error instanceof Error ? error : new Error(String(error));
|
|
591
|
-
logger2.error(
|
|
540
|
+
logger2.error(
|
|
541
|
+
`Telegram initialization attempt ${retryCount + 1} failed: ${lastError.message}`
|
|
542
|
+
);
|
|
592
543
|
retryCount++;
|
|
593
544
|
if (retryCount < maxRetries) {
|
|
594
545
|
const delay = 2 ** retryCount * 1e3;
|
|
@@ -597,7 +548,9 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
597
548
|
}
|
|
598
549
|
}
|
|
599
550
|
}
|
|
600
|
-
throw new Error(
|
|
551
|
+
throw new Error(
|
|
552
|
+
`Telegram initialization failed after ${maxRetries} attempts. Last error: ${lastError == null ? void 0 : lastError.message}`
|
|
553
|
+
);
|
|
601
554
|
}
|
|
602
555
|
/**
|
|
603
556
|
* Stops the agent runtime.
|
|
@@ -774,14 +727,8 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
774
727
|
...worldPayload,
|
|
775
728
|
chat
|
|
776
729
|
};
|
|
777
|
-
this.runtime.emitEvent(
|
|
778
|
-
|
|
779
|
-
worldPayload
|
|
780
|
-
);
|
|
781
|
-
this.runtime.emitEvent(
|
|
782
|
-
"TELEGRAM_WORLD_JOINED" /* WORLD_JOINED */,
|
|
783
|
-
telegramWorldPayload
|
|
784
|
-
);
|
|
730
|
+
this.runtime.emitEvent(EventType2.WORLD_JOINED, worldPayload);
|
|
731
|
+
this.runtime.emitEvent("TELEGRAM_WORLD_JOINED" /* WORLD_JOINED */, telegramWorldPayload);
|
|
785
732
|
if (chat.type === "group" || chat.type === "supergroup") {
|
|
786
733
|
this.setupEntityTracking(chat.id);
|
|
787
734
|
}
|
|
@@ -858,15 +805,11 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
858
805
|
first_name: ctx.from.first_name
|
|
859
806
|
}
|
|
860
807
|
};
|
|
861
|
-
this.runtime.emitEvent(
|
|
862
|
-
|
|
863
|
-
|
|
808
|
+
this.runtime.emitEvent(EventType2.ENTITY_JOINED, entityJoinedPayload);
|
|
809
|
+
this.runtime.emitEvent("TELEGRAM_ENTITY_JOINED" /* ENTITY_JOINED */, telegramEntityJoinedPayload);
|
|
810
|
+
logger2.info(
|
|
811
|
+
`Tracked new Telegram entity: ${ctx.from.username || ctx.from.first_name || entityId}`
|
|
864
812
|
);
|
|
865
|
-
this.runtime.emitEvent(
|
|
866
|
-
"TELEGRAM_ENTITY_JOINED" /* ENTITY_JOINED */,
|
|
867
|
-
telegramEntityJoinedPayload
|
|
868
|
-
);
|
|
869
|
-
logger2.info(`Tracked new Telegram entity: ${ctx.from.username || ctx.from.first_name || entityId}`);
|
|
870
813
|
} catch (error) {
|
|
871
814
|
logger2.error(`Error syncing new Telegram entity ${entityId} from chat ${chatId}:`, error);
|
|
872
815
|
}
|
|
@@ -909,15 +852,11 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
909
852
|
first_name: leftUser.first_name
|
|
910
853
|
}
|
|
911
854
|
};
|
|
912
|
-
this.runtime.emitEvent(
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
this.runtime.emitEvent(
|
|
917
|
-
"TELEGRAM_ENTITY_LEFT" /* ENTITY_LEFT */,
|
|
918
|
-
telegramEntityLeftPayload
|
|
855
|
+
this.runtime.emitEvent(EventType2.ENTITY_LEFT, entityLeftPayload);
|
|
856
|
+
this.runtime.emitEvent("TELEGRAM_ENTITY_LEFT" /* ENTITY_LEFT */, telegramEntityLeftPayload);
|
|
857
|
+
logger2.info(
|
|
858
|
+
`Entity ${leftUser.username || leftUser.first_name || leftUser.id} left chat ${chatId}`
|
|
919
859
|
);
|
|
920
|
-
logger2.info(`Entity ${leftUser.username || leftUser.first_name || leftUser.id} left chat ${chatId}`);
|
|
921
860
|
}
|
|
922
861
|
} catch (error) {
|
|
923
862
|
logger2.error(`Error handling Telegram entity leaving chat ${chatId}:`, error);
|
|
@@ -1003,22 +942,21 @@ var TelegramTestSuite = class {
|
|
|
1003
942
|
this.telegramClient = runtime.getService("telegram");
|
|
1004
943
|
this.bot = this.telegramClient.messageManager.bot;
|
|
1005
944
|
this.messageManager = this.telegramClient.messageManager;
|
|
1006
|
-
logger3.
|
|
945
|
+
logger3.debug("Telegram bot initialized successfully.");
|
|
1007
946
|
}
|
|
1008
947
|
async testSendingTextMessage(runtime) {
|
|
1009
948
|
try {
|
|
1010
949
|
if (!this.bot) throw new Error("Bot not initialized.");
|
|
1011
950
|
const chatId = this.validateChatId(runtime);
|
|
1012
951
|
await this.bot.telegram.sendMessage(chatId, "Testing Telegram message!");
|
|
1013
|
-
logger3.
|
|
952
|
+
logger3.debug("Message sent successfully.");
|
|
1014
953
|
} catch (error) {
|
|
1015
954
|
throw new Error(`Error sending Telegram message: ${error}`);
|
|
1016
955
|
}
|
|
1017
956
|
}
|
|
1018
957
|
async testSendingMessageWithAttachment(runtime) {
|
|
1019
958
|
try {
|
|
1020
|
-
if (!this.messageManager)
|
|
1021
|
-
throw new Error("MessageManager not initialized.");
|
|
959
|
+
if (!this.messageManager) throw new Error("MessageManager not initialized.");
|
|
1022
960
|
const chat = await this.getChatInfo(runtime);
|
|
1023
961
|
const mockContext = {
|
|
1024
962
|
chat,
|
|
@@ -1039,15 +977,10 @@ var TelegramTestSuite = class {
|
|
|
1039
977
|
}
|
|
1040
978
|
]
|
|
1041
979
|
};
|
|
1042
|
-
await this.messageManager.sendMessageInChunks(
|
|
1043
|
-
mockContext,
|
|
1044
|
-
messageContent
|
|
1045
|
-
);
|
|
980
|
+
await this.messageManager.sendMessageInChunks(mockContext, messageContent);
|
|
1046
981
|
logger3.success("Message with image attachment sent successfully.");
|
|
1047
982
|
} catch (error) {
|
|
1048
|
-
throw new Error(
|
|
1049
|
-
`Error sending Telegram message with attachment: ${error}`
|
|
1050
|
-
);
|
|
983
|
+
throw new Error(`Error sending Telegram message with attachment: ${error}`);
|
|
1051
984
|
}
|
|
1052
985
|
}
|
|
1053
986
|
async testHandlingMessage(runtime) {
|
|
@@ -1068,7 +1001,6 @@ var TelegramTestSuite = class {
|
|
|
1068
1001
|
text: `@${(_a = this.bot.botInfo) == null ? void 0 : _a.username}! Hello!`,
|
|
1069
1002
|
date: Math.floor(Date.now() / 1e3),
|
|
1070
1003
|
chat
|
|
1071
|
-
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
|
|
1072
1004
|
},
|
|
1073
1005
|
telegram: this.bot.telegram
|
|
1074
1006
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/constants.ts","../src/service.ts","../src/environment.ts","../src/messageManager.ts","../src/utils.ts","../src/tests.ts","../src/index.ts"],"sourcesContent":["export const MESSAGE_CONSTANTS = {\n\tMAX_MESSAGES: 50,\n\tRECENT_MESSAGE_COUNT: 5,\n\tCHAT_HISTORY_COUNT: 10,\n\tDEFAULT_SIMILARITY_THRESHOLD: 0.6,\n\tDEFAULT_SIMILARITY_THRESHOLD_FOLLOW_UPS: 0.4,\n\tINTEREST_DECAY_TIME: 5 * 60 * 1000, // 5 minutes\n\tPARTIAL_INTEREST_DECAY: 3 * 60 * 1000, // 3 minutes\n} as const;\n\nexport const TELEGRAM_SERVICE_NAME = \"telegram\";\n","import { ChannelType, type Entity, EventTypes, type IAgentRuntime, Role, type Room, Service, type UUID, type World, createUniqueUuid, logger } from \"@elizaos/core\";\nimport { type Context, Telegraf } from \"telegraf\";\nimport { TELEGRAM_SERVICE_NAME } from \"./constants\";\nimport { validateTelegramConfig } from \"./environment\";\nimport { MessageManager } from \"./messageManager\";\nimport { TelegramEventTypes } from \"./types\";\n\n/**\n * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.\n * @extends Service\n */\n\nexport class TelegramService extends Service {\n\tstatic serviceType = TELEGRAM_SERVICE_NAME;\n\tcapabilityDescription = \"The agent is able to send and receive messages on telegram\";\n\tprivate bot: Telegraf<Context>;\n\tpublic messageManager: MessageManager;\n\tprivate options;\n\tprivate knownChats: Map<string, any> = new Map();\n\n\t/**\n\t * Constructor for TelegramService class.\n\t * @param {IAgentRuntime} runtime - The runtime object for the agent.\n\t */\n\tconstructor(runtime: IAgentRuntime) {\n\t\tsuper(runtime);\n\t\tlogger.log(\"📱 Constructing new TelegramService...\");\n\t\tthis.options = {\n\t\t\ttelegram: {\n\t\t\t\tapiRoot: runtime.getSetting(\"TELEGRAM_API_ROOT\") ||\n\t\t\t\t\tprocess.env.TELEGRAM_API_ROOT ||\n\t\t\t\t\t\"https://api.telegram.org\",\n\t\t\t},\n\t\t};\n\t\tconst botToken = runtime.getSetting(\"TELEGRAM_BOT_TOKEN\");\n\t\tthis.bot = new Telegraf(botToken, this.options);\n\t\tthis.messageManager = new MessageManager(this.bot, this.runtime);\n\t\tlogger.log(\"✅ TelegramService constructor completed\");\n\t}\n\n\t/**\n\t * Starts the Telegram service for the given runtime.\n\t *\n\t * @param {IAgentRuntime} runtime - The agent runtime to start the Telegram service for.\n\t * @returns {Promise<TelegramService>} A promise that resolves with the initialized TelegramService.\n\t */\n\tstatic async start(runtime: IAgentRuntime): Promise<TelegramService> {\n\t\tawait validateTelegramConfig(runtime);\n\n\t\tconst maxRetries = 5;\n\t\tlet retryCount = 0;\n\t\tlet lastError: Error | null = null;\n\n\t\twhile (retryCount < maxRetries) {\n\t\t\ttry {\n\t\t\t\tconst service = new TelegramService(runtime);\n\n\t\t\t\tlogger.success(\n\t\t\t\t\t`✅ Telegram client successfully started for character ${runtime.character.name}`\n\t\t\t\t);\n\n\t\t\t\tlogger.log(\"🚀 Starting Telegram bot...\");\n\t\t\t\tawait service.initializeBot();\n\t\t\t\tservice.setupMessageHandlers();\n\n\t\t\t\t// Wait for bot to be ready by testing getMe()\n\t\t\t\tawait service.bot.telegram.getMe();\n\n\t\t\t\treturn service;\n\t\t\t} catch (error) {\n\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\tlogger.error(`Telegram initialization attempt ${retryCount + 1} failed: ${lastError.message}`);\n\t\t\t\tretryCount++;\n\n\t\t\t\tif (retryCount < maxRetries) {\n\t\t\t\t\tconst delay = 2 ** retryCount * 1000; // Exponential backoff\n\t\t\t\t\tlogger.info(`Retrying Telegram initialization in ${delay / 1000} seconds...`);\n\t\t\t\t\tawait new Promise(resolve => setTimeout(resolve, delay));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tthrow new Error(`Telegram initialization failed after ${maxRetries} attempts. Last error: ${lastError?.message}`);\n\t}\n\n\t/**\n\t * Stops the agent runtime.\n\t * @param {IAgentRuntime} runtime - The agent runtime to stop\n\t */\n\tstatic async stop(runtime: IAgentRuntime) {\n\t\t// Implement shutdown if necessary\n\t\tconst tgClient = runtime.getService(TELEGRAM_SERVICE_NAME);\n\t\tif (tgClient) {\n\t\t\tawait tgClient.stop();\n\t\t}\n\t}\n\n\t/**\n\t * Asynchronously stops the bot.\n\t *\n\t * @returns A Promise that resolves once the bot has stopped.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.bot.stop();\n\t}\n\n\t/**\n\t * Initializes the Telegram bot by launching it, getting bot info, and setting up message manager.\n\t * @returns {Promise<void>} A Promise that resolves when the initialization is complete.\n\t */\n\tprivate async initializeBot(): Promise<void> {\n\t\tthis.bot.launch({\n\t\t\tdropPendingUpdates: true,\n\t\t\tallowedUpdates: [\"message\", \"message_reaction\"],\n\t\t});\n\n\t\t// Get bot info for identification purposes\n\t\tconst botInfo = await this.bot.telegram.getMe();\n\t\tlogger.log(`Bot info: ${JSON.stringify(botInfo)}`);\n\n\t\t// Handle sigint and sigterm signals to gracefully stop the bot\n\t\tprocess.once(\"SIGINT\", () => this.bot.stop(\"SIGINT\"));\n\t\tprocess.once(\"SIGTERM\", () => this.bot.stop(\"SIGTERM\"));\n\t}\n\n\t/**\n\t * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.\n\t * @param {Context} ctx - The context of the incoming update.\n\t * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.\n\t */\n\tprivate async isGroupAuthorized(ctx: Context): Promise<boolean> {\n\t\tconst chatId = ctx.chat?.id.toString();\n\t\tif (!chatId) return false;\n\n\t\t// If this is a chat we haven't seen before, emit WORLD_JOINED event\n\t\tif (!this.knownChats.has(chatId)) {\n\t\t\tawait this.handleNewChat(ctx);\n\t\t}\n\n\t\tconst allowedChats = this.runtime.getSetting(\"TELEGRAM_ALLOWED_CHATS\");\n\t\tif (!allowedChats) {\n\t\t\treturn true; // All chats are allowed if no restriction is set\n\t\t}\n\n\t\ttry {\n\t\t\tconst allowedChatsList = JSON.parse(allowedChats as string);\n\t\t\treturn allowedChatsList.includes(chatId);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error parsing TELEGRAM_ALLOWED_CHATS:\", error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Handles new chat discovery and emits WORLD_JOINED event\n\t * @param {Context} ctx - The context of the incoming update\n\t */\n\tprivate async handleNewChat(ctx: Context): Promise<void> {\n\t\tif (!ctx.chat) return;\n\n\t\tconst chat = ctx.chat;\n\t\tconst chatId = chat.id.toString();\n\n\t\t// Mark this chat as known\n\t\tthis.knownChats.set(chatId, chat);\n\n\t\t// Get chat title based on type\n\t\tlet chatTitle: string;\n\t\tlet channelType: ChannelType;\n\n\t\tswitch (chat.type) {\n\t\t\tcase 'private':\n\t\t\t\tchatTitle = `Chat with ${chat.first_name || 'Unknown User'}`;\n\t\t\t\tchannelType = ChannelType.DM;\n\t\t\t\tbreak;\n\t\t\tcase 'group':\n\t\t\t\tchatTitle = chat.title || 'Unknown Group';\n\t\t\t\tchannelType = ChannelType.GROUP;\n\t\t\t\tbreak;\n\t\t\tcase 'supergroup':\n\t\t\t\tchatTitle = chat.title || 'Unknown Supergroup';\n\t\t\t\tchannelType = ChannelType.GROUP;\n\t\t\t\tbreak;\n\t\t\tcase 'channel':\n\t\t\t\tchatTitle = chat.title || 'Unknown Channel';\n\t\t\t\tchannelType = ChannelType.FEED;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tchatTitle = 'Unknown Chat';\n\t\t\t\tchannelType = ChannelType.GROUP;\n\t\t}\n\n\t\t// Create standardized world data\n\t\tconst worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n\t\tconst roomId = createUniqueUuid(this.runtime, chatId) as UUID;\n\n\t\t// Build world representation\n\t\tconst world: World = {\n\t\t\tid: worldId,\n\t\t\tname: chatTitle,\n\t\t\tagentId: this.runtime.agentId,\n\t\t\tserverId: chatId,\n\t\t\tmetadata: {\n\t\t\t\tsource: \"telegram\",\n\t\t\t\townership: { ownerId: chatId },\n\t\t\t\troles: {\n\t\t\t\t\t[chatId]: Role.OWNER,\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\n\t\t// Build room representation\n\t\tconst room: Room = {\n\t\t\tid: roomId,\n\t\t\tname: chatTitle,\n\t\t\tsource: \"telegram\",\n\t\t\ttype: channelType,\n\t\t\tchannelId: chatId,\n\t\t\tserverId: chatId,\n\t\t\tworldId: worldId,\n\t\t};\n\n\t\t// Build users list\n\t\tconst users: Entity[] = [];\n\t\t// For private chats, add the user\n\t\tif (chat.type === 'private' && chat.id) {\n\t\t\tconst userId = createUniqueUuid(this.runtime, chat.id.toString()) as UUID;\n\t\t\tusers.push({\n\t\t\t\tid: userId,\n\t\t\t\tnames: [chat.first_name || 'Unknown User'],\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\tmetadata: {\n\t\t\t\t\ttelegram: {\n\t\t\t\t\t\tid: chat.id.toString(),\n\t\t\t\t\t\tusername: chat.username || 'unknown',\n\t\t\t\t\t\tname: chat.first_name || 'Unknown User',\n\t\t\t\t\t},\n\t\t\t\t\tsource: \"telegram\"\n\t\t\t\t}\n\t\t\t});\n\t\t} else if (chat.type === 'group' || chat.type === 'supergroup') {\n\t\t\t// For groups and supergroups, try to get member information\n\t\t\ttry {\n\t\t\t\t// Get chat administrators (this is what's available through the Bot API)\n\t\t\t\tconst admins = await this.bot.telegram.getChatAdministrators(chat.id);\n\n\t\t\t\tif (admins && admins.length > 0) {\n\t\t\t\t\tfor (const admin of admins) {\n\t\t\t\t\t\tconst userId = createUniqueUuid(this.runtime, admin.user.id.toString()) as UUID;\n\t\t\t\t\t\tusers.push({\n\t\t\t\t\t\t\tid: userId,\n\t\t\t\t\t\t\tnames: [admin.user.first_name || admin.user.username || 'Unknown Admin'],\n\t\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\t\ttelegram: {\n\t\t\t\t\t\t\t\t\tid: admin.user.id.toString(),\n\t\t\t\t\t\t\t\t\tusername: admin.user.username || 'unknown',\n\t\t\t\t\t\t\t\t\tname: admin.user.first_name || 'Unknown Admin',\n\t\t\t\t\t\t\t\t\tisAdmin: true,\n\t\t\t\t\t\t\t\t\tadminTitle: admin.custom_title || (admin.status === 'creator' ? 'Owner' : 'Admin')\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\t\t\t\troles: [admin.status === 'creator' ? Role.OWNER : Role.ADMIN]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Additionally, we can estimate member count\n\t\t\t\ttry {\n\t\t\t\t\tconst chatInfo = await this.bot.telegram.getChat(chat.id);\n\t\t\t\t\tif (chatInfo && 'member_count' in chatInfo) {\n\t\t\t\t\t\t// Store this information in the world metadata\n\t\t\t\t\t\tworld.metadata.memberCount = chatInfo.member_count;\n\t\t\t\t\t}\n\t\t\t\t} catch (countError) {\n\t\t\t\t\tlogger.warn(`Could not get member count for chat ${chatId}: ${countError}`);\n\t\t\t\t}\n\n\t\t\t} catch (error) {\n\t\t\t\tlogger.warn(`Could not fetch administrators for chat ${chatId}: ${error}`);\n\t\t\t}\n\t\t}\n\n\t\t// Create payload for world events\n\t\tconst worldPayload = {\n\t\t\truntime: this.runtime,\n\t\t\tworld,\n\t\t\trooms: [room],\n\t\t\tentities: users,\n\t\t\tsource: \"telegram\"\n\t\t};\n\n\t\t// Create Telegram-specific payload\n\t\tconst telegramWorldPayload = {\n\t\t\t...worldPayload,\n\t\t\tchat\n\t\t};\n\n\t\t// Emit generic WORLD_JOINED event\n\t\tthis.runtime.emitEvent(\n\t\t\tEventTypes.WORLD_JOINED,\n\t\t\tworldPayload\n\t\t);\n\n\t\t// Emit platform-specific WORLD_JOINED event\n\t\tthis.runtime.emitEvent(\n\t\t\tTelegramEventTypes.WORLD_JOINED,\n\t\t\ttelegramWorldPayload\n\t\t);\n\n\t\t// Set up a handler to track new entities as they interact with the chat\n\t\tif (chat.type === 'group' || chat.type === 'supergroup') {\n\t\t\tthis.setupEntityTracking(chat.id);\n\t\t}\n\t}\n\n\t/**\n\t * Sets up message and reaction handlers for the bot.\n\t *\n\t * @private\n\t * @returns {void}\n\t */\n\tprivate setupMessageHandlers(): void {\n\t\t// Regular message handler\n\t\tthis.bot.on(\"message\", async (ctx) => {\n\t\t\ttry {\n\t\t\t\tif (!(await this.isGroupAuthorized(ctx))) return;\n\t\t\t\tawait this.messageManager.handleMessage(ctx);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error handling message:\", error);\n\t\t\t}\n\t\t});\n\n\t\t// Reaction handler\n\t\tthis.bot.on(\"message_reaction\", async (ctx) => {\n\t\t\ttry {\n\t\t\t\tif (!(await this.isGroupAuthorized(ctx))) return;\n\t\t\t\tawait this.messageManager.handleReaction(ctx);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error handling reaction:\", error);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * Sets up tracking for new entities in a group chat to sync them as entities\n\t * @param {number} chatId - The Telegram chat ID to track entities for\n\t */\n\tprivate setupEntityTracking(chatId: number): void {\n\t\t// We'll maintain a set of entity IDs we've already synced\n\t\tconst syncedEntityIds = new Set<string>();\n\n\t\t// Add handler to track new message authors\n\t\tthis.bot.on('message', async (ctx) => {\n\t\t\tif (!ctx.chat || ctx.chat.id !== chatId || !ctx.from) return;\n\n\t\t\tconst entityId = ctx.from.id.toString();\n\t\t\tif (syncedEntityIds.has(entityId)) return;\n\n\t\t\t// Add to synced set to avoid duplicate processing\n\t\t\tsyncedEntityIds.add(entityId);\n\n\t\t\t// Sync this entity\n\t\t\tconst entityUuid = createUniqueUuid(this.runtime, entityId) as UUID;\n\t\t\tconst worldId = createUniqueUuid(this.runtime, chatId.toString()) as UUID;\n\t\t\tconst chatIdStr = chatId.toString();\n\n\t\t\ttry {\n\t\t\t\t// Create entity\n\t\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\t\tentityId: entityUuid,\n\t\t\t\t\troomId: createUniqueUuid(this.runtime, chatIdStr),\n\t\t\t\t\tuserName: ctx.from.username || ctx.from.first_name || 'Unknown Entity',\n\t\t\t\t\tname: ctx.from.first_name || ctx.from.username || 'Unknown Entity',\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tchannelId: chatIdStr,\n\t\t\t\t\tserverId: chatIdStr,\n\t\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t\t\tworldId,\n\t\t\t\t});\n\n\t\t\t\t// Create entity joined payload\n\t\t\t\tconst entityJoinedPayload = {\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tentityId: entityUuid,\n\t\t\t\t\tentity: {\n\t\t\t\t\t\tid: entityId,\n\t\t\t\t\t\tusername: ctx.from.username || ctx.from.first_name || 'Unknown Entity',\n\t\t\t\t\t\tdisplayName: ctx.from.first_name || ctx.from.username || 'Unknown Entity'\n\t\t\t\t\t},\n\t\t\t\t\tworldId,\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tmetadata: {\n\t\t\t\t\t\tjoinedAt: Date.now()\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t// Create Telegram-specific payload\n\t\t\t\tconst telegramEntityJoinedPayload = {\n\t\t\t\t\t...entityJoinedPayload,\n\t\t\t\t\ttelegramUser: {\n\t\t\t\t\t\tid: ctx.from.id,\n\t\t\t\t\t\tusername: ctx.from.username,\n\t\t\t\t\t\tfirst_name: ctx.from.first_name\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\t// Emit generic ENTITY_JOINED event\n\t\t\t\tthis.runtime.emitEvent(\n\t\t\t\t\tEventTypes.ENTITY_JOINED,\n\t\t\t\t\tentityJoinedPayload\n\t\t\t\t);\n\n\t\t\t\t// Emit platform-specific ENTITY_JOINED event\n\t\t\t\tthis.runtime.emitEvent(\n\t\t\t\t\tTelegramEventTypes.ENTITY_JOINED,\n\t\t\t\t\ttelegramEntityJoinedPayload\n\t\t\t\t);\n\n\t\t\t\tlogger.info(`Tracked new Telegram entity: ${ctx.from.username || ctx.from.first_name || entityId}`);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error syncing new Telegram entity ${entityId} from chat ${chatId}:`, error);\n\t\t\t}\n\t\t});\n\n\t\t// Track when entities leave chat (from service message)\n\t\tthis.bot.on('left_chat_member', async (ctx) => {\n\t\t\tif (!ctx.message?.left_chat_member || ctx.chat?.id !== chatId) return;\n\n\t\t\tconst leftUser = ctx.message.left_chat_member;\n\t\t\tconst entityId = createUniqueUuid(this.runtime, leftUser.id.toString()) as UUID;\n\t\t\tconst chatIdStr = chatId.toString();\n\t\t\tconst worldId = createUniqueUuid(this.runtime, chatIdStr);\n\n\t\t\ttry {\n\t\t\t\t// Get the entity\n\t\t\t\tconst entity = await this.runtime.getEntityById(entityId);\n\t\t\t\tif (entity) {\n\t\t\t\t\t// Update entity metadata to show as inactive\n\t\t\t\t\tentity.metadata = {\n\t\t\t\t\t\t...entity.metadata,\n\t\t\t\t\t\tstatus: \"INACTIVE\",\n\t\t\t\t\t\tleftAt: Date.now(),\n\t\t\t\t\t};\n\t\t\t\t\tawait this.runtime.updateEntity(entity);\n\n\t\t\t\t\t// Create entity left payload\n\t\t\t\t\tconst entityLeftPayload = {\n\t\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tentity: {\n\t\t\t\t\t\t\tid: leftUser.id.toString(),\n\t\t\t\t\t\t\tusername: leftUser.username || leftUser.first_name || 'Unknown Entity',\n\t\t\t\t\t\t\tdisplayName: leftUser.first_name || leftUser.username || 'Unknown Entity'\n\t\t\t\t\t\t},\n\t\t\t\t\t\tworldId,\n\t\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tleftAt: Date.now()\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t// Create Telegram-specific payload\n\t\t\t\t\tconst telegramEntityLeftPayload = {\n\t\t\t\t\t\t...entityLeftPayload,\n\t\t\t\t\t\ttelegramUser: {\n\t\t\t\t\t\t\tid: leftUser.id,\n\t\t\t\t\t\t\tusername: leftUser.username,\n\t\t\t\t\t\t\tfirst_name: leftUser.first_name\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\t// Emit generic ENTITY_LEFT event\n\t\t\t\t\tthis.runtime.emitEvent(\n\t\t\t\t\t\tEventTypes.ENTITY_LEFT,\n\t\t\t\t\t\tentityLeftPayload\n\t\t\t\t\t);\n\n\t\t\t\t\t// Emit platform-specific ENTITY_LEFT event\n\t\t\t\t\tthis.runtime.emitEvent(\n\t\t\t\t\t\tTelegramEventTypes.ENTITY_LEFT,\n\t\t\t\t\t\ttelegramEntityLeftPayload\n\t\t\t\t\t);\n\n\t\t\t\t\tlogger.info(`Entity ${leftUser.username || leftUser.first_name || leftUser.id} left chat ${chatId}`);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error handling Telegram entity leaving chat ${chatId}:`, error);\n\t\t\t}\n\t\t});\n\t}\n}\n","import type { IAgentRuntime } from \"@elizaos/core\";\nimport { z } from \"zod\";\n\nexport const telegramEnvSchema = z.object({\n\tTELEGRAM_BOT_TOKEN: z.string().min(1, \"Telegram bot token is required\"),\n});\n\n/**\n * Represents the type definition for configuring a Telegram bot based on the inferred schema.\n */\nexport type TelegramConfig = z.infer<typeof telegramEnvSchema>;\n\n/**\n * Validates the Telegram configuration by retrieving the Telegram bot token from the runtime settings or environment variables.\n *\n * @param {IAgentRuntime} runtime - The agent runtime used to get the setting.\n * @returns {Promise<TelegramConfig>} A promise that resolves with the validated Telegram configuration.\n */\nexport async function validateTelegramConfig(\n\truntime: IAgentRuntime,\n): Promise<TelegramConfig> {\n\ttry {\n\t\tconst config = {\n\t\t\tTELEGRAM_BOT_TOKEN:\n\t\t\t\truntime.getSetting(\"TELEGRAM_BOT_TOKEN\") ||\n\t\t\t\tprocess.env.TELEGRAM_BOT_TOKEN,\n\t\t};\n\n\t\treturn telegramEnvSchema.parse(config);\n\t} catch (error) {\n\t\tif (error instanceof z.ZodError) {\n\t\t\tconst errorMessages = error.errors\n\t\t\t\t.map((err) => `${err.path.join(\".\")}: ${err.message}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\tthrow new Error(\n\t\t\t\t`Telegram configuration validation failed:\\n${errorMessages}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n","import {\n\tChannelType,\n\ttype Content,\n\tEventTypes,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Media,\n\ttype Memory,\n\tModelType,\n\ttype UUID,\n\tcreateUniqueUuid,\n\tlogger,\n} from \"@elizaos/core\";\nimport type { Chat, Message, ReactionType, Update } from \"@telegraf/types\";\nimport type { Context, NarrowedContext, Telegraf } from \"telegraf\";\nimport { TelegramEventTypes, type TelegramMessageReceivedPayload, type TelegramMessageSentPayload, type TelegramReactionReceivedPayload } from \"./types\";\nimport { escapeMarkdown } from \"./utils\";\n\nimport fs from \"node:fs\";\n\n/**\n * Enum representing different types of media.\n * @enum { string }\n * @readonly\n */\nexport enum MediaType {\n\tPHOTO = \"photo\",\n\tVIDEO = \"video\",\n\tDOCUMENT = \"document\",\n\tAUDIO = \"audio\",\n\tANIMATION = \"animation\",\n}\n\nconst MAX_MESSAGE_LENGTH = 4096; // Telegram's max message length\n\nconst getChannelType = (chat: Chat): ChannelType => {\n\tif (chat.type === \"private\") return ChannelType.DM;\n\tif (chat.type === \"supergroup\") return ChannelType.GROUP;\n\tif (chat.type === \"channel\") return ChannelType.GROUP;\n\tif (chat.type === \"group\") return ChannelType.GROUP;\n};\n\n/**\n * Class representing a message manager.\n * @class\n */\nexport class MessageManager {\n\tpublic bot: Telegraf<Context>;\n\tprotected runtime: IAgentRuntime;\n\n\t/**\n\t * Constructor for creating a new instance of a BotAgent.\n\t *\n\t * @param {Telegraf<Context>} bot - The Telegraf instance used for interacting with the bot platform.\n\t * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n\t */\n\tconstructor(bot: Telegraf<Context>, runtime: IAgentRuntime) {\n\t\tthis.bot = bot;\n\t\tthis.runtime = runtime;\n\t}\n\n\t// Process image messages and generate descriptions\n\t/**\n\t * Process an image from a Telegram message to extract the image URL and description.\n\t *\n\t * @param {Message} message - The Telegram message object containing the image.\n\t * @returns {Promise<{ description: string } | null>} The description of the processed image or null if no image found.\n\t */\n\tasync processImage(\n\t\tmessage: Message,\n\t): Promise<{ description: string } | null> {\n\t\ttry {\n\t\t\tlet imageUrl: string | null = null;\n\n\t\t\tlogger.info(`Telegram Message: ${message}`);\n\n\t\t\tif (\"photo\" in message && message.photo?.length > 0) {\n\t\t\t\tconst photo = message.photo[message.photo.length - 1];\n\t\t\t\tconst fileLink = await this.bot.telegram.getFileLink(photo.file_id);\n\t\t\t\timageUrl = fileLink.toString();\n\t\t\t} else if (\n\t\t\t\t\"document\" in message &&\n\t\t\t\tmessage.document?.mime_type?.startsWith(\"image/\")\n\t\t\t) {\n\t\t\t\tconst fileLink = await this.bot.telegram.getFileLink(\n\t\t\t\t\tmessage.document.file_id,\n\t\t\t\t);\n\t\t\t\timageUrl = fileLink.toString();\n\t\t\t}\n\n\t\t\tif (imageUrl) {\n\t\t\t\tconst { title, description } = await this.runtime.useModel(\n\t\t\t\t\tModelType.IMAGE_DESCRIPTION,\n\t\t\t\t\timageUrl,\n\t\t\t\t);\n\t\t\t\treturn { description: `[Image: ${title}\\n${description}]` };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(\"❌ Error processing image:\", error);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t// Send long messages in chunks\n\t/**\n\t * Sends a message in chunks, handling attachments and splitting the message if necessary\n\t *\n\t * @param {Context} ctx - The context object representing the current state of the bot\n\t * @param {Content} content - The content of the message to be sent\n\t * @param {number} [replyToMessageId] - The ID of the message to reply to, if any\n\t * @returns {Promise<Message.TextMessage[]>} - An array of TextMessage objects representing the messages sent\n\t */\n\tasync sendMessageInChunks(\n\t\tctx: Context,\n\t\tcontent: Content,\n\t\treplyToMessageId?: number,\n\t): Promise<Message.TextMessage[]> {\n\t\tif (content.attachments && content.attachments.length > 0) {\n\t\t\tcontent.attachments.map(async (attachment: Media) => {\n\t\t\t\tconst typeMap: { [key: string]: MediaType } = {\n\t\t\t\t\t\"image/gif\": MediaType.ANIMATION,\n\t\t\t\t\timage: MediaType.PHOTO,\n\t\t\t\t\tdoc: MediaType.DOCUMENT,\n\t\t\t\t\tvideo: MediaType.VIDEO,\n\t\t\t\t\taudio: MediaType.AUDIO,\n\t\t\t\t};\n\n\t\t\t\tlet mediaType: MediaType | undefined = undefined;\n\n\t\t\t\tfor (const prefix in typeMap) {\n\t\t\t\t\tif (attachment.contentType.startsWith(prefix)) {\n\t\t\t\t\t\tmediaType = typeMap[prefix];\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!mediaType) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Unsupported Telegram attachment content type: ${attachment.contentType}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tawait this.sendMedia(\n\t\t\t\t\tctx,\n\t\t\t\t\tattachment.url,\n\t\t\t\t\tmediaType,\n\t\t\t\t\tattachment.description,\n\t\t\t\t);\n\t\t\t});\n\t\t} else {\n\t\t\tconst chunks = this.splitMessage(content.text);\n\t\t\tconst sentMessages: Message.TextMessage[] = [];\n\n\t\t\tfor (let i = 0; i < chunks.length; i++) {\n\t\t\t\tconst chunk = escapeMarkdown(chunks[i]);\n\t\t\t\tconst sentMessage = (await ctx.telegram.sendMessage(\n\t\t\t\t\tctx.chat.id,\n\t\t\t\t\tchunk,\n\t\t\t\t\t{\n\t\t\t\t\t\treply_parameters:\n\t\t\t\t\t\t\ti === 0 && replyToMessageId\n\t\t\t\t\t\t\t\t? { message_id: replyToMessageId }\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\tparse_mode: \"Markdown\",\n\t\t\t\t\t},\n\t\t\t\t)) as Message.TextMessage;\n\n\t\t\t\tsentMessages.push(sentMessage);\n\t\t\t}\n\n\t\t\treturn sentMessages;\n\t\t}\n\t}\n\n\t/**\n\t * Sends media to a chat using the Telegram API.\n\t *\n\t * @param {Context} ctx - The context object containing information about the current chat.\n\t * @param {string} mediaPath - The path to the media to be sent, either a URL or a local file path.\n\t * @param {MediaType} type - The type of media being sent (PHOTO, VIDEO, DOCUMENT, AUDIO, or ANIMATION).\n\t * @param {string} [caption] - Optional caption for the media being sent.\n\t *\n\t * @returns {Promise<void>} A Promise that resolves when the media is successfully sent.\n\t */\n\tasync sendMedia(\n\t\tctx: Context,\n\t\tmediaPath: string,\n\t\ttype: MediaType,\n\t\tcaption?: string,\n\t): Promise<void> {\n\t\ttry {\n\t\t\tconst isUrl = /^(http|https):\\/\\//.test(mediaPath);\n\t\t\t// biome-ignore lint/complexity/noBannedTypes: <explanation>\n\t\t\tconst sendFunctionMap: Record<MediaType, Function> = {\n\t\t\t\t[MediaType.PHOTO]: ctx.telegram.sendPhoto.bind(ctx.telegram),\n\t\t\t\t[MediaType.VIDEO]: ctx.telegram.sendVideo.bind(ctx.telegram),\n\t\t\t\t[MediaType.DOCUMENT]: ctx.telegram.sendDocument.bind(ctx.telegram),\n\t\t\t\t[MediaType.AUDIO]: ctx.telegram.sendAudio.bind(ctx.telegram),\n\t\t\t\t[MediaType.ANIMATION]: ctx.telegram.sendAnimation.bind(ctx.telegram),\n\t\t\t};\n\n\t\t\tconst sendFunction = sendFunctionMap[type];\n\n\t\t\tif (!sendFunction) {\n\t\t\t\tthrow new Error(`Unsupported media type: ${type}`);\n\t\t\t}\n\n\t\t\tif (isUrl) {\n\t\t\t\t// Handle HTTP URLs\n\t\t\t\tawait sendFunction(ctx.chat.id, mediaPath, { caption });\n\t\t\t} else {\n\t\t\t\t// Handle local file paths\n\t\t\t\tif (!fs.existsSync(mediaPath)) {\n\t\t\t\t\tthrow new Error(`File not found at path: ${mediaPath}`);\n\t\t\t\t}\n\n\t\t\t\tconst fileStream = fs.createReadStream(mediaPath);\n\n\t\t\t\ttry {\n\t\t\t\t\tawait sendFunction(ctx.chat.id, { source: fileStream }, { caption });\n\t\t\t\t} finally {\n\t\t\t\t\tfileStream.destroy();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.info(\n\t\t\t\t`${\n\t\t\t\t\ttype.charAt(0).toUpperCase() + type.slice(1)\n\t\t\t\t} sent successfully: ${mediaPath}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\n\t\t\t\t`Failed to send ${type}. Path: ${mediaPath}. Error: ${error.message}`,\n\t\t\t);\n\t\t\tlogger.debug(error.stack);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t// Split message into smaller parts\n\t/**\n\t * Splits a given text into an array of strings based on the maximum message length.\n\t *\n\t * @param {string} text - The text to split into chunks.\n\t * @returns {string[]} An array of strings with each element representing a chunk of the original text.\n\t */\n\tprivate splitMessage(text: string): string[] {\n\t\tconst chunks: string[] = [];\n\t\tlet currentChunk = \"\";\n\n\t\tconst lines = text.split(\"\\n\");\n\t\tfor (const line of lines) {\n\t\t\tif (currentChunk.length + line.length + 1 <= MAX_MESSAGE_LENGTH) {\n\t\t\t\tcurrentChunk += (currentChunk ? \"\\n\" : \"\") + line;\n\t\t\t} else {\n\t\t\t\tif (currentChunk) chunks.push(currentChunk);\n\t\t\t\tcurrentChunk = line;\n\t\t\t}\n\t\t}\n\n\t\tif (currentChunk) chunks.push(currentChunk);\n\t\treturn chunks;\n\t}\n\n\t// Main handler for incoming messages\n\t/**\n\t * Handle incoming messages from Telegram and process them accordingly.\n\t * @param {Context} ctx - The context object containing information about the message.\n\t * @returns {Promise<void>}\n\t */\n\tpublic async handleMessage(ctx: Context): Promise<void> {\n\t\t// Type guard to ensure message exists\n\t\tif (!ctx.message || !ctx.from) return;\n\n\t\tconst message = ctx.message as Message.TextMessage;\n\n\t\ttry {\n\t\t\t// Convert IDs to UUIDs\n\t\t\tconst entityId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\tctx.from.id.toString(),\n\t\t\t) as UUID;\n\t\t\tconst userName =\n\t\t\t\tctx.from.username || ctx.from.first_name || \"Unknown User\";\n\t\t\tconst roomId = createUniqueUuid(this.runtime, ctx.chat?.id.toString());\n\n\t\t\t// Get message ID\n\t\t\tconst messageId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\tmessage?.message_id?.toString(),\n\t\t\t);\n\n\t\t\t// Handle images\n\t\t\tconst imageInfo = await this.processImage(message);\n\n\t\t\t// Get message text - use type guards for safety\n\t\t\tlet messageText = \"\";\n\t\t\tif (\"text\" in message && message.text) {\n\t\t\t\tmessageText = message.text;\n\t\t\t} else if (\"caption\" in message && message.caption) {\n\t\t\t\tmessageText = message.caption as string;\n\t\t\t}\n\n\t\t\t// Combine text and image description\n\t\t\tconst fullText = imageInfo\n\t\t\t\t? `${messageText} ${imageInfo.description}`\n\t\t\t\t: messageText;\n\t\t\tif (!fullText) return;\n\n\t\t\t// Get chat type and determine channel type\n\t\t\tconst chat = message.chat as Chat;\n\t\t\tconst channelType = getChannelType(chat);\n\n\t\t\t// Get world and room IDs\n\t\t\t// For private chats, the world is the chat itself\n\t\t\t// For groups/channels, the world is the supergroup/channel\n\t\t\tconst worldId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\tchat.type === \"private\" ? `private_${chat.id}` : chat.id.toString()\n\t\t\t);\n\n\t\t\t// Get world and room names\n\t\t\tconst worldName =\n\t\t\t\tchat.type === \"supergroup\"\n\t\t\t\t\t? (chat as Chat.SupergroupChat).title\n\t\t\t\t\t: chat.type === \"channel\"\n\t\t\t\t\t\t? (chat as Chat.ChannelChat).title\n\t\t\t\t\t\t: chat.type === \"private\"\n\t\t\t\t\t\t\t? `Chat with ${(chat as Chat.PrivateChat).first_name || 'Unknown'}`\n\t\t\t\t\t\t\t: \"Telegram\";\n\n\t\t\tconst roomName =\n\t\t\t\tchat.type === \"private\"\n\t\t\t\t\t? (chat as Chat.PrivateChat).first_name\n\t\t\t\t\t: chat.type === \"supergroup\"\n\t\t\t\t\t\t? (chat as Chat.SupergroupChat).title\n\t\t\t\t\t\t: chat.type === \"channel\"\n\t\t\t\t\t\t\t? (chat as Chat.ChannelChat).title\n\t\t\t\t\t\t\t: chat.type === \"group\"\n\t\t\t\t\t\t\t\t? (chat as Chat.GroupChat).title\n\t\t\t\t\t\t\t\t: \"Unknown Group\";\n\n\t\t\t// Ensure entity connection with proper world/server ID handling\n\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t\tuserName,\n\t\t\t\tname: userName,\n\t\t\t\tsource: \"telegram\",\n\t\t\t\tchannelId: ctx.chat.id.toString(),\n\t\t\t\tserverId: chat.type === \"private\" ? undefined : chat.id.toString(), // Only set serverId for non-private chats\n\t\t\t\ttype: channelType,\n\t\t\t\tworldId: worldId\n\t\t\t});\n\n\t\t\t// Ensure room exists\n\t\t\tconst room = {\n\t\t\t\tid: roomId,\n\t\t\t\tname: roomName,\n\t\t\t\tsource: \"telegram\",\n\t\t\t\ttype: channelType,\n\t\t\t\tchannelId: ctx.chat.id.toString(),\n\t\t\t\tserverId: chat.type === \"private\" ? undefined : chat.id.toString(),\n\t\t\t\tworldId: worldId,\n\t\t\t};\n\t\t\t\n\t\t\tawait this.runtime.ensureRoomExists(room);\n\n\t\t\t// Create the memory object\n\t\t\tconst memory: Memory = {\n\t\t\t\tid: messageId,\n\t\t\t\tentityId,\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\troomId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: fullText,\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tchannelType: channelType,\n\t\t\t\t\tinReplyTo:\n\t\t\t\t\t\t\"reply_to_message\" in message && message.reply_to_message\n\t\t\t\t\t\t\t? createUniqueUuid(\n\t\t\t\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t\t\t\tmessage.reply_to_message.message_id.toString(),\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tcreatedAt: message.date * 1000,\n\t\t\t};\n\n\t\t\t// Create callback for handling responses\n\t\t\tconst callback: HandlerCallback = async (\n\t\t\t\tcontent: Content,\n\t\t\t\t_files?: string[],\n\t\t\t) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst sentMessages = await this.sendMessageInChunks(\n\t\t\t\t\t\tctx,\n\t\t\t\t\t\tcontent,\n\t\t\t\t\t\tmessage.message_id,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (!sentMessages) return [];\n\n\t\t\t\t\tconst memories: Memory[] = [];\n\t\t\t\t\tfor (let i = 0; i < sentMessages.length; i++) {\n\t\t\t\t\t\tconst sentMessage = sentMessages[i];\n\t\t\t\t\t\tconst _isLastMessage = i === sentMessages.length - 1;\n\n\t\t\t\t\t\tconst responseMemory: Memory = {\n\t\t\t\t\t\t\tid: createUniqueUuid(\n\t\t\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t\t\tsentMessage.message_id.toString(),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\t\troomId,\n\t\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t\t...content,\n\t\t\t\t\t\t\t\ttext: sentMessage.text,\n\t\t\t\t\t\t\t\tinReplyTo: messageId,\n\t\t\t\t\t\t\t\tchannelType: channelType,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcreatedAt: sentMessage.date * 1000,\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tawait this.runtime.createMemory(responseMemory, \"messages\");\n\t\t\t\t\t\tmemories.push(responseMemory);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn memories;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(\"Error in message callback:\", error);\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// Let the bootstrap plugin handle the message\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tEventTypes.MESSAGE_RECEIVED,\n\t\t\t\t{\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tmessage: memory,\n\t\t\t\t\tcallback,\n\t\t\t\t\tsource: \"telegram\"\n\t\t\t\t},\n\t\t\t);\n\t\t\t\n\t\t\t// Also emit the platform-specific event\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tTelegramEventTypes.MESSAGE_RECEIVED,\n\t\t\t\t{\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tmessage: memory,\n\t\t\t\t\tcallback,\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tctx,\n\t\t\t\t\toriginalMessage: message\n\t\t\t\t} as TelegramMessageReceivedPayload\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error handling Telegram message:\", {\n\t\t\t\terror,\n\t\t\t\tchatId: ctx.chat?.id,\n\t\t\t\tmessageId: ctx.message?.message_id,\n\t\t\t\tfrom: ctx.from?.username || ctx.from?.id\n\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Handles the reaction event triggered by a user reacting to a message.\n\t * * @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update\n\t * @returns {Promise<void>} A Promise that resolves when the reaction handling is complete\n\t */\n\tpublic async handleReaction(\n\t\tctx: NarrowedContext<Context<Update>, Update.MessageReactionUpdate>,\n\t): Promise<void> {\n\t\t// Ensure we have the necessary data\n\t\tif (!ctx.update.message_reaction || !ctx.from) return;\n\n\t\tconst reaction = ctx.update.message_reaction;\n\t\tconst reactionType = reaction.new_reaction[0].type;\n\t\tconst reactionEmoji = (reaction.new_reaction[0] as ReactionType).type;\n\n\t\ttry {\n\t\t\tconst entityId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\tctx.from.id.toString(),\n\t\t\t) as UUID;\n\t\t\tconst roomId = createUniqueUuid(this.runtime, ctx.chat.id.toString());\n\t\t\tconst worldId = createUniqueUuid(this.runtime, ctx.chat.id.toString());\n\n\t\t\tconst reactionId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\t`${reaction.message_id}-${ctx.from.id}-${Date.now()}`,\n\t\t\t);\n\n\t\t\t// Create reaction memory\n\t\t\tconst memory: Memory = {\n\t\t\t\tid: reactionId,\n\t\t\t\tentityId,\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\troomId,\n\t\t\t\tcontent: {\n\t\t\t\t\tchannelType: getChannelType(reaction.chat as Chat),\n\t\t\t\t\ttext: `Reacted with: ${reactionType === \"emoji\" ? reactionEmoji : reactionType}`,\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tinReplyTo: createUniqueUuid(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\treaction.message_id.toString(),\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\tcreatedAt: Date.now(),\n\t\t\t};\n\n\t\t\t// Create callback for handling reaction responses\n\t\t\tconst callback: HandlerCallback = async (content: Content) => {\n\t\t\t\ttry {\n\t\t\t\t\tconst sentMessage = await ctx.reply(content.text);\n\t\t\t\t\tconst responseMemory: Memory = {\n\t\t\t\t\t\tid: createUniqueUuid(\n\t\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t\tsentMessage.message_id.toString(),\n\t\t\t\t\t\t),\n\t\t\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\troomId,\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\t...content,\n\t\t\t\t\t\t\tinReplyTo: reactionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcreatedAt: sentMessage.date * 1000,\n\t\t\t\t\t};\n\t\t\t\t\treturn [responseMemory];\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(\"Error in reaction callback:\", error);\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// Let the bootstrap plugin handle the reaction\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tEventTypes.REACTION_RECEIVED,\n\t\t\t\t{\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tmessage: memory,\n\t\t\t\t\tcallback,\n\t\t\t\t\tsource: \"telegram\"\n\t\t\t\t},\n\t\t\t);\n\t\t\t\n\t\t\t// Also emit the platform-specific event\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tTelegramEventTypes.REACTION_RECEIVED,\n\t\t\t\t{\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tmessage: memory,\n\t\t\t\t\tcallback,\n\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\tctx,\n\t\t\t\t\treactionString: reactionType === \"emoji\" ? reactionEmoji : reactionType,\n\t\t\t\t\toriginalReaction: reaction.new_reaction[0] as ReactionType\n\t\t\t\t} as TelegramReactionReceivedPayload\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error handling reaction:\", error);\n\t\t}\n\t}\n\n\t/**\n\t * Sends a message to a Telegram chat and emits appropriate events\n\t * @param {number | string} chatId - The Telegram chat ID to send the message to\n\t * @param {Content} content - The content to send\n\t * @param {number} [replyToMessageId] - Optional message ID to reply to\n\t * @returns {Promise<Message.TextMessage[]>} The sent messages\n\t */\n\tpublic async sendMessage(\n\t\tchatId: number | string,\n\t\tcontent: Content,\n\t\treplyToMessageId?: number\n\t): Promise<Message.TextMessage[]> {\n\t\ttry {\n\t\t\t// Create a context-like object for sending\n\t\t\tconst ctx = { \n\t\t\t\tchat: { id: chatId },\n\t\t\t\ttelegram: this.bot.telegram\n\t\t\t};\n\t\t\t\n\t\t\tconst sentMessages = await this.sendMessageInChunks(\n\t\t\t\tctx as Context,\n\t\t\t\tcontent,\n\t\t\t\treplyToMessageId\n\t\t\t);\n\n\t\t\tif (!sentMessages?.length) return [];\n\n\t\t\t// Create room ID\n\t\t\tconst roomId = createUniqueUuid(this.runtime, chatId.toString());\n\t\t\t\n\t\t\t// Create memories for the sent messages\n\t\t\tconst memories: Memory[] = [];\n\t\t\tfor (const sentMessage of sentMessages) {\n\t\t\t\tconst memory: Memory = {\n\t\t\t\t\tid: createUniqueUuid(this.runtime, sentMessage.message_id.toString()),\n\t\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\troomId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\t...content,\n\t\t\t\t\t\ttext: sentMessage.text,\n\t\t\t\t\t\tsource: \"telegram\",\n\t\t\t\t\t\tchannelType: getChannelType({ \n\t\t\t\t\t\t\tid: typeof chatId === 'string' ? Number.parseInt(chatId, 10) : chatId,\n\t\t\t\t\t\t\ttype: \"private\" // Default to private, will be overridden if in context\n\t\t\t\t\t\t} as Chat)\n\t\t\t\t\t},\n\t\t\t\t\tcreatedAt: sentMessage.date * 1000\n\t\t\t\t};\n\t\t\t\t\n\t\t\t\tawait this.runtime.createMemory(memory, \"messages\");\n\t\t\t\tmemories.push(memory);\n\t\t\t}\n\n\t\t\t// Emit both generic and platform-specific message sent events\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tEventTypes.MESSAGE_SENT,\n\t\t\t\t{\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tmessages: memories,\n\t\t\t\t\troomId,\n\t\t\t\t\tsource: \"telegram\"\n\t\t\t\t},\n\t\t\t);\n\t\t\t\n\t\t\t// Also emit platform-specific event\n\t\t\tthis.runtime.emitEvent(\n\t\t\t\tTelegramEventTypes.MESSAGE_SENT,\n\t\t\t\t{\n\t\t\t\t\toriginalMessages: sentMessages,\n\t\t\t\t\tchatId\n\t\t\t\t} as TelegramMessageSentPayload\n\t\t\t);\n\t\t\t\n\t\t\treturn sentMessages;\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error sending message to Telegram:\", error);\n\t\t\treturn [];\n\t\t}\n\t}\n}\n","/**\n * Escapes Markdown special characters in the given text, excluding code blocks.\n * @param {string} text - The text to escape Markdown characters from.\n * @returns {string} The text with escaped Markdown characters.\n */\nexport function escapeMarkdown(text: string): string {\n\t// Don't escape if it's a code block\n\tif (text.startsWith(\"```\") && text.endsWith(\"```\")) {\n\t\treturn text;\n\t}\n\n\t// Split the text by code blocks\n\tconst parts = text.split(/(```[\\s\\S]*?```)/g);\n\n\treturn parts\n\t\t.map((part, index) => {\n\t\t\t// If it's a code block (odd indices in the split result will be code blocks)\n\t\t\tif (index % 2 === 1) {\n\t\t\t\treturn part;\n\t\t\t}\n\t\t\t// For regular text, only escape characters that need escaping in Markdown\n\t\t\treturn (\n\t\t\t\tpart\n\t\t\t\t\t// First preserve any intended inline code spans\n\t\t\t\t\t.replace(/`.*?`/g, (match) => match)\n\t\t\t\t\t// Then only escape the minimal set of special characters that need escaping in Markdown mode\n\t\t\t\t\t.replace(/([*_`\\\\])/g, \"\\\\$1\")\n\t\t\t);\n\t\t})\n\t\t.join(\"\");\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\tconst chunks: string[] = [];\n\tlet currentChunk = \"\";\n\n\tconst lines = text.split(\"\\n\");\n\tfor (const line of lines) {\n\t\tif (currentChunk.length + line.length + 1 <= maxLength) {\n\t\t\tcurrentChunk += (currentChunk ? \"\\n\" : \"\") + line;\n\t\t} else {\n\t\t\tif (currentChunk) chunks.push(currentChunk);\n\t\t\tcurrentChunk = line;\n\t\t}\n\t}\n\n\tif (currentChunk) chunks.push(currentChunk);\n\treturn chunks;\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\";\n\nconst TEST_IMAGE_URL =\n\t\"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\tname = \"telegram\";\n\tprivate telegramClient: TelegramService = null;\n\tprivate bot: Telegraf<Context> | null = null;\n\tprivate messageManager: MessageManager | null = null;\n\ttests: { name: string; fn: (runtime: IAgentRuntime) => Promise<void> }[];\n\n\t/**\n\t * Constructor for initializing a set of test cases for a Telegram bot.\n\t *\n\t * @constructor\n\t * @property {Array<Object>} tests - An array of test cases with name and corresponding test functions.\n\t * @property {string} tests.name - The name of the test case.\n\t * @property {function} tests.fn - The test function to be executed.\n\t */\n\tconstructor() {\n\t\tthis.tests = [\n\t\t\t{\n\t\t\t\tname: \"Initialize and Validate Telegram Bot Connection\",\n\t\t\t\tfn: this.testCreatingTelegramBot.bind(this),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Send Basic Text Message to Telegram Chat\",\n\t\t\t\tfn: this.testSendingTextMessage.bind(this),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Send Text Message with an Image Attachment\",\n\t\t\t\tfn: this.testSendingMessageWithAttachment.bind(this),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Handle and Process Incoming Telegram Messages\",\n\t\t\t\tfn: this.testHandlingMessage.bind(this),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Process and Validate Image Attachments in Incoming Messages\",\n\t\t\t\tfn: this.testProcessingImages.bind(this),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * Retrieves the Telegram test chat ID from environment variables.\n\t *\n\t * Reference on getting the Telegram chat ID:\n\t * https://stackoverflow.com/a/32572159\n\t */\n\t/**\n\t * Validates the chat ID by checking if it is set in the runtime settings or environment variables.\n\t * If not set, an error is thrown with a message instructing to provide a valid chat ID.\n\t * @param {IAgentRuntime} runtime - The runtime object that provides access to the settings and environment variables.\n\t * @throws {Error} If TELEGRAM_TEST_CHAT_ID is not set in the runtime settings or environment variables.\n\t * @returns {string} The validated chat ID.\n\t */\n\tvalidateChatId(runtime: IAgentRuntime) {\n\t\tconst testChatId =\n\t\t\truntime.getSetting(\"TELEGRAM_TEST_CHAT_ID\") ||\n\t\t\tprocess.env.TELEGRAM_TEST_CHAT_ID;\n\t\tif (!testChatId) {\n\t\t\tthrow new Error(\n\t\t\t\t\"TELEGRAM_TEST_CHAT_ID is not set. Please provide a valid chat ID in the environment variables.\",\n\t\t\t);\n\t\t}\n\t\treturn testChatId;\n\t}\n\n\tasync getChatInfo(runtime: IAgentRuntime): Promise<Context[\"chat\"]> {\n\t\ttry {\n\t\t\tconst chatId = this.validateChatId(runtime);\n\t\t\tconst chat = await this.bot.telegram.getChat(chatId);\n\t\t\tlogger.log(`Fetched real chat: ${JSON.stringify(chat)}`);\n\t\t\treturn chat;\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error fetching real Telegram chat: ${error}`);\n\t\t}\n\t}\n\n\tasync testCreatingTelegramBot(runtime: IAgentRuntime) {\n\t\tthis.telegramClient = runtime.getService(\"telegram\") as TelegramService;\n\t\tthis.bot = this.telegramClient.messageManager.bot;\n\t\tthis.messageManager = this.telegramClient.messageManager;\n\t\tlogger.success(\"Telegram bot initialized successfully.\");\n\t}\n\n\tasync testSendingTextMessage(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tif (!this.bot) throw new Error(\"Bot not initialized.\");\n\n\t\t\tconst chatId = this.validateChatId(runtime);\n\t\t\tawait this.bot.telegram.sendMessage(chatId, \"Testing Telegram message!\");\n\t\t\tlogger.success(\"Message sent successfully.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error sending Telegram message: ${error}`);\n\t\t}\n\t}\n\n\tasync testSendingMessageWithAttachment(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tif (!this.messageManager)\n\t\t\t\tthrow new Error(\"MessageManager not initialized.\");\n\n\t\t\tconst chat = await this.getChatInfo(runtime);\n\t\t\tconst mockContext: Partial<Context> = {\n\t\t\t\tchat,\n\t\t\t\tfrom: { id: 123, username: \"TestUser\" } as User,\n\t\t\t\ttelegram: this.bot.telegram,\n\t\t\t};\n\n\t\t\tconst messageContent = {\n\t\t\t\ttext: \"Here is an image attachment:\",\n\t\t\t\tattachments: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"123\",\n\t\t\t\t\t\ttitle: \"Sample Image\",\n\t\t\t\t\t\tsource: TEST_IMAGE_URL,\n\t\t\t\t\t\ttext: \"Sample Image\",\n\t\t\t\t\t\turl: TEST_IMAGE_URL,\n\t\t\t\t\t\tcontentType: \"image/png\",\n\t\t\t\t\t\tdescription: \"Sample Image\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t};\n\n\t\t\tawait this.messageManager.sendMessageInChunks(\n\t\t\t\tmockContext as Context,\n\t\t\t\tmessageContent,\n\t\t\t);\n\n\t\t\tlogger.success(\"Message with image attachment sent successfully.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Error sending Telegram message with attachment: ${error}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync testHandlingMessage(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst chat = await this.getChatInfo(runtime);\n\t\t\tconst mockContext: Partial<Context> = {\n\t\t\t\tchat,\n\t\t\t\tfrom: {\n\t\t\t\t\tid: 123,\n\t\t\t\t\tusername: \"TestUser\",\n\t\t\t\t\tis_bot: false,\n\t\t\t\t\tfirst_name: \"Test\",\n\t\t\t\t\tlast_name: \"User\",\n\t\t\t\t} as User,\n\t\t\t\tmessage: {\n\t\t\t\t\tmessage_id: undefined,\n\t\t\t\t\ttext: `@${this.bot.botInfo?.username}! Hello!`,\n\t\t\t\t\tdate: Math.floor(Date.now() / 1000),\n\t\t\t\t\tchat,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: <explanation>\n\t\t\t\t} as any,\n\t\t\t\ttelegram: this.bot.telegram,\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\tawait this.messageManager.handleMessage(mockContext as Context);\n\t\t\t} catch (error) {\n\t\t\t\tthrow new Error(`Error handling Telegram message: ${error}`);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error handling Telegram message: ${error}`);\n\t\t}\n\t}\n\n\tasync testProcessingImages(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst chatId = this.validateChatId(runtime);\n\t\t\tconst fileId = await this.getFileId(chatId, TEST_IMAGE_URL);\n\n\t\t\tconst mockMessage = {\n\t\t\t\tmessage_id: undefined,\n\t\t\t\tchat: { id: chatId } as Chat,\n\t\t\t\tdate: Math.floor(Date.now() / 1000),\n\t\t\t\tphoto: [{ file_id: fileId }],\n\t\t\t\ttext: `@${this.bot.botInfo?.username}!`,\n\t\t\t};\n\n\t\t\tconst { description } =\n\t\t\t\tawait this.messageManager.processImage(mockMessage);\n\t\t\tif (!description) {\n\t\t\t\tthrow new Error(\"Error processing Telegram image\");\n\t\t\t}\n\t\t\tlogger.log(`Processing Telegram image successfully: ${description}`);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error processing Telegram image: ${error}`);\n\t\t}\n\t}\n\n\tasync getFileId(chatId: string, imageUrl: string) {\n\t\ttry {\n\t\t\tconst message = await this.bot.telegram.sendPhoto(chatId, imageUrl);\n\t\t\treturn message.photo[message.photo.length - 1].file_id;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Error sending image: ${error}`);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n","import type { Plugin } from \"@elizaos/core\";\nimport { TELEGRAM_SERVICE_NAME } from \"./constants\";\nimport { TelegramService } from \"./service\";\nimport { TelegramTestSuite } from \"./tests\";\n\nconst telegramPlugin: Plugin = {\n\tname: TELEGRAM_SERVICE_NAME,\n\tdescription: \"Telegram client plugin\",\n\tservices: [TelegramService],\n\ttests: [new TelegramTestSuite()],\n};\nexport default telegramPlugin;\n"],"mappings":";AAAO,IAAM,oBAAoB;AAAA,EAChC,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;AAClC;AAEO,IAAM,wBAAwB;;;ACVrC,SAAS,eAAAA,cAA0B,cAAAC,aAAgC,MAAiB,SAAgC,oBAAAC,mBAAkB,UAAAC,eAAc;AACpJ,SAAuB,gBAAgB;;;ACAvC,SAAS,SAAS;AAEX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACzC,oBAAoB,EAAE,OAAO,EAAE,IAAI,GAAG,gCAAgC;AACvE,CAAC;AAaD,eAAsB,uBACrB,SAC0B;AAC1B,MAAI;AACH,UAAM,SAAS;AAAA,MACd,oBACC,QAAQ,WAAW,oBAAoB,KACvC,QAAQ,IAAI;AAAA,IACd;AAEA,WAAO,kBAAkB,MAAM,MAAM;AAAA,EACtC,SAAS,OAAO;AACf,QAAI,iBAAiB,EAAE,UAAU;AAChC,YAAM,gBAAgB,MAAM,OAC1B,IAAI,CAAC,QAAQ,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,KAAK,IAAI,OAAO,EAAE,EACpD,KAAK,IAAI;AACX,YAAM,IAAI;AAAA,QACT;AAAA,EAA8C,aAAa;AAAA,MAC5D;AAAA,IACD;AACA,UAAM;AAAA,EACP;AACD;;;ACxCA;AAAA,EACC;AAAA,EAEA;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,OACM;;;ACPA,SAAS,eAAe,MAAsB;AAEpD,MAAI,K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AE,SAAS,OAAO,CAAC;AAAA,QAC3B,MAAM,KAAI,UAAK,IAAI,YAAT,mBAAkB,QAAQ;AAAA,MACrC;AAEA,YAAM,EAAE,YAAY,IACnB,MAAM,KAAK,eAAe,aAAa,WAAW;AACnD,UAAI,CAAC,aAAa;AACjB,cAAM,IAAI,MAAM,iCAAiC;AAAA,MAClD;AACA,MAAAA,QAAO,IAAI,2CAA2C,WAAW,EAAE;AAAA,IACpE,SAAS,OAAO;AACf,YAAM,IAAI,MAAM,oCAAoC,KAAK,EAAE;AAAA,IAC5D;AAAA,EACD;AAAA,EAEA,MAAM,UAAU,QAAgB,UAAkB;AACjD,QAAI;AACH,YAAM,UAAU,MAAM,KAAK,IAAI,SAAS,UAAU,QAAQ,QAAQ;AAClE,aAAO,QAAQ,MAAM,QAAQ,MAAM,SAAS,CAAC,EAAE;AAAA,IAChD,SAAS,OAAO;AACf,MAAAA,QAAO,MAAM,wBAAwB,KAAK,EAAE;AAC5C,YAAM;AAAA,IACP;AAAA,EACD;AACD;;;ACxNA,IAAM,iBAAyB;AAAA,EAC9B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU,CAAC,eAAe;AAAA,EAC1B,OAAO,CAAC,IAAI,kBAAkB,CAAC;AAChC;AACA,IAAO,gBAAQ;","names":["ChannelType","EventTypes","createUniqueUuid","logger","logger","ChannelType","createUniqueUuid","EventTypes","logger"]}
|
|
1
|
+
{"version":3,"sources":["../src/constants.ts","../src/service.ts","../src/environment.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 Entity,\n EventType,\n type IAgentRuntime,\n Role,\n type Room,\n Service,\n type UUID,\n type World,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport { type Context, Telegraf } from 'telegraf';\nimport { TELEGRAM_SERVICE_NAME } from './constants';\nimport { validateTelegramConfig } from './environment';\nimport { MessageManager } from './messageManager';\nimport { TelegramEventTypes } from './types';\n\n/**\n * Class representing a Telegram service that allows the agent to send and receive messages on Telegram.\n * @extends Service\n */\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>;\n public messageManager: MessageManager;\n private options;\n private knownChats: Map<string, any> = new Map();\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.log('📱 Constructing new TelegramService...');\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 const botToken = runtime.getSetting('TELEGRAM_BOT_TOKEN');\n this.bot = new Telegraf(botToken, this.options);\n this.messageManager = new MessageManager(this.bot, this.runtime);\n logger.log('✅ TelegramService constructor completed');\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 await validateTelegramConfig(runtime);\n\n const maxRetries = 5;\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n const service = new TelegramService(runtime);\n\n logger.success(\n `✅ Telegram client successfully started for character ${runtime.character.name}`\n );\n\n logger.log('🚀 Starting Telegram bot...');\n await service.initializeBot();\n service.setupMessageHandlers();\n\n // Wait for bot to be ready by testing getMe()\n await service.bot.telegram.getMe();\n\n return service;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error(\n `Telegram initialization attempt ${retryCount + 1} failed: ${lastError.message}`\n );\n retryCount++;\n\n if (retryCount < maxRetries) {\n const delay = 2 ** retryCount * 1000; // Exponential backoff\n logger.info(`Retrying Telegram initialization in ${delay / 1000} seconds...`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n throw new Error(\n `Telegram initialization failed after ${maxRetries} attempts. Last error: ${lastError?.message}`\n );\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.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.log(`Bot info: ${JSON.stringify(botInfo)}`);\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 * 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 // If this is a chat we haven't seen before, emit WORLD_JOINED event\n if (!this.knownChats.has(chatId)) {\n await this.handleNewChat(ctx);\n }\n\n const allowedChats = this.runtime.getSetting('TELEGRAM_ALLOWED_CHATS');\n if (!allowedChats) {\n return true; // All chats are allowed if no restriction is set\n }\n\n try {\n const allowedChatsList = JSON.parse(allowedChats as string);\n return allowedChatsList.includes(chatId);\n } catch (error) {\n logger.error('Error parsing TELEGRAM_ALLOWED_CHATS:', error);\n return false;\n }\n }\n\n /**\n * Handles new chat discovery and emits WORLD_JOINED event\n * @param {Context} ctx - The context of the incoming update\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 based on type\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 // Create standardized world data\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n const roomId = createUniqueUuid(this.runtime, chatId) as UUID;\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 ownership: { ownerId: chatId },\n roles: {\n [chatId]: Role.OWNER,\n },\n },\n };\n\n // Build room representation\n const room: Room = {\n id: roomId,\n name: chatTitle,\n source: 'telegram',\n type: channelType,\n channelId: chatId,\n serverId: chatId,\n worldId: worldId,\n };\n\n // Build users list\n const users: Entity[] = [];\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 users.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 } 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 users.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 }\n }\n\n // Additionally, we can estimate member count\n try {\n const chatInfo = await this.bot.telegram.getChat(chat.id);\n if (chatInfo && 'member_count' in chatInfo) {\n // Store this information in the world metadata\n world.metadata.memberCount = chatInfo.member_count;\n }\n } catch (countError) {\n logger.warn(`Could not get member count for chat ${chatId}: ${countError}`);\n }\n } catch (error) {\n logger.warn(`Could not fetch administrators for chat ${chatId}: ${error}`);\n }\n }\n\n // Create payload for world events\n const worldPayload = {\n runtime: this.runtime,\n world,\n rooms: [room],\n entities: users,\n source: 'telegram',\n };\n\n // Create Telegram-specific payload\n const telegramWorldPayload = {\n ...worldPayload,\n chat,\n };\n\n // Emit generic WORLD_JOINED event\n this.runtime.emitEvent(EventType.WORLD_JOINED, worldPayload);\n\n // Emit platform-specific WORLD_JOINED event\n this.runtime.emitEvent(TelegramEventTypes.WORLD_JOINED, telegramWorldPayload);\n\n // Set up a handler to track new entities as they interact with the chat\n if (chat.type === 'group' || chat.type === 'supergroup') {\n this.setupEntityTracking(chat.id);\n }\n }\n\n /**\n * Sets up message and reaction handlers for the bot.\n *\n * @private\n * @returns {void}\n */\n private setupMessageHandlers(): void {\n // Regular message handler\n this.bot.on('message', async (ctx) => {\n try {\n if (!(await this.isGroupAuthorized(ctx))) return;\n await this.messageManager.handleMessage(ctx);\n } catch (error) {\n logger.error('Error handling message:', error);\n }\n });\n\n // Reaction handler\n this.bot.on('message_reaction', async (ctx) => {\n try {\n if (!(await this.isGroupAuthorized(ctx))) return;\n await this.messageManager.handleReaction(ctx);\n } catch (error) {\n logger.error('Error handling reaction:', error);\n }\n });\n }\n\n /**\n * Sets up tracking for new entities in a group chat to sync them as entities\n * @param {number} chatId - The Telegram chat ID to track entities for\n */\n private setupEntityTracking(chatId: number): void {\n // We'll maintain a set of entity IDs we've already synced\n const syncedEntityIds = new Set<string>();\n\n // Add handler to track new message authors\n this.bot.on('message', async (ctx) => {\n if (!ctx.chat || ctx.chat.id !== chatId || !ctx.from) return;\n\n const entityId = ctx.from.id.toString();\n if (syncedEntityIds.has(entityId)) return;\n\n // Add to synced set to avoid duplicate processing\n syncedEntityIds.add(entityId);\n\n // Sync this entity\n const entityUuid = createUniqueUuid(this.runtime, entityId) as UUID;\n const worldId = createUniqueUuid(this.runtime, chatId.toString()) as UUID;\n const chatIdStr = chatId.toString();\n\n try {\n // Create entity\n await this.runtime.ensureConnection({\n entityId: entityUuid,\n roomId: createUniqueUuid(this.runtime, chatIdStr),\n userName: ctx.from.username || ctx.from.first_name || 'Unknown Entity',\n name: ctx.from.first_name || ctx.from.username || 'Unknown Entity',\n source: 'telegram',\n channelId: chatIdStr,\n serverId: chatIdStr,\n type: ChannelType.GROUP,\n worldId,\n });\n\n // Create entity joined payload\n const entityJoinedPayload = {\n runtime: this.runtime,\n entityId: entityUuid,\n entity: {\n id: entityId,\n username: ctx.from.username || ctx.from.first_name || 'Unknown Entity',\n displayName: ctx.from.first_name || ctx.from.username || 'Unknown Entity',\n },\n worldId,\n source: 'telegram',\n metadata: {\n joinedAt: Date.now(),\n },\n };\n\n // Create Telegram-specific payload\n const telegramEntityJoinedPayload = {\n ...entityJoinedPayload,\n telegramUser: {\n id: ctx.from.id,\n username: ctx.from.username,\n first_name: ctx.from.first_name,\n },\n };\n\n // Emit generic ENTITY_JOINED event\n this.runtime.emitEvent(EventType.ENTITY_JOINED, entityJoinedPayload);\n\n // Emit platform-specific ENTITY_JOINED event\n this.runtime.emitEvent(TelegramEventTypes.ENTITY_JOINED, telegramEntityJoinedPayload);\n\n logger.info(\n `Tracked new Telegram entity: ${ctx.from.username || ctx.from.first_name || entityId}`\n );\n } catch (error) {\n logger.error(`Error syncing new Telegram entity ${entityId} from chat ${chatId}:`, error);\n }\n });\n\n // Track when entities leave chat (from service message)\n this.bot.on('left_chat_member', async (ctx) => {\n if (!ctx.message?.left_chat_member || ctx.chat?.id !== chatId) return;\n\n const leftUser = ctx.message.left_chat_member;\n const entityId = createUniqueUuid(this.runtime, leftUser.id.toString()) as UUID;\n const chatIdStr = chatId.toString();\n const worldId = createUniqueUuid(this.runtime, chatIdStr);\n\n try {\n // Get the entity\n const entity = await this.runtime.getEntityById(entityId);\n if (entity) {\n // Update entity metadata to show as inactive\n entity.metadata = {\n ...entity.metadata,\n status: 'INACTIVE',\n leftAt: Date.now(),\n };\n await this.runtime.updateEntity(entity);\n\n // Create entity left payload\n const entityLeftPayload = {\n runtime: this.runtime,\n entityId,\n entity: {\n id: leftUser.id.toString(),\n username: leftUser.username || leftUser.first_name || 'Unknown Entity',\n displayName: leftUser.first_name || leftUser.username || 'Unknown Entity',\n },\n worldId,\n source: 'telegram',\n metadata: {\n leftAt: Date.now(),\n },\n };\n\n // Create Telegram-specific payload\n const telegramEntityLeftPayload = {\n ...entityLeftPayload,\n telegramUser: {\n id: leftUser.id,\n username: leftUser.username,\n first_name: leftUser.first_name,\n },\n };\n\n // Emit generic ENTITY_LEFT event\n this.runtime.emitEvent(EventType.ENTITY_LEFT, entityLeftPayload);\n\n // Emit platform-specific ENTITY_LEFT event\n this.runtime.emitEvent(TelegramEventTypes.ENTITY_LEFT, telegramEntityLeftPayload);\n\n logger.info(\n `Entity ${leftUser.username || leftUser.first_name || leftUser.id} left chat ${chatId}`\n );\n }\n } catch (error) {\n logger.error(`Error handling Telegram entity leaving chat ${chatId}:`, error);\n }\n });\n }\n}\n","import type { IAgentRuntime } from '@elizaos/core';\nimport { z } from 'zod';\n\nexport const telegramEnvSchema = z.object({\n TELEGRAM_BOT_TOKEN: z.string().min(1, 'Telegram bot token is required'),\n});\n\n/**\n * Represents the type definition for configuring a Telegram bot based on the inferred schema.\n */\nexport type TelegramConfig = z.infer<typeof telegramEnvSchema>;\n\n/**\n * Validates the Telegram configuration by retrieving the Telegram bot token from the runtime settings or environment variables.\n *\n * @param {IAgentRuntime} runtime - The agent runtime used to get the setting.\n * @returns {Promise<TelegramConfig>} A promise that resolves with the validated Telegram configuration.\n */\nexport async function validateTelegramConfig(runtime: IAgentRuntime): Promise<TelegramConfig> {\n try {\n const config = {\n TELEGRAM_BOT_TOKEN:\n runtime.getSetting('TELEGRAM_BOT_TOKEN') || process.env.TELEGRAM_BOT_TOKEN,\n };\n\n return telegramEnvSchema.parse(config);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join('.')}: ${err.message}`)\n .join('\\n');\n throw new Error(`Telegram configuration validation failed:\\n${errorMessages}`);\n }\n throw error;\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 type UUID,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport type { Chat, Message, ReactionType, Update } from '@telegraf/types';\nimport type { Context, NarrowedContext, Telegraf } from 'telegraf';\nimport {\n TelegramEventTypes,\n type TelegramMessageReceivedPayload,\n type TelegramMessageSentPayload,\n type TelegramReactionReceivedPayload,\n} from './types';\nimport { escapeMarkdown } from './utils';\n\nimport fs from 'node:fs';\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 if (chat.type === 'private') return ChannelType.DM;\n if (chat.type === 'supergroup') return ChannelType.GROUP;\n if (chat.type === 'channel') return ChannelType.GROUP;\n if (chat.type === 'group') return ChannelType.GROUP;\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 // Process image messages and generate descriptions\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.info(`Telegram Message: ${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 ('document' in message && message.document?.mime_type?.startsWith('image/')) {\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 console.error('❌ Error processing image:', error);\n }\n\n return null;\n }\n\n // Send long messages in chunks\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 {Content} 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: Content,\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 } else {\n const chunks = this.splitMessage(content.text);\n const sentMessages: Message.TextMessage[] = [];\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = escapeMarkdown(chunks[i]);\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: 'Markdown',\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 (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 await sendFunction(ctx.chat.id, { source: fileStream }, { caption });\n } finally {\n fileStream.destroy();\n }\n }\n\n logger.info(\n `${type.charAt(0).toUpperCase() + type.slice(1)} sent successfully: ${mediaPath}`\n );\n } catch (error) {\n logger.error(`Failed to send ${type}. Path: ${mediaPath}. Error: ${error.message}`);\n logger.debug(error.stack);\n throw error;\n }\n }\n\n // Split message into smaller parts\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 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 // Main handler for incoming messages\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 const userName = ctx.from.username || ctx.from.first_name || 'Unknown User';\n const roomId = createUniqueUuid(this.runtime, ctx.chat?.id.toString());\n\n // Get message ID\n const messageId = createUniqueUuid(this.runtime, message?.message_id?.toString());\n\n // Handle images\n const imageInfo = await this.processImage(message);\n\n // Get message text - use type guards for safety\n let messageText = '';\n if ('text' in message && message.text) {\n messageText = message.text;\n } else if ('caption' in message && message.caption) {\n messageText = message.caption as string;\n }\n\n // Combine text and image description\n const fullText = imageInfo ? `${messageText} ${imageInfo.description}` : messageText;\n if (!fullText) return;\n\n // Get chat type and determine channel type\n const chat = message.chat as Chat;\n const channelType = getChannelType(chat);\n\n // Get world and room IDs\n // For private chats, the world is the chat itself\n // For groups/channels, the world is the supergroup/channel\n const worldId = createUniqueUuid(\n this.runtime,\n chat.type === 'private' ? `private_${chat.id}` : chat.id.toString()\n );\n\n // Get world and room names\n const worldName =\n chat.type === 'supergroup'\n ? (chat as Chat.SupergroupChat).title\n : chat.type === 'channel'\n ? (chat as Chat.ChannelChat).title\n : chat.type === 'private'\n ? `Chat with ${(chat as Chat.PrivateChat).first_name || 'Unknown'}`\n : 'Telegram';\n\n const roomName =\n chat.type === 'private'\n ? (chat as Chat.PrivateChat).first_name\n : chat.type === 'supergroup'\n ? (chat as Chat.SupergroupChat).title\n : chat.type === 'channel'\n ? (chat as Chat.ChannelChat).title\n : chat.type === 'group'\n ? (chat as Chat.GroupChat).title\n : 'Unknown Group';\n\n // Ensure entity connection with proper world/server ID handling\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName,\n name: userName,\n source: 'telegram',\n channelId: ctx.chat.id.toString(),\n serverId: chat.type === 'private' ? undefined : chat.id.toString(), // Only set serverId for non-private chats\n type: channelType,\n worldId: worldId,\n });\n\n // Ensure room exists\n const room = {\n id: roomId,\n name: roomName,\n source: 'telegram',\n type: channelType,\n channelId: ctx.chat.id.toString(),\n serverId: chat.type === 'private' ? undefined : chat.id.toString(),\n worldId: worldId,\n };\n\n await this.runtime.ensureRoomExists(room);\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: fullText,\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 createdAt: message.date * 1000,\n };\n\n // Create callback for handling responses\n const callback: HandlerCallback = async (content: Content, _files?: string[]) => {\n try {\n const sentMessages = await this.sendMessageInChunks(ctx, content, message.message_id);\n\n if (!sentMessages) return [];\n\n const memories: Memory[] = [];\n for (let i = 0; i < sentMessages.length; i++) {\n const sentMessage = sentMessages[i];\n const _isLastMessage = i === sentMessages.length - 1;\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 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('Error in message callback:', error);\n return [];\n }\n };\n\n // Let the bootstrap plugin handle the message\n this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n });\n\n // Also emit the platform-specific event\n this.runtime.emitEvent(TelegramEventTypes.MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n source: 'telegram',\n ctx,\n originalMessage: message,\n } as TelegramMessageReceivedPayload);\n } catch (error) {\n logger.error('Error handling Telegram message:', {\n error,\n chatId: ctx.chat?.id,\n messageId: ctx.message?.message_id,\n from: ctx.from?.username || ctx.from?.id,\n });\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 reactionType = reaction.new_reaction[0].type;\n const reactionEmoji = (reaction.new_reaction[0] as ReactionType).type;\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 const worldId = 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 const sentMessage = await ctx.reply(content.text);\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('Error in reaction callback:', error);\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 });\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 reactionString: reactionType === 'emoji' ? reactionEmoji : reactionType,\n originalReaction: reaction.new_reaction[0] as ReactionType,\n } as TelegramReactionReceivedPayload);\n } catch (error) {\n logger.error('Error handling reaction:', error);\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 room 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 messages: memories,\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('Error sending message to Telegram:', error);\n return [];\n }\n }\n}\n","/**\n * Escapes Markdown special characters in the given text, excluding code blocks.\n * @param {string} text - The text to escape Markdown characters from.\n * @returns {string} The text with escaped Markdown characters.\n */\nexport function escapeMarkdown(text: string): string {\n // Don't escape if it's a code block\n if (text.startsWith('```') && text.endsWith('```')) {\n return text;\n }\n\n // Split the text by code blocks\n const parts = text.split(/(```[\\s\\S]*?```)/g);\n\n return parts\n .map((part, index) => {\n // If it's a code block (odd indices in the split result will be code blocks)\n if (index % 2 === 1) {\n return part;\n }\n // For regular text, only escape characters that need escaping in Markdown\n return (\n part\n // First preserve any intended inline code spans\n .replace(/`.*?`/g, (match) => match)\n // Then only escape the minimal set of special characters that need escaping in Markdown mode\n .replace(/([*_`\\\\])/g, '\\\\$1')\n );\n })\n .join('');\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 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","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';\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;\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 const chat = await this.bot.telegram.getChat(chatId);\n logger.log(`Fetched real chat: ${JSON.stringify(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 this.bot = this.telegramClient.messageManager.bot;\n this.messageManager = this.telegramClient.messageManager;\n logger.debug('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('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\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(mockContext as Context, messageContent);\n\n logger.success('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 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 const chatId = this.validateChatId(runtime);\n const fileId = await this.getFileId(chatId, TEST_IMAGE_URL);\n\n const mockMessage = {\n message_id: undefined,\n chat: { id: chatId } as Chat,\n date: Math.floor(Date.now() / 1000),\n photo: [{ file_id: fileId }],\n text: `@${this.bot.botInfo?.username}!`,\n };\n\n const { description } = await this.messageManager.processImage(mockMessage);\n if (!description) {\n throw new Error('Error processing Telegram image');\n }\n logger.log(`Processing Telegram image successfully: ${description}`);\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 const message = await this.bot.telegram.sendPhoto(chatId, imageUrl);\n return message.photo[message.photo.length - 1].file_id;\n } catch (error) {\n logger.error(`Error sending image: ${error}`);\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';\n\nconst telegramPlugin: Plugin = {\n name: TELEGRAM_SERVICE_NAME,\n description: 'Telegram client plugin',\n services: [TelegramService],\n tests: [new TelegramTestSuite()],\n};\nexport default telegramPlugin;\n"],"mappings":";AAAO,IAAM,oBAAoB;AAAA,EAC/B,cAAc;AAAA,EACd,sBAAsB;AA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,SAAS,OAAO;AACd,MAAAA,QAAO,MAAM,wBAAwB,KAAK,EAAE;AAC5C,YAAM;AAAA,IACR;AAAA,EACF;AACF;;;AC/MA,IAAM,iBAAyB;AAAA,EAC7B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU,CAAC,eAAe;AAAA,EAC1B,OAAO,CAAC,IAAI,kBAAkB,CAAC;AACjC;AACA,IAAO,gBAAQ;","names":["ChannelType","EventType","createUniqueUuid","logger","logger","ChannelType","createUniqueUuid","EventType","logger"]}
|
package/package.json
CHANGED
|
@@ -1,42 +1,45 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
2
|
+
"name": "@elizaos/plugin-telegram",
|
|
3
|
+
"version": "1.0.0-alpha.65",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"module": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
"./package.json": "./package.json",
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist"
|
|
19
|
+
],
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@telegraf/types": "7.1.0",
|
|
22
|
+
"strip-literal": "^3.0.0",
|
|
23
|
+
"telegraf": "4.16.3",
|
|
24
|
+
"type-detect": "^4.1.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"prettier": "3.5.3",
|
|
28
|
+
"tsup": "8.4.0",
|
|
29
|
+
"vitest": "1.6.1"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsup",
|
|
33
|
+
"dev": "tsup --watch",
|
|
34
|
+
"test": "vitest run",
|
|
35
|
+
"test:watch": "vitest",
|
|
36
|
+
"lint": "prettier --write ./src",
|
|
37
|
+
"clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
|
|
38
|
+
"format": "prettier --write ./src",
|
|
39
|
+
"format:check": "prettier --check ./src"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"gitHead": "8c706f7a89a77ac0c401b6a55e5b9613f839ed3f"
|
|
42
45
|
}
|