Baza wiedzy GetMyBot

External Handler

Move complex bot logic to your own server. WebSocket connection, events, commands, and what happens if the connection drops.

Na tej stronie

An external handler runs part of your bot's logic on your own server. For example, your program calculates a personalized offer from your database, while GetMyBot receives the customer's message and sends the prepared reply in Telegram.

This setup is for a developer. Your program connects to GetMyBot over a persistent WebSocket connection, receives events, and returns commands in Telegram Bot API format. Simple replies and questionnaires can stay in the visual builder.

What it is

Use an external handler when your program needs to control the conversation: run custom calculations, read your database, or choose the next question using complex rules. You can hand off one reaction and keep the others in the visual builder.

Your program receives an event when a rule runs, a customer replies, or a button is pressed. It tells GetMyBot what the bot should do. GetMyBot checks the commands, queues them, and sends them using the bot token. The platform limits send frequency, retries temporary failures, prevents duplicates, and records messages in the conversation history.

How it works

  • GetMyBot accepts the WebSocket connection. Your program connects to it; you do not need to expose a public address for your program. GetMyBot does not make outgoing requests to it.
  • Authentication via an integration token. The service presents a token on connection; GetMyBot verifies it against a hash and keeps the connection open.
  • Events and commands use Telegram Bot API format. Your program receives an event and replies with a list of calls in the form "method + parameters", as with a regular Telegram bot.
  • GetMyBot executes commands using its bot token. Your program does not call Telegram directly. Commands are checked and placed in GetMyBot's internal send queue (outbox), where rate limits, retries, duplicate prevention, and logging apply.

One connection handles all conversations for that integration. Events from different customers are distinguished by session_id, the conversation identifier.

Setting up the integration

  1. Open the Integrations section in the left menu and click Add integration.
  2. Select the External Handler service and give it a name.
  3. After creation, the card will show:
    • WebSocket address: in the form wss://api.mybot.app/ext/ws/<integrationID>. Here <integrationID> is this integration's unique identifier (UUID). Your program connects to this address; the ID must be in the path.
    • Connection token: shown once at creation time. Copy it and store it somewhere safe; you cannot view the token again (it is stored only as a hash).
    • Rotate token: the button generates a new token and immediately invalidates the old one. After rotating, update the token in your service.
    • Online indicator: shows whether your service currently holds an active connection.

Additional integration parameters that affect the protocol:

  • session_ttl_seconds: session lifetime in seconds (default 3600).
  • on_unavailable_reaction_id: a fallback reaction that is triggered if the service is offline when the trigger fires (see Reliability).

Binding to a reaction

The external handler is connected not as a separate trigger but as an action. In the reaction editor, add the Send to external handler action and select the desired integration.

Any existing GetMyBot trigger can open a dialog: a command, text, button press, parameter from a link, incoming web request, or schedule. When such a trigger fires and reaches the action, GetMyBot opens a proxy session and sends the service a session.open event.

If your program is disconnected at that moment, GetMyBot runs the fallback reaction from the integration setting (on_unavailable_reaction_id). Without one, the customer receives no reply or error message.

Connection and authentication

Endpoint: GET /ext/ws/{integrationID} over WebSocket (wss). integrationID is the UUID of the External Handler integration. Frame size limit: 256 KiB.

You can authenticate in one of two ways.

1. Header during handshake (preferred). Pass the token in the Authorization header:

Authorization: Bearer <token>

2. Auth frame. If no Bearer header is provided, send the following as the first frame within 10 seconds of establishing the connection:

{ "type": "auth", "token": "<token>" }

If the auth frame is not received within 10 seconds, the connection is closed with code 4401. An invalid token in either method also results in close 4401.

The token is generated when the integration is created, shown once, and stored only as a hash (sha256); verification is constant-time. Token rotation:

POST /api/bots/{botID}/integrations/{integrationID}/rotate-token

The endpoint returns a new plaintext token; the old one stops working immediately.

Events: bot → service

Each event is a JSON frame (EventEnvelope). The type field is one of: session.open, message, callback, session.cancel, session.expired.

Full set of envelope fields:

{
  "type": "session.open",
  "session_id": "string",
  "bot_id": "string",
  "user": {
    "tg_user_id": 123456789,
    "first_name": "Ivan",
    "username": "ivan",
    "params": { "utm": "promo" }
  },
  "chat": { "id": 123456789, "type": "private" },
  "update": { "...": "raw Telegram Update (raw JSON)" },
  "event": { "...": "normalized GetMyBot event (raw JSON)" }
}
  • session_id: session (dialog) identifier.
  • bot_id: bot identifier.
  • user: user data: tg_user_id (int64), optional first_name, username, and params: user parameters (including those from a link), a key→value map.
  • chat: chat: id (int64) and type (e.g. "private").
  • update: raw Telegram Update (raw JSON). Present for session.open, message, callback.
  • event: normalized GetMyBot event (raw JSON).

