@elizaos/plugin-telegram 1.0.10 → 1.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  Role,
20
20
  Service,
21
21
  createUniqueUuid as createUniqueUuid2,
22
- logger as logger2
22
+ logger as logger3
23
23
  } from "@elizaos/core";
24
24
  import { Telegraf } from "telegraf";
25
25
 
@@ -28,13 +28,15 @@ import {
28
28
  ChannelType,
29
29
  EventType,
30
30
  ModelType,
31
+ ServiceType,
31
32
  createUniqueUuid,
32
- logger
33
+ logger as logger2
33
34
  } from "@elizaos/core";
34
35
  import { Markup as Markup2 } from "telegraf";
35
36
 
36
37
  // src/utils.ts
37
38
  import { Markup } from "telegraf";
39
+ import { logger } from "@elizaos/core";
38
40
  var TELEGRAM_RESERVED_REGEX = /([_*[\]()~`>#+\-=|{}.!\\])/g;
39
41
  function escapePlainText(text) {
40
42
  if (!text) return "";
@@ -127,14 +129,32 @@ function convertMarkdownToTelegram(markdown) {
127
129
  }
128
130
  function convertToTelegramButtons(buttons) {
129
131
  if (!buttons) return [];
130
- return buttons.map((button) => {
132
+ const telegramButtons = [];
133
+ for (const button of buttons) {
134
+ if (!button || !button.text || !button.url) {
135
+ logger.warn({ button }, "Invalid button configuration, skipping");
136
+ continue;
137
+ }
138
+ let telegramButton;
131
139
  switch (button.kind) {
132
140
  case "login":
133
- return Markup.button.login(button.text, button.url);
141
+ telegramButton = Markup.button.login(button.text, button.url);
142
+ break;
134
143
  case "url":
135
- return Markup.button.url(button.text, button.url);
144
+ telegramButton = Markup.button.url(button.text, button.url);
145
+ break;
146
+ default:
147
+ logger.warn({ src: "plugin:telegram", buttonKind: button.kind }, "Unknown button kind, treating as URL button");
148
+ telegramButton = Markup.button.url(button.text, button.url);
149
+ break;
136
150
  }
137
- });
151
+ telegramButtons.push(telegramButton);
152
+ }
153
+ return telegramButtons;
154
+ }
155
+ function cleanText(text) {
156
+ if (!text) return "";
157
+ return text.split("\0").join("");
138
158
  }
139
159
 
140
160
  // src/messageManager.ts
@@ -165,7 +185,6 @@ var MessageManager = class {
165
185
  this.bot = bot;
166
186
  this.runtime = runtime;
167
187
  }
168
- // Process image messages and generate descriptions
169
188
  /**
170
189
  * Process an image from a Telegram message to extract the image URL and description.
171
190
  *
@@ -175,12 +194,12 @@ var MessageManager = class {
175
194
  async processImage(message) {
176
195
  try {
177
196
  let imageUrl = null;
178
- logger.info(`Telegram Message: ${JSON.stringify(message, null, 2)}`);
197
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, messageId: message.message_id }, "Processing image from message");
179
198
  if ("photo" in message && message.photo?.length > 0) {
180
199
  const photo = message.photo[message.photo.length - 1];
181
200
  const fileLink = await this.bot.telegram.getFileLink(photo.file_id);
182
201
  imageUrl = fileLink.toString();
183
- } else if ("document" in message && message.document?.mime_type?.startsWith("image/")) {
202
+ } else if ("document" in message && message.document?.mime_type?.startsWith("image/") && !message.document?.mime_type?.startsWith("application/pdf")) {
184
203
  const fileLink = await this.bot.telegram.getFileLink(message.document.file_id);
185
204
  imageUrl = fileLink.toString();
186
205
  }
@@ -193,11 +212,237 @@ var MessageManager = class {
193
212
  ${description}]` };
194
213
  }
