### Register Telegram Webhook (Bash) Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This bash script demonstrates how to register a webhook with the Telegram Bot API using curl. It shows the basic POST request format and provides an example with placeholder values, along with the expected success response from Telegram. ```bash # Регистрация webhook вручную curl --request POST \ --url "https://api.telegram.org/bot/setWebhook?url=" # Пример с реальными значениями: curl --request POST \ --url "https://api.telegram.org/bot123456789:ABCdefGHIjklMNOpqrsTUVwxyz/setWebhook?url=https://functions.yandexcloud.net/d4e1234567890" # Ожидаемый ответ при успехе: # {"ok":true,"result":true,"description":"Webhook was set"} ``` -------------------------------- ### Start Yandex Cloud Workflow Integration (JavaScript) Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This JavaScript function integrates with Yandex Cloud Workflows by sending Telegram message data to a specified workflow for further processing. It requires an IAM token for authentication and handles success and error responses from the Yandex Cloud API. ```javascript async function startWorkflow(ctx, text, chatId, id) { try { // Получаем IAM-токен из контекста Cloud Function const token = globalContext.token.access_token; if (!token) { await ctx.reply("Ошибка: отсутствует токен авторизации для вызова Yandex Cloud Workflows."); return; } // Вызов API Yandex Cloud Workflows const response = await fetch("https://serverless-workflows.api.cloud.yandex.net/workflows/v1/execution/start", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}` }, body: JSON.stringify({ workflowId: id, input: { inputJson: JSON.stringify({ message: text, chatId: chatId }) } }) }); if (response.ok) { await ctx.reply("Сообщение успешно отправлено в Yandex Cloud Workflows."); } else { const errorText = await response.text(); await ctx.reply(`Ошибка при отправке в Yandex Cloud Workflows. Статус: ${response.status}, Ответ: ${errorText}`); } } catch (error) { console.error("Ошибка при вызове Yandex Cloud Workflows:", error); await ctx.reply(`Произошла ошибка при отправке в Yandex Cloud Workflows: ${error.message}`); } } ``` -------------------------------- ### Telegraf Text Message Handler Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This JavaScript code sets up a handler for all incoming text messages in a Telegraf Telegram bot. It greets the user and includes optional logic to start a Yandex Cloud Workflow if a workflowId is provided. The BOT_TOKEN environment variable is required. ```javascript const { Telegraf } = require('telegraf'); const bot = new Telegraf(process.env.BOT_TOKEN); bot.on('text', async (ctx) => { const text = ctx.message.text; const chatId = ctx.message.chat.id; // Приветствие пользователя await ctx.reply(`Hello, ${ctx.message.from.username}`); // Опциональный запуск workflow (требуется указать workflowId) var workflowId = null; // Укажите реальный workflowId if (workflowId != null) { await startWorkflow(ctx, text, chatId, workflowId); } }); // Пример: пользователь отправляет "Привет" // Ответ бота: "Hello, john_doe" ``` -------------------------------- ### Telegraf /start Command Handler Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This JavaScript code implements the /start command handler for a Telegram bot built with Telegraf. When a user initiates a chat, the bot responds with a welcome message. It relies on the BOT_TOKEN environment variable. ```javascript const { Telegraf } = require('telegraf'); const bot = new Telegraf(process.env.BOT_TOKEN); bot.start((ctx) => { ctx.reply(`Hello. My name is Workflow Telegram Bot Deloyed by SourceCraft CI and Powered by Yandex Cloud Function.`); }); // Пример ответа бота: // Hello. // My name is Workflow Telegram Bot // Deployed by SourceCraft CI and Powered by Yandex Cloud Function. ``` -------------------------------- ### Deploy Yandex Cloud Function with yc-cli Source: https://github.com/sourcecraft/template-tg-bot.git/blob/main/README.md This snippet demonstrates how to deploy a Yandex Cloud Function using the `yc-cli` container. It shows how to set environment variables for the Yandex Cloud CLI, including the IAM token and folder ID, and then lists the available serverless functions. This approach allows for more complex deployment scenarios than the basic `yc-function` cube. ```yaml - name: get-functions env: # Подставьте в блок для получения значений outputs имя кубика с # IAM-токеном, например get-iam-token. YC_IAM_TOKEN: ${{ cubes.<имя_кубика_с_IAM-токеном>.outputs.IAM_TOKEN }} YC_FOLDER_ID: ${{ tokens.<имя_токена>.folder_id }} image: name: cr.yandex/sourcecraft/yc-cli:latest entrypoint: "" script: - | yc config set folder-id $YC_FOLDER_ID yc serverless function list ``` -------------------------------- ### SourceCraft CI/CD Pipeline Configuration (YAML) Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This YAML file configures the SourceCraft CI/CD pipeline for automatically deploying a Telegram bot to Yandex Cloud Functions. It defines deployment triggers, input parameters for the bot, environment variables, and the deployment task using a Yandex Cloud Function cube. ```yaml # .sourcecraft/ci.yaml on: pull_request: - workflows: deploy-tg-bot-workflow filter: source_branches: ["**", "!test**"] target_branches: "main" tokens: SERVICE_CONNECTION_WITH_TOKEN: service_connection: "default-service-connection" scope: org workflows: deploy-tg-bot-workflow: inputs: bot-username: type: string required: true description: Your Telegram bot username without _bot from BotFather bot-token: type: string default: "YOUR_TG_BOT_TOKEN" description: Your Telegram bot token from BotFather env: YC_BOT_NAME: ${{ inputs.bot-username }} TG_BOT_TOKEN: ${{ inputs.bot-token }} tasks: - name: deploy-tg-backend-task cubes: - name: deploy-func env: ID_TOKEN: ${{ tokens.SERVICE_CONNECTION_WITH_TOKEN.id_token }} YC_SA_ID: ${{ tokens.SERVICE_CONNECTION_WITH_TOKEN.service_account_id }} YC_FOLDER_ID: ${{ tokens.SERVICE_CONNECTION_WITH_TOKEN.folder_id }} YC_FUNCTION_NAME: ${{ cubes.format-name.outputs.function_name }} YC_FUNCTION_RUNTIME: nodejs22 YC_FUNCTION_ENTRYPOINT: index.handler SOURCE_PATH: "./src" ENVIRONMENT: "BOT_TOKEN=${{ inputs.bot-token }}" PUBLIC: true image: cr.yandex/sourcecraft/yc-function:latest ``` -------------------------------- ### Telegraf /help Command Handler Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This JavaScript snippet defines the /help command handler for a Telegraf-based Telegram bot. It provides users with information about the bot's capabilities when they send the /help command. The BOT_TOKEN environment variable is necessary for bot operation. ```javascript const { Telegraf } = require('telegraf'); const bot = new Telegraf(process.env.BOT_TOKEN); bot.help((ctx) => { ctx.reply(`Hello, ${ctx.message.from.username}.\nI can say Hello and start Yandex Cloud workflow if you specify workflowId`); }); // Пример ответа для пользователя @john_doe: // Hello, john_doe. // I can say Hello and start Yandex Cloud workflow if you specify workflowId ``` -------------------------------- ### Yandex Cloud Function Handler with Telegraf Source: https://context7.com/sourcecraft/template-tg-bot.git/llms.txt This JavaScript code defines the main handler for Yandex Cloud Functions. It receives HTTP requests from Telegram, parses the message body, and passes it to the Telegraf bot for processing. It requires the BOT_TOKEN environment variable for authentication. ```javascript // src/index.js const { Telegraf } = require('telegraf'); const bot = new Telegraf(process.env.BOT_TOKEN); // Обработчик для Yandex Cloud Functions module.exports.handler = async function (event, context) { // Сохраняем контекст для доступа к токену авторизации globalContext = context; // Парсим входящее сообщение от Telegram const message = JSON.parse(event.body); // Передаем сообщение боту для обработки await bot.handleUpdate(message); return { statusCode: 200, body: '', }; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.