Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make telegram client #63

Merged
merged 10 commits into from
Jan 31, 2025

Conversation

FemiOje
Copy link
Contributor

@FemiOje FemiOje commented Jan 29, 2025

  • Added telegram.ts and example-telegram.ts
  • Used telegram(gramJS) for bot and user login/sendMessages/channel scraping

Summary by CodeRabbit

  • New Features

    • Added Telegram bot integration with support for sending and retrieving messages.
    • Introduced environment configuration for Telegram API credentials.
  • Chores

    • Added new Telegram-related dependencies.
    • Created new script to run Telegram example.
  • Documentation

    • Updated .env.example with Telegram-specific environment variables.

Copy link

vercel bot commented Jan 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
daydreams ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 30, 2025 11:48pm

Copy link
Contributor

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request introduces Telegram integration capabilities to the project. It adds new environment variables for Telegram bot authentication, creates a new TelegramClient class in the core IO module, and provides an example implementation for a Telegram bot. The changes include adding Telegram-related dependencies, updating the environment variable schema, and implementing a comprehensive client for interacting with the Telegram API.

Changes

File Change Summary
.env.example Added Telegram-related environment variables: TELEGRAM_STARTUP_CHAT_ID, TELEGRAM_TOKEN, TELEGRAM_API_ID, TELEGRAM_API_HASH, TELEGRAM_USER_SESSION
examples/example-telegram.ts New example script demonstrating Telegram bot implementation with core components, including a main function
package.json Added telegram script and telegram package dependency
packages/core/src/core/env.ts Extended environment variable schema with Telegram-related string properties
packages/core/src/core/io/telegram.ts New file implementing TelegramClient with interfaces for Telegram interactions, including message handling
.vscode/settings.json Added TypeScript formatter configuration for improved editing experience

Possibly related PRs

  • feat: discord v0.1 #55: Introduces environment variables for Discord integration, similar to the Telegram integration approach in this PR.

Poem

🐰 A Telegram Tale of Code Delight
Whiskers twitching with API might,
Bunnies sending messages so bright,
Environment vars now set just right,
Telegram bot takes its first flight!
🚀📱

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
packages/core/src/core/io/telegram.ts (2)

232-260: Logging messages using console.log
Currently, sending a message logs details with both this.logger.info and console.log (e.g. for DRY_RUN). Consider standardizing on the logger for consistency and better log-level management.


310-323: No handling of media or non-text messages
In parseMessage(), the message text is defaulted to an empty string if message.text is unset. If you want to handle photos, videos, or other media, consider extending this method to support additional message types.

examples/example-telegram.ts (1)

66-75: Using one consistent client configuration
Two possible Telegram clients (bot vs. user) are shown—one commented out. If you need to switch, consider using environment flags or configuration logic instead of manually commenting/uncommenting.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa77f77 and eea806b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (5)
  • .env.example (1 hunks)
  • examples/example-telegram.ts (1 hunks)
  • package.json (2 hunks)
  • packages/core/src/core/env.ts (1 hunks)
  • packages/core/src/core/io/telegram.ts (1 hunks)
🔇 Additional comments (7)
packages/core/src/core/io/telegram.ts (1)

348-380: Comprehensive chat retrieval
This method robustly covers fetching channel, group, and private chat details. The structured return objects for each chat type make it straightforward to integrate further features (e.g., retrieving members).

packages/core/src/core/env.ts (1)

15-17: New environment variables appear correct
The added variables (TELEGRAM_TOKEN, TELEGRAM_API_ID, and TELEGRAM_API_HASH) are properly validated as strings. Ensure they are not logged anywhere in plaintext and are kept confidential.

examples/example-telegram.ts (2)

26-26: Potential data loss risk
await vectorDb.purge() clears all previous sessions/data. Confirm that this is intentional; if not, consider removing or restricting it.


160-171: Graceful shutdown implementation
The SIGINT handler neatly logs out the Telegram client and removes the handlers. This is well-structured and should help avoid resource leaks.

.env.example (1)

23-25: Ensure secure handling of Telegram credentials.