195
214
  } catch (error) {
196
- console.error("\u274C Error processing image:", error);
215
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error processing image");
216
+ }
217
+ return null;
218
+ }
219
+ /**
220
+ * Process a document from a Telegram message to extract the document URL and description.
221
+ * Handles PDFs and other document types by converting them to text when possible.
222
+ *
223
+ * @param {Message} message - The Telegram message object containing the document.
224
+ * @returns {Promise<{ description: string } | null>} The description of the processed document or null if no document found.
225
+ */
226
+ async processDocument(message) {
227
+ try {
228
+ if (!("document" in message) || !message.document) {
229
+ return null;
230
+ }
231
+ const document = message.document;
232
+ const fileLink = await this.bot.telegram.getFileLink(document.file_id);
233
+ const documentUrl = fileLink.toString();
234
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: document.file_name, mimeType: document.mime_type, fileSize: document.file_size }, "Processing document");
235
+ const documentProcessor = this.getDocumentProcessor(document.mime_type);
236
+ if (documentProcessor) {
237
+ return await documentProcessor(document, documentUrl);
238
+ }
239
+ return {
240
+ title: `Document: ${document.file_name || "Unknown Document"}`,
241
+ fullText: "",
242
+ formattedDescription: `[Document: ${document.file_name || "Unknown Document"}
243
+ Type: ${document.mime_type || "unknown"}
244
+ Size: ${document.file_size || 0} bytes]`,
245
+ fileName: document.file_name || "Unknown Document",
246
+ mimeType: document.mime_type,
247
+ fileSize: document.file_size
248
+ };
249
+ } catch (error) {
250
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error processing document");
251
+ return null;
252
+ }
253
+ }
254
+ /**
255
+ * Get the appropriate document processor based on MIME type.
256
+ */
257
+ getDocumentProcessor(mimeType) {
258
+ if (!mimeType) return null;
259
+ const processors = {
260
+ "application/pdf": this.processPdfDocument.bind(this),
261
+ "text/": this.processTextDocument.bind(this),
262
+ // covers text/plain, text/csv, text/markdown, etc.
263
+ "application/json": this.processTextDocument.bind(this)
264
+ };
265
+ for (const [pattern, processor] of Object.entries(processors)) {
266
+ if (mimeType.startsWith(pattern)) {
267
+ return processor;
268
+ }
197
269
  }
198
270
  return null;
199
271
  }
