Skip to content

Commit 5565830

Browse files
Merge pull request #530 from ai16z/fix/telegram
fix: Fix/telegram
2 parents 4cfe830 + 21a8c96 commit 5565830

File tree

4 files changed

+113
-119
lines changed

4 files changed

+113
-119
lines changed

packages/client-telegram/src/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const TelegramClientInterface: Client = {
2020
return tg;
2121
},
2222
stop: async (_runtime: IAgentRuntime) => {
23-
console.warn("Telegram client does not support stopping yet");
23+
elizaLogger.warn("Telegram client does not support stopping yet");
2424
},
2525
};
2626

packages/client-telegram/src/messageManager.ts

+37-34
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Message } from "@telegraf/types";
22
import { Context, Telegraf } from "telegraf";
33

4-
import { composeContext } from "@ai16z/eliza";
4+
import { composeContext, elizaLogger, ServiceType } from "@ai16z/eliza";
55
import { embeddingZeroVector } from "@ai16z/eliza";
66
import {
77
Content,
@@ -17,7 +17,6 @@ import { stringToUuid } from "@ai16z/eliza";
1717

1818
import { generateMessageResponse, generateShouldRespond } from "@ai16z/eliza";
1919
import { messageCompletionFooter, shouldRespondFooter } from "@ai16z/eliza";
20-
import { ImageDescriptionService } from "@ai16z/plugin-node";
2120

2221
const MAX_MESSAGE_LENGTH = 4096; // Telegram's max message length
2322

@@ -137,57 +136,49 @@ Thread of Tweets You Are Replying To:
137136
export class MessageManager {
138137
public bot: Telegraf<Context>;
139138
private runtime: IAgentRuntime;
140-
private imageService: IImageDescriptionService;
141139

142140
constructor(bot: Telegraf<Context>, runtime: IAgentRuntime) {
143141
this.bot = bot;
144142
this.runtime = runtime;
145-
this.imageService = ImageDescriptionService.getInstance();
146143
}
147144

148145
// Process image messages and generate descriptions
149146
private async processImage(
150147
message: Message
151148
): Promise<{ description: string } | null> {
152-
// console.log(
153-
// "🖼️ Processing image message:",
154-
// JSON.stringify(message, null, 2)
155-
// );
156-
157149
try {
158150
let imageUrl: string | null = null;
159151

160-
// Handle photo messages
161152
if ("photo" in message && message.photo?.length > 0) {
162153
const photo = message.photo[message.photo.length - 1];
163154
const fileLink = await this.bot.telegram.getFileLink(
164155
photo.file_id
165156
);
166157
imageUrl = fileLink.toString();
167-
}
168-
// Handle image documents
169-
else if (
158+
} else if (
170159
"document" in message &&
171160
message.document?.mime_type?.startsWith("image/")
172161
) {
173-
const doc = message.document;
174162
const fileLink = await this.bot.telegram.getFileLink(
175-
doc.file_id
163+
message.document.file_id
176164
);
177165
imageUrl = fileLink.toString();
178166
}
179167

180168
if (imageUrl) {
169+
const imageDescriptionService =
170+
this.runtime.getService<IImageDescriptionService>(
171+
ServiceType.IMAGE_DESCRIPTION
172+
);
181173
const { title, description } =
182-
await this.imageService.describeImage(imageUrl);
183-
const fullDescription = `[Image: ${title}\n${description}]`;
184-
return { description: fullDescription };
174+
await imageDescriptionService.describeImage(imageUrl);
175+
return { description: `[Image: ${title}\n${description}]` };
185176
}
186177
} catch (error) {
187178
console.error("❌ Error processing image:", error);
188179
}
189180

190-
return null; // No image found
181+
return null;
191182
}
192183

193184
// Decide if the bot should respond to the message
@@ -196,7 +187,6 @@ export class MessageManager {
196187
state: State
197188
): Promise<boolean> {
198189
// Respond if bot is mentioned
199-
200190
if (
201191
"text" in message &&
202192
message.text?.includes(`@${this.bot.botInfo?.username}`)
@@ -209,7 +199,7 @@ export class MessageManager {
209199
return true;
210200
}
211201

212-
// Respond to images in group chats
202+
// Don't respond to images in group chats
213203
if (
214204
"photo" in message ||
215205
("document" in message &&
@@ -238,7 +228,7 @@ export class MessageManager {
238228
return response === "RESPOND";
239229
}
240230

241-
return false; // No criteria met
231+
return false;
242232
}
243233

244234
// Send long messages in chunks
@@ -291,7 +281,7 @@ export class MessageManager {
291281
// Generate a response using AI
292282
private async _generateResponse(
293283
message: Memory,
294-
state: State,
284+
_state: State,
295285
context: string
296286
): Promise<Content> {
297287
const { userId, roomId } = message;
@@ -306,9 +296,10 @@ export class MessageManager {
306296
console.error("❌ No response from generateMessageResponse");
307297
return null;
308298
}
299+
309300
await this.runtime.databaseAdapter.log({
310301
body: { message, context, response },
311-
userId: userId,
302+
userId,
312303
roomId,
313304
type: "response",
314305
});
@@ -342,14 +333,23 @@ export class MessageManager {
342333
try {
343334
// Convert IDs to UUIDs
344335
const userId = stringToUuid(ctx.from.id.toString()) as UUID;
336+
337+
// Get user name
345338
const userName =
346339
ctx.from.username || ctx.from.first_name || "Unknown User";
340+
341+
// Get chat ID
347342
const chatId = stringToUuid(
348343
ctx.chat?.id.toString() + "-" + this.runtime.agentId
349344
) as UUID;
345+
346+
// Get agent ID
350347
const agentId = this.runtime.agentId;
348+
349+
// Get room ID
351350
const roomId = chatId;
352351

352+
// Ensure connection
353353
await this.runtime.ensureConnection(
354354
userId,
355355
roomId,
@@ -358,6 +358,7 @@ export class MessageManager {
358358
"telegram"
359359
);
360360

361+
// Get message ID
361362
const messageId = stringToUuid(
362363
message.message_id.toString() + "-" + this.runtime.agentId
363364
) as UUID;
@@ -382,17 +383,18 @@ export class MessageManager {
382383
return; // Skip if no content
383384
}
384385

386+
// Create content
385387
const content: Content = {
386388
text: fullText,
387389
source: "telegram",
388-
// inReplyTo:
389-
// "reply_to_message" in message && message.reply_to_message
390-
// ? stringToUuid(
391-
// message.reply_to_message.message_id.toString() +
392-
// "-" +
393-
// this.runtime.agentId
394-
// )
395-
// : undefined,
390+
inReplyTo:
391+
"reply_to_message" in message && message.reply_to_message
392+
? stringToUuid(
393+
message.reply_to_message.message_id.toString() +
394+
"-" +
395+
this.runtime.agentId
396+
)
397+
: undefined,
396398
};
397399

398400
// Create memory for the message
@@ -406,6 +408,7 @@ export class MessageManager {
406408
embedding: embeddingZeroVector,
407409
};
408410

411+
// Create memory
409412
await this.runtime.messageManager.createMemory(memory);
410413

411414
// Update state with the new memory
@@ -498,8 +501,8 @@ export class MessageManager {
498501

499502
await this.runtime.evaluate(memory, state, shouldRespond);
500503
} catch (error) {
501-
console.error("❌ Error handling message:", error);
502-
console.error("Error sending message:", error);
504+
elizaLogger.error("❌ Error handling message:", error);
505+
elizaLogger.error("Error sending message:", error);
503506
}
504507
}
505508
}

packages/client-telegram/src/telegramClient.ts

+65-73
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import { Context, Telegraf } from "telegraf";
2-
3-
import { IAgentRuntime } from "@ai16z/eliza";
2+
import { IAgentRuntime, elizaLogger } from "@ai16z/eliza";
43
import { MessageManager } from "./messageManager.ts";
5-
import { elizaLogger } from "@ai16z/eliza";
64

75
export class TelegramClient {
86
private bot: Telegraf<Context>;
@@ -14,94 +12,88 @@ export class TelegramClient {
1412
this.runtime = runtime;
1513
this.bot = new Telegraf(botToken);
1614
this.messageManager = new MessageManager(this.bot, this.runtime);
17-
1815
elizaLogger.log("✅ TelegramClient constructor completed");
1916
}
2017

2118
public async start(): Promise<void> {
2219
elizaLogger.log("🚀 Starting Telegram bot...");
2320
try {
24-
this.bot.launch({
25-
dropPendingUpdates: true,
26-
});
27-
elizaLogger.log(
28-
"✨ Telegram bot successfully launched and is running!"
29-
);
21+
await this.initializeBot();
22+
this.setupMessageHandlers();
23+
this.setupShutdownHandlers();
24+
} catch (error) {
25+
elizaLogger.error("❌ Failed to launch Telegram bot:", error);
26+
throw error;
27+
}
28+
}
3029

31-
await this.bot.telegram.getMe().then((botInfo) => {
32-
this.bot.botInfo = botInfo;
33-
});
30+
private async initializeBot(): Promise<void> {
31+
this.bot.launch({ dropPendingUpdates: true });
32+
elizaLogger.log(
33+
"✨ Telegram bot successfully launched and is running!"
34+
);
3435

35-
elizaLogger.success(`Bot username: @${this.bot.botInfo?.username}`);
36+
const botInfo = await this.bot.telegram.getMe();
37+
this.bot.botInfo = botInfo;
38+
elizaLogger.success(`Bot username: @${botInfo.username}`);
3639

37-
this.messageManager.bot = this.bot;
40+
this.messageManager.bot = this.bot;
41+
}
3842

39-
// Include if you want to view message maanger bot info
40-
// console.log(`Message Manager bot info: @${this.messageManager.bot}`);
43+
private setupMessageHandlers(): void {
44+
elizaLogger.log("Setting up message handler...");
4145

42-
elizaLogger.log("Setting up message handler...");
46+
this.bot.on("message", async (ctx) => {
47+
try {
48+
await this.messageManager.handleMessage(ctx);
49+
} catch (error) {
50+
elizaLogger.error("❌ Error handling message:", error);
51+
await ctx.reply(
52+
"An error occurred while processing your message."
53+
);
54+
}
55+
});
4356

44-
this.bot.on("message", async (ctx) => {
45-
try {
46-
// console.log("📥 Received message:", ctx.message);
47-
await this.messageManager.handleMessage(ctx);
48-
} catch (error) {
49-
elizaLogger.error("❌ Error handling message:", error);
50-
await ctx.reply(
51-
"An error occurred while processing your message."
52-
);
53-
}
54-
});
57+
this.bot.on("photo", (ctx) => {
58+
elizaLogger.log(
59+
"📸 Received photo message with caption:",
60+
ctx.message.caption
61+
);
62+
});
5563

56-
// Handle specific message types for better logging
57-
this.bot.on("photo", (ctx) => {
58-
elizaLogger.log(
59-
"📸 Received photo message with caption:",
60-
ctx.message.caption
61-
);
62-
});
64+
this.bot.on("document", (ctx) => {
65+
elizaLogger.log(
66+
"📎 Received document message:",
67+
ctx.message.document.file_name
68+
);
69+
});
6370

64-
this.bot.on("document", (ctx) => {
65-
elizaLogger.log(
66-
"📎 Received document message:",
67-
ctx.message.document.file_name
68-
);
69-
});
71+
this.bot.catch((err, ctx) => {
72+
elizaLogger.error(`❌ Telegram Error for ${ctx.updateType}:`, err);
73+
ctx.reply("An unexpected error occurred. Please try again later.");
74+
});
75+
}
7076

71-
this.bot.catch((err, ctx) => {
77+
private setupShutdownHandlers(): void {
78+
const shutdownHandler = async (signal: string) => {
79+
elizaLogger.log(
80+
`⚠️ Received ${signal}. Shutting down Telegram bot gracefully...`
81+
);
82+
try {
83+
await this.stop();
84+
elizaLogger.log("🛑 Telegram bot stopped gracefully");
85+
} catch (error) {
7286
elizaLogger.error(
73-
`❌ Telegram Error for ${ctx.updateType}:`,
74-
err
75-
);
76-
ctx.reply(
77-
"An unexpected error occurred. Please try again later."
87+
"❌ Error during Telegram bot shutdown:",
88+
error
7889
);
79-
});
90+
throw error;
91+
}
92+
};
8093

81-
// Graceful shutdown handlers
82-
const shutdownHandler = async (signal: string) => {
83-
elizaLogger.log(
84-
`⚠️ Received ${signal}. Shutting down Telegram bot gracefully...`
85-
);
86-
try {
87-
await this.stop();
88-
elizaLogger.log("🛑 Telegram bot stopped gracefully");
89-
} catch (error) {
90-
elizaLogger.error(
91-
"❌ Error during Telegram bot shutdown:",
92-
error
93-
);
94-
throw error;
95-
}
96-
};
97-
98-
process.once("SIGINT", () => shutdownHandler("SIGINT"));
99-
process.once("SIGTERM", () => shutdownHandler("SIGTERM"));
100-
process.once("SIGHUP", () => shutdownHandler("SIGHUP"));
101-
} catch (error) {
102-
elizaLogger.error("❌ Failed to launch Telegram bot:", error);
103-
throw error;
104-
}
94+
process.once("SIGINT", () => shutdownHandler("SIGINT"));
95+
process.once("SIGTERM", () => shutdownHandler("SIGTERM"));
96+
process.once("SIGHUP", () => shutdownHandler("SIGHUP"));
10597
}
10698

10799
public async stop(): Promise<void> {

0 commit comments

Comments
 (0)