The content varies by type:

  • session.open: a trigger fired, a new dialog was opened. Contains update (raw Update) and event (full normalized event), user.params are populated.
  • message: delivered when the service is "holding an expectation" (expect = text/any) and the user sent a message. Content is the same as for session.open.
  • callback: the user pressed a button that the service had previously sent. update is raw; user contains only tg_user_id; event contains only the original callback_data set by the service in the button:
{ "callback_data": "<original value set by the service in the button>" }
  • session.cancel / session.expired: minimal envelope: session_id, bot_id, user.tg_user_id, chat.id (for cancel also chat.type). No update/event fields. These events are delivered only if the service is online: they are not placed in the offline queue.

Commands: service → bot

A command is a JSON frame (CommandEnvelope). The type field is one of: execute, session.close, auth, ping, pong.

{
  "type": "execute",
  "session_id": "string",
  "methods": [
    { "method": "sendMessage", "params": { "text": "Hello" } }
  ],
  "expect": "none"
}
  • session_id: the session this command belongs to.
  • token: only for type: "auth" (see Connection and authentication).
  • methods: array of objects { "method": "<Telegram Bot API method name>", "params": { ... } }. The method name is exactly as in the Telegram Bot API (e.g. sendMessage), params is the parameter object for that method.
  • expect: whether the service is waiting for a user reply: "none", "text", or "any" (an empty value is treated as none).
  • session.close: explicitly close the dialog.

Commands do not go to Telegram directly: GetMyBot validates them and places them in its outbox, from where they are sent using the bot token (with rate limiting, retries, deduplication, and a dialog log).

How execute is processed

An execute command is ignored entirely if session_id is empty or the conversation was not found, is closed, has expired, or belongs to another integration.

Then:

  • Command frequency: up to 60 execute commands per minute per conversation (sliding window). Extra commands are ignored.
  • Up to 30 methods in a single execute; extras are silently discarded.
  • Each method is checked against the whitelist (see Allowed methods): a method not on the list is rejected.
  • Chat protection: if params contains chat_id or from_chat_id with a value that is neither 0 nor the conversation's chat_id, the method is rejected: it cannot send to another chat. You can omit chat_id; GetMyBot supplies the current chat ID.
  • Inline buttons with callback_data are automatically tokenized (internal form x:<token>); button lifetime = until session expiry. Buttons of type url/webapp/switch_inline are left unchanged.

Allowed methods

The service commands the bot, so the set of methods is limited to a whitelist: only sending and working with messages in the current dialog. Methods not on the list are silently ignored (not an error).

  • sending: sendMessage, sendPhoto, sendDocument, sendVideo, sendAudio, sendMediaGroup, sendAnimation, sendVoice, sendLocation, sendChatAction;
  • editing and deleting: editMessageText, editMessageCaption, editMessageReplyMarkup, deleteMessage;
  • acknowledging a button press: answerCallbackQuery;
  • forwarding and copying: forwardMessage, copyMessage;
  • pinning: pinChatMessage, unpinChatMessage.

Account-level methods (setWebhook, getUpdates, logOut, close, setMyCommands, etc.) are not allowed.

Expectation and session lifecycle

After each execute, the fate of the session depends on expect and whether the command contained inline buttons with callback_data:

  • expect = text or any: the user's next message will be forwarded to the service as a message event.
  • expect = none AND the command had NO inline buttons with callback: the session closes automatically. This is a "terminal" message.
  • expect = none, BUT there are callback buttons: the session stays open: button presses are captured as long as the button tokens are alive (until TTL).

Important: expect does not affect button press reception. Presses on tokenized buttons are captured regardless of the expect value: as long as the session and the button token are alive. expect controls only whether the service is waiting for a text/arbitrary reply.

Dialog boundaries

The dialog context lives exactly as long as the session is open:

  • Text reply while an expectation is active (expect = text/any): forwarded to the service as a message event, not triggering the bot's normal reactions.
  • A tokenized button press: forwarded to the service as a callback event with the original callback_data. GetMyBot always acknowledges the press itself (answerCallbackQuery); ownership is verified (bot + user + session chat). A button press does not close the session.
  • /cancel (also /cancel@bot and the Russian word отмена) while an external session is active: the session closes, session.cancel is sent to the service, and the user receives Отменено.. The English word cancel is not a built-in cancellation command.
  • One dialog per user. Opening a new session evicts the user's previous open session: it receives session.cancel.
  • TTL expiry. After the timer fires, the session is marked expired and (if the service is online) session.expired is sent to the service.

Limits and timeouts

  • Frame size: 256 KiB.
  • Session TTL: 3600 seconds by default (configurable via the session_ttl_seconds integration parameter).
  • Command rate: 60 execute per minute per session (sliding window).
  • Methods per execute: up to 30 (extras are discarded).
  • Open sessions per integration: up to 1000.
  • Offline queue: up to 100 events per session.
  • Heartbeat: ping every 30 seconds; inactivity timeout: 60 seconds.
  • Auth frame timeout: 10 seconds.