200
- // Send long messages in chunks
272
+ /**
273
+ * Process PDF documents by converting them to text.
274
+ */
275
+ async processPdfDocument(document, documentUrl) {
276
+ try {
277
+ const pdfService = this.runtime.getService(ServiceType.PDF);
278
+ if (!pdfService) {
279
+ logger2.warn({ src: "plugin:telegram", agentId: this.runtime.agentId }, "PDF service not available, using fallback");
280
+ return {
281
+ title: `PDF Document: ${document.file_name || "Unknown Document"}`,
282
+ fullText: "",
283
+ formattedDescription: `[PDF Document: ${document.file_name || "Unknown Document"}
284
+ Size: ${document.file_size || 0} bytes
285
+ Unable to extract text content]`,
286
+ fileName: document.file_name || "Unknown Document",
287
+ mimeType: document.mime_type,
288
+ fileSize: document.file_size
289
+ };
290
+ }
291
+ const response = await fetch(documentUrl);
292
+ if (!response.ok) {
293
+ throw new Error(`Failed to fetch PDF: ${response.status}`);
294
+ }
295
+ const pdfBuffer = await response.arrayBuffer();
296
+ const text = await pdfService.convertPdfToText(Buffer.from(pdfBuffer));
297
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, "PDF processed successfully");
298
+ return {
299
+ title: document.file_name || "Unknown Document",
300
+ fullText: text,
301
+ formattedDescription: `[PDF Document: ${document.file_name || "Unknown Document"}
302
+ Size: ${document.file_size || 0} bytes
303
+ Text extracted successfully: ${text.length} characters]`,
304
+ fileName: document.file_name || "Unknown Document",
305
+ mimeType: document.mime_type,
306
+ fileSize: document.file_size
307
+ };
308
+ } catch (error) {
309
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, "Error processing PDF document");
310
+ return {
311
+ title: `PDF Document: ${document.file_name || "Unknown Document"}`,
312
+ fullText: "",
313
+ formattedDescription: `[PDF Document: ${document.file_name || "Unknown Document"}
314
+ Size: ${document.file_size || 0} bytes
315
+ Error: Unable to extract text content]`,
316
+ fileName: document.file_name || "Unknown Document",
317
+ mimeType: document.mime_type,
318
+ fileSize: document.file_size
319
+ };
320
+ }
321
+ }
322
+ /**
323
+ * Process text documents by fetching their content.
324
+ */
325
+ async processTextDocument(document, documentUrl) {
326
+ try {
327
+ const response = await fetch(documentUrl);
328
+ if (!response.ok) {
329
+ throw new Error(`Failed to fetch text document: ${response.status}`);
330
+ }
331
+ const text = await response.text();
332
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: document.file_name, charactersExtracted: text.length }, "Text document processed successfully");
333
+ return {
334
+ title: document.file_name || "Unknown Document",
335
+ fullText: text,
336
+ formattedDescription: `[Text Document: ${document.file_name || "Unknown Document"}
337
+ Size: ${document.file_size || 0} bytes
338
+ Text extracted successfully: ${text.length} characters]`,
339
+ fileName: document.file_name || "Unknown Document",
340
+ mimeType: document.mime_type,
341
+ fileSize: document.file_size
342
+ };
343
+ } catch (error) {
344
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: document.file_name, error: error instanceof Error ? error.message : String(error) }, "Error processing text document");
345
+ return {
346
+ title: `Text Document: ${document.file_name || "Unknown Document"}`,
347
+ fullText: "",
348
+ formattedDescription: `[Text Document: ${document.file_name || "Unknown Document"}
349
+ Size: ${document.file_size || 0} bytes
350
+ Error: Unable to read content]`,
351
+ fileName: document.file_name || "Unknown Document",
352
+ mimeType: document.mime_type,
353
+ fileSize: document.file_size
354
+ };
355
+ }
356
+ }
357
+ /**
358
+ * Processes the message content, documents, and images to generate
359
+ * processed content and media attachments.
360
+ *
361
+ * @param {Message} message The message to process
362
+ * @returns {Promise<{ processedContent: string; attachments: Media[] }>} Processed content and media attachments
363
+ */
364
+ async processMessage(message) {
365
+ let processedContent = "";
366
+ let attachments = [];
367
+ if ("text" in message && message.text) {
368
+ processedContent = message.text;
369
+ } else if ("caption" in message && message.caption) {
370
+ processedContent = message.caption;
371
+ }
372
+ if ("document" in message && message.document) {
373
+ const document = message.document;
374
+ const documentInfo = await this.processDocument(message);
375
+ if (documentInfo) {
376
+ try {
377
+ const fileLink = await this.bot.telegram.getFileLink(document.file_id);
378
+ const title = documentInfo.title;
379
+ const fullText = documentInfo.fullText;
380
+ if (fullText) {
381
+ const documentContent = `
382
+
383
+ --- DOCUMENT CONTENT ---
384
+ Title: ${title}
385
+
386
+ Full Content:
387
+ ${fullText}
388
+ --- END DOCUMENT ---
389
+
390
+ `;
391
+ processedContent += documentContent;
392
+ }
393
+ attachments.push({
394
+ id: document.file_id,
395
+ url: fileLink.toString(),
396
+ title,
397
+ source: document.mime_type?.startsWith("application/pdf") ? "PDF" : "Document",
398
+ description: documentInfo.formattedDescription,
399
+ text: fullText
400
+ });
401
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: documentInfo.fileName }, "Document processed successfully");
402
+ } catch (error) {
403
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, fileName: documentInfo.fileName, error: error instanceof Error ? error.message : String(error) }, "Error processing document");
404
+ attachments.push({
405
+ id: document.file_id,
406
+ url: "",
407
+ title: `Document: ${documentInfo.fileName}`,
408
+ source: "Document",
409
+ description: `Document processing failed: ${documentInfo.fileName}`,
410
+ text: `Document: ${documentInfo.fileName}
411
+ Size: ${documentInfo.fileSize || 0} bytes
412
+ Type: ${documentInfo.mimeType || "unknown"}`
413
+ });
414
+ }
415
+ } else {
416
+ attachments.push({
417
+ id: document.file_id,
418
+ url: "",
419
+ title: `Document: ${document.file_name || "Unknown Document"}`,
420
+ source: "Document",
421
+ description: `Document: ${document.file_name || "Unknown Document"}`,
422
+ text: `Document: ${document.file_name || "Unknown Document"}
423
+ Size: ${document.file_size || 0} bytes
424
+ Type: ${document.mime_type || "unknown"}`
425
+ });
426
+ }
427
+ }
428
+ if ("photo" in message && message.photo?.length > 0) {
429
+ const imageInfo = await this.processImage(message);
430
+ if (imageInfo) {
431
+ const photo = message.photo[message.photo.length - 1];
432
+ const fileLink = await this.bot.telegram.getFileLink(photo.file_id);
433
+ attachments.push({
434
+ id: photo.file_id,
435
+ url: fileLink.toString(),
436
+ title: "Image Attachment",
437
+ source: "Image",
438
+ description: imageInfo.description,
439
+ text: imageInfo.description
440
+ });
441
+ }
442
+ }
443
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, hasContent: !!processedContent, attachmentsCount: attachments.length }, "Message processed");
444
+ return { processedContent, attachments };
445
+ }
201
446
  /**
202
447
  * Sends a message in chunks, handling attachments and splitting the message if necessary
203
448
  *
@@ -236,14 +481,14 @@ ${description}]` };
236
481
  const sentMessages = [];
237
482
  const telegramButtons = convertToTelegramButtons(content.buttons ?? []);
238
483
  if (!ctx.chat) {
239
- logger.error("sendMessageInChunks: ctx.chat is undefined");
484
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId }, "sendMessageInChunks: ctx.chat is undefined");
240
485
  return [];
241
486
  }
242
487
  await ctx.telegram.sendChatAction(ctx.chat.id, "typing");
243
488
  for (let i = 0; i < chunks.length; i++) {
244
489
  const chunk = convertMarkdownToTelegram(chunks[i]);
245
490
  if (!ctx.chat) {
246
- logger.error("sendMessageInChunks loop: ctx.chat is undefined");
491
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId }, "sendMessageInChunks loop: ctx.chat is undefined");
247
492
  continue;
248
493
  }
249
494
  const sentMessage = await ctx.telegram.sendMessage(ctx.chat.id, chunk, {
@@ -299,19 +544,12 @@ ${description}]` };
299
544
  fileStream.destroy();
300
545
  }
301
546
  }
302
- logger.info(
303
- `${type.charAt(0).toUpperCase() + type.slice(1)} sent successfully: ${mediaPath}`
304
- );
547
+ logger2.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, mediaType: type, mediaPath }, "Media sent successfully");
305
548
  } catch (error) {
306
- const errorMessage = error instanceof Error ? error.message : String(error);
307
- logger.error(
308
- { originalError: error },
309
- `Failed to send ${type}. Path: ${mediaPath}. Error: ${errorMessage}`
310
- );
549
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, mediaType: type, mediaPath, error: error instanceof Error ? error.message : String(error) }, "Failed to send media");
311
550
  throw error;
312
551
  }
313
552
  }
314
- // Split message into smaller parts
315
553
  /**
316
554
  * Splits a given text into an array of strings based on the maximum message length.
317
555
  *
@@ -334,7 +572,6 @@ ${description}]` };
334
572
  if (currentChunk) chunks.push(currentChunk);
335
573
  return chunks;
336
574
  }
337
- // Main handler for incoming messages
338
575
  /**
339
576
  * Handle incoming messages from Telegram and process them accordingly.
340
577
  * @param {Context} ctx - The context object containing information about the message.
@@ -347,21 +584,23 @@ ${description}]` };
347
584
  const entityId = createUniqueUuid(this.runtime, ctx.from.id.toString());
348
585
  const threadId = "is_topic_message" in message && message.is_topic_message ? message.message_thread_id?.toString() : void 0;
349
586
  if (!ctx.chat) {
350
- logger.error("handleMessage: ctx.chat is undefined");
587
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId }, "handleMessage: ctx.chat is undefined");
351
588
  return;
352
589
  }
353
590
  const telegramRoomid = threadId ? `${ctx.chat.id}-${threadId}` : ctx.chat.id.toString();
354
591
  const roomId = createUniqueUuid(this.runtime, telegramRoomid);
355
592
  const messageId = createUniqueUuid(this.runtime, message?.message_id?.toString());
356
- const imageInfo = await this.processImage(message);
357
- let messageText = "";
358
- if ("text" in message && message.text) {
359
- messageText = message.text;
360
- } else if ("caption" in message && message.caption) {
361
- messageText = message.caption;
593
+ const { processedContent, attachments } = await this.processMessage(message);
594
+ const cleanedContent = cleanText(processedContent);
595
+ const cleanedAttachments = attachments.map((att) => ({
596
+ ...att,
597
+ text: cleanText(att.text),
598
+ description: cleanText(att.description),
599
+ title: cleanText(att.title)
600
+ }));
601
+ if (!cleanedContent && cleanedAttachments.length === 0) {
602
+ return;
362
603
  }
363
- const fullText = imageInfo ? `${messageText} ${imageInfo.description}` : messageText;
364
- if (!fullText) return;
365
604
  const chat = message.chat;
366
605
  const channelType = getChannelType(chat);
367
606
  const sourceId = createUniqueUuid(this.runtime, "" + chat.id);
@@ -383,10 +622,9 @@ ${description}]` };
383
622
  agentId: this.runtime.agentId,
384
623
  roomId,
385
624
  content: {
386
- text: fullText,
387
- // attachments?
625
+ text: cleanedContent || " ",
626
+ attachments: cleanedAttachments,
388
627
  source: "telegram",
389
- // url?
390
628
  channelType,
391
629
  inReplyTo: "reply_to_message" in message && message.reply_to_message ? createUniqueUuid(this.runtime, message.reply_to_message.message_id.toString()) : void 0
392
630
  },
@@ -442,34 +680,19 @@ ${description}]` };
442
680
  }
443
681
  return memories;
444
682
  } catch (error) {
445
- logger.error({ error }, "Error in message callback");
683
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error in message callback");
446
684
  return [];
447
685
  }
448
686
  };
449
- this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {
450
- runtime: this.runtime,
451
- message: memory,
452
- callback,
453
- source: "telegram"
454
- });
455
- this.runtime.emitEvent("TELEGRAM_MESSAGE_RECEIVED" /* MESSAGE_RECEIVED */, {
456
- runtime: this.runtime,
457
- message: memory,
458
- callback,
459
- source: "telegram",
460
- ctx,
461
- originalMessage: message
462
- });
687
+ if (!this.runtime.messageService) {
688
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId }, "Message service is not available");
689
+ throw new Error(
690
+ "Message service is not initialized. Ensure the message service is properly configured."
691
+ );
692
+ }
693
+ await this.runtime.messageService.handleMessage(this.runtime, memory, callback);
463
694
  } catch (error) {
464
- logger.error(
465
- {
466
- error,
467
- chatId: ctx.chat?.id,
468
- messageId: ctx.message?.message_id,
469
- from: ctx.from?.username || ctx.from?.id
470
- },
471
- "Error handling Telegram message"
472
- );
695
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId: ctx.chat?.id, messageId: ctx.message?.message_id, from: ctx.from?.username || ctx.from?.id, error: error instanceof Error ? error.message : String(error) }, "Error handling Telegram message");
473
696
  throw error;