These are sensitive credentials that grant access to your Telegram application and bot. Please ensure:

  1. The actual values are never committed to version control
  2. Production values are securely managed (e.g., using secret management services)
  3. Access is restricted to necessary services only

Let's verify no real credentials are accidentally committed:

✅ Verification successful

No sensitive Telegram credentials found in the codebase

The verification confirms that only placeholder keys are present in .env.example and no actual Telegram credentials are committed to the repository. This follows security best practices for credential management.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for potential Telegram credentials in the codebase
rg -i "telegram.*[0-9a-f]{32}|[0-9]{8,10}:[0-9a-zA-Z-]{35}" --type-not=git

Length of output: 104


Script:

#!/bin/bash
# Search for Telegram bot tokens (format: 123456789:ABCdef...)
rg -i "[0-9]{8,10}:[0-9a-zA-Z-]{35}" --no-ignore

# Search for API hashes (32 hex characters) near "telegram"
rg -i "telegram.*[0-9a-f]{32}" --no-ignore
rg -i "[0-9a-f]{32}.*telegram" --no-ignore

# Search for API IDs (8-10 digits) near "telegram"
rg -i "telegram.*[0-9]{8,10}(?![0-9])" --no-ignore
rg -i "[0-9]{8,10}(?![0-9]).*telegram" --no-ignore

# Check git history for potential leaks
git log -p | rg -i "telegram.*[0-9a-f]{32}|[0-9]{8,10}:[0-9a-zA-Z-]{35}"

Length of output: 746


Script:

#!/bin/bash
# Search for potential Telegram credentials with simpler patterns
rg -i "telegram.*[0-9]{8,}" --no-ignore
rg -i --pcre2 "telegram.*\d{8,10}\b" --no-ignore

# Specifically check .env and config files
fd -e env -e env.example -e config -e yml -e yaml -e json | xargs rg -i "telegram.*=.*[0-9]+"

Length of output: 188

package.json (2)

10-10: LGTM!

The new script follows the existing naming pattern and correctly points to the example file.


26-26: Verify package versions for security vulnerabilities.

Please verify:

  1. The telegram package (v2.26.16) is the latest stable version
  2. The express package (v4.21.2) seems outdated. Consider updating to the latest stable version

Let's check for known vulnerabilities and latest versions:

Also applies to: 31-31

Comment on lines 154 to 183
private async userLogin(): Promise<void> {
try {
if (!this.credentials.bot_token || !this.credentials.api_id || !this.credentials.api_hash) {
throw new Error("Bot token, Api ID and Api hash are required for bot login.");
}
this.client = new GramJSClient(
new StringSession(this.credentials.session?.toString() || ""),
this.credentials.api_id as number,
this.credentials.api_hash as string,
{
connectionRetries: 5,
}
);

await this.client.connect();
this.logger.info("TelegramClient", "Telegram client connected.");
console.log("Session String: ", await this.client.session.save())

this.logger.info("TelegramClient", "User details:", {
client: this.client.getMe()
});

this.logger.info("TelegramClient", "User login successful.");
} catch (error) {
this.logger.error("TelegramClient", "Failed to login as user", {
error,
});
throw error;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incorrect error message for user login
In userLogin(), the code checks for the presence of bot_token, api_id, and api_hash, then throws an error stating "Bot token, Api ID and Api hash are required for bot login." However, user login typically doesn't require bot_token. This might be a copy-paste oversight.

Apply this diff to correct the message:

-            throw new Error("Bot token, Api ID and Api hash are required for bot login.");
+            throw new Error("API ID and API HASH are required for user login.");

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 125 to 153
private async botLogin(): Promise<void> {
if (!this.credentials.bot_token || !this.credentials.api_id || !this.credentials.api_hash) {
throw new Error("Bot token, Api ID and Api hash are required for bot login.");
}
try {
this.client = new GramJSClient(
new StringSession(""),
this.credentials.api_id as number,
this.credentials.api_hash as string,
{
connectionRetries: 5,
})

await this.client.start({
botAuthToken: env.TELEGRAM_TOKEN,
});
console.log(this.client.session.save());

this.logger.info("TelegramClient", "Bot user:", {
client: await this.client.getMe()
});
this.logger.info("TelegramClient", "Bot login successful.");
} catch (error) {
this.logger.error("TelegramClient", "Failed to login as bot", {
error,
});
throw error;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Use validated credentials instead of accessing environment variables directly
The botLogin method validates this.credentials.bot_token but then uses env.TELEGRAM_TOKEN directly. This is redundant and could be simplified by using the already validated credentials.

  • In packages/core/src/core/io/telegram.ts, replace botAuthToken: env.TELEGRAM_TOKEN with botAuthToken: this.credentials.bot_token
🔗 Analysis chain

Potential mismatch between this.credentials.bot_token and env.TELEGRAM_TOKEN
While the constructor stores the bot token in this.credentials.bot_token, the botLogin method uses env.TELEGRAM_TOKEN. This might cause confusion or unintended behavior when the credentials differ from values in environment variables.

As a follow-up, consider running this script to detect any usage inconsistencies, ensuring that all references to the bot token are aligned:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Searching for references to bot_token vs TELEGRAM_TOKEN
rg -A 3 "bot_token"
rg -A 3 "TELEGRAM_TOKEN"

Length of output: 2916

.env.example Outdated
Comment on lines 22 to 25
# gramJS needs to be supplied all of these values (regardless of whether you're running a user client or bot)
TELEGRAM_TOKEN=
TELEGRAM_API_ID=
TELEGRAM_API_HASH=
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Add documentation links for obtaining Telegram credentials

The verification confirms there is no existing documentation for setting up Telegram credentials. Please add setup instructions to the project documentation, including:

🔗 Analysis chain

Add documentation links for obtaining Telegram credentials.

While the comment indicates these values are required, it would be helpful to add specific instructions or links for obtaining these credentials:

Please ensure these credentials are properly documented in the project's setup guide or README.md.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if setup instructions exist in README
rg -i "telegram.*credentials|telegram.*setup" README.md

Length of output: 107


Script:

#!/bin/bash
# Find all markdown files and documentation directories
fd -t f -e md
fd -t d "^docs$|^documentation$|^wiki$" -d 2

Length of output: 618


Script:

#!/bin/bash
# Search for Telegram-related content in documentation
rg -i "telegram|gramjs" -A 3 -B 3 "*.md"

Length of output: 87


Script:

#!/bin/bash
# Search for Telegram-related content in all found markdown files
rg -i "telegram|gramjs" -A 3 -B 3 "readme.md" "docs/README.md" "docs/docs/pages/api-reference/**/*.md"

Length of output: 178

@ponderingdemocritus
Copy link
Contributor

Great start! could you update to the new types that i just pushed

@ponderingdemocritus ponderingdemocritus changed the title Make telegram client feat: Make telegram client Jan 29, 2025
@ponderingdemocritus
Copy link
Contributor

could you fix the conflicts

@FemiOje
Copy link
Contributor Author

FemiOje commented Jan 30, 2025

on it!

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (4)
examples/example-telegram.ts (4)

30-34: Document model selection rationale.

The commented model selection needs explanation. Consider adding a comment explaining why one model is preferred over the other.

 const llmClient = new LLMClient({
-    // model: "openrouter:deepseek/deepseek-r1", // Using a supported model
+    // Using the distilled model for better performance while maintaining quality
     model: "openrouter:deepseek/deepseek-r1-distill-llama-70b",
     temperature: 0.3,
 });

79-89: Document or remove commented code.

The commented user client configuration should either be documented explaining its purpose or removed if not needed.

Consider adding a comment explaining the use case for the user client or remove it if it's not needed.


143-154: Enhance shutdown error handling.

The shutdown process should handle potential errors during cleanup operations.

 process.on("SIGINT", async () => {
     console.log(chalk.yellow("\n\nShutting down..."));
 
     // Clean up resources
-    telegram.logout();
-    core.removeIOHandler("telegram_channel_scraper");
-    core.removeIOHandler("telegram_send_message");
-    rl.close();
+    try {
+        await telegram.logout();
+        core.removeIOHandler("telegram_channel_scraper");
+        core.removeIOHandler("telegram_send_message");
+        rl.close();
+        console.log(chalk.green("✅ Shutdown complete"));
+    } catch (error) {
+        console.error(chalk.red("Error during shutdown:"), error);
+    } finally {
+        process.exit(0);
+    }
-    console.log(chalk.green("✅ Shutdown complete"));
-    process.exit(0);
 });

158-161: Enhance error handling in main execution.

Consider adding more detailed error handling and cleanup in case of fatal errors.

 main().catch((error) => {
-    console.error(chalk.red("Fatal error:"), error);
+    console.error(chalk.red("Fatal error:"), error.message);
+    console.error(chalk.red("Stack trace:"), error.stack);
+    // Attempt cleanup before exit
+    try {
+        telegram?.logout();
+    } catch (cleanupError) {
+        console.error(chalk.red("Error during cleanup:"), cleanupError);
+    }
     process.exit(1);
 });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80f47b7 and d07e1de.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • examples/example-telegram.ts (1 hunks)
🔇 Additional comments (2)
examples/example-telegram.ts (2)

1-15: LGTM! Well-organized imports.

The imports are properly structured and include all necessary dependencies for the Telegram bot implementation.


26-26: Add safeguards for data purging.

Purging data without confirmation could lead to accidental data loss. Consider adding a confirmation mechanism or environment flag.

-    await vectorDb.purge(); // Clear previous session data
+    if (env.ALLOW_DATA_PURGE === 'true') {
+        console.log(chalk.yellow('⚠️ Purging previous session data...'));
+        await vectorDb.purge();
+    }

Comment on lines +42 to +46
const scheduledTaskDb = new MongoDb(
"mongodb://localhost:27017",
"myApp",
"scheduled_tasks"
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Configure MongoDB connection via environment variables.

Similar to ChromaDB, the MongoDB connection details should be configurable through environment variables.

 const scheduledTaskDb = new MongoDb(
-    "mongodb://localhost:27017",
-    "myApp",
-    "scheduled_tasks"
+    env.MONGODB_URL,
+    env.MONGODB_DB_NAME,
+    env.MONGODB_COLLECTION
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const scheduledTaskDb = new MongoDb(
"mongodb://localhost:27017",
"myApp",
"scheduled_tasks"
);
const scheduledTaskDb = new MongoDb(
env.MONGODB_URL,
env.MONGODB_DB_NAME,
env.MONGODB_COLLECTION
);

Comment on lines 108 to 129
core.registerIOHandler({
name: "telegram_send_message",
role: HandlerRole.OUTPUT,
execute: async (data: unknown) => {
const messageData = data as {
content: string;
chatId: number;
};
return telegram.createSendMessageOutput().handler(messageData);
},
outputSchema: z
.object({
content: z.string(),
chatId: z
.number()
.optional()
.describe("The chat ID for the message"),
})
.describe(
"This is for sending a message."
),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling to message sender.

The message sender handler should include error handling for failed message delivery.

 execute: async (data: unknown) => {
     const messageData = data as {
         content: string;
         chatId: number;
     };
-    return telegram.createSendMessageOutput().handler(messageData);
+    try {
+        return await telegram.createSendMessageOutput().handler(messageData);
+    } catch (error) {
+        console.error(chalk.red('Failed to send message:'), error);
+        throw new Error(`Failed to send message: ${error.message}`);
+    }
 },
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
core.registerIOHandler({
name: "telegram_send_message",
role: HandlerRole.OUTPUT,
execute: async (data: unknown) => {
const messageData = data as {
content: string;
chatId: number;
};
return telegram.createSendMessageOutput().handler(messageData);
},
outputSchema: z
.object({
content: z.string(),
chatId: z
.number()
.optional()
.describe("The chat ID for the message"),
})
.describe(
"This is for sending a message."
),
});
core.registerIOHandler({
name: "telegram_send_message",
role: HandlerRole.OUTPUT,
execute: async (data: unknown) => {
const messageData = data as {
content: string;
chatId: number;
};
try {
return await telegram.createSendMessageOutput().handler(messageData);
} catch (error) {
console.error(chalk.red('Failed to send message:'), error);
throw new Error(`Failed to send message: ${error.message}`);
}
},
outputSchema: z
.object({
content: z.string(),
chatId: z
.number()
.optional()
.describe("The chat ID for the message"),
})
.describe(
"This is for sending a message."
),
});

Comment on lines +21 to +24
const vectorDb = new ChromaVectorDB("telegram_agent", {
chromaUrl: "http://localhost:8000",
logLevel: loglevel,
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Move database URL to environment variables.

Hardcoding the ChromaDB URL reduces configurability and portability. Consider moving it to environment variables.

 const vectorDb = new ChromaVectorDB("telegram_agent", {
-    chromaUrl: "http://localhost:8000",
+    chromaUrl: env.CHROMA_DB_URL,
     logLevel: loglevel,
 });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 93 to 104
core.registerIOHandler({
name: "telegram_channel_scraper",
role: HandlerRole.INPUT,
execute: async (data: unknown) => {
const messageData = data as {
chatId: number;
limit?: number;
offset?: number;
};
return telegram.createChannelScraper().handler(messageData);
}
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add input schema validation for channel scraper.

The channel scraper handler uses type assertion without validation. Consider adding a zod schema similar to the output handler.

 core.registerIOHandler({
     name: "telegram_channel_scraper",
     role: HandlerRole.INPUT,
+    inputSchema: z
+        .object({
+            chatId: z.number(),
+            limit: z.number().optional(),
+            offset: z.number().optional(),
+        })
+        .describe("Schema for scraping messages from a Telegram channel"),
     execute: async (data: unknown) => {
-        const messageData = data as {
-            chatId: number;
-            limit?: number;
-            offset?: number;
-        };
+        const messageData = data;
         return telegram.createChannelScraper().handler(messageData);
     }
 });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 67 to 75
const telegram = new TelegramClient(
{
bot_token: env.TELEGRAM_TOKEN,
api_id: parseInt(env.TELEGRAM_API_ID as string),
api_hash: env.TELEGRAM_API_HASH,
is_bot: true,
},
loglevel,
);
Copy link
Contributor

@coderabbitai coderabbitai bot Jan 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add input validation for API credentials.

The parseInt conversion of TELEGRAM_API_ID lacks error handling. Consider adding validation to ensure the value is a valid number.

+const apiId = parseInt(env.TELEGRAM_API_ID as string);
+if (isNaN(apiId)) {
+    throw new Error('TELEGRAM_API_ID must be a valid number');
+}
 const telegram = new TelegramClient(
     {
         bot_token: env.TELEGRAM_TOKEN,
-        api_id: parseInt(env.TELEGRAM_API_ID as string),
+        api_id: apiId,
         api_hash: env.TELEGRAM_API_HASH,
         is_bot: true,
     },
     loglevel,
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const telegram = new TelegramClient(
{
bot_token: env.TELEGRAM_TOKEN,
api_id: parseInt(env.TELEGRAM_API_ID as string),
api_hash: env.TELEGRAM_API_HASH,
is_bot: true,
},
loglevel,
);
const apiId = parseInt(env.TELEGRAM_API_ID as string);
if (isNaN(apiId)) {
throw new Error('TELEGRAM_API_ID must be a valid number');
}
const telegram = new TelegramClient(
{
bot_token: env.TELEGRAM_TOKEN,
api_id: apiId,
api_hash: env.TELEGRAM_API_HASH,
is_bot: true,
},
loglevel,
);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@FemiOje
Copy link
Contributor Author

FemiOje commented Jan 30, 2025

@ponderingdemocritus I've fixed the conflicts and updated to the new types 👌

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/core/src/core/io/telegram.ts (1)

125-161: 🛠️ Refactor suggestion

Use the validated bot token instead of direct env reference.
This is a repeated suggestion from previous reviews. By referencing env.TELEGRAM_TOKEN directly (line 139), you risk a mismatch between validated this.credentials.bot_token and environment variables.

- botAuthToken: env.TELEGRAM_TOKEN,
+ botAuthToken: this.credentials.bot_token,
🧹 Nitpick comments (9)
packages/core/src/core/io/telegram.ts (9)

42-49: Consider naming consistency for message identifiers.
Currently, the Message interface uses message_id, while the user interface uses id. For better uniformity, consider making these fields consistently named, e.g., both as id or messageId.


51-65: Evaluate session handling in TelegramCredentials.
Placing session data inside TelegramCredentials is convenient but can blur responsibilities, especially if you later expand user account or multi-bot functionalities. As a future refactoring, consider separating session logic into its own interface or class to avoid mixing credentials with ephemeral session information.


220-266: Interactive login may not suit all production scenarios.
Using readline for credential prompts is neat for local debugging but can block a containerized or daemonized process. Consider providing a non-interactive alternative for environments lacking a TTY.


268-286: DRY approach for startup messages.
botLogin() and userLogin() each implement a similar “startup message” pattern. Consider consolidating this logic to reduce duplication and ease maintenance.


319-333: Reuse naming consistently.
The function is called createChannelScraper, but it’s also suitable for private or group chats. Optionally rename to convey a broader scope, e.g. createChatScraper.


335-367: Parallelize channel scraping for performance gains.
Inside createPeriodicChannelScraper, you gather messages by iterating channels sequentially. Consider parallelizing these fetches (e.g., Promise.all) if Telegram rate limits allow, to reduce overall scraping time.


405-451: Review supergroup edge cases.
The code handles channels, chats, and users, but large supergroups often behave like channels. Ensure no special handling is needed for supergroup IDs or restricted chats.


468-489: Fetch real names for “Unknown” placeholders.
By default, you label private chats “Unknown” or group chats “Unknown Group.” Consider an additional fetch if you want the actual names.


491-522: Synchronized approach with getChatInfo.
parseChat and getChatInfo replicate some logic. If you want consistent naming or dynamic data, consider merging or reusing the same resolution logic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d07e1de and aabe8c2.

📒 Files selected for processing (4)
  • .env.example (1 hunks)
  • examples/example-telegram.ts (1 hunks)
  • packages/core/src/core/env.ts (1 hunks)
  • packages/core/src/core/io/telegram.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/example-telegram.ts
🔇 Additional comments (12)
packages/core/src/core/io/telegram.ts (9)

1-39: Good separation of interfaces.
The new interfaces (User, PrivateChat, GroupChat, ChannelChat, etc.) are clear and well-documented. Having them in one file centralizes Telegram-related definitions.


85-100: Constructor and logging config look solid.
Your approach to initialize and store a logger per instance is a good pattern, ensuring each client has isolated logging.


102-123: Confirm re-initialization approach.
When this.isInitialized is true, the method returns without re-initializing. Verify that this is desirable behavior if credentials or environment variables change during the runtime. If re-initialization is needed, add logic to handle it cleanly.


147-152: Add validation for TELEGRAM_STARTUP_CHAT_ID.
Passing NaN to sendMessage is possible if parseInt(env.TELEGRAM_STARTUP_CHAT_ID) fails. Consider validating this to avoid runtime errors.


162-218: Handle sessions passed as Session instances.
sessionString = this.credentials.session?.toString() is fine for string-based sessions, but if the user passes a Session object, ensure it serializes properly or handle that scenario distinctly.


288-300: Logout method logic is straightforward.
This method cleanly destroys the client session and logs out. The implementation is succinct and appears correct.


302-317: Output creation for sending messages is well-structured.
Offering a minimal shape of data plus a handler function is a great pattern for integrable “outputs.” This helps keep your business logic decoupled from the actual method calls.


369-403: Robust error checks for chatId.
If chatId is invalid, the Telegram API call may fail. Optionally add a quick validation or transform logic prior to calling sendMessage to enhance reliability.


453-466: Message parsing approach is clear.
Mapping raw Api.Message to your custom Message interface is straightforward and easy to maintain. Good job.

packages/core/src/core/env.ts (2)

15-17: Telegram credentials marked as required.
It’s valid to require the TELEGRAM_TOKEN, TELEGRAM_API_ID, and TELEGRAM_API_HASH in most scenarios. Confirm if you intend to support “user-only” flows with no bot token or vice versa; if so, you’ll need to adjust the validation accordingly.


25-26: Make sure optional vars are handled gracefully.
TELEGRAM_STARTUP_CHAT_ID and TELEGRAM_USER_SESSION are optional. Confirm the rest of your logic properly accounts for undefined.

.env.example (1)

22-38: Document how to obtain credentials.
Previously suggested in another review, referencing official Telegram docs and BotFather can help new contributors set up the environment correctly.

+# For more details on obtaining TELEGRAM_TOKEN, see https://t.me/botfather
+# For TELEGRAM_API_ID and TELEGRAM_API_HASH, see https://my.telegram.org/apps

await this.client.start({
botAuthToken: env.TELEGRAM_TOKEN,
});
console.log(this.client.session.save());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid printing session tokens to console.
Directly logging the session string can leak sensitive information, especially if logs are exposed or persisted.

- console.log(this.client.session.save());
+ // Remove or mask this log statement to avoid exposing the session token.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(this.client.session.save());
// Remove or mask this log statement to avoid exposing the session token.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/core/src/core/io/telegram.ts (2)

210-221: Store user session strings securely
Relying on plain-text session strings may pose a security risk if persisted or shared inadvertently. Consider using a secure storage mechanism or encrypting the session data before storing.


446-458: Consider using getDialogs or a more comprehensive method for bots
Api.messages.GetChats({ id: [] }) may not return all chats or might behave unexpectedly for certain bot configurations. Investigate if an alternate method like getDialogs or a different API method is more suitable for retrieving complete bot chat lists.

.vscode/settings.json (1)

13-15: Ensure consistent default formatter across the workspace
Having Prettier set as the default on save while simultaneously specifying “vscode.typescript-language-features” for TypeScript may lead to conflicting formatting styles. Consider aligning them by removing one or unifying the formatter preference to maintain consistency across your codebase.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aabe8c2 and 968d9ef.

📒 Files selected for processing (3)
  • .vscode/settings.json (1 hunks)
  • examples/example-telegram.ts (1 hunks)
  • packages/core/src/core/io/telegram.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/example-telegram.ts
🔇 Additional comments (5)
packages/core/src/core/io/telegram.ts (5)

147-148: Use the validated bot token from credentials
This code directly references env.TELEGRAM_TOKEN despite verifying this.credentials.bot_token above. To avoid confusion and ensure consistency, consider using this.credentials.bot_token instead of accessing the environment variable.


149-149: Avoid printing session tokens to console
Displaying session strings in logs can reveal sensitive information if logs are publicly accessible or stored. It’s safer to remove or mask this output to protect user data.


264-265: Refrain from printing session tokens
Printing the newly generated session string can lead to accidental exposure of credentials. Please remove or redact this log in production.


420-431: Good fallback approach for unknown entities
Gracefully handling entity resolution errors by sending the message via raw chat ID ensures reliable delivery in edge cases where the entity isn’t found.


464-475: Efficiently iterating dialog entities
This loop efficiently filters out dialogs without entities. The subsequent mapping provides a clear structure for the resulting list. No issues here—well done!

Comment on lines +101 to +111
// Set up Telegram bot client with credentials
// const telegram = new TelegramClient(
// {
// bot_token: env.TELEGRAM_TOKEN,
// api_id: parseInt(env.TELEGRAM_API_ID as string),
// api_hash: env.TELEGRAM_API_HASH,
// is_bot: true,
// session: undefined,
// },
// loglevel,
// );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete this

@ponderingdemocritus ponderingdemocritus merged commit 32f5b6a into daydreamsai:main Jan 31, 2025
7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants