### Initialize and Start Bot Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Basic setup for creating a bot instance and starting the connection to MAX servers. ```javascript import { Bot } from '@maxhub/max-bot-api'; // Создайте экземпляр класса Bot и передайте ему токен const bot = new Bot(process.env.BOT_TOKEN); // Добавьте слушатели обновлений // MAX Bot API будет вызывать их, когда пользователи взаимодействуют с ботом // Обработчик для команды '/start' bot.command('start', (ctx) => ctx.reply('Добро пожаловать!')); // Обработчик для любого другого сообщения bot.on('message_created', (ctx) => ctx.reply('Новое сообщение')); // Теперь можно запустить бота, чтобы он подключился к серверам MAX и ждал обновлений bot.start(); ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/js Commands to create a project directory and install the MAX Bot API using various package managers. ```bash # Создайте папку и перейдите в неё mkdir my-first-bot cd my-first-bot # Установите MAX Bot API # Для npm npm install --save @maxhub/max-bot-api # Для yarn yarn add @maxhub/max-bot-api # Для pnpm pnpm add @maxhub/max-bot-api # Для deno deno add npm:@maxhub/max-bot-api # Установите и настройте TypeScript (опционально) yarn add -D typescript npx tsc --init ``` -------------------------------- ### Initialize Go Project and Install MAX Bot API Client Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/go Use these bash commands to create a new Go module, initialize it, and install the necessary MAX Bot API client library. ```bash # Создаём новую папку для исходного кода вашего модуля Go и перейдите в неё mkdir my-first-bot cd my-first-bot # Запускаем свой модуль с помощью команды go mod init. go mod init first-max-bot # Устанавливаем библиотеку для работы с MAX API на golang go get github.com/max-messenger/max-bot-api-client-go ``` -------------------------------- ### Install MAX Bot API Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Commands to initialize a project and install the library using various package managers. ```bash # Создайте папку и перейдите в неё mkdir my-first-bot cd my-first-bot # Установите MAX Bot API # Для npm npm install --save @maxhub/max-bot-api # Для yarn yarn add @maxhub/max-bot-api # Для pnpm pnpm add @maxhub/max-bot-api # Для deno deno add npm:@maxhub/max-bot-api # Установите и настройте TypeScript (опционально) yarn add -D typescript npx tsc --init ``` -------------------------------- ### Install MAX Bot API Go Library Source: https://dev.max.ru/docs/chatbots/bots-coding/library/go Use these commands to create a new Go project and install the MAX Bot API client library. The `go mod init` command initializes dependency tracking. ```bash # Создайте новую папку для исходного кода вашего модуля Go и перейдите в неё mkdir my-first-bot cd my-first-bot # Запустите свой модуль с помощью команды go mod init. go mod init first-max-bot # Установите библиотеку для работы с MAX API на golang go get github.com/max-messenger/max-bot-api-client-go ``` -------------------------------- ### Example GET /me response Source: https://dev.max.ru/docs-api A sample JSON response returned by the server when querying the /me endpoint. ```json { "user_id": 1, "name": "My Bot", "username": "my_bot", "is_bot": true, "last_activity_time": 1737500130100 } ``` -------------------------------- ### Initialize Bot Instance Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/js Basic setup for the Bot class using an environment variable for the token. ```javascript import { Bot } from '@maxhub/max-bot-api'; const bot = new Bot(process.env.BOT_TOKEN); // Токен, полученный при регистрации бота в MAX bot.start(); // Запускает получение обновлений ``` -------------------------------- ### GET /?start= Source: https://dev.max.ru/docs/chatbots/bots-coding/prepare Constructs a deep link to trigger a bot with specific payload data. ```APIDOC ## GET /?start= ### Description Creates a deep link for a bot. When a user clicks this link, the bot receives a 'bot_started' update. ### Parameters #### Path Parameters - **botName** (string) - Required - The bot's unique nickname. #### Query Parameters - **start** (string) - Optional - Additional data (payload) up to 128 characters. ``` -------------------------------- ### Attachments Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Guides on sending various types of attachments, including files, images, videos, audio, stickers, locations, and shares, using tokens or direct uploads. ```APIDOC ## Sending Attachments ### Description Methods for handling and sending various types of attachments. ### File Attachments (using tokens) ```javascript // Image const image = new ImageAttachment({ token: 'existingImageToken' }); await ctx.reply('', { attachments: [image.toJson()] }); // Video const video = new VideoAttachment({ token: 'existingVideoToken' }); await ctx.reply('', { attachments: [video.toJson()] }); // Audio const audio = new AudioAttachment({ token: 'existingAudioToken' }); await ctx.reply('', { attachments: [audio.toJson()] }); // Generic File const file = new FileAttachment({ token: 'existingFileToken' }); await ctx.reply('', { attachments: [file.toJson()] }); ``` ### Uploading Files via `ctx.api` - `ctx.api.uploadImage(options)` - `ctx.api.uploadVideo(options)` - `ctx.api.uploadAudio(options)` - `ctx.api.uploadFile(options)` **Upload Example (Image from file path):** ```javascript const image = await ctx.api.uploadImage({ source: '/path/to/image' }); await ctx.reply('Это фото загружено из файла', { attachments: [image.toJson()] }); ``` **Upload Example (Image from URL):** ```javascript const image = await ctx.api.uploadImage({ url: 'https://upload.wikimedia.org/wikipedia/commons/7/72/Maxmessenger.png' }); await ctx.reply('', { attachments: [image.toJson()] }); ``` ### Other Attachment Types ```javascript // Sticker const sticker = new StickerAttachment({ code: "stickerCode" }); await ctx.reply('', { attachments: [sticker.toJson()] }); // Location const location = new LocationAttachment({ lon: 0, lat: 0 }); await ctx.reply('', { attachments: [location.toJson()] }); // Share const share = new ShareAttachment({ url: "messagePublicUrl", token: "attachmentToken" }); await ctx.reply('', { attachments: [share.toJson()] }); ``` ``` -------------------------------- ### Raw API Request Methods Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Interact with the raw API using GET, POST, PUT, PATCH, and DELETE methods. This allows for fine-grained control over API calls, including path and query parameters. ```javascript ctx.api.raw.get('method', {/* параметры запроса */}); ``` ```javascript ctx.api.raw.post('method', {/* параметры запроса */}); ``` ```javascript ctx.api.raw.put('method', {/* параметры запроса */}); ``` ```javascript ctx.api.raw.patch('method', {/* параметры запроса */}); ``` ```javascript ctx.api.raw.delete('method', {/* параметры запроса */}); ``` ```javascript await ctx.api.raw.patch('chats/{chat_id}', { path: { chat_id: 123 }, body: { title: 'New Title' }, query: { notify: false }, }); ``` -------------------------------- ### Basic Bot Structure with MAX Bot API Client Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/go This Go code sets up the main function, initializes the bot API client using an environment variable for the token, and demonstrates fetching bot information. ```go package main import ( "fmt" maxbot "github.com/max-messenger/max-bot-api-client-go" ) func main() { api := maxbot.New(os.Getenv("TOKEN")) // Some methods demo: info, err := api.Bots.GetBot() fmt.Printf("Get me: %#v %#v", info, err) } ``` -------------------------------- ### Implement Hello Command Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/js Registers a command and sets up a basic reply handler for the bot. ```javascript import { Bot } from '@maxhub/max-bot-api'; const bot = new Bot(process.env.BOT_TOKEN); // Устанавливает список команд, который пользователь будет видеть в чате с ботом bot.api.setMyCommands([ { name: 'hello', description: 'Поприветствовать бота', }, ]); // Обработчик команды '/hello' bot.command('hello', (ctx) => { return ctx.reply('Привет! ✨'); }); bot.start(); ``` -------------------------------- ### Кодирование нескольких параметров в payload Source: https://dev.max.ru/docs/chatbots/bots-coding/prepare Способ передачи нескольких значений через один параметр start путём их объединения в строку. ```text ?start=param1_value1_param2_value2 ``` -------------------------------- ### Initialize Bot with Token Source: https://dev.max.ru/docs/chatbots/bots-coding/library/go Create a new bot instance using the `maxbot.New` constructor, passing the bot token obtained from environment variables. It's recommended to use environment variables for security. ```go package main import ( "fmt" maxbot "github.com/max-messenger/max-bot-api-client-go" "os" ) func main() { api := maxbot.New(os.Getenv("TOKEN")) // Some methods demo: info, err := api.Bots.GetBot() fmt.Printf("Get me: %#v %#v", info, err) } ``` -------------------------------- ### Run Bot with Environment Variable Source: https://dev.max.ru/docs/chatbots/bots-coding/library/go Execute your Go bot by setting the `BOT_TOKEN` environment variable and running the `go run` command. Replace `` with your actual bot token. ```bash # Передайте переменную окружения и запустите бота BOT_TOKEN="" go run ``` -------------------------------- ### Implement Personalized Hello Command Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/js Handles the hello command by retrieving user data to provide a personalized greeting. ```javascript import { Bot } from '@maxhub/max-bot-api'; const bot = new Bot(process.env.BOT_TOKEN); bot.api.setMyCommands([ { name: 'hello', description: 'Поприветствовать бота', }, ]); bot.command('hello', (ctx) => { const user = ctx.user(); // Получаем данные пользователя из нового события if (!user) { // Если пользователя не получилось определить, просто поздороваемся  return ctx.reply('Привет! ✨'); } // Если пользователя определён, поздороваемся адресно return ctx.reply(`Привет, ${ctx.user()}! ✨`); }); bot.start(); ``` -------------------------------- ### Raw API Calls Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Provides methods for making raw API requests (GET, POST, PUT, PATCH, DELETE) to specific endpoints, including path parameters, request bodies, and query parameters. ```APIDOC ## Raw API Calls ### Description Allows making raw HTTP requests to the API using various methods. ### Methods - `ctx.api.raw.get(method, [params])` - `ctx.api.raw.post(method, [params])` - `ctx.api.raw.put(method, [params])` - `ctx.api.raw.patch(method, [params])` - `ctx.api.raw.delete(method, [params])` ### Parameters - **method** (string) - The API method or endpoint path. - **params** (object, optional) - An object containing request parameters: - **path** (object) - Path parameters for the request. - **body** (object) - The request body. - **query** (object) - Query parameters for the request. ### Request Example ```javascript // Example of patching a chat await ctx.api.raw.patch('chats/{chat_id}', { path: { chat_id: 123 }, body: { title: 'New Title' }, query: { notify: false } }); ``` ``` -------------------------------- ### Handle Commands and Actions Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Methods for responding to specific commands, text patterns, or callback actions. ```javascript // Обработчик команды '/start' bot.command('start', async (ctx) => {/* ... */}); // Сравнение текста сообщения со строкой или регулярным выражением bot.hears('hello', async (ctx) => {/* ... */}); bot.hears(/echo (.+)?/, async (ctx) => {/* ... */}); // Обработчик нажатия на callback-кнопку с указанным payload bot.action('connect_wallet', async (ctx) => {/* ... */}); bot.action(/color:(.+)/, async (ctx) => {/* ... */}); ``` -------------------------------- ### Basic Go Program Structure Source: https://dev.max.ru/docs/chatbots/bots-coding/library/go This is a fundamental Go program structure. The `package main` declaration is required for executable programs, and the `main` function serves as the entry point. ```go package main import "fmt" func main() { fmt.Println("Hello Max Bot Go") } ``` -------------------------------- ### Run Bot Process Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Commands to compile TypeScript and execute the bot script with environment variables. ```bash # Скомпилируйте код, если вы использовали TypeScript npx tsc # Передайте переменную окружения и запустите бота BOT_TOKEN="" node bot.js ``` -------------------------------- ### Handle Bot Updates and Send Messages Source: https://dev.max.ru/docs/chatbots/bots-coding/library/go This code snippet demonstrates how to set up an update handler to process incoming messages and send a reply. It uses `context` for cancellation and listens for `MessageCreatedUpdate` events. ```go package main import ( "context" "fmt" "os" "os/signal" "syscall" maxbot "github.com/max-messenger/max-bot-api-client-go" schemes "github.com/max-messenger/max-bot-api-client-go/schemes" ) func main() { api := maxbot.New(os.Getenv("TOKEN")) // Some methods demo: info, err := api.Bots.GetBot() fmt.Printf("Get me: %#v %#v", info, err) ctx, cancel := context.WithCancel(context.Background()) go func() { exit := make(chan os.Signal) signal.Notify(exit, os.Kill, os.Interrupt) <-exit cancel() }() for upd := range api.GetUpdates(ctx) { // Чтение из канала с обновлениями switch upd := upd.(type) { // Определение типа пришедшего обновления case *schemes.MessageCreatedUpdate: // Отправка сообщения _, err := api.Messages.Send(maxbot.NewMessage().SetChat(upd.Message.Recipient.ChatId).SetText("Hello from Bot")) if err != nil { fmt.Printf("Error sending message: %v\n", err) } } } } ``` -------------------------------- ### Creating Inline Keyboards Source: https://dev.max.ru/docs-api How to structure a message to include an inline keyboard with buttons. ```APIDOC ## Creating Inline Keyboards To add an inline keyboard to a message, include an `InlineKeyboardAttachment` in the message's `attachments` array. ### Example Message with Inline Keyboard ```json { "text": "This is a message with an inline keyboard.", "attachments": [ { "type": "inline_keyboard", "payload": { "buttons": [ [ { "type": "callback", "text": "Click Me!", "payload": "user_action_1" }, { "type": "link", "text": "Visit MAX", "url": "https://max.ru" } ], [ { "type": "request_contact", "text": "Share Contact" } ] ] } } ] } ``` **Notes on Keyboard Layout:** - Button text is centered and may be truncated if it exceeds button width. - Buttons within the same row have equal width. - The width of each row of buttons matches the total keyboard width. - All buttons have a default equal height. ``` -------------------------------- ### Implement Greeting Functionality in Go Bot Source: https://dev.max.ru/docs/chatbots/bots-coding/hellobot/go This Go code extends the basic bot structure to handle incoming messages, specifically responding with 'Привет! ✨' to any message. It sets up a context for graceful shutdown and listens for updates. ```go package main import ( "fmt" maxbot "github.com/max-messenger/max-bot-api-client-go" ) func main() { api := maxbot.New(os.Getenv("TOKEN")) // Some methods demo: info, err := api.Bots.GetBot() fmt.Printf("Get me: %#v %#v", info, err) ctx, cancel := context.WithCancel(context.Background()) // создам go func() { exit := make(chan os.Signal) signal.Notify(exit, os.Kill, os.Interrupt) <-exit cancel() }() for upd := range api.GetUpdates(ctx) { // Чтение из канала с обновлениями switch upd := upd.(type) { // Определение типа пришедшего обновления case *schemes.MessageCreatedUpdate: // Отправка сообщения _, err := api.Messages.Send(maxbot.NewMessage().SetChat(upd.Message.Recipient.ChatId).SetText("Привет! ✨")) } } } ``` -------------------------------- ### Bot Startup Update (Webhook/Long Polling) Source: https://dev.max.ru/docs/chatbots/bots-coding/prepare Describes the structure of the update received by the bot when a user initiates a session via a deep link. ```APIDOC ## Bot Startup Update ### Description When a user follows a deep link, the bot receives an update of type 'bot_started'. ### Response - **update_type** (string) - Always 'bot_started'. - **timestamp** (integer) - Event time. - **chat_id** (integer) - ID of the chat. - **user** (object) - Information about the user who started the bot. - **payload** (string) - The value passed from the URL. ### Response Example { "update_type": "bot_started", "timestamp": 1573226679188, "chat_id": 1234567890, "user": { "user_id": 1234567890, "name": "Иван", "username": "ivan_petrov" }, "payload": "promo_summer2025" } ``` -------------------------------- ### Message Formatting Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Demonstrates how to format messages using Markdown or HTML for bold, italics, and links. ```APIDOC ## Message Formatting ### Description Allows formatting message text using Markdown or HTML. ### Markdown Formatting ```javascript await bot.api.sendMessageToChat( 12345, '**Привет!** _Добро пожаловать_ в [MAX](https://dev.max.ru).', { format: 'markdown' } ); ``` ### HTML Formatting ```javascript await bot.api.sendMessageToChat( 12345, 'Привет! Добро пожаловать в MAX.', { format: 'html' } ); ``` ``` -------------------------------- ### Open App Button Definition Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Allows opening a mini-application. It takes the button text, an optional web app URL, and an optional contact ID. ```typescript button.openApp(text: string, webApp?: string, contactId?: number); ``` -------------------------------- ### Структура обновления bot_started Source: https://dev.max.ru/docs/chatbots/bots-coding/prepare Пример JSON-объекта, который получает бот при переходе пользователя по диплинку. ```json { "update_type": "bot_started", "timestamp": 1573226679188, "chat_id": 1234567890, "user": { "user_id": 1234567890, "name": "Иван", "username": "ivan_petrov" }, "payload": "promo_summer2025" } ``` -------------------------------- ### Upload and Attach Image from File Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Upload an image from a local file path using `ctx.api.uploadImage` and then attach it to a message. The uploaded image returns an `Attachment` instance. ```javascript const image = await ctx.api.uploadImage({ source: '/path/to/image' }); await ctx.reply('Это фото загружено из файла', { attachments: [image.toJson()], }); ``` -------------------------------- ### Create an Inline Keyboard Source: https://dev.max.ru/docs/chatbots/bots-coding/library/js Use `Keyboard.inlineKeyboard` to create a keyboard with multiple rows of buttons. Buttons in the same row should have equal width. This keyboard can be sent to the user in a message. ```typescript const keyboard = Keyboard.inlineKeyboard([ // Первая строка с тремя кнопками [ Keyboard.button.callback('default'), Keyboard.button.callback('positive', { intent: 'positive' }), Keyboard.button.callback('negative', { intent: 'negative' }), ], // Вторая строка с одной кнопкой [Keyboard.button.link('Открыть MAX', 'https://max.ru')], ]); // Далее мы можем отправить клавиатуру пользователю в сообщении, например, при вызове команды страт bot.command('start', (ctx: Context) => { ctx.reply('Добро пожаловать!', {attachments: [keyboard]}) }); ``` -------------------------------- ### Clipboard button configuration Source: https://dev.max.ru/docs-api JSON structure for defining a clipboard button that copies the payload text to the user's clipboard. ```json { "type": "clipboard", // Тип кнопки "text": "Скопировать", // Текст кнопки "payload": "123456" // Текст, который будет скопирован } ```