474
697
  }
475
698
  }
@@ -527,7 +750,7 @@ ${description}]` };
527
750
  };
528
751
  return [responseMemory];
529
752
  } catch (error) {
530
- logger.error({ error }, "Error in reaction callback");
753
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error in reaction callback");
531
754
  return [];
532
755
  }
533
756
  };
@@ -554,14 +777,7 @@ ${description}]` };
554
777
  originalReaction: reaction.new_reaction[0]
555
778
  });
556
779
  } catch (error) {
557
- const errorMessage = error instanceof Error ? error.message : String(error);
558
- logger.error(
559
- {
560
- error: errorMessage,
561
- originalError: error
562
- },
563
- "Error handling reaction"
564
- );
780
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error handling reaction");
565
781
  }
566
782
  }
567
783
  /**
@@ -620,14 +836,7 @@ ${description}]` };
620
836
  });
621
837
  return sentMessages;
622
838
  } catch (error) {
623
- const errorMessage = error instanceof Error ? error.message : String(error);
624
- logger.error(
625
- {
626
- error: errorMessage,
627
- originalError: error
628
- },
629
- "Error sending message to Telegram"
630
- );
839
+ logger2.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, "Error sending message to Telegram");
631
840
  return [];
632
841
  }
633
842
  }
@@ -648,10 +857,10 @@ var TelegramService = class _TelegramService extends Service {
648
857
  */
