@elizaos/plugin-telegram 1.0.0-beta.7 → 1.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/index.js +306 -247
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2025 Shaw Walters
|
|
3
|
+
Copyright (c) 2025 Shaw Walters and elizaOS Contributors
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/dist/index.js
CHANGED
|
@@ -249,8 +249,11 @@ ${description}]` };
|
|
|
249
249
|
const message = ctx.message;
|
|
250
250
|
try {
|
|
251
251
|
const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString());
|
|
252
|
-
const
|
|
253
|
-
const roomId = createUniqueUuid(
|
|
252
|
+
const threadId = "is_topic_message" in message && message.is_topic_message ? (_a = message.message_thread_id) == null ? void 0 : _a.toString() : void 0;
|
|
253
|
+
const roomId = createUniqueUuid(
|
|
254
|
+
this.runtime,
|
|
255
|
+
threadId ? `${ctx.chat.id}-${threadId}` : ctx.chat.id.toString()
|
|
256
|
+
);
|
|
254
257
|
const messageId = createUniqueUuid(this.runtime, (_b = message == null ? void 0 : message.message_id) == null ? void 0 : _b.toString());
|
|
255
258
|
const imageInfo = await this.processImage(message);
|
|
256
259
|
let messageText = "";
|
|
@@ -263,34 +266,6 @@ ${description}]` };
|
|
|
263
266
|
if (!fullText) return;
|
|
264
267
|
const chat = message.chat;
|
|
265
268
|
const channelType = getChannelType(chat);
|
|
266
|
-
const worldId = createUniqueUuid(
|
|
267
|
-
this.runtime,
|
|
268
|
-
chat.type === "private" ? `private_${chat.id}` : chat.id.toString()
|
|
269
|
-
);
|
|
270
|
-
const worldName = chat.type === "supergroup" ? chat.title : chat.type === "channel" ? chat.title : chat.type === "private" ? `Chat with ${chat.first_name || "Unknown"}` : "Telegram";
|
|
271
|
-
const roomName = chat.type === "private" ? chat.first_name : chat.type === "supergroup" ? chat.title : chat.type === "channel" ? chat.title : chat.type === "group" ? chat.title : "Unknown Group";
|
|
272
|
-
await this.runtime.ensureConnection({
|
|
273
|
-
entityId,
|
|
274
|
-
roomId,
|
|
275
|
-
userName,
|
|
276
|
-
name: userName,
|
|
277
|
-
source: "telegram",
|
|
278
|
-
channelId: ctx.chat.id.toString(),
|
|
279
|
-
serverId: chat.type === "private" ? void 0 : chat.id.toString(),
|
|
280
|
-
// Only set serverId for non-private chats
|
|
281
|
-
type: channelType,
|
|
282
|
-
worldId
|
|
283
|
-
});
|
|
284
|
-
const room = {
|
|
285
|
-
id: roomId,
|
|
286
|
-
name: roomName,
|
|
287
|
-
source: "telegram",
|
|
288
|
-
type: channelType,
|
|
289
|
-
channelId: ctx.chat.id.toString(),
|
|
290
|
-
serverId: chat.type === "private" ? void 0 : chat.id.toString(),
|
|
291
|
-
worldId
|
|
292
|
-
};
|
|
293
|
-
await this.runtime.ensureRoomExists(room);
|
|
294
269
|
const memory = {
|
|
295
270
|
id: messageId,
|
|
296
271
|
entityId,
|
|
@@ -306,6 +281,7 @@ ${description}]` };
|
|
|
306
281
|
};
|
|
307
282
|
const callback = async (content, _files) => {
|
|
308
283
|
try {
|
|
284
|
+
if (!content.text) return [];
|
|
309
285
|
const sentMessages = await this.sendMessageInChunks(ctx, content, message.message_id);
|
|
310
286
|
if (!sentMessages) return [];
|
|
311
287
|
const memories = [];
|
|
@@ -360,7 +336,7 @@ ${description}]` };
|
|
|
360
336
|
}
|
|
361
337
|
/**
|
|
362
338
|
* Handles the reaction event triggered by a user reacting to a message.
|
|
363
|
-
*
|
|
339
|
+
* @param {NarrowedContext<Context<Update>, Update.MessageReactionUpdate>} ctx The context of the message reaction update
|
|
364
340
|
* @returns {Promise<void>} A Promise that resolves when the reaction handling is complete
|
|
365
341
|
*/
|
|
366
342
|
async handleReaction(ctx) {
|
|
@@ -371,7 +347,6 @@ ${description}]` };
|
|
|
371
347
|
try {
|
|
372
348
|
const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString());
|
|
373
349
|
const roomId = createUniqueUuid(this.runtime, ctx.chat.id.toString());
|
|
374
|
-
const worldId = createUniqueUuid(this.runtime, ctx.chat.id.toString());
|
|
375
350
|
const reactionId = createUniqueUuid(
|
|
376
351
|
this.runtime,
|
|
377
352
|
`${reaction.message_id}-${ctx.from.id}-${Date.now()}`
|
|
@@ -472,7 +447,9 @@ ${description}]` };
|
|
|
472
447
|
}
|
|
473
448
|
this.runtime.emitEvent(EventType.MESSAGE_SENT, {
|
|
474
449
|
runtime: this.runtime,
|
|
475
|
-
|
|
450
|
+
message: {
|
|
451
|
+
content
|
|
452
|
+
},
|
|
476
453
|
roomId,
|
|
477
454
|
source: "telegram"
|
|
478
455
|
});
|
|
@@ -496,6 +473,7 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
496
473
|
messageManager;
|
|
497
474
|
options;
|
|
498
475
|
knownChats = /* @__PURE__ */ new Map();
|
|
476
|
+
syncedEntityIds = /* @__PURE__ */ new Set();
|
|
499
477
|
/**
|
|
500
478
|
* Constructor for TelegramService class.
|
|
501
479
|
* @param {IAgentRuntime} runtime - The runtime object for the agent.
|
|
@@ -532,6 +510,7 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
532
510
|
);
|
|
533
511
|
logger2.log("\u{1F680} Starting Telegram bot...");
|
|
534
512
|
await service.initializeBot();
|
|
513
|
+
service.setupMiddlewares();
|
|
535
514
|
service.setupMessageHandlers();
|
|
536
515
|
await service.bot.telegram.getMe();
|
|
537
516
|
return service;
|
|
@@ -584,6 +563,75 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
584
563
|
process.once("SIGINT", () => this.bot.stop("SIGINT"));
|
|
585
564
|
process.once("SIGTERM", () => this.bot.stop("SIGTERM"));
|
|
586
565
|
}
|
|
566
|
+
/**
|
|
567
|
+
* Sets up the middleware chain for preprocessing messages before they reach handlers.
|
|
568
|
+
* This critical method establishes a sequential processing pipeline that:
|
|
569
|
+
*
|
|
570
|
+
* 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings
|
|
571
|
+
* 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed
|
|
572
|
+
* 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management
|
|
573
|
+
* 4. Entity Synchronization - Ensures message senders are properly synchronized as entities
|
|
574
|
+
*
|
|
575
|
+
* The middleware chain runs in sequence for each message, with each step potentially
|
|
576
|
+
* enriching the context or stopping processing if conditions aren't met.
|
|
577
|
+
* This preprocessing is essential for maintaining consistent state before message handlers execute.
|
|
578
|
+
* @private
|
|
579
|
+
*/
|
|
580
|
+
setupMiddlewares() {
|
|
581
|
+
this.bot.use(async (ctx, next) => {
|
|
582
|
+
if (!await this.isGroupAuthorized(ctx)) return;
|
|
583
|
+
await next();
|
|
584
|
+
});
|
|
585
|
+
this.bot.use(async (ctx, next) => {
|
|
586
|
+
if (!ctx.chat) return next();
|
|
587
|
+
const chatId = ctx.chat.id.toString();
|
|
588
|
+
if (!this.knownChats.has(chatId)) {
|
|
589
|
+
await this.handleNewChat(ctx);
|
|
590
|
+
}
|
|
591
|
+
await next();
|
|
592
|
+
});
|
|
593
|
+
this.bot.use(async (ctx, next) => {
|
|
594
|
+
var _a;
|
|
595
|
+
if (!ctx.chat || !((_a = ctx.message) == null ? void 0 : _a.message_thread_id) || ctx.chat.type === "private")
|
|
596
|
+
return next();
|
|
597
|
+
const chat = ctx.chat;
|
|
598
|
+
if (chat.type === "supergroup" && chat.is_forum) {
|
|
599
|
+
try {
|
|
600
|
+
await this.handleForumTopic(ctx);
|
|
601
|
+
} catch (error) {
|
|
602
|
+
logger2.error(`Error handling forum topic: ${error}`);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
await next();
|
|
606
|
+
});
|
|
607
|
+
this.bot.use(async (ctx, next) => {
|
|
608
|
+
if (!ctx.chat || !ctx.from || ctx.chat.type === "private") return next();
|
|
609
|
+
await this.syncEntity(ctx);
|
|
610
|
+
await next();
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* Sets up message and reaction handlers for the bot.
|
|
615
|
+
*
|
|
616
|
+
* @private
|
|
617
|
+
* @returns {void}
|
|
618
|
+
*/
|
|
619
|
+
setupMessageHandlers() {
|
|
620
|
+
this.bot.on("message", async (ctx) => {
|
|
621
|
+
try {
|
|
622
|
+
await this.messageManager.handleMessage(ctx);
|
|
623
|
+
} catch (error) {
|
|
624
|
+
logger2.error("Error handling message:", error);
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
this.bot.on("message_reaction", async (ctx) => {
|
|
628
|
+
try {
|
|
629
|
+
await this.messageManager.handleReaction(ctx);
|
|
630
|
+
} catch (error) {
|
|
631
|
+
logger2.error("Error handling reaction:", error);
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
}
|
|
587
635
|
/**
|
|
588
636
|
* Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.
|
|
589
637
|
* @param {Context} ctx - The context of the incoming update.
|
|
@@ -593,9 +641,6 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
593
641
|
var _a;
|
|
594
642
|
const chatId = (_a = ctx.chat) == null ? void 0 : _a.id.toString();
|
|
595
643
|
if (!chatId) return false;
|
|
596
|
-
if (!this.knownChats.has(chatId)) {
|
|
597
|
-
await this.handleNewChat(ctx);
|
|
598
|
-
}
|
|
599
644
|
const allowedChats = this.runtime.getSetting("TELEGRAM_ALLOWED_CHATS");
|
|
600
645
|
if (!allowedChats) {
|
|
601
646
|
return true;
|
|
@@ -608,6 +653,116 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
608
653
|
return false;
|
|
609
654
|
}
|
|
610
655
|
}
|
|
656
|
+
/**
|
|
657
|
+
* Synchronizes an entity from a message context
|
|
658
|
+
* @param {Context} ctx - The context of the incoming update
|
|
659
|
+
* @returns {Promise<void>}
|
|
660
|
+
*/
|
|
661
|
+
async syncEntity(ctx) {
|
|
662
|
+
if (!ctx.chat) return;
|
|
663
|
+
if (ctx.from) {
|
|
664
|
+
const telegramId = ctx.from.id.toString();
|
|
665
|
+
if (!this.syncedEntityIds.has(telegramId)) {
|
|
666
|
+
const entityId = createUniqueUuid2(this.runtime, telegramId);
|
|
667
|
+
const existingEntity = await this.runtime.getEntityById(entityId);
|
|
668
|
+
if (!existingEntity) {
|
|
669
|
+
await this.runtime.createEntity({
|
|
670
|
+
id: entityId,
|
|
671
|
+
agentId: this.runtime.agentId,
|
|
672
|
+
names: [ctx.from.first_name || ctx.from.username || "Unknown User"],
|
|
673
|
+
metadata: {
|
|
674
|
+
telegram: ctx.from,
|
|
675
|
+
username: ctx.from.username,
|
|
676
|
+
first_name: ctx.from.first_name,
|
|
677
|
+
status: "ACTIVE",
|
|
678
|
+
joinedAt: Date.now()
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
this.syncedEntityIds.add(telegramId);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (ctx.message && "new_chat_member" in ctx.message) {
|
|
686
|
+
const newMember = ctx.message.new_chat_member;
|
|
687
|
+
const telegramId = newMember.id.toString();
|
|
688
|
+
const entityId = createUniqueUuid2(this.runtime, telegramId);
|
|
689
|
+
await this.runtime.createEntity({
|
|
690
|
+
id: entityId,
|
|
691
|
+
agentId: this.runtime.agentId,
|
|
692
|
+
names: [newMember.first_name || newMember.username || "Unknown User"],
|
|
693
|
+
metadata: {
|
|
694
|
+
telegram: newMember,
|
|
695
|
+
username: newMember.username,
|
|
696
|
+
first_name: newMember.first_name,
|
|
697
|
+
status: "ACTIVE",
|
|
698
|
+
joinedAt: Date.now()
|
|
699
|
+
}
|
|
700
|
+
});
|
|
701
|
+
this.syncedEntityIds.add(telegramId);
|
|
702
|
+
}
|
|
703
|
+
if (ctx.message && "left_chat_member" in ctx.message) {
|
|
704
|
+
const leftMember = ctx.message.left_chat_member;
|
|
705
|
+
const telegramId = leftMember.id.toString();
|
|
706
|
+
const entityId = createUniqueUuid2(this.runtime, telegramId);
|
|
707
|
+
const existingEntity = await this.runtime.getEntityById(entityId);
|
|
708
|
+
if (existingEntity) {
|
|
709
|
+
existingEntity.metadata = {
|
|
710
|
+
...existingEntity.metadata,
|
|
711
|
+
status: "INACTIVE",
|
|
712
|
+
leftAt: Date.now()
|
|
713
|
+
};
|
|
714
|
+
await this.runtime.updateEntity(existingEntity);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Handles forum topics by creating appropriate rooms
|
|
720
|
+
* @param {Context} ctx - The context of the incoming update
|
|
721
|
+
*/
|
|
722
|
+
async handleForumTopic(ctx) {
|
|
723
|
+
var _a;
|
|
724
|
+
if (!ctx.chat || !((_a = ctx.message) == null ? void 0 : _a.message_thread_id)) return;
|
|
725
|
+
const chat = ctx.chat;
|
|
726
|
+
const chatId = chat.id.toString();
|
|
727
|
+
const threadId = ctx.message.message_thread_id.toString();
|
|
728
|
+
const worldId = createUniqueUuid2(this.runtime, chatId);
|
|
729
|
+
const roomId = createUniqueUuid2(this.runtime, `${chatId}-${threadId}`);
|
|
730
|
+
const existingRoom = await this.runtime.getRoom(roomId);
|
|
731
|
+
if (existingRoom) return;
|
|
732
|
+
try {
|
|
733
|
+
let topicName = `Topic #${threadId}`;
|
|
734
|
+
if (ctx.message && "reply_to_message" in ctx.message) {
|
|
735
|
+
const replyMessage = ctx.message.reply_to_message;
|
|
736
|
+
if (replyMessage && "forum_topic_created" in replyMessage) {
|
|
737
|
+
const topicCreated = replyMessage.forum_topic_created;
|
|
738
|
+
if (topicCreated && topicCreated.name) {
|
|
739
|
+
topicName = topicCreated.name;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
const room = {
|
|
744
|
+
id: roomId,
|
|
745
|
+
name: topicName,
|
|
746
|
+
source: "telegram",
|
|
747
|
+
type: ChannelType2.GROUP,
|
|
748
|
+
channelId: `${chatId}-${threadId}`,
|
|
749
|
+
serverId: chatId,
|
|
750
|
+
worldId,
|
|
751
|
+
metadata: {
|
|
752
|
+
threadId,
|
|
753
|
+
isForumTopic: true,
|
|
754
|
+
parentChatId: chatId
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
await this.runtime.ensureRoomExists(room);
|
|
758
|
+
logger2.debug(`Created room for forum topic: ${topicName} (${roomId})`);
|
|
759
|
+
} catch (error) {
|
|
760
|
+
logger2.error(
|
|
761
|
+
`Error handling forum topic: ${error instanceof Error ? error.message : String(error)}`
|
|
762
|
+
);
|
|
763
|
+
throw error;
|
|
764
|
+
}
|
|
765
|
+
}
|
|
611
766
|
/**
|
|
612
767
|
* Handles new chat discovery and emits WORLD_JOINED event
|
|
613
768
|
* @param {Context} ctx - The context of the incoming update
|
|
@@ -617,31 +772,23 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
617
772
|
const chat = ctx.chat;
|
|
618
773
|
const chatId = chat.id.toString();
|
|
619
774
|
this.knownChats.set(chatId, chat);
|
|
620
|
-
|
|
621
|
-
let channelType;
|
|
622
|
-
switch (chat.type) {
|
|
623
|
-
case "private":
|
|
624
|
-
chatTitle = `Chat with ${chat.first_name || "Unknown User"}`;
|
|
625
|
-
channelType = ChannelType2.DM;
|
|
626
|
-
break;
|
|
627
|
-
case "group":
|
|
628
|
-
chatTitle = chat.title || "Unknown Group";
|
|
629
|
-
channelType = ChannelType2.GROUP;
|
|
630
|
-
break;
|
|
631
|
-
case "supergroup":
|
|
632
|
-
chatTitle = chat.title || "Unknown Supergroup";
|
|
633
|
-
channelType = ChannelType2.GROUP;
|
|
634
|
-
break;
|
|
635
|
-
case "channel":
|
|
636
|
-
chatTitle = chat.title || "Unknown Channel";
|
|
637
|
-
channelType = ChannelType2.FEED;
|
|
638
|
-
break;
|
|
639
|
-
default:
|
|
640
|
-
chatTitle = "Unknown Chat";
|
|
641
|
-
channelType = ChannelType2.GROUP;
|
|
642
|
-
}
|
|
775
|
+
const { chatTitle, channelType } = this.getChatTypeInfo(chat);
|
|
643
776
|
const worldId = createUniqueUuid2(this.runtime, chatId);
|
|
644
|
-
const
|
|
777
|
+
const userId = ctx.from ? createUniqueUuid2(this.runtime, ctx.from.id.toString()) : null;
|
|
778
|
+
let admins = [];
|
|
779
|
+
let owner = null;
|
|
780
|
+
if (chat.type === "group" || chat.type === "supergroup" || chat.type === "channel") {
|
|
781
|
+
try {
|
|
782
|
+
admins = await ctx.getChatAdministrators();
|
|
783
|
+
owner = admins.find((admin) => admin.status === "creator");
|
|
784
|
+
} catch (error) {
|
|
785
|
+
logger2.warn(`Could not get chat administrators: ${error.message}`);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
let ownerId = userId;
|
|
789
|
+
if (owner) {
|
|
790
|
+
ownerId = createUniqueUuid2(this.runtime, String(owner.user.id));
|
|
791
|
+
}
|
|
645
792
|
const world = {
|
|
646
793
|
id: worldId,
|
|
647
794
|
name: chatTitle,
|
|
@@ -649,14 +796,17 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
649
796
|
serverId: chatId,
|
|
650
797
|
metadata: {
|
|
651
798
|
source: "telegram",
|
|
652
|
-
ownership: { ownerId
|
|
653
|
-
roles: {
|
|
654
|
-
[
|
|
655
|
-
}
|
|
799
|
+
ownership: { ownerId },
|
|
800
|
+
roles: ownerId ? {
|
|
801
|
+
[ownerId]: Role.OWNER
|
|
802
|
+
} : {},
|
|
803
|
+
chatType: chat.type,
|
|
804
|
+
isForumEnabled: chat.type === "supergroup" && chat.is_forum
|
|
656
805
|
}
|
|
657
806
|
};
|
|
807
|
+
const entities = await this.buildStandardizedEntities(chat);
|
|
658
808
|
const room = {
|
|
659
|
-
id:
|
|
809
|
+
id: createUniqueUuid2(this.runtime, chatId),
|
|
660
810
|
name: chatTitle,
|
|
661
811
|
source: "telegram",
|
|
662
812
|
type: channelType,
|
|
@@ -664,204 +814,113 @@ var TelegramService = class _TelegramService extends Service {
|
|
|
664
814
|
serverId: chatId,
|
|
665
815
|
worldId
|
|
666
816
|
};
|
|
667
|
-
const users = [];
|
|
668
|
-
if (chat.type === "private" && chat.id) {
|
|
669
|
-
const userId = createUniqueUuid2(this.runtime, chat.id.toString());
|
|
670
|
-
users.push({
|
|
671
|
-
id: userId,
|
|
672
|
-
names: [chat.first_name || "Unknown User"],
|
|
673
|
-
agentId: this.runtime.agentId,
|
|
674
|
-
metadata: {
|
|
675
|
-
telegram: {
|
|
676
|
-
id: chat.id.toString(),
|
|
677
|
-
username: chat.username || "unknown",
|
|
678
|
-
name: chat.first_name || "Unknown User"
|
|
679
|
-
},
|
|
680
|
-
source: "telegram"
|
|
681
|
-
}
|
|
682
|
-
});
|
|
683
|
-
} else if (chat.type === "group" || chat.type === "supergroup") {
|
|
684
|
-
try {
|
|
685
|
-
const admins = await this.bot.telegram.getChatAdministrators(chat.id);
|
|
686
|
-
if (admins && admins.length > 0) {
|
|
687
|
-
for (const admin of admins) {
|
|
688
|
-
const userId = createUniqueUuid2(this.runtime, admin.user.id.toString());
|
|
689
|
-
users.push({
|
|
690
|
-
id: userId,
|
|
691
|
-
names: [admin.user.first_name || admin.user.username || "Unknown Admin"],
|
|
692
|
-
agentId: this.runtime.agentId,
|
|
693
|
-
metadata: {
|
|
694
|
-
telegram: {
|
|
695
|
-
id: admin.user.id.toString(),
|
|
696
|
-
username: admin.user.username || "unknown",
|
|
697
|
-
name: admin.user.first_name || "Unknown Admin",
|
|
698
|
-
isAdmin: true,
|
|
699
|
-
adminTitle: admin.custom_title || (admin.status === "creator" ? "Owner" : "Admin")
|
|
700
|
-
},
|
|
701
|
-
source: "telegram",
|
|
702
|
-
roles: [admin.status === "creator" ? Role.OWNER : Role.ADMIN]
|
|
703
|
-
}
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
}
|
|
707
|
-
try {
|
|
708
|
-
const chatInfo = await this.bot.telegram.getChat(chat.id);
|
|
709
|
-
if (chatInfo && "member_count" in chatInfo) {
|
|
710
|
-
world.metadata.memberCount = chatInfo.member_count;
|
|
711
|
-
}
|
|
712
|
-
} catch (countError) {
|
|
713
|
-
logger2.warn(`Could not get member count for chat ${chatId}: ${countError}`);
|
|
714
|
-
}
|
|
715
|
-
} catch (error) {
|
|
716
|
-
logger2.warn(`Could not fetch administrators for chat ${chatId}: ${error}`);
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
817
|
const worldPayload = {
|
|
720
818
|
runtime: this.runtime,
|
|
721
819
|
world,
|
|
722
820
|
rooms: [room],
|
|
723
|
-
entities
|
|
724
|
-
source: "telegram"
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
821
|
+
entities,
|
|
822
|
+
source: "telegram",
|
|
823
|
+
onComplete: () => {
|
|
824
|
+
const telegramWorldPayload = {
|
|
825
|
+
...worldPayload,
|
|
826
|
+
chat,
|
|
827
|
+
botUsername: this.bot.botInfo.username
|
|
828
|
+
};
|
|
829
|
+
if (chat.type === "group" || chat.type === "supergroup" || chat.type === "channel") {
|
|
830
|
+
this.runtime.emitEvent("TELEGRAM_WORLD_JOINED" /* WORLD_JOINED */, telegramWorldPayload);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
729
833
|
};
|
|
730
|
-
this.runtime.emitEvent(EventType2.WORLD_JOINED, worldPayload);
|
|
731
|
-
this.runtime.emitEvent("TELEGRAM_WORLD_JOINED" /* WORLD_JOINED */, telegramWorldPayload);
|
|
732
|
-
if (chat.type === "group" || chat.type === "supergroup") {
|
|
733
|
-
this.setupEntityTracking(chat.id);
|
|
734
|
-
}
|
|
834
|
+
await this.runtime.emitEvent(EventType2.WORLD_JOINED, worldPayload);
|
|
735
835
|
}
|
|
736
836
|
/**
|
|
737
|
-
*
|
|
738
|
-
*
|
|
739
|
-
* @
|
|
740
|
-
* @returns {void}
|
|
837
|
+
* Gets chat title and channel type based on Telegram chat type
|
|
838
|
+
* @param {any} chat - The Telegram chat object
|
|
839
|
+
* @returns {Object} Object containing chatTitle and channelType
|
|
741
840
|
*/
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
841
|
+
getChatTypeInfo(chat) {
|
|
842
|
+
let chatTitle;
|
|
843
|
+
let channelType;
|
|
844
|
+
switch (chat.type) {
|
|
845
|
+
case "private":
|
|
846
|
+
chatTitle = `Chat with ${chat.first_name || "Unknown User"}`;
|
|
847
|
+
channelType = ChannelType2.DM;
|
|
848
|
+
break;
|
|
849
|
+
case "group":
|
|
850
|
+
chatTitle = chat.title || "Unknown Group";
|
|
851
|
+
channelType = ChannelType2.GROUP;
|
|
852
|
+
break;
|
|
853
|
+
case "supergroup":
|
|
854
|
+
chatTitle = chat.title || "Unknown Supergroup";
|
|
855
|
+
channelType = ChannelType2.GROUP;
|
|
856
|
+
break;
|
|
857
|
+
case "channel":
|
|
858
|
+
chatTitle = chat.title || "Unknown Channel";
|
|
859
|
+
channelType = ChannelType2.FEED;
|
|
860
|
+
break;
|
|
861
|
+
default:
|
|
862
|
+
chatTitle = "Unknown Chat";
|
|
863
|
+
channelType = ChannelType2.GROUP;
|
|
864
|
+
}
|
|
865
|
+
return { chatTitle, channelType };
|
|
759
866
|
}
|
|
760
867
|
/**
|
|
761
|
-
*
|
|
762
|
-
* @param
|
|
868
|
+
* Builds standardized entity representations from Telegram chat data
|
|
869
|
+
* @param chat - The Telegram chat object
|
|
870
|
+
* @returns Array of standardized Entity objects
|
|
763
871
|
*/
|
|
764
|
-
|
|
765
|
-
const
|
|
766
|
-
|
|
767
|
-
if (
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
const chatIdStr = chatId.toString();
|
|
774
|
-
try {
|
|
775
|
-
await this.runtime.ensureConnection({
|
|
776
|
-
entityId: entityUuid,
|
|
777
|
-
roomId: createUniqueUuid2(this.runtime, chatIdStr),
|
|
778
|
-
userName: ctx.from.username || ctx.from.first_name || "Unknown Entity",
|
|
779
|
-
name: ctx.from.first_name || ctx.from.username || "Unknown Entity",
|
|
780
|
-
source: "telegram",
|
|
781
|
-
channelId: chatIdStr,
|
|
782
|
-
serverId: chatIdStr,
|
|
783
|
-
type: ChannelType2.GROUP,
|
|
784
|
-
worldId
|
|
785
|
-
});
|
|
786
|
-
const entityJoinedPayload = {
|
|
787
|
-
runtime: this.runtime,
|
|
788
|
-
entityId: entityUuid,
|
|
789
|
-
entity: {
|
|
790
|
-
id: entityId,
|
|
791
|
-
username: ctx.from.username || ctx.from.first_name || "Unknown Entity",
|
|
792
|
-
displayName: ctx.from.first_name || ctx.from.username || "Unknown Entity"
|
|
793
|
-
},
|
|
794
|
-
worldId,
|
|
795
|
-
source: "telegram",
|
|
872
|
+
async buildStandardizedEntities(chat) {
|
|
873
|
+
const entities = [];
|
|
874
|
+
try {
|
|
875
|
+
if (chat.type === "private" && chat.id) {
|
|
876
|
+
const userId = createUniqueUuid2(this.runtime, chat.id.toString());
|
|
877
|
+
entities.push({
|
|
878
|
+
id: userId,
|
|
879
|
+
names: [chat.first_name || "Unknown User"],
|
|
880
|
+
agentId: this.runtime.agentId,
|
|
796
881
|
metadata: {
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
...entityJoinedPayload,
|
|
802
|
-
telegramUser: {
|
|
803
|
-
id: ctx.from.id,
|
|
804
|
-
username: ctx.from.username,
|
|
805
|
-
first_name: ctx.from.first_name
|
|
806
|
-
}
|
|
807
|
-
};
|
|
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}`
|
|
812
|
-
);
|
|
813
|
-
} catch (error) {
|
|
814
|
-
logger2.error(`Error syncing new Telegram entity ${entityId} from chat ${chatId}:`, error);
|
|
815
|
-
}
|
|
816
|
-
});
|
|
817
|
-
this.bot.on("left_chat_member", async (ctx) => {
|
|
818
|
-
var _a, _b;
|
|
819
|
-
if (!((_a = ctx.message) == null ? void 0 : _a.left_chat_member) || ((_b = ctx.chat) == null ? void 0 : _b.id) !== chatId) return;
|
|
820
|
-
const leftUser = ctx.message.left_chat_member;
|
|
821
|
-
const entityId = createUniqueUuid2(this.runtime, leftUser.id.toString());
|
|
822
|
-
const chatIdStr = chatId.toString();
|
|
823
|
-
const worldId = createUniqueUuid2(this.runtime, chatIdStr);
|
|
824
|
-
try {
|
|
825
|
-
const entity = await this.runtime.getEntityById(entityId);
|
|
826
|
-
if (entity) {
|
|
827
|
-
entity.metadata = {
|
|
828
|
-
...entity.metadata,
|
|
829
|
-
status: "INACTIVE",
|
|
830
|
-
leftAt: Date.now()
|
|
831
|
-
};
|
|
832
|
-
await this.runtime.updateEntity(entity);
|
|
833
|
-
const entityLeftPayload = {
|
|
834
|
-
runtime: this.runtime,
|
|
835
|
-
entityId,
|
|
836
|
-
entity: {
|
|
837
|
-
id: leftUser.id.toString(),
|
|
838
|
-
username: leftUser.username || leftUser.first_name || "Unknown Entity",
|
|
839
|
-
displayName: leftUser.first_name || leftUser.username || "Unknown Entity"
|
|
882
|
+
telegram: {
|
|
883
|
+
id: chat.id.toString(),
|
|
884
|
+
username: chat.username || "unknown",
|
|
885
|
+
name: chat.first_name || "Unknown User"
|
|
840
886
|
},
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
887
|
+
source: "telegram"
|
|
888
|
+
}
|
|
889
|
+
});
|
|
890
|
+
} else if (chat.type === "group" || chat.type === "supergroup") {
|
|
891
|
+
try {
|
|
892
|
+
const admins = await this.bot.telegram.getChatAdministrators(chat.id);
|
|
893
|
+
if (admins && admins.length > 0) {
|
|
894
|
+
for (const admin of admins) {
|
|
895
|
+
const userId = createUniqueUuid2(this.runtime, admin.user.id.toString());
|
|
896
|
+
entities.push({
|
|
897
|
+
id: userId,
|
|
898
|
+
names: [admin.user.first_name || admin.user.username || "Unknown Admin"],
|
|
899
|
+
agentId: this.runtime.agentId,
|
|
900
|
+
metadata: {
|
|
901
|
+
telegram: {
|
|
902
|
+
id: admin.user.id.toString(),
|
|
903
|
+
username: admin.user.username || "unknown",
|
|
904
|
+
name: admin.user.first_name || "Unknown Admin",
|
|
905
|
+
isAdmin: true,
|
|
906
|
+
adminTitle: admin.custom_title || (admin.status === "creator" ? "Owner" : "Admin")
|
|
907
|
+
},
|
|
908
|
+
source: "telegram",
|
|
909
|
+
roles: [admin.status === "creator" ? Role.OWNER : Role.ADMIN]
|
|
910
|
+
}
|
|
911
|
+
});
|
|
853
912
|
}
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
logger2.info(
|
|
858
|
-
`Entity ${leftUser.username || leftUser.first_name || leftUser.id} left chat ${chatId}`
|
|
859
|
-
);
|
|
913
|
+
}
|
|
914
|
+
} catch (error) {
|
|
915
|
+
logger2.warn(`Could not fetch administrators for chat ${chat.id}: ${error}`);
|
|
860
916
|
}
|
|
861
|
-
} catch (error) {
|
|
862
|
-
logger2.error(`Error handling Telegram entity leaving chat ${chatId}:`, error);
|
|
863
917
|
}
|
|
864
|
-
})
|
|
918
|
+
} catch (error) {
|
|
919
|
+
logger2.error(
|
|
920
|
+
`Error building standardized entities: ${error instanceof Error ? error.message : String(error)}`
|
|
921
|
+
);
|
|
922
|
+
}
|
|
923
|
+
return entities;
|
|
865
924
|
}
|
|
866
925
|
};
|
|
867
926
|
|
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 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;AAAA,EACtB,oBAAoB;AAAA,EACpB,8BAA8B;AAAA,EAC9B,yCAAyC;AAAA,EACzC,qBAAqB,IAAI,KAAK;AAAA;AAAA,EAC9B,wBAAwB,IAAI,KAAK;AAAA;AACnC;AAEO,IAAM,wBAAwB;;;ACVrC;AAAA,EACE,eAAAA;AAAA,EAEA,aAAAC;AAAA,EAEA;AAAA,EAEA;AAAA,EAGA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;AACP,SAAuB,gBAAgB;;;ACZvC,SAAS,SAAS;AAEX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,oBAAoB,EAAE,OAAO,EAAE,IAAI,GAAG,gCAAgC;AACxE,CAAC;AAaD,eAAsB,uBAAuB,SAAiD;AAC5F,MAAI;AACF,UAAM,SAAS;AAAA,MACb,oBACE,QAAQ,WAAW,oBAAoB,KAAK,QAAQ,IAAI;AAAA,IAC5D;AAEA,WAAO,kBAAkB,MAAM,MAAM;AAAA,EACvC,SAAS,OAAO;AACd,QAAI,iBAAiB,EAAE,UAAU;AAC/B,YAAM,gBAAgB,MAAM,OACzB,IAAI,CAAC,QAAQ,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,KAAK,IAAI,OAAO,EAAE,EACpD,KAAK,IAAI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A,MACtC;AAEA,YAAM,EAAE,YAAY,IAAI,MAAM,KAAK,eAAe,aAAa,WAAW;AAC1E,UAAI,CAAC,aAAa;AAChB,cAAM,IAAI,MAAM,iCAAiC;AAAA,MACnD;AACA,MAAAA,QAAO,IAAI,2CAA2C,WAAW,EAAE;AAAA,IACrE,SAAS,OAAO;AACd,YAAM,IAAI,MAAM,oCAAoC,KAAK,EAAE;AAAA,IAC7D;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,QAAgB,UAAkB;AAChD,QAAI;AACF,YAAM,UAAU,MAAM,KAAK,IAAI,SAAS,UAAU,QAAQ,QAAQ;AAClE,aAAO,QAAQ,MAAM,QAAQ,MAAM,SAAS,CAAC,EAAE;AAAA,IACjD,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"]}
|
|
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, TelegramWorldPayload } 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 private syncedEntityIds: Set<string> = new Set<string>();\n\n /**\n * Constructor for TelegramService class.\n * @param {IAgentRuntime} runtime - The runtime object for the agent.\n */\n constructor(runtime: IAgentRuntime) {\n super(runtime);\n logger.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\n // Set up middlewares before message handlers to ensure proper preprocessing\n service.setupMiddlewares();\n\n // Set up message handlers after middlewares\n service.setupMessageHandlers();\n\n // Wait for bot to be ready by testing getMe()\n await service.bot.telegram.getMe();\n\n 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 * Sets up the middleware chain for preprocessing messages before they reach handlers.\n * This critical method establishes a sequential processing pipeline that:\n *\n * 1. Authorization - Verifies if a chat is allowed to interact with the bot based on configured settings\n * 2. Chat Discovery - Ensures chat entities and worlds exist in the runtime, creating them if needed\n * 3. Forum Topics - Handles Telegram forum topics as separate rooms for better conversation management\n * 4. Entity Synchronization - Ensures message senders are properly synchronized as entities\n *\n * The middleware chain runs in sequence for each message, with each step potentially\n * enriching the context or stopping processing if conditions aren't met.\n * This preprocessing is essential for maintaining consistent state before message handlers execute.\n * @private\n */\n private setupMiddlewares(): void {\n // Authorization middleware - checks if chat is allowed to interact with the bot\n this.bot.use(async (ctx, next) => {\n if (!(await this.isGroupAuthorized(ctx))) return;\n await next();\n });\n\n // Chat discovery middleware - ensures the chat and world exist.\n this.bot.use(async (ctx, next) => {\n if (!ctx.chat) return next();\n\n const chatId = ctx.chat.id.toString();\n\n // If we haven't seen this chat before, process it\n if (!this.knownChats.has(chatId)) {\n // Create a promise for this processing that other middleware calls can wait on\n await this.handleNewChat(ctx);\n }\n\n await next();\n });\n\n // Forum topic middleware - handle forum topics as separate rooms\n this.bot.use(async (ctx, next) => {\n if (!ctx.chat || !ctx.message?.message_thread_id || ctx.chat.type === 'private')\n return next();\n\n const chat = ctx.chat;\n if (chat.type === 'supergroup' && chat.is_forum) {\n try {\n await this.handleForumTopic(ctx);\n } catch (error) {\n logger.error(`Error handling forum topic: ${error}`);\n }\n }\n\n await next();\n });\n\n // Entity synchronization middleware - ensures the message sender is synced\n this.bot.use(async (ctx, next) => {\n if (!ctx.chat || !ctx.from || ctx.chat.type === 'private') return next();\n await this.syncEntity(ctx);\n await next();\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 // Message handling is now simplified since all preprocessing is done by middleware\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 await this.messageManager.handleReaction(ctx);\n } catch (error) {\n logger.error('Error handling reaction:', error);\n }\n });\n }\n\n /**\n * Checks if a group is authorized, based on the TELEGRAM_ALLOWED_CHATS setting.\n * @param {Context} ctx - The context of the incoming update.\n * @returns {Promise<boolean>} A Promise that resolves with a boolean indicating if the group is authorized.\n */\n private async isGroupAuthorized(ctx: Context): Promise<boolean> {\n const chatId = ctx.chat?.id.toString();\n if (!chatId) return false;\n\n const allowedChats = this.runtime.getSetting('TELEGRAM_ALLOWED_CHATS');\n if (!allowedChats) {\n return true;\n }\n\n try {\n const allowedChatsList = JSON.parse(allowedChats as string);\n return allowedChatsList.includes(chatId);\n } catch (error) {\n logger.error('Error parsing TELEGRAM_ALLOWED_CHATS:', error);\n return false;\n }\n }\n\n /**\n * Synchronizes an entity from a message context\n * @param {Context} ctx - The context of the incoming update\n * @returns {Promise<void>}\n */\n private async syncEntity(ctx: Context): Promise<void> {\n if (!ctx.chat) return;\n\n // Handle message sender\n if (ctx.from) {\n const telegramId = ctx.from.id.toString();\n if (!this.syncedEntityIds.has(telegramId)) {\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n const existingEntity = await this.runtime.getEntityById(entityId);\n\n if (!existingEntity) {\n await this.runtime.createEntity({\n id: entityId,\n agentId: this.runtime.agentId,\n names: [ctx.from.first_name || ctx.from.username || 'Unknown User'],\n metadata: {\n telegram: ctx.from,\n username: ctx.from.username,\n first_name: ctx.from.first_name,\n status: 'ACTIVE',\n joinedAt: Date.now(),\n },\n });\n }\n\n this.syncedEntityIds.add(telegramId);\n }\n }\n\n // Handle new chat member\n if (ctx.message && 'new_chat_member' in ctx.message) {\n const newMember = ctx.message.new_chat_member as any;\n const telegramId = newMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n await this.runtime.createEntity({\n id: entityId,\n agentId: this.runtime.agentId,\n names: [newMember.first_name || newMember.username || 'Unknown User'],\n metadata: {\n telegram: newMember,\n username: newMember.username,\n first_name: newMember.first_name,\n status: 'ACTIVE',\n joinedAt: Date.now(),\n },\n });\n\n this.syncedEntityIds.add(telegramId);\n }\n\n // Handle left chat member\n if (ctx.message && 'left_chat_member' in ctx.message) {\n const leftMember = ctx.message.left_chat_member as any;\n const telegramId = leftMember.id.toString();\n const entityId = createUniqueUuid(this.runtime, telegramId) as UUID;\n\n const existingEntity = await this.runtime.getEntityById(entityId);\n if (existingEntity) {\n existingEntity.metadata = {\n ...existingEntity.metadata,\n status: 'INACTIVE',\n leftAt: Date.now(),\n };\n await this.runtime.updateEntity(existingEntity);\n }\n }\n }\n\n /**\n * Handles forum topics by creating appropriate rooms\n * @param {Context} ctx - The context of the incoming update\n */\n private async handleForumTopic(ctx: Context): Promise<void> {\n if (!ctx.chat || !ctx.message?.message_thread_id) return;\n\n const chat = ctx.chat;\n const chatId = chat.id.toString();\n const threadId = ctx.message.message_thread_id.toString();\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n const roomId = createUniqueUuid(this.runtime, `${chatId}-${threadId}`) as UUID;\n\n // Check if room already exists\n const existingRoom = await this.runtime.getRoom(roomId);\n if (existingRoom) return;\n\n try {\n // Get topic information\n let topicName = `Topic #${threadId}`;\n\n // Try to extract topic name from the message if it's a forum topic creation\n if (ctx.message && 'reply_to_message' in ctx.message) {\n const replyMessage = ctx.message.reply_to_message as any;\n if (replyMessage && 'forum_topic_created' in replyMessage) {\n const topicCreated = replyMessage.forum_topic_created as { name: string };\n if (topicCreated && topicCreated.name) {\n topicName = topicCreated.name;\n }\n }\n }\n\n // Create a room for this topic\n const room: Room = {\n id: roomId,\n name: topicName,\n source: 'telegram',\n type: ChannelType.GROUP,\n channelId: `${chatId}-${threadId}`,\n serverId: chatId,\n worldId,\n metadata: {\n threadId: threadId,\n isForumTopic: true,\n parentChatId: chatId,\n },\n };\n\n await this.runtime.ensureRoomExists(room);\n logger.debug(`Created room for forum topic: ${topicName} (${roomId})`);\n } catch (error) {\n logger.error(\n `Error handling forum topic: ${error instanceof Error ? error.message : String(error)}`\n );\n throw error;\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 and channel type\n const { chatTitle, channelType } = this.getChatTypeInfo(chat);\n\n const worldId = createUniqueUuid(this.runtime, chatId) as UUID;\n const userId = ctx.from\n ? (createUniqueUuid(this.runtime, ctx.from.id.toString()) as UUID)\n : null;\n\n let admins = [];\n let owner = null;\n if (chat.type === 'group' || chat.type === 'supergroup' || chat.type === 'channel') {\n try {\n admins = await ctx.getChatAdministrators();\n owner = admins.find((admin) => admin.status === 'creator');\n } catch (error) {\n logger.warn(`Could not get chat administrators: ${error.message}`);\n }\n }\n\n let ownerId = userId;\n\n if (owner) {\n ownerId = createUniqueUuid(this.runtime, String(owner.user.id)) as UUID;\n }\n\n // Build world representation\n const world: World = {\n id: worldId,\n name: chatTitle,\n agentId: this.runtime.agentId,\n serverId: chatId,\n metadata: {\n source: 'telegram',\n ownership: { ownerId },\n roles: ownerId\n ? {\n [ownerId]: Role.OWNER,\n }\n : {},\n chatType: chat.type,\n isForumEnabled: chat.type === 'supergroup' && chat.is_forum,\n },\n };\n\n const entities = await this.buildStandardizedEntities(chat);\n\n const room = {\n id: createUniqueUuid(this.runtime, chatId) as UUID,\n name: chatTitle,\n source: 'telegram',\n type: channelType,\n channelId: chatId,\n serverId: chatId,\n worldId,\n };\n\n // Create payload for world events\n const worldPayload = {\n runtime: this.runtime,\n world,\n rooms: [room],\n entities,\n source: 'telegram',\n onComplete: () => {\n const telegramWorldPayload: TelegramWorldPayload = {\n ...worldPayload,\n chat,\n botUsername: this.bot.botInfo.username,\n };\n\n if (chat.type === 'group' || chat.type === 'supergroup' || chat.type === 'channel') {\n this.runtime.emitEvent(TelegramEventTypes.WORLD_JOINED, telegramWorldPayload);\n }\n },\n };\n\n // Emit generic WORLD_JOINED event\n await this.runtime.emitEvent(EventType.WORLD_JOINED, worldPayload);\n }\n\n /**\n * Gets chat title and channel type based on Telegram chat type\n * @param {any} chat - The Telegram chat object\n * @returns {Object} Object containing chatTitle and channelType\n */\n private getChatTypeInfo(chat: any): { chatTitle: string; channelType: ChannelType } {\n let chatTitle: string;\n let channelType: ChannelType;\n\n switch (chat.type) {\n case 'private':\n chatTitle = `Chat with ${chat.first_name || 'Unknown User'}`;\n channelType = ChannelType.DM;\n break;\n case 'group':\n chatTitle = chat.title || 'Unknown Group';\n channelType = ChannelType.GROUP;\n break;\n case 'supergroup':\n chatTitle = chat.title || 'Unknown Supergroup';\n channelType = ChannelType.GROUP;\n break;\n case 'channel':\n chatTitle = chat.title || 'Unknown Channel';\n channelType = ChannelType.FEED;\n break;\n default:\n chatTitle = 'Unknown Chat';\n channelType = ChannelType.GROUP;\n }\n\n return { chatTitle, channelType };\n }\n\n /**\n * Builds standardized entity representations from Telegram chat data\n * @param chat - The Telegram chat object\n * @returns Array of standardized Entity objects\n */\n private async buildStandardizedEntities(chat: any): Promise<Entity[]> {\n const entities: Entity[] = [];\n\n try {\n // For private chats, add the user\n if (chat.type === 'private' && chat.id) {\n const userId = createUniqueUuid(this.runtime, chat.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [chat.first_name || 'Unknown User'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: chat.id.toString(),\n username: chat.username || 'unknown',\n name: chat.first_name || 'Unknown User',\n },\n source: 'telegram',\n },\n });\n } else if (chat.type === 'group' || chat.type === 'supergroup') {\n // For groups and supergroups, try to get member information\n try {\n // Get chat administrators (this is what's available through the Bot API)\n const admins = await this.bot.telegram.getChatAdministrators(chat.id);\n\n if (admins && admins.length > 0) {\n for (const admin of admins) {\n const userId = createUniqueUuid(this.runtime, admin.user.id.toString()) as UUID;\n entities.push({\n id: userId,\n names: [admin.user.first_name || admin.user.username || 'Unknown Admin'],\n agentId: this.runtime.agentId,\n metadata: {\n telegram: {\n id: admin.user.id.toString(),\n username: admin.user.username || 'unknown',\n name: admin.user.first_name || 'Unknown Admin',\n isAdmin: true,\n adminTitle:\n admin.custom_title || (admin.status === 'creator' ? 'Owner' : 'Admin'),\n },\n source: 'telegram',\n roles: [admin.status === 'creator' ? Role.OWNER : Role.ADMIN],\n },\n });\n }\n }\n } catch (error) {\n logger.warn(`Could not fetch administrators for chat ${chat.id}: ${error}`);\n }\n }\n } catch (error) {\n logger.error(\n `Error building standardized entities: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n return entities;\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\n const threadId =\n 'is_topic_message' in message && message.is_topic_message\n ? message.message_thread_id?.toString()\n : undefined;\n\n // Generate room ID based on whether this is in a forum topic\n const roomId = createUniqueUuid(\n this.runtime,\n threadId ? `${ctx.chat.id}-${threadId}` : ctx.chat.id.toString()\n ) as UUID;\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 // 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 // If response is from reasoning do not send it.\n if (!content.text) return [];\n\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\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 message: {\n content: content,\n },\n roomId,\n source: 'telegram',\n });\n\n // Also emit platform-specific event\n this.runtime.emitEvent(TelegramEventTypes.MESSAGE_SENT, {\n originalMessages: sentMessages,\n chatId,\n } as TelegramMessageSentPayload);\n\n return sentMessages;\n } catch (error) {\n logger.error('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;AAAA,EACtB,oBAAoB;AAAA,EACpB,8BAA8B;AAAA,EAC9B,yCAAyC;AAAA,EACzC,qBAAqB,IAAI,KAAK;AAAA;AAAA,EAC9B,wBAAwB,IAAI,KAAK;AAAA;AACnC;AAEO,IAAM,wBAAwB;;;ACVrC;AAAA,EACE,eAAAA;AAAA,EAEA,aAAAC;AAAA,EAEA;AAAA,EAEA;AAAA,EAGA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;AACP,SAAuB,gBAAgB;;;ACZvC,SAAS,SAAS;AAEX,IAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,oBAAoB,EAAE,OAAO,EAAE,IAAI,GAAG,gCAAgC;AACxE,CAAC;AAaD,eAAsB,uBAAuB,SAAiD;AAC5F,MAAI;AACF,UAAM,SAAS;AAAA,MACb,oBACE,QAAQ,WAAW,oBAAoB,KAAK,QAAQ,IAAI;AAAA,IAC5D;AAEA,WAAO,kBAAkB,MAAM,MAAM;AAAA,EACvC,SAAS,OAAO;AACd,QAAI,iBAAiB,EAAE,UAAU;AAC/B,YAAM,gBAAgB,MAAM,OACzB,IAAI,CAAC,QAAQ,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,KAAK,IAAI,OAAO,EAAE,EACpD,KAAK,IAAI;AACZ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AM,UAAU,QAAgB,UAAkB;AAChD,QAAI;AACF,YAAM,UAAU,MAAM,KAAK,IAAI,SAAS,UAAU,QAAQ,QAAQ;AAClE,aAAO,QAAQ,MAAM,QAAQ,MAAM,SAAS,CAAC,EAAE;AAAA,IACjD,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","createUniqueUuid","ChannelType","EventType","logger"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elizaos/plugin-telegram",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -41,5 +41,5 @@
|
|
|
41
41
|
"publishConfig": {
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
|
-
"gitHead": "
|
|
44
|
+
"gitHead": "a84e25ee21e33387a1303e62a2f95dc670ffddd4"
|
|
45
45
|
}
|