### Getting Started: Your First Bot Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/000-introduction.md This section guides users through creating their very first Telegram bot using the Telegraf framework. It covers the initial setup and basic functionality. ```javascript import { Telegraf } from 'telegraf'; const bot = new Telegraf('YOUR_BOT_TOKEN'); bot.start((ctx) => ctx.reply('Welcome!')); bot.help((ctx) => ctx.reply('Send me sticker')); bot.on('sticker', (ctx) => ctx.reply('👍')); bot.hears('hi', (ctx) => ctx.reply('Hey there')); bot.launch(); // Enable graceful stop process.once('SIGINT', () => bot.stop('SIGINT')); process.once('SIGTERM', () => bot.stop('SIGTERM')); ``` -------------------------------- ### Serve Telegram Mini App Locally Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/serve/README.md Instructions to install dependencies and serve the Telegram Mini App example locally using pnpm. ```bash pnpm install pnpm serve ``` -------------------------------- ### Project Setup and Telegraf Installation Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md Commands to create a new project directory, navigate into it, and install the Telegraf library. It also includes optional steps for setting up TypeScript. ```shell # create folder mkdir my-first-bot # enter folder cd my-first-bot # install Telegraf npm install telegraf # install typescript as a dev-dependency (optional, but recommended) npm install --dev typescript # initialise a typescript config npx tsc --init ``` -------------------------------- ### Telegraf Test Environment Setup Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Shows how to enable the test environment for Telegraf by passing the `testEnv: true` option during bot initialization. Remember to switch back to your production token and remove this option for deployment. ```TS const bot = new Telegraf(testServerToken, { telegram: { testEnv: true } }); ``` -------------------------------- ### Complete Telegraf Bot Example Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md A consolidated example of a basic Telegram bot using Telegraf, including initialization, the '/start' command handler, and launching the bot. ```typescript import { Telegraf } from "telegraf"; const bot = new Telegraf(process.env.BOT_TOKEN); bot.start(ctx => { return ctx.reply(`Hello ${ctx.update.message.from.first_name}!`); }); bot.launch(); ``` -------------------------------- ### Initialize Telegram Web App Script Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Includes the necessary script to enable the `window.Telegram.WebApp` API in your web application. This script should be included before your own JavaScript. ```HTML ``` -------------------------------- ### Environment Variables Configuration Example (.env file) Source: https://github.com/feathers-studio/telegraf-docs/blob/master/README.md An example of how to define environment variables in a `.env` file for a Telegraf bot. This includes common variables like PORT, WEBHOOK_DOMAIN, and BOT_TOKEN. It is crucial to add this file to `.gitignore` to prevent credential leaks. ```yaml # .env PORT=3000 WEBHOOK_DOMAIN=bot.example.com BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 ``` -------------------------------- ### Telegram Web App API Initialization and Expansion Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Demonstrates how to access the Telegram Web App API and perform basic actions like signaling readiness and expanding the app to full screen. ```TS const app = window.Telegram.WebApp; // Call as soon as your page is ready for the user to see app.ready(); // Expand your web app to full screen app.expand(); ``` -------------------------------- ### Launching the Telegraf Bot Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md Shows the basic method to start the Telegraf bot, which by default uses long-polling to listen for updates from Telegram. ```typescript bot.launch(); ``` -------------------------------- ### Example User-Bot Interaction for Channel Promotion Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/broadcasting.md An example of how a bot can prompt users to join a Telegram channel for updates within a typical conversation flow. ```text User: /start Bot: Hello, this is a cat video downloader bot. To download a video, simply send its link. To get updates on our purry friends, join @examplecatchannel! ``` -------------------------------- ### Basic Session Middleware Setup Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Demonstrates how to import and use the session middleware in a Telegraf bot. This makes `ctx.session` available for storing user-specific data. ```TypeScript import { Telegraf, session } from "telegraf"; const bot = new Telegraf(token); bot.use(session()); // session is ready to use! ``` -------------------------------- ### Answering Web App Queries with Telegraf Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Demonstrates how to use `answerWebAppQuery` to send a response back to a Mini App, typically after validating `initData`. This is useful for interactive elements within the Mini App. ```TS bot.telegram.answerWebAppQuery({ id: "0", type: "article", title: "Hello Mini App!", input_message_content: { message_text: "This message was sent from answerWebAppQuery", }, }); ``` -------------------------------- ### Telegraf Bot Instance for API Queries Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Shows how to create a Telegraf bot instance specifically for making API queries (like `answerWebAppQuery`) without launching the bot itself. This is useful when your application server is separate from your bot server. ```TS new Telegraf(token) // Do not call bot.launch() ``` -------------------------------- ### Respond to Text Messages Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/002-listen-and-respond.md Provides an example of how to send a simple text response to a received text message using `ctx.sendMessage`. This is a basic example of bot interaction. ```TS (Node) bot.on(message("text"), async ctx => { await ctx.sendMessage("Hello!"); }); ``` -------------------------------- ### Telegram Web App API Reference Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Provides an overview of the Telegram Web App API, including methods for initialization, interaction, and data handling. It also references the availability of TypeScript types and the official Telegram documentation for comprehensive details. ```APIDOC Telegram.WebApp API: - ready(): Signals that the app is ready. - expand(): Expands the web app to full screen. - initData: Unsafe initialization data. - sendData(data: string): Sends data to the bot. - switchInlineQuery(query: string, cacheTime?: number): Switches to inline mode. - close(): Closes the web app. TypeScript Types: Available via `@types/telegram-web-app`. Official Documentation: https://core.telegram.org/bots/webapps ``` -------------------------------- ### Telegram Web App Launching from Attachment Menu Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Information regarding launching Mini Apps from the attachment menu on the Telegram Ad Platform. This feature is typically for major advertisers and may require a significant deposit. Refer to Telegram's official documentation for detailed requirements. ```APIDOC Telegram Web App Attachment Menu: Availability: Major advertisers on Telegram Ad Platform. Requirements: Potentially requires an upfront deposit of at least $1M. Testing: Available on the test server. Reference: https://core.telegram.org/bots/webapps#launching-mini-apps-from-the-attachment-menu ``` -------------------------------- ### Validate initData on Web App (Client-Side) Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md This snippet demonstrates how to fetch validation results for `initData` from the server within a Telegraf web app. It listens for the 'ready' event and sends the `app.initData` to a '/validate-init' endpoint. ```TS window.addEventListener("ready", async function () { const data = await fetch( "/validate-init", { method: "POST", body: app.initData }, ).then(res => res.json()); }); ``` -------------------------------- ### Persistent Session with Redis Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Illustrates how to configure persistent sessions using Redis as the storage backend. This requires installing `@telegraf/session/redis` and providing the Redis connection URL. ```TypeScript import { Redis } from "@telegraf/session/redis"; const store = Redis({ // this assumes you're using a locally installed Redis daemon running at 6379 url: "redis://127.0.0.1:6379", }); // pass the store to session bot.use(session({ store })); ``` -------------------------------- ### Receiving Web App Data in Telegraf Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md Illustrates how to handle data sent from a Mini App using `sendData`. The data is received as a service message and can be parsed as JSON or text. ```TS bot.on(message("web_app_data", async ctx => { // assuming sendData was called with a JSON string const data = ctx.webAppData.data.json(); // or if sendData was called with plaintext const text = ctx.webAppData.data.text(); })); ``` -------------------------------- ### TypeScript Context Augmentation for Session Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Shows how to extend the Telegraf `Context` type to include session data with specific properties, like a `count` in this example. It also demonstrates setting a default session value. ```TypeScript import { Telegraf, session, type Context } from "telegraf"; import type { Update } from "telegraf/types"; interface MyContext extends Context { session: { count: number }, }; // Telegraf constructor accepts a custom Context type const bot = new Telegraf(token); // we can also set a default value for session: bot.use(session({ defaultSession: () => ({ count: 0 }) })); bot.use(ctx => { // ctx.session is available }); ``` -------------------------------- ### Validate initData on Server (Node.js) Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/mini-apps/README.md This server-side code validates `initData` using HMAC-SHA256. It reconstructs the check string from the provided data, generates a secret key using the bot token, and compares the generated hash with the hash provided in the `initData`. Requires `node:crypto` and `URLSearchParams`. ```TS import { createHmac } from "node:crypto"; function HMAC_SHA256(key: string | Buffer, secret: string) { return createHmac("sha256", key).update(secret); } function getCheckString(data: URLSearchParams) { const items: [k: string, v: string][] = []; // remove hash for (const [k, v] of data.entries()) if (k !== "hash") items.push([k, v]); return items.sort(([a], [b]) => a.localeCompare(b)) // sort keys .map(([k, v]) => `${k}=${v}`) // combine key-value pairs .join("\n"); } app.post("/validate-init", (req, res) => { const data = new URLSearchParams(req.body); const data_check_string = getCheckString(data); const secret_key = HMAC_SHA256("WebAppData", process.env.BOT_TOKEN!).digest(); const hash = HMAC_SHA256(secret_key, data_check_string).digest("hex"); if (hash === data.get("hash")) // validated! return res.json(Object.fromEntries(data.entries())); return res.status(401).json({}); }); ``` -------------------------------- ### Safe Session Usage: Handling Concurrent Updates Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Explains how concurrent updates can affect session data. If multiple middlewares modify `ctx.session`, all changes are persisted. This example shows two middlewares incrementing a session counter. ```TypeScript bot.use(async (ctx, next) => { ctx.session.count++; // increment once return next(); // pass control to next middleware }); bot.on("message", async (ctx, next) => { ctx.session.count++; // increment again }); // all middleware have run. ctx.session will be written back to store ``` -------------------------------- ### Handling the /start Command Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md Implements a handler for the '/start' command, which replies to the user with a personalized greeting using information from the context object. ```typescript // Remember, this should ideally be written before `bot.launch()`! bot.start(ctx => { return ctx.reply(`Hello ${ctx.update.message.from.first_name}!`); }); ``` -------------------------------- ### Initializing Telegraf Bot Instance Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md Demonstrates how to import the Telegraf class and create a new bot instance, using an environment variable for the bot token. ```typescript import { Telegraf } from "telegraf"; const bot = new Telegraf(process.env.BOT_TOKEN); ``` -------------------------------- ### Running the Telegraf Bot Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/001-your-first-bot.md Instructions on how to compile TypeScript code (if used) and run the Node.js bot application. ```shell # Compile first, if you're using TS npx tsc # Run the bot node index.js ``` -------------------------------- ### Available npm Scripts Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/functions/aws-lambda/README.md This snippet lists the available npm scripts for managing the Telegraf bot deployment on AWS Lambda. These scripts abstract common Serverless Framework commands. ```shell npm run serverless # alias for the serverless binary npm run release npm run purge npm run set-webhook ``` -------------------------------- ### fmt Helpers: Captions and Single Helpers Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Illustrates using fmt helpers with message captions and demonstrates using individual helpers like bold. ```TS (Node) ctx.replyWithPhoto(file.id, { caption: fmt`File name: ${bold(fileName)}` }); ctx.replyWithPhoto(file.id, { caption: bold`File name: ${fileName}` }); ctx.replyWithPhoto(file.id, { caption: bold(fileName) }); ``` -------------------------------- ### fmt Helpers: pre Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Explains how to use the `pre` helper for pre-formatted code blocks, including specifying the language. ```TS (Node) // As a tagged template literal, allows string interpolation. pre("TypeScript")`Hello, ${name}`; // As a function, accepts a single string, and does not support nesting pre("TS")("Hello, " + name); ``` -------------------------------- ### Listen for Basic Update Types Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/002-listen-and-respond.md Demonstrates how to listen for general update types like 'message', 'callback_query', and 'chat_join_request' using the `bot.on()` method in Telegraf. This is the fundamental way to receive events from Telegram. ```TS (Node) bot.on("message", ctx => { // Use ctx.message }); bot.on("callback_query", ctx => { // Use ctx.callbackQuery }); bot.on("chat_join_request", ctx => { // Use ctx.chatJoinRequest }); ``` -------------------------------- ### Environment Variable Configuration for Telegraf Bots Source: https://github.com/feathers-studio/telegraf-docs/blob/master/README.md Demonstrates how to configure Telegraf bots using environment variables for sensitive information like bot tokens and webhook domains. It includes assertions to ensure required variables are set and provides a default for the port. ```typescript // default to port 3000 if PORT is not set const port = Number(process.env.PORT) || 3000; // assert and refuse to start bot if token or webhookDomain is not passed if (!process.env.BOT_TOKEN) throw new Error('"BOT_TOKEN" env var is required!'); if (!process.env.WEBHOOK_DOMAIN) throw new Error('"WEBHOOK_DOMAIN" env var is required!'); ``` -------------------------------- ### fmt Helpers: Nested Formatting and Links Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Demonstrates advanced usage of fmt helpers with nested formatting, mentions, and inline links. ```TS (Node) import { fmt, bold, italics, mention } from "telegraf/format"; ctx.reply(fmt` Ground control to ${bold`${mention("Major Tom", ctx.from.id)}`} ${bold`Lock your ${italic`Soyuz hatch`}`} And ${italic`put your helmet on`} — ${link("David Bowie", "https://en.wikipedia.org/wiki/David_Bowie")} `); ``` -------------------------------- ### fmt Helpers: link Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Illustrates the usage of the `link` helper to create inline links, which must be used as a function. ```TS (Node) link("Link text", URL); ``` -------------------------------- ### fmt Helpers: Basic Formatting Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Introduces the fmt helpers for creating formatted messages using template literals, including bold, italic, and underline. ```TS (Node) import { fmt, bold, italic, underline } from "telegraf/format"; ctx.sendMessage(fmt` ${bold`Bold`}, ${italic`italic`}, and ${underline`underline`}! `); ``` -------------------------------- ### fmt Helpers: code Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Demonstrates how to use the `code` helper for inline monospaced text, supporting template literals and function calls. ```TS (Node) // As a tagged template literal, allows string interpolation. code`Hello, ${name}`; // As a function, accepts a single string, and does not support nesting code("Hello, " + name); ``` -------------------------------- ### Base Telegraf Context Object Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Illustrates the fundamental properties and their expected types within a Telegraf `ctx` object. This serves as a reference for understanding the data available for each request. ```TS (Node) { update: { update_id: number }, telegram: { token: string, response: undefined /* differs based on the configuration */, options: { apiRoot: 'https://api.telegram.org', apiMode: 'bot', webhookReply: boolean, agent: [Agent], attachmentAgent: undefined /* differs based on the configuration */, testEnv: boolean } }, botInfo: { id: number /* Your bot unique id */ , is_bot: true, first_name: string, username: string, can_join_groups: boolean, can_read_all_group_messages: boolean, supports_inline_queries: boolean }, state: {} } ``` -------------------------------- ### Filter Specific Message and Callback Query Types Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/002-listen-and-respond.md Shows how to use Telegraf filters to listen for specific types of messages (e.g., text messages) and callback queries (e.g., those with data). This allows for more granular event handling. ```TS (Node) // import filters import { message, callbackQuery, channelPost } from "telegraf/filters" bot.on(message("text"), ctx => { // Use ctx.message.text }); bot.on(callbackQuery("data"), ctx => { // Use ctx.callbackQuery.data }); bot.on(channelPost("video"), ctx => { // Use ctx.channelPost.video }); ``` -------------------------------- ### Filter for Complex Message Properties Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/002-listen-and-respond.md Illustrates how to filter for messages with specific properties, such as forwarded messages or photos that are part of an album. This enables handling more complex user interactions. ```TS (Node) // Listen for text messages that were forwarded bot.on(message("forward_from", "text"), ctx => { // These properties are accessible: ctx.message.text; ctx.message.forward_from.first_name; }); // Listen for photos messages that are part of an album (media group) bot.on(message("photo", "media_group_id"), ctx => { // These properties are accessible: ctx.message.photo; ctx.message.media_group_id; }); ``` -------------------------------- ### Logging Telegraf Context Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet demonstrates how to log the `ctx` object to the console within a Telegraf middleware. It's useful for inspecting the context's shape for different request types. ```TS (Node) import { Telegraf } from "telegraf"; const bot = new Telegraf(process.env.BOT_TOKEN); // Your bot token bot.use(ctx => { console.log(ctx); }); bot.launch(); // Enable graceful stop process.once('SIGINT', () => bot.stop('SIGINT')); process.once('SIGTERM', () => bot.stop('SIGTERM')); ``` -------------------------------- ### Safe Session Usage: Awaiting Async Operations Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Highlights the importance of awaiting or returning all asynchronous operations within middleware to prevent race conditions. This ensures session data is handled correctly before the next middleware or update is processed. ```TypeScript bot.on("message", async ctx => { // ❌ BAD! You did not await ctx.reply() ctx.reply("Hello there!"); // ✅ Good, you awaited your requests. await ctx.reply("Hello there!"); // Also applies to any other async calls you may make: const res = await fetch(API_URL); // Returning calls is also okay, because the promise will be returned return ctx.sendAnimation(GOOD_MORNING_GIF); }); ``` -------------------------------- ### User Sends Sticker Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet illustrates the message structure when a user sends a sticker. It highlights that the 'from' and 'chat' objects remain consistent with text messages, while a 'sticker' object is added to contain sticker-specific details. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, sticker: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */ } } ``` -------------------------------- ### fmt Helpers: bold, italic, underline, strikethrough, spoiler Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Shows the usage of basic text formatting helpers (bold, italic, underline, strikethrough, spoiler) with both tagged template literals and as functions. ```TS (Node) // As a tagged template literal, allows string interpolation and nested formatting // Here, only `name` is underlined fmt`Hello, ${underline`${name}`}`; // The entire text is bold, but `name` is also italic bold`Hello, ${italic`${name}`}`; // As a function, accepts a single string, and does not support nesting bold("Hello, " + name); ``` -------------------------------- ### Graceful Shutdown for Telegraf Bots Source: https://github.com/feathers-studio/telegraf-docs/blob/master/README.md Ensures that Telegraf bot connections are gracefully closed before the Node.js process is terminated. This is achieved by using `process.once` to listen for SIGINT and SIGTERM signals and calling `bot.stop()`. ```typescript process.once("SIGINT", () => bot.stop("SIGINT")); process.once("SIGTERM", () => bot.stop("SIGTERM")); ``` -------------------------------- ### Bot Joins Channel as Admin Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Represents the `my_chat_member` update object when a bot first joins a channel as an administrator. It details the `chat` information, `from` user, `old_chat_member` status (e.g., 'left'), and `new_chat_member` status (e.g., 'administrator') with associated permissions. ```TS (Node) { my_chat_member: { chat: { "id": number /* Channel unique number id */, "title": string /* Channel title/name */, "type": string /* e.g. "channel" */ }, from: { "id": number, "is_bot": boolean, "first_name": string, "username": string, "language_code": string /* e.g. "en" */ }, date: number /* Unix/Epoch based date */ old_chat_member: { "user": { "id": number, "is_bot": boolean, "first_name": string, "username": string }, "status": string /* e.g. "left" */ }, new_chat_member: { "user": { "id": number, "is_bot": boolean, "first_name": string, "username": string }, "status": string /* e.g. "administrator" */, "can_be_edited": boolean, "can_manage_chat": boolean, "can_change_info": boolean, "can_post_messages": boolean, "can_edit_messages": boolean, "can_delete_messages": boolean, "can_invite_users": boolean, "can_restrict_members": boolean, "can_promote_members": boolean, "can_manage_video_chats": boolean, "can_post_stories": boolean, "can_edit_stories": boolean, "can_delete_stories": boolean, "is_anonymous": boolean, "can_manage_voice_chats": boolean } } } ``` -------------------------------- ### Safe Session Usage: Error Handling and Rollback Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Demonstrates that session data is persisted even if a middleware throws an error. If session data needs to be rolled back on error, it must be explicitly handled within the middleware. ```TypeScript bot.use(async (ctx, next) => { ctx.session.count++; // increment count await functionThatThrows(); return next(); }); // incremented count will still be written to store ``` -------------------------------- ### Audio Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Defines the structure for audio messages, including duration, title, MIME type, and thumbnail details. ```TS (Node) audio: { "duration": number /* In seconds */, "file_name": string, "mime_type": string /* e.g. "audio/mpeg" */, "title": string, "thumbnail": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "thumb": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "file_id": string, "file_unique_id": string, "file_size": number, } ``` -------------------------------- ### Send Message to Channel Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/broadcasting.md Demonstrates how a bot can send a message to a Telegram channel after being added as an admin. This is a recommended approach for broadcasting updates. ```TS (Node) bot.telegram.sendMessage(channelId, message); ``` -------------------------------- ### Setting the Telegram Webhook Source: https://github.com/feathers-studio/telegraf-docs/blob/master/examples/functions/aws-lambda/README.md This command demonstrates how to set the Telegram webhook URL for your deployed Lambda function using the Telegraf helper function. It requires your bot token and the full URL of your Lambda function endpoint. ```shell npm run set-webhook -- -t $BOT_TOKEN -D '{ "url": $FULL_URL_TO_FUNCTION }' ``` -------------------------------- ### Forwarded Channel File Message/Post Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Outlines the structure of a message object when a user forwards a file message or post from a channel. It includes fields for `forward_from_chat`, `forward_from_message_id`, `forward_signature`, `forward_date`, and the `document` object. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, forward_from_chat: [Object] /* Stays the same in this scenario */, forward_from_message_id: number /* Original id of the message in the channel */, forward_signature: string /* Optional: Will only be received if the channel had admins signature turned on when posting this message */, forward_date: number /* Original Unix/Epoch based date of the message */, text: string, document: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */, caption: string /* Optional: Will only be received if the file has a description/caption */, caption_entities: [Array] /* Entities will only be received in case of a: mention, code etc... */ } } ``` -------------------------------- ### GIF Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Details the structure for GIF messages, which include both animation and document properties, along with thumbnail information. ```TS (Node) // A GIf has both of these properties available animation: { "mime_type": string /* e.g. "video/mp4" */, "duration": number, "width": number, "height": number, "thumbnail": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "thumb": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "file_id": string, "file_unique_id": string, "file_size": number }, document: { "mime_type": string, "thumbnail": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "thumb": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "file_id": string, "file_unique_id": string, "file_size": number } ``` -------------------------------- ### File/Document Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Outlines the structure for general file or document messages, including file name, MIME type, and file identifiers. ```TS (Node) document: { "file_name": string, "mime_type": string /* e.g. "application/zip" */, "file_id": string, "file_unique_id": string, "file_size": number, } ``` -------------------------------- ### User Sends File Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet defines the message structure when a user sends a file. Similar to GIFs, it includes the 'document' object, which holds the file-related information. The 'from' and 'chat' fields remain consistent. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, document: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */ } } ``` -------------------------------- ### Video Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Details the structure for video messages, including duration, dimensions, MIME type, and thumbnail information. ```TS (Node) video: { "duration": number /* In seconds */, "width": number, "height": number, "file_name": string, "mime_type": string /* e.g. "video/mp4" */, "thumbnail": { "file_id": string , "file_unique_id": string, "file_size": number, "width": number, "height": number }, "thumb": { "file_id": string , "file_unique_id": string, "file_size": number, "width": number, "height": number }, "file_id": string , "file_unique_id": string, "file_size": number, } ``` -------------------------------- ### HTML Formatting Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Shows how to format messages using HTML tags for bold, italic, underlined text, and inline code. ```TS (Node) ctx.replyWithHTML("``Bold, italic, and underlines!"); bot.telegram.sendMessage("``Bold, italic, and underlines!", { parse_mode: "HTML" }); ``` -------------------------------- ### User Sends GIF Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet shows the message structure for a GIF. It includes the standard message and chat information, along with 'animation' and 'document' objects, both of which can contain details about the sent GIF. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, animation: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */, document: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */ } } ``` -------------------------------- ### Create User Mention Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Generates a mention link for a user using their unique ID. This function is intended for use within Telegraf message composition and cannot be nested. ```typescript mention("User", userId); ``` -------------------------------- ### Webhook Mode Configuration Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Instructs to disable `webhookReply` when using Telegraf in webhook mode to avoid potential issues with session handling and replies. ```TypeScript const bot = new Telegraf(token, { telegram: { webhookReply: false } }) ``` -------------------------------- ### User Forwards Channel Message with Photo Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet illustrates the structure for a forwarded channel message that contains a photo. It includes 'forward_from_chat', 'forward_from_message_id', and 'forward_date'. The 'photo' field indicates the presence of images, and 'caption'/'caption_entities' provide details about any accompanying text. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, forward_from_chat: [Object], forward_from_message_id: number /* Original message id */, forward_date: number /* Unix/Epoch based date */, photo: [Array] /* This forwarded message contained photos */, caption: string, caption_entities: [Array] } } ``` -------------------------------- ### Safe Session Usage: Avoiding Stale Data Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/session.md Warns against writing stale session data, especially after awaiting asynchronous operations. It's crucial to ensure the session data being written is the most current version. ```TypeScript bot.on(message("text"), async ctx => { // reading value from session const count = ctx.session.count; const response = await fetch(API_URL, { body: count }); // ⚠️ WARNING! You wrote stale value to session. // Another request may have updated session while you awaited fetch, be careful of that ctx.session.count = count + 1; // ✅ Good, you wrote immediately after reading ctx.session.count = ctx.session.count + 1; }); ``` -------------------------------- ### New Text Message in Channel (Sign Messages Off) Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Illustrates the `channel_post` object structure for a new text message in a channel when the 'Sign messages' setting is turned off. It includes `message_id`, `sender_chat`, `chat`, `date`, and `text`. The `author_signature` field is noted as optional and present only when signing is enabled. ```TS (Node) { channel_post: { author_signature: string /* Optional */, message_id: number, sender_chat: { "id": number, "title": string, "type": string }, chat: [Object] /* Stays the same */,, date: number /* Unix/Epoch based date */, text: string } } ``` -------------------------------- ### Sticker Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Defines the structure of a sticker message object, including dimensions, emoji, set name, animation status, and thumbnail details. ```TS (Node) sticker: { "width": number, "height": number, "emoji": string /* e.g. "😂" */, "set_name": string /* The sticker pack name */, "is_animated": boolean, "is_video": boolean, "type": string /* e.g. "regular" etc. */, "thumbnail": { "file_id": string /* e.g. "AAMCBAADGQEAAgNdZRqJ2Kq_XCeyHHLUwUadueLpqc4AAhoRAAKVjflQoYfb2mrP1ZoBAAdtAAMwBA"*/, "file_unique_id": string /* e.g. "AQADGhEAApWN-VBy" */, "file_size": number, "width": number, "height": number }, "thumb": { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, "file_id": string, "file_unique_id": string, "file_size": number } ``` -------------------------------- ### User Forwards Channel Text Message/Post Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md This snippet describes the message structure when a user forwards a post from a channel. It includes 'forward_from_chat' to identify the source channel, 'forward_from_message_id' for the original message ID, and 'forward_signature' if available. The 'text' and 'entities' fields are also included. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, forward_from_chat: { "id": number /* Channel unique id */, "title": string, "username": string /* Channel id that starts with @ */, "type": string /* e.g. "channel" etc. */ }, forward_from_message_id: number /* Original id of the message in the channel */, forward_signature: string /* Optional: Will only be received if the channel had admins signature turned on when posting this message */, forward_date: number /* Original Unix/Epoch based date of the message */, text: string, entities: [ { "offset": number, "length": number, "type": string } ] /* Entities will only be received in case of a: mention, code etc... */ } } ``` -------------------------------- ### Forwarded Channel Voice Message/Post Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Details the message object structure for forwarded voice messages or posts from a channel. It includes fields like `forward_from_chat`, `forward_from_message_id`, `forward_signature`, and `forward_date`. ```TS (Node) { message: { message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, forward_from_chat: [Object] /* Stays the same in this scenario */ , forward_from_message_id: number /* Original id of the message in the channel */, forward_signature: string /* Optional: Will only be received if the channel had admins signature turned on when posting this message */, forward_date: number /* Original Unix/Epoch based date of the message */, voice: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */, caption: string, caption_entities: [Array] /* Entities will only be received in case of a: mention, code etc... */ } } ``` -------------------------------- ### Photo Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Describes the structure of a photo message, noting that the array contains different sizes of the same photo. ```TS (Node) photo: [ { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number }, { "file_id": string, "file_unique_id": string, "file_size": number, "width": number, "height": number } ] ``` -------------------------------- ### Voice Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Specifies the structure for voice messages, including duration, MIME type, and file identifiers. ```TS (Node) voice: { "duration": number /* In seconds */, "mime_type": string /* e.g. "audio/mpeg" */, "file_id": string, "file_unique_id": string, "file_size": number, } ``` -------------------------------- ### Forwarded Channel Audio Message Structure Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/context-shapes-overview.md Describes the structure of a message object when a user forwards an audio message from a channel. It highlights that forward-related fields might not be available due to Telegram implementation. ```TS (Node) { message: { audio: [Object] /* refer to ## Specific Telegram message objects based on the type of the message */ message_id: number, from: [Object] /* Stays the same in this scenario */, chat: [Object] /* Stays the same in this scenario */, date: number /* Unix/Epoch based date */, caption: string, caption_entities: [Array] } } ``` -------------------------------- ### MarkdownV2 Formatting Source: https://github.com/feathers-studio/telegraf-docs/blob/master/guide/formatting.md Demonstrates how to use MarkdownV2 for bold, italic, and underlined text, including escaping special characters. ```TS (Node) ctx.replyWithMarkdownV2("*Bold*, _italic_, and __underlines__\\!"); bot.telegram.sendMessage("*Bold*, _italic_, and __underlines__\\!", { parse_mode: "MarkdownV2" }); ``` ```TS (Node) ctx.replyWithMarkdownV2("Sending an asterisk: \\*"); // sends "Sending an asterisk: *" ```