649
858
  constructor(runtime) {
650
859
  super(runtime);
651
- logger2.log("\u{1F4F1} Constructing new TelegramService...");
860
+ logger3.debug({ src: "plugin:telegram", agentId: runtime.agentId }, "Constructing TelegramService");
652
861
  const botToken = runtime.getSetting("TELEGRAM_BOT_TOKEN");
653
862
  if (!botToken || botToken.trim() === "") {
654
- logger2.warn("Telegram Bot Token not provided - Telegram functionality will be unavailable");
863
+ logger3.warn({ src: "plugin:telegram", agentId: runtime.agentId }, "Bot token not provided, Telegram functionality unavailable");
655
864
  this.bot = null;
656
865
  this.messageManager = null;
657
866
  return;
@@ -664,11 +873,9 @@ var TelegramService = class _TelegramService extends Service {
664
873
  try {
665
874
  this.bot = new Telegraf(botToken, this.options);
666
875
  this.messageManager = new MessageManager(this.bot, this.runtime);
667
- logger2.log("\u2705 TelegramService constructor completed");
876
+ logger3.debug({ src: "plugin:telegram", agentId: runtime.agentId }, "TelegramService constructor completed");
668
877
  } catch (error) {
669
- logger2.error(
670
- `Error initializing Telegram bot: ${error instanceof Error ? error.message : String(error)}`
671
- );
878
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Failed to initialize Telegram bot");
672
879
  this.bot = null;
673
880
  this.messageManager = null;
674
881
  }
@@ -682,7 +889,7 @@ var TelegramService = class _TelegramService extends Service {
682
889
  static async start(runtime) {
683
890
  const service = new _TelegramService(runtime);
684
891
  if (!service.bot) {
685
- logger2.warn("Telegram service started without bot functionality - no bot token provided");
892
+ logger3.warn({ src: "plugin:telegram", agentId: runtime.agentId }, "Service started without bot functionality");
686
893
  return service;
687
894
  }
688
895
  const maxRetries = 5;
@@ -690,31 +897,25 @@ var TelegramService = class _TelegramService extends Service {
690
897
  let lastError = null;
691
898
  while (retryCount < maxRetries) {
692
899
  try {
693
- logger2.success(
694
- `\u2705 Telegram client successfully started for character ${runtime.character.name}`
695
- );
696
- logger2.log("\u{1F680} Starting Telegram bot...");
900
+ logger3.info({ src: "plugin:telegram", agentId: runtime.agentId, agentName: runtime.character.name }, "Starting Telegram bot");
697
901
  await service.initializeBot();
698
902
  service.setupMiddlewares();
699
903
  service.setupMessageHandlers();
700
904
  await service.bot.telegram.getMe();
905
+ logger3.success({ src: "plugin:telegram", agentId: runtime.agentId, agentName: runtime.character.name }, "Telegram bot started successfully");
701
906
  return service;
702
907
  } catch (error) {
703
908
  lastError = error instanceof Error ? error : new Error(String(error));
704
- logger2.error(
705
- `Telegram initialization attempt ${retryCount + 1} failed: ${lastError.message}`
706
- );
909
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId, attempt: retryCount + 1, error: lastError.message }, "Initialization attempt failed");
707
910
  retryCount++;
708
911
  if (retryCount < maxRetries) {
709
912
  const delay = 2 ** retryCount * 1e3;
710
- logger2.info(`Retrying Telegram initialization in ${delay / 1e3} seconds...`);
913
+ logger3.info({ src: "plugin:telegram", agentId: runtime.agentId, delaySeconds: delay / 1e3 }, "Retrying initialization");
711
914
  await new Promise((resolve) => setTimeout(resolve, delay));
712
915
  }
713
916
  }
714
917
  }
715
- logger2.error(
716
- `Telegram initialization failed after ${maxRetries} attempts. Last error: ${lastError?.message}. Service will continue without Telegram functionality.`
717
- );
918
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId, maxRetries, error: lastError?.message }, "Initialization failed after all attempts");
718
919
  return service;
719
920
  }
720
921
  /**
@@ -751,7 +952,7 @@ var TelegramService = class _TelegramService extends Service {
751
952
  allowedUpdates: ["message", "message_reaction"]
752
953
  });
753
954
  const botInfo = await this.bot.telegram.getMe();
754
- logger2.log(`Bot info: ${JSON.stringify(botInfo)}`);
955
+ logger3.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, botId: botInfo.id, botUsername: botInfo.username }, "Bot info retrieved");
755
956
  process.once("SIGINT", () => this.bot?.stop("SIGINT"));
756
957
  process.once("SIGTERM", () => this.bot?.stop("SIGTERM"));
757
958
  }
@@ -785,7 +986,7 @@ var TelegramService = class _TelegramService extends Service {
785
986
  */
786
987
  async authorizationMiddleware(ctx, next) {
787
988
  if (!await this.isGroupAuthorized(ctx)) {
788
- logger2.debug("Chat not authorized, skipping message processing");
989
+ logger3.debug({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId: ctx.chat?.id }, "Chat not authorized, skipping");
789
990
  return;
790
991
  }
791
992
  await next();
@@ -825,7 +1026,7 @@ var TelegramService = class _TelegramService extends Service {
825
1026
  try {
826
1027
  await this.handleForumTopic(ctx);
827
1028
  } catch (error) {
828
- logger2.error({ error }, `Error handling forum topic: ${error}`);
1029
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, "Error handling forum topic");
829
1030
  }
830
1031
  }
831
1032
  if (ctx.from && ctx.chat.type !== "private") {
@@ -843,14 +1044,14 @@ var TelegramService = class _TelegramService extends Service {
843
1044
  try {
844
1045
  await this.messageManager.handleMessage(ctx);
845
1046
  } catch (error) {
846
- logger2.error({ error }, "Error handling message");
1047
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error handling message");
847
1048
  }
848
1049
  });
849
1050
  this.bot?.on("message_reaction", async (ctx) => {
850
1051
  try {
851
1052
  await this.messageManager.handleReaction(ctx);
852
1053
  } catch (error) {
853
- logger2.error({ error }, "Error handling reaction");
1054
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error handling reaction");
854
1055
  }
855
1056
  });
856
1057
  }