Reliability (heartbeat, offline, queue, fallback)

Heartbeat is a periodic connection check. A fallback is a backup response if your program is unavailable. Set one up in advance, for example to tell the customer there is a delay and offer an operator chat.

  • Heartbeat. The server sends a {"type":"ping"} frame every 30 seconds. If there is no activity from the client for more than 60 seconds, the connection is closed. The client may send its own ping/pong frames to keep the connection alive. A dropped connection does not kill dialogs: sessions live in the database until their TTL or until reconnection.
  • Reconnection is the service's responsibility. If the connection drops, your service must reconnect. Open sessions in the database survive restarts until their TTL expires.
  • Fallback when offline at trigger time. If the service is not connected when a reaction fires, the fallback reaction from the integration setting (on_unavailable_reaction_id) is triggered. If none is set, nothing happens (silently).
  • Queue during a connection loss. Undelivered message and callback events are stored until the conversation expires, up to 100 per conversation, in arrival order (FIFO). They are sent to your program when it reconnects. session.open, session.cancel, and session.expired are not queued.
  • At-most-once delivery. Redelivery is not guaranteed. If the queue fills or its retention time ends, an event is lost. Your program should be able to continue the conversation after such a gap.

Online indicator

You can check whether the service holds an active connection via the endpoint:

GET /api/bots/{botID}/integrations/{integrationID}/status

Response:

{ "online": true }

The same indicator is available on the integration card in the dashboard. The MCP equivalent is the get_integration_status tool.

Security

GetMyBot executes commands from a third-party service using its own bot token, so protection is strict.

  • No SSRF surface. GetMyBot acts as the WebSocket server and never makes outbound connections to the service: it is the service that connects to GetMyBot. There is no externally controlled URL that the platform fetches.
  • Token stored as a hash (sha256), constant-time verification, rotation supported.
  • Tenant isolation. A command is tightly bound to its integration; a session is bound to a bot + user + chat. Events from other bots never reach your socket.
  • Method whitelist + forced chat_id prevent the bot from being used as a broadcaster to arbitrary chats.
  • Bot token is never exposed externally: the service never communicates with Telegram directly.
  • Secret masking. The integration token and sensitive values are hidden in the activity log and system logs.

Examples

Minimal handler: on dialog open, sends a message and closes the session (expect: "none"). Substitute your integration id and token. The address must include <integrationID> in the path.

Node.js

import WebSocket from "ws";

const URL = `wss://api.mybot.app/ext/ws/${process.env.MYBOT_INTEGRATION_ID}`;
const ws = new WebSocket(URL, {
  headers: { Authorization: `Bearer ${process.env.MYBOT_TOKEN}` },
});

ws.on("message", (raw) => {
  const ev = JSON.parse(raw);
  if (ev.type === "session.open") {
    ws.send(JSON.stringify({
      type: "execute",
      session_id: ev.session_id,
      expect: "none",
      methods: [{ method: "sendMessage", params: { text: "Hello from the external handler!" } }],
    }));
  }
});

Python

import json, os, asyncio, websockets

async def main():
    url = f"wss://api.mybot.app/ext/ws/{os.environ['MYBOT_INTEGRATION_ID']}"
    headers = {"Authorization": f"Bearer {os.environ['MYBOT_TOKEN']}"}
    async with websockets.connect(url, additional_headers=headers) as ws:
        async for raw in ws:
            ev = json.loads(raw)
            if ev["type"] == "session.open":
                await ws.send(json.dumps({
                    "type": "execute",
                    "session_id": ev["session_id"],
                    "expect": "none",
                    "methods": [
                        {"method": "sendMessage", "params": {"text": "Hello from the external handler!"}}
                    ],
                }))

asyncio.run(main())

Inline button and callback handling

To catch a button press, send a button with callback_data (GetMyBot tokenizes it automatically). With expect: "none" and a button present, the session stays open while the button token is alive: the press arrives as a callback event in which event.callback_data equals the original value. You do not need to acknowledge the press (answerCallbackQuery): GetMyBot does it automatically.

if (ev.type === "session.open") {
  ws.send(JSON.stringify({
    type: "execute",
    session_id: ev.session_id,
    expect: "none",
    methods: [{
      method: "sendMessage",
      params: {
        text: "Press the button",
        reply_markup: { inline_keyboard: [[{ text: "Let's go", callback_data: "go" }]] },
      },
    }],
  }));
} else if (ev.type === "callback" && ev.event.callback_data === "go") {
  ws.send(JSON.stringify({
    type: "execute",
    session_id: ev.session_id,
    expect: "none",
    methods: [{ method: "sendMessage", params: { text: "Button pressed!" } }],
  }));
}

What's next