Skip to content

Commit 302c1d3

Browse files
authored
✨ tweak: Add docstrings to dev - Merge pull request #8 from wgtechlabs/coderabbitai/docstrings/rBEa
2 parents 74b19fa + 04b75d4 commit 302c1d3

File tree

5 files changed

+162
-104
lines changed

5 files changed

+162
-104
lines changed

src/bot.ts

Lines changed: 42 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@ import { BotsStore } from './sdk/bots-brain/index.js';
1212
import { BotContext, TelegramError, CommandHandler } from './types/index.js';
1313

1414
/**
15-
* Creates a new Telegram bot instance
16-
*
17-
* @param token - The Telegram Bot API token
18-
* @returns A new Telegraf bot instance
15+
* Creates and returns a new Telegraf bot instance using the provided Telegram Bot API token.
16+
*
17+
* @param token - The Telegram Bot API token to authenticate the bot
18+
* @returns The initialized Telegraf bot instance
19+
* @throws If the token is missing or empty
1920
*/
2021
export function createBot(token: string): Telegraf<BotContext> {
2122
if (!token) {
@@ -25,10 +26,9 @@ export function createBot(token: string): Telegraf<BotContext> {
2526
}
2627

2728
/**
28-
* Configures the bot's command handlers
29-
*
30-
* @param bot - The Telegraf bot instance
31-
* @param commands - Array of command objects with name and handler
29+
* Registers command handlers on the bot for each specified command.
30+
*
31+
* @param commands - List of command definitions, each containing a command name and its handler function.
3232
*/
3333
export function configureCommands(
3434
bot: Telegraf<BotContext>,
@@ -40,22 +40,23 @@ export function configureCommands(
4040
}
4141

4242
/**
43-
* Starts the bot polling for updates
44-
*
45-
* @param bot - The Telegraf bot instance
43+
* Starts the bot's polling mechanism to receive updates from Telegram.
44+
*
45+
* Initiates the process for the bot to listen for and handle incoming messages and events.
4646
*/
4747
export function startPolling(bot: Telegraf<BotContext>): void {
4848
bot.launch();
4949
}
5050

5151
/**
52-
* Safely send a message with error handling for blocked users and other common errors
53-
*
54-
* @param bot - The Telegraf bot instance
55-
* @param chatId - The chat ID to send the message to
56-
* @param text - The message text
57-
* @param options - Additional options for sendMessage
58-
* @returns The sent message object or null if failed
52+
* Sends a message to a specified chat, handling common Telegram errors such as blocked users, chat not found, and rate limits.
53+
*
54+
* Attempts to send a message and performs cleanup if the bot is blocked or the chat does not exist. Returns null if sending fails due to these conditions or rate limiting; otherwise, returns the sent message object.
55+
*
56+
* @param chatId - The target chat ID
57+
* @param text - The message text to send
58+
* @param options - Optional parameters for message formatting and behavior
59+
* @returns The sent message object, or null if the message could not be delivered due to blocking, chat not found, or rate limiting
5960
*/
6061
export async function safeSendMessage(
6162
bot: Telegraf<BotContext>,
@@ -106,12 +107,14 @@ export async function safeSendMessage(
106107
}
107108

108109
/**
109-
* Safely reply to a message with cleanup handling for blocked users
110-
*
111-
* @param ctx - The Telegraf context object
112-
* @param text - The message text to reply with
113-
* @param options - Additional options for the reply
114-
* @returns The sent message object or null if failed
110+
* Replies to a message in the given context, handling errors such as blocked users, missing chats, and rate limits.
111+
*
112+
* If the bot is blocked or the chat is not found, associated user data is cleaned up and null is returned. If rate limits are exceeded, a warning is logged and null is returned. Other errors are logged and re-thrown.
113+
*
114+
* @param ctx - The Telegraf context for the incoming message
115+
* @param text - The reply message text
116+
* @param options - Optional parameters for the reply
117+
* @returns The sent message object, or null if the reply could not be sent due to blocking, missing chat, or rate limiting
115118
*/
116119
export async function safeReply(
117120
ctx: BotContext,
@@ -170,15 +173,17 @@ export async function safeReply(
170173
}
171174

172175
/**
173-
* Safely edit a message text with cleanup handling for blocked users
174-
*
176+
* Attempts to edit the text of a Telegram message, handling common errors such as blocked users, missing chats, rate limits, and non-critical edit failures.
177+
*
178+
* If the bot is blocked or the chat is not found, associated user data is cleaned up and `null` is returned. Rate limit errors also result in `null`. If the message is not found or already modified, the error is logged and `null` is returned. Other errors are logged and re-thrown.
179+
*
175180
* @param ctx - The Telegraf context object
176-
* @param chatId - The chat ID
177-
* @param messageId - The message ID to edit
178-
* @param inlineMessageId - Inline message ID (if applicable)
179-
* @param text - The new message text
180-
* @param options - Additional options for editing
181-
* @returns The edited message object or null if failed
181+
* @param chatId - The target chat ID
182+
* @param messageId - The ID of the message to edit
183+
* @param inlineMessageId - The inline message ID, if applicable
184+
* @param text - The new text for the message
185+
* @param options - Additional options for editing the message
186+
* @returns The edited message object, or `null` if the operation fails due to handled errors
182187
*/
183188
export async function safeEditMessageText(
184189
ctx: BotContext,
@@ -248,10 +253,11 @@ export async function safeEditMessageText(
248253
}
249254

250255
/**
251-
* Clean up user data when bot is blocked or chat is not found
252-
* This implements the fix from GitHub issue telegraf/telegraf#1513
253-
*
254-
* @param chatId - The chat ID of the blocked user
256+
* Cleans up all local data associated with a chat when the bot is blocked or the chat is not found.
257+
*
258+
* Removes tickets and customer mappings related to the specified chat from persistent storage. User state data is not explicitly removed but will expire automatically. Errors during cleanup are logged but do not interrupt bot operation.
259+
*
260+
* @param chatId - The Telegram chat ID to clean up data for
255261
*/
256262
async function cleanupBlockedUser(chatId: number): Promise<void> {
257263
try {

src/commands/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,9 @@ export const processSupportConversation = async (ctx: BotContext): Promise<boole
520520
};
521521

522522
/**
523-
* Handles the email field input and completes the ticket process
523+
* Processes the email input step of the support ticket conversation and completes ticket creation.
524+
*
525+
* If the user enters "skip", an auto-generated email is used. The function then finalizes the ticket by interacting with external services to create the customer, user, and ticket records, updates the user with confirmation or error messages, and clears the user's conversation state.
524526
*/
525527
async function handleEmailField(ctx: BotContext, userState: any, messageText: string): Promise<void> {
526528
try {

src/events/message.ts

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,27 @@ import { safeReply, safeEditMessageText } from '../bot.js';
1313
import type { BotContext } from '../types/index.js';
1414

1515
/**
16-
* Checks if a message is from a group chat (not a channel)
16+
* Returns true if the message originates from a group or supergroup chat.
17+
*
18+
* @returns True if the chat type is 'group' or 'supergroup'; otherwise, false.
1719
*/
1820
export function isGroupChat(ctx: BotContext): boolean {
1921
return ctx.chat?.type === 'group' || ctx.chat?.type === 'supergroup';
2022
}
2123

2224
/**
23-
* Checks if a message is from a private chat
25+
* Determines whether the current chat is a private chat.
26+
*
27+
* @returns True if the chat type is 'private'; otherwise, false.
2428
*/
2529
export function isPrivateChat(ctx: BotContext): boolean {
2630
return ctx.chat?.type === 'private';
2731
}
2832

2933
/**
30-
* Handles all incoming messages
31-
*
32-
* This function routes messages to appropriate handlers based on chat type
33-
* and processes text messages against registered patterns
34+
* Main handler for incoming Telegram messages, routing them to appropriate processors based on chat type and message context.
35+
*
36+
* Determines whether to process the message as a command, support conversation, ticket reply, private chat, or group chat, and delegates handling accordingly. Prevents automatic responses in group chats and ensures that only relevant handlers are invoked for each message type.
3437
*/
3538
export async function handleMessage(ctx: BotContext, next: () => Promise<void>): Promise<void> {
3639
try {
@@ -100,7 +103,11 @@ export async function handleMessage(ctx: BotContext, next: () => Promise<void>):
100103
}
101104

102105
/**
103-
* Handles replies to ticket confirmation messages
106+
* Processes replies to ticket confirmation or agent messages and routes them for handling.
107+
*
108+
* Checks if the incoming message is a reply to a ticket confirmation or agent message, and if so, processes the reply accordingly. Returns true if the reply was handled, or false otherwise.
109+
*
110+
* @returns True if the reply was processed as a ticket or agent message reply; false otherwise.
104111
*/
105112
async function handleTicketReply(ctx: BotContext): Promise<boolean> {
106113
try {
@@ -157,7 +164,11 @@ async function handleTicketReply(ctx: BotContext): Promise<boolean> {
157164
}
158165

159166
/**
160-
* Handles replies to ticket confirmation messages
167+
* Processes a reply to a ticket confirmation message by validating the reply, sending the message to the ticket conversation, and updating the user with a status message.
168+
*
169+
* @param ctx - The Telegram bot context for the incoming message
170+
* @param ticketInfo - Information about the ticket to which the reply is associated
171+
* @returns True if the reply was processed (successfully or with an error status message), or false if validation failed or an unexpected error occurred
161172
*/
162173
async function handleTicketConfirmationReply(ctx: BotContext, ticketInfo: any): Promise<boolean> {
163174
try {
@@ -214,7 +225,9 @@ async function handleTicketConfirmationReply(ctx: BotContext, ticketInfo: any):
214225
}
215226

216227
/**
217-
* Validates the reply context and ticket information
228+
* Validates that the reply message and sender information are present and extracts user and message details for ticket processing.
229+
*
230+
* @returns An object indicating whether the reply is valid. If valid, includes the sender's Telegram user ID, username, and message text.
218231
*/
219232
async function validateTicketReply(ctx: BotContext, ticketInfo: any): Promise<{ isValid: false } | { isValid: true; telegramUserId: number; username: string | undefined; message: string }> {
220233
if (!ctx.from || !ctx.message || !('text' in ctx.message)) {
@@ -243,7 +256,9 @@ async function validateTicketReply(ctx: BotContext, ticketInfo: any): Promise<{
243256
}
244257

245258
/**
246-
* Processes and sends the ticket message to Unthread
259+
* Sends a user's message to the specified ticket conversation in Unthread.
260+
*
261+
* Retrieves or creates user data based on the Telegram user ID and username, then sends the provided message to the ticket conversation identified by the ticket information.
247262
*/
248263
async function processTicketMessage(ticketInfo: any, telegramUserId: number, username: string | undefined, message: string): Promise<void> {
249264
// Get user information from database
@@ -272,7 +287,9 @@ async function processTicketMessage(ticketInfo: any, telegramUserId: number, use
272287
}
273288

274289
/**
275-
* Updates the status message and handles cleanup
290+
* Updates a status message to indicate success or error, then deletes it after a short delay.
291+
*
292+
* The message is updated to show a checkmark for success or an error icon for failure, and is automatically removed after 3 seconds (success) or 5 seconds (error).
276293
*/
277294
async function updateStatusMessage(ctx: BotContext, statusMsg: any, isSuccess: boolean): Promise<void> {
278295
if (isSuccess) {
@@ -307,7 +324,11 @@ async function updateStatusMessage(ctx: BotContext, statusMsg: any, isSuccess: b
307324
}
308325

309326
/**
310-
* Handles replies to agent messages
327+
* Processes a user's reply to an agent message by forwarding it to the corresponding Unthread conversation.
328+
*
329+
* Sends a status message indicating progress, updates it upon success or error, and deletes the status message after a delay. Returns true if the reply was processed, false otherwise.
330+
*
331+
* @returns True if the reply was handled (successfully sent or error occurred), false if the context was invalid.
311332
*/
312333
async function handleAgentMessageReply(ctx: BotContext, agentMessageInfo: any): Promise<boolean> {
313334
try {
@@ -400,7 +421,9 @@ async function handleAgentMessageReply(ctx: BotContext, agentMessageInfo: any):
400421
}
401422

402423
/**
403-
* Handles messages from private chats (direct messages to the bot)
424+
* Processes incoming messages from private chats and responds with an about message for non-command texts.
425+
*
426+
* Skips messages that are commands, allowing them to be handled by their respective handlers.
404427
*/
405428
export async function handlePrivateMessage(ctx: BotContext): Promise<void> {
406429
try {
@@ -438,7 +461,9 @@ export async function handlePrivateMessage(ctx: BotContext): Promise<void> {
438461
}
439462

440463
/**
441-
* Handles messages from group chats
464+
* Processes incoming messages from group chats without sending automatic responses.
465+
*
466+
* Logs detailed information about the group, sender, and message content for monitoring and debugging purposes.
442467
*/
443468
export async function handleGroupMessage(ctx: BotContext): Promise<void> {
444469
try {

src/index.ts

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,17 @@ bot.on('callback_query', async (ctx) => {
193193
});
194194

195195
/**
196-
* Retry helper function with exponential backoff
196+
* Executes an asynchronous operation with retries and exponential backoff on failure.
197+
*
198+
* Retries the provided async operation up to a specified number of times, increasing the delay between attempts exponentially up to a maximum delay. Logs warnings on each retry and an error if all attempts fail.
199+
*
200+
* @param operation - The asynchronous function to execute and retry on failure
201+
* @param maxRetries - Maximum number of retry attempts (default: 5)
202+
* @param initialDelayMs - Initial delay in milliseconds before the first retry (default: 1000)
203+
* @param maxDelayMs - Maximum delay in milliseconds between retries (default: 30000)
204+
* @param operationName - Name used in log messages to identify the operation (default: 'operation')
205+
* @returns The result of the successful operation
206+
* @throws The last encountered error if all retries fail
197207
*/
198208
async function retryWithBackoff<T>(
199209
operation: () => Promise<T>,
@@ -421,11 +431,11 @@ bot.catch(async (error: any, ctx?: BotContext) => {
421431
});
422432

423433
/**
424-
* Clean up user data when bot is blocked or chat is not found
425-
* This implements the fix from GitHub issue telegraf/telegraf#1513
426-
* Global version for use in error handlers
427-
*
428-
* @param chatId - The chat ID of the blocked user
434+
* Removes all tickets and customer mappings associated with a Telegram chat when the bot is blocked or the chat is not found.
435+
*
436+
* Cleans up related tickets and customer data in storage for the specified chat ID. User state data is not explicitly removed but will expire automatically.
437+
*
438+
* @param chatId - The Telegram chat ID to clean up.
429439
*/
430440
async function cleanupBlockedUserGlobal(chatId: number): Promise<void> {
431441
try {
@@ -485,9 +495,9 @@ async function cleanupBlockedUserGlobal(chatId: number): Promise<void> {
485495
}
486496

487497
/**
488-
* Performs graceful shutdown of all services
489-
*
490-
* Properly close database connections, stop webhook consumer, and stop the bot
498+
* Shuts down all services and resources used by the bot, ensuring a clean exit.
499+
*
500+
* Stops the webhook consumer if running, shuts down the BotsStore, closes database connections, and exits the process. Logs each shutdown step and exits with an error code if any shutdown operation fails.
491501
*/
492502
async function gracefulShutdown(): Promise<void> {
493503
try {

0 commit comments

Comments
 (0)