@@ -870,7 +1071,7 @@ var TelegramService = class _TelegramService extends Service {
870
1071
  const allowedChatsList = JSON.parse(allowedChats);
871
1072
  return allowedChatsList.includes(chatId);
872
1073
  } catch (error) {
873
- logger2.error({ error }, "Error parsing TELEGRAM_ALLOWED_CHATS");
1074
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error parsing TELEGRAM_ALLOWED_CHATS");
874
1075
  return false;
875
1076
  }
876
1077
  }
@@ -1059,9 +1260,7 @@ var TelegramService = class _TelegramService extends Service {
1059
1260
  );
1060
1261
  owner = foundOwner || null;
1061
1262
  } catch (error) {
1062
- logger2.warn(
1063
- `Could not get chat administrators: ${error instanceof Error ? error.message : String(error)}`
1064
- );
1263
+ logger3.warn({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, "Could not get chat administrators");
1065
1264
  }
1066
1265
  }
1067
1266
  let ownerId = userId;
@@ -1172,13 +1371,11 @@ var TelegramService = class _TelegramService extends Service {
1172
1371
  worldId
1173
1372
  });
1174
1373
  } else {
1175
- logger2.warn(
1176
- `Skipping entity sync due to missing ID: ${JSON.stringify(entity.names)}`
1177
- );
1374
+ logger3.warn({ src: "plugin:telegram", agentId: this.runtime.agentId, entityNames: entity.names }, "Skipping entity sync due to missing ID");
1178
1375
  }
1179
1376
  } catch (err) {
1180
1377
  const telegramMetadata = entity.metadata?.telegram;
1181
- logger2.warn(`Failed to sync user ${telegramMetadata?.username}: ${err}`);
1378
+ logger3.warn({ src: "plugin:telegram", agentId: this.runtime.agentId, username: telegramMetadata?.username, error: err instanceof Error ? err.message : String(err) }, "Failed to sync user");
1182
1379
  }
1183
1380
  })
1184
1381
  );
@@ -1274,13 +1471,11 @@ var TelegramService = class _TelegramService extends Service {
1274
1471
  }
1275
1472
  }
1276
1473
  } catch (error) {
1277
- logger2.warn(`Could not fetch administrators for chat ${chat.id}: ${error}`);
1474
+ logger3.warn({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId: chat.id, error: error instanceof Error ? error.message : String(error) }, "Could not fetch administrators");
1278
1475
  }
1279
1476
  }
1280
1477
  } catch (error) {
1281
- logger2.error(
1282
- `Error building standardized entities: ${error instanceof Error ? error.message : String(error)}`
1283
- );
1478
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, error: error instanceof Error ? error.message : String(error) }, "Error building standardized entities");
1284
1479
  }
1285
1480
  return entities;
1286
1481
  }
@@ -1330,9 +1525,7 @@ var TelegramService = class _TelegramService extends Service {
1330
1525
  };
1331
1526
  return room;
1332
1527
  } catch (error) {
1333
- logger2.error(
1334
- `Error building forum topic room: ${error instanceof Error ? error.message : String(error)}`
1335
- );
1528
+ logger3.error({ src: "plugin:telegram", agentId: this.runtime.agentId, chatId, threadId, error: error instanceof Error ? error.message : String(error) }, "Error building forum topic room");
1336
1529
  return null;
1337
1530
  }
1338
1531
  }
@@ -1342,14 +1535,14 @@ var TelegramService = class _TelegramService extends Service {
1342
1535
  "telegram",
1343
1536
  serviceInstance.handleSendMessage.bind(serviceInstance)
1344
1537
  );
1345
- logger2.info("[Telegram] Registered send handler.");
1538
+ logger3.info({ src: "plugin:telegram", agentId: runtime.agentId }, "Registered send handler");
1346
1539
  } else {
1347
- logger2.warn("[Telegram] Cannot register send handler - bot not initialized.");
1540
+ logger3.warn({ src: "plugin:telegram", agentId: runtime.agentId }, "Cannot register send handler, bot not initialized");
1348
1541
  }
1349
1542
  }
1350
1543
  async handleSendMessage(runtime, target, content) {
1351
1544
  if (!this.bot || !this.messageManager) {
1352
- logger2.error("[Telegram SendHandler] Bot not initialized - cannot send messages.");
1545
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId }, "Bot not initialized, cannot send messages");
1353
1546
  throw new Error("Telegram bot is not initialized. Please provide TELEGRAM_BOT_TOKEN.");
1354
1547
  }
1355
1548
  let chatId;
@@ -1361,7 +1554,7 @@ var TelegramService = class _TelegramService extends Service {
1361
1554
  if (!chatId)
1362
1555
  throw new Error(`Could not resolve Telegram chat ID from roomId ${target.roomId}`);
1363
1556
  } else if (target.entityId) {
1364
- logger2.error("[Telegram SendHandler] Sending DMs via entityId not implemented yet.");
1557
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId, entityId: target.entityId }, "Sending DMs via entityId not implemented");
1365
1558
  throw new Error("Sending DMs via entityId is not yet supported for Telegram.");
