-
Notifications
You must be signed in to change notification settings - Fork 66
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
feat: Make telegram client #63
Conversation
…dreams into make-telegram-client
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
WalkthroughThis pull request introduces Telegram integration capabilities to the project. It adds new environment variables for Telegram bot authentication, creates a new Changes
Possibly related PRs
Poem
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 usingconsole.log
Currently, sending a message logs details with boththis.logger.info
andconsole.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
InparseMessage()
, the message text is defaulted to an empty string ifmessage.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
⛔ 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
, andTELEGRAM_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:
- The actual values are never committed to version control
- Production values are securely managed (e.g., using secret management services)
- 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=gitLength 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:
- The
telegram
package (v2.26.16) is the latest stable version- The
express
package (v4.21.2) seems outdated. Consider updating to the latest stable versionLet's check for known vulnerabilities and latest versions:
Also applies to: 31-31
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; | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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; | ||
} | ||
} |
There was a problem hiding this comment.
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
, replacebotAuthToken: env.TELEGRAM_TOKEN
withbotAuthToken: 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
# 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= |
There was a problem hiding this comment.
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:
- How to obtain TELEGRAM_TOKEN from BotFather (https://t.me/botfather)
- Steps to get TELEGRAM_API_ID and TELEGRAM_API_HASH from Telegram's developer portal (https://my.telegram.org/apps)
- Any additional configuration requirements for gramJS
🔗 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:
- TELEGRAM_TOKEN: From BotFather (https://t.me/botfather)
- TELEGRAM_API_ID and TELEGRAM_API_HASH: From Telegram's developer portal (https://my.telegram.org/apps)
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
Great start! could you update to the new types that i just pushed |
could you fix the conflicts |
on it! |
There was a problem hiding this 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
⛔ 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(); + }
const scheduledTaskDb = new MongoDb( | ||
"mongodb://localhost:27017", | ||
"myApp", | ||
"scheduled_tasks" | ||
); |
There was a problem hiding this comment.
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.
const scheduledTaskDb = new MongoDb( | |
"mongodb://localhost:27017", | |
"myApp", | |
"scheduled_tasks" | |
); | |
const scheduledTaskDb = new MongoDb( | |
env.MONGODB_URL, | |
env.MONGODB_DB_NAME, | |
env.MONGODB_COLLECTION | |
); |
examples/example-telegram.ts
Outdated
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." | ||
), | ||
}); |
There was a problem hiding this comment.
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.
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." | |
), | |
}); |
const vectorDb = new ChromaVectorDB("telegram_agent", { | ||
chromaUrl: "http://localhost:8000", | ||
logLevel: loglevel, | ||
}); |
There was a problem hiding this comment.
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.
examples/example-telegram.ts
Outdated
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); | ||
} | ||
}); |
There was a problem hiding this comment.
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.
examples/example-telegram.ts
Outdated
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, | ||
); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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, | |
); |
There was a problem hiding this comment.
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!
@ponderingdemocritus I've fixed the conflicts and updated to the new types 👌 |
There was a problem hiding this 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 suggestionUse the validated bot token instead of direct env reference.
This is a repeated suggestion from previous reviews. By referencingenv.TELEGRAM_TOKEN
directly (line 139), you risk a mismatch between validatedthis.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, theMessage
interface usesmessage_id
, while the user interface usesid
. For better uniformity, consider making these fields consistently named, e.g., both asid
ormessageId
.
51-65
: Evaluate session handling inTelegramCredentials
.
Placing session data insideTelegramCredentials
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.
Usingreadline
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()
anduserLogin()
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 calledcreateChannelScraper
, 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.
InsidecreatePeriodicChannelScraper
, 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 withgetChatInfo
.
parseChat
andgetChatInfo
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
📒 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.
Whenthis.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 forTELEGRAM_STARTUP_CHAT_ID
.
PassingNaN
tosendMessage
is possible ifparseInt(env.TELEGRAM_STARTUP_CHAT_ID)
fails. Consider validating this to avoid runtime errors.
162-218
: Handle sessions passed asSession
instances.
sessionString = this.credentials.session?.toString()
is fine for string-based sessions, but if the user passes aSession
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 forchatId
.
IfchatId
is invalid, the Telegram API call may fail. Optionally add a quick validation or transform logic prior to callingsendMessage
to enhance reliability.
453-466
: Message parsing approach is clear.
Mapping rawApi.Message
to your customMessage
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 theTELEGRAM_TOKEN
,TELEGRAM_API_ID
, andTELEGRAM_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
andTELEGRAM_USER_SESSION
are optional. Confirm the rest of your logic properly accounts forundefined
..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()); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
console.log(this.client.session.save()); | |
// Remove or mask this log statement to avoid exposing the session token. |
There was a problem hiding this 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 likegetDialogs
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
📒 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 referencesenv.TELEGRAM_TOKEN
despite verifyingthis.credentials.bot_token
above. To avoid confusion and ensure consistency, consider usingthis.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!
// 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, | ||
// ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
delete this
Summary by CodeRabbit
New Features
Chores
Documentation
.env.example
with Telegram-specific environment variables.