1366
1559
  } else {
1367
1560
  throw new Error("Telegram SendHandler requires channelId, roomId, or entityId.");
@@ -1373,22 +1566,16 @@ var TelegramService = class _TelegramService extends Service {
1373
1566
  }
1374
1567
  try {
1375
1568
  await this.messageManager.sendMessage(chatId, content);
1376
- logger2.info(`[Telegram SendHandler] Message sent to chat ID: ${chatId}`);
1569
+ logger3.info({ src: "plugin:telegram", agentId: runtime.agentId, chatId }, "Message sent");
1377
1570
  } catch (error) {
1378
- logger2.error(
1379
- {
1380
- target,
1381
- content
1382
- },
1383
- `[Telegram SendHandler] Error sending message: ${error instanceof Error ? error.message : String(error)}`
1384
- );
1571
+ logger3.error({ src: "plugin:telegram", agentId: runtime.agentId, chatId, error: error instanceof Error ? error.message : String(error) }, "Error sending message");
1385
1572
  throw error;
1386
1573
  }
1387
1574
  }
1388
1575
  };
1389
1576
 
1390
1577
  // src/tests.ts
1391
- import { logger as logger3 } from "@elizaos/core";
1578
+ import { logger as logger4 } from "@elizaos/core";
1392
1579
  var TEST_IMAGE_URL = "https://github.com/elizaOS/awesome-eliza/blob/main/assets/eliza-logo.jpg?raw=true";
1393
1580
  var TelegramTestSuite = class {
1394
1581
  name = "telegram";
@@ -1457,7 +1644,7 @@ var TelegramTestSuite = class {
1457
1644
  throw new Error("Bot is not initialized.");
1458
1645
  }
1459
1646
  const chat = await this.bot.telegram.getChat(chatId);
1460
- logger3.log(`Fetched real chat: ${JSON.stringify(chat)}`);
1647
+ logger4.debug({ src: "plugin:telegram", chatId }, "Fetched real chat");
1461
1648
  return chat;
1462
1649
  } catch (error) {
1463
1650
  throw new Error(`Error fetching real Telegram chat: ${error}`);
@@ -1472,14 +1659,14 @@ var TelegramTestSuite = class {
1472
1659
  }
1473
1660
  this.bot = this.telegramClient.messageManager.bot;
1474
1661
  this.messageManager = this.telegramClient.messageManager;
1475
- logger3.debug("Telegram bot initialized successfully.");
1662
+ logger4.debug({ src: "plugin:telegram" }, "Telegram bot initialized successfully");
1476
1663
  }
1477
1664
  async testSendingTextMessage(runtime) {
1478
1665
  try {
1479
1666
  if (!this.bot) throw new Error("Bot not initialized.");
1480
1667
  const chatId = this.validateChatId(runtime);
1481
1668
  await this.bot.telegram.sendMessage(chatId, "Testing Telegram message!");
1482
- logger3.debug("Message sent successfully.");
1669
+ logger4.debug({ src: "plugin:telegram", chatId }, "Message sent successfully");
1483
1670
  } catch (error) {
1484
1671
  throw new Error(`Error sending Telegram message: ${error}`);
1485
1672
  }
@@ -1512,7 +1699,7 @@ var TelegramTestSuite = class {
1512
1699
  mockContext,
1513
1700
  messageContent
1514
1701
  );
1515
- logger3.success("Message with image attachment sent successfully.");
1702
+ logger4.success({ src: "plugin:telegram" }, "Message with image attachment sent successfully");
1516
1703
  } catch (error) {
1517
1704
  throw new Error(`Error sending Telegram message with attachment: ${error}`);
1518
1705
  }
@@ -1573,7 +1760,7 @@ var TelegramTestSuite = class {
1573
1760
  throw new Error("Error processing Telegram image or description not found");
1574
1761
  }
1575
1762
  const { description } = result;
1576
- logger3.log(`Processing Telegram image successfully: ${description}`);
1763
+ logger4.debug({ src: "plugin:telegram", description }, "Processing Telegram image successfully");
1577
1764
  } catch (error) {
1578
1765
  throw new Error(`Error processing Telegram image: ${error}`);
1579
1766
  }
@@ -1589,7 +1776,7 @@ var TelegramTestSuite = class {
1589
1776
  }
1590
1777
  return message.photo[message.photo.length - 1].file_id;
1591
1778
  } catch (error) {
1592
- logger3.error({ error }, `Error sending image: ${error}`);
1779
+ logger4.error({ src: "plugin:telegram", chatId, error: error instanceof Error ? error.message : String(error) }, "Error sending image");
1593
1780
  throw error;
1594
1781
  }
1595
1782
  }