A-chat for developers

Bots: getting started

This page shows how to make a bot for A-chat, get its token, receive messages and answer them. The full list of methods and types is in the Bot API reference.

What a bot is

A bot is an account run by a program. It has a name, an @name that ends in bot, a picture and a short description. People find it by its @name in the search and write to it like to anyone else.

Your program talks to A-chat over HTTPS through the Bot API. Methods take parameters as JSON or a form and answer with JSON objects; the reference lists every one.

A few rules shape what a bot can do:

Make a bot

There are three ways. All of them make the same bot, and you can manage it from any of them later.

On the developer portal

developer.a-chat.app is a small cabinet for everything you make on A-chat: bots, mini apps, games and sites. Sign in with your A-chat account (password, passkey, or a QR code from your phone) and open Bots → New bot. There you set the profile, the picture, the links and the commands of every language, turn on inline mode and the group settings, see and replace the token, see how the bot gets its updates (the webhook, what waits, the last errors) and send it a test update, see its statistics, manage its games, and delete it.

With @achatbot

@achatbot is A-chat’s own bot for making bots. Open a chat with it and send /newbot. It asks for a display name, then for an @name. When the @name is free, the bot is made.

Its commands:

Command What it does
/newbot Make a new bot.
/mybots List your bots, each with its own buttons.
/token Show the token card of a bot.
/revoke Revoke a bot’s token.
/setname Change the display name.
/setdescription Change “What can this bot do?”.
/setabouttext Change the short “about” line.
/setuserpic Points you to My bots, where the picture is set.
/setcommands Set the default command list, one command - description per line.
/setlinks Set the website, privacy policy and terms of use links. Send - to remove one.
/setprivacy, /setjoingroups Group settings: privacy mode, and whether the bot may be added to groups.
/setinline, /setinlinefeedback, /setinlinegeo Inline mode, its placeholder, whether the bot gets chosen_inline_result, and whether it asks for the person’s place.
/stats The bot’s statistics.
/deletebot Delete a bot. It asks first.
/newapp, /myapps, /linkapp Make and manage mini apps, and link one to a bot. See Mini apps.
/cancel Stop what you are doing.
/help Show this list.

@achatbot never writes a token into the chat. Its token card shows the token masked, and Show and copy opens your own bot screen in the app, where you confirm it is you.

In the app: My bots

On the phone, the web version or the desktop app, open Settings → For developers → My bots. Tap New bot, enter the name and the @name.

The same screen lets you change the name, the about line, the description, the picture, the links and the inline mode, see and replace the token, see the mini app linked to the bot, see its statistics, and delete the bot. A mini app is linked to a bot from My mini apps. The group settings are in @achatbot and on the developer portal.

Rules for names

The token

The token is the only key to your bot. It looks like 7000000123:AbCdEf... : the bot’s number, a colon and a secret of 43 characters.

Keep the token on your server. Never put it in a web page, a mini app or a public repository.

Calling the API

Every method is called at:

https://api.a-chat.app/bot<token>/<method>

Every answer is JSON:

{ "ok": true, "result": { "id": 7000000123, "is_bot": true, "first_name": "Echo", "username": "echo_demo_bot" } }
{ "ok": false, "error_code": 403, "description": "Forbidden: bot was blocked by the user" }

A 429 answer has parameters.retry_after (seconds) and a Retry-After header. Wait that long and try again.

Try it:

curl "https://api.a-chat.app/bot123456:ABC.../getMe"

Getting updates

An update is something that happened for your bot: a message, a button press, an inline query. Updates are kept for 24 hours. You get them in one of two ways, never both at once.

Long polling: getUpdates

Call getUpdates in a loop. Pass offset = the last update_id you handled + 1. That confirms the earlier updates, and they are removed. Pass timeout (up to 50 seconds) so the call waits until something arrives.

curl "https://api.a-chat.app/bot123456:ABC.../getUpdates?offset=0&timeout=50"

getUpdates answers 409 Conflict while a webhook is set.

Webhook: setWebhook

Give A-chat an HTTPS address, and it posts each update there as JSON.

curl "https://api.a-chat.app/bot123456:ABC.../setWebhook" \
  -d url=https://example.com/achat/hook \
  -d secret_token=change-me-to-a-long-random-string

A minimal webhook receiver in Node.js:

import http from 'node:http';

const SECRET = process.env.WEBHOOK_SECRET;

http
  .createServer((req, res) => {
    if (req.method !== 'POST' || req.headers['x-bot-api-secret-token'] !== SECRET) {
      res.writeHead(403).end();
      return;
    }
    let body = '';
    req.on('data', (chunk) => (body += chunk));
    req.on('end', () => {
      const update = JSON.parse(body);
      console.log('update', update.update_id);
      res.writeHead(200).end();
    });
  })
  .listen(8080);

Put it behind your HTTPS server or proxy.

An echo bot

The bot below answers every text with the same text. It uses long polling, so it needs no public address.

Python

Needs Python 3.8+ and requests (pip install requests).

import os
import time

import requests

TOKEN = os.environ["BOT_TOKEN"]  # 123456:ABC...
API = f"https://api.a-chat.app/bot{TOKEN}/"


class ApiError(Exception):
    def __init__(self, data):
        super().__init__(f'{data.get("error_code")}: {data.get("description")}')
        self.retry_after = data.get("parameters", {}).get("retry_after")


def call(method, **params):
    response = requests.post(API + method, json=params, timeout=70)
    data = response.json()
    if not data.get("ok"):
        raise ApiError(data)
    return data["result"]


def main():
    me = call("getMe")
    print(f'Running as @{me["username"]}')
    offset = 0
    while True:
        try:
            updates = call("getUpdates", offset=offset, timeout=50)
        except (requests.RequestException, ApiError) as error:
            print("getUpdates failed:", error)
            time.sleep(getattr(error, "retry_after", None) or 3)
            continue
        for update in updates:
            offset = update["update_id"] + 1
            message = update.get("message")
            if not message or "text" not in message:
                continue
            try:
                call("sendMessage", chat_id=message["chat"]["id"], text=message["text"])
            except ApiError as error:
                # For example 403: the person blocked the bot.
                print("sendMessage failed:", error)
                if error.retry_after:
                    time.sleep(error.retry_after)


if __name__ == "__main__":
    main()

Node.js

Needs Node.js 18+ (built-in fetch). Save it as echo.mjs and run BOT_TOKEN=123456:ABC... node echo.mjs.

const TOKEN = process.env.BOT_TOKEN; // 123456:ABC...
const API = `https://api.a-chat.app/bot${TOKEN}/`;

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

async function call(method, params = {}) {
  const response = await fetch(API + method, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  const data = await response.json();
  if (!data.ok) {
    const error = new Error(`${data.error_code}: ${data.description}`);
    error.retryAfter = data.parameters?.retry_after;
    throw error;
  }
  return data.result;
}

const me = await call('getMe');
console.log(`Running as @${me.username}`);

let offset = 0;
for (;;) {
  let updates;
  try {
    updates = await call('getUpdates', { offset, timeout: 50 });
  } catch (error) {
    console.error('getUpdates failed:', error.message);
    await sleep(error.retryAfter ?? 3);
    continue;
  }
  for (const update of updates) {
    offset = update.update_id + 1;
    const message = update.message;
    if (!message?.text) continue;
    try {
      await call('sendMessage', { chat_id: message.chat.id, text: message.text });
    } catch (error) {
      // For example 403: the person blocked the bot.
      console.error('sendMessage failed:', error.message);
      if (error.retryAfter) await sleep(error.retryAfter);
    }
  }
}

Formatting

A bot’s text can have bold, italic, underline, strikethrough, spoilers, code, code blocks, links on words and quotes. Use parse_mode:

curl "https://api.a-chat.app/bot123456:ABC.../sendMessage" \
  -d chat_id=7000000042 \
  -d parse_mode=HTML \
  --data-urlencode 'text=<b>Order 42</b> is ready. <spoiler>Code: 7731</spoiler>'

Two more marks: a mention of an account by its number (<a href="a-chat://user?id=7000000042">Anna</a>, a tap opens the profile), and a sticker drawn in place of words (<emoji id="...">😀</emoji>).

Captions of files take the same, with caption_entities, and so do inline results. The apps find @name mentions, #hashtags and links in the words by themselves. All the rules are in Formatting.

Keyboards

Send buttons with the reply_markup parameter of sendMessage and of the methods that send files.

Inline keyboard

Buttons under the message, in rows.

{
  "chat_id": 7000000042,
  "text": "Pick one",
  "reply_markup": {
    "inline_keyboard": [
      [{ "text": "Yes", "callback_data": "vote:yes" }, { "text": "No", "callback_data": "vote:no" }],
      [{ "text": "Our site", "url": "https://example.com" }],
      [{ "text": "Copy code", "copy_text": { "text": "PROMO-2026" } }]
    ]
  }
}
Button field What a tap does
callback_data Sends your bot a callback_query update with this data (1 to 64 bytes).
url Opens an https link. The app asks the person first.
web_app Opens your bot’s linked mini app. See Mini apps.
copy_text Copies the text (1 to 256 characters).
switch_inline_query The person picks a chat, and its field gets @yourbot <query>. See Inline mode.
switch_inline_query_current_chat The field of this chat gets @yourbot <query>.

Answer every callback_query with answerCallbackQuery. Answer within 7 seconds to show a toast or an alert to the person. Later answers (up to 15 minutes) are accepted but show nothing.

curl "https://api.a-chat.app/bot123456:ABC.../answerCallbackQuery" \
  -d callback_query_id=6f1c... -d text="Vote counted"

To change the buttons, call editMessageReplyMarkup. To change the text, call editMessageText; the words of a file, editMessageCaption; the file itself, editMessageMedia. An edit of the text or the caption without reply_markup removes the buttons.

Limits: up to 100 buttons, up to 8 in a row, labels 1 to 64 characters. The phone app shows at most 12 rows and 48 buttons, so keep keyboards small.

Reply keyboard

A keyboard in place of the system keyboard. Its buttons send their text as a message from the person.

{
  "chat_id": 7000000042,
  "text": "Choose a size",
  "reply_markup": {
    "keyboard": [["Small", "Medium", "Large"], [{ "text": "Share my location", "request_location": true }]],
    "resize_keyboard": true,
    "one_time_keyboard": true,
    "input_field_placeholder": "Size"
  }
}

The apps show the keys of the bot’s newest message that has a keyboard, in place of the letters, by your rows; a key sends its words. one_time_keyboard hides it once a key is pressed; remove_keyboard and force_reply take it away.

The button left of the message field in your bot’s chat shows your commands by default. setChatMenuButton can make it open your bot’s linked mini app instead, for everybody or for one person:

{ "menu_button": { "type": "web_app", "text": "Open shop", "web_app": { "url": "https://shop.example.com/" } } }

The address must be on the hosts of the mini app linked to the bot. { "type": "commands" } or { "type": "default" } goes back to the commands.

Commands

Set the list of your bot’s commands with setMyCommands:

{
  "commands": [
    { "command": "start", "description": "Start the bot" },
    { "command": "help", "description": "What I can do" }
  ]
}
What Where to set it Limit
Display name My bots, /setname, or setMyName 1 to 64 characters
About line (shown in the profile) My bots, /setabouttext, or setMyShortDescription up to 120 characters
“What can this bot do?” My bots, /setdescription, or setMyDescription up to 512 characters
Picture My bots only an image you upload
Website, privacy policy, terms of use My bots or /setlinks https, up to 500 characters each, all optional

setMyName, setMyDescription and setMyShortDescription take a language_code. The apps show the text in the person’s language when you set one, and the default otherwise.

The profile of a bot shows its creator’s @name, and the links you set.

The start screen

When a person opens an empty chat with a bot, the app shows the bot’s card instead of the message field:

Start sends /start. Your bot gets it as a normal message update. From then on the bot may write to that person.

When a person sends /start <parameter>, the parameter (up to 64 of A-Za-z0-9_-) is kept for the bot.

Link What it is for
https://a-chat.app/b/<yourbot> The bot’s chat.
https://a-chat.app/b/<yourbot>?start=<parameter> The bot’s chat, started with /start <parameter>.
https://a-chat.app/b/<yourbot>?startgroup=<parameter> Add the bot to one of the person’s groups. See Groups and channels.
https://a-chat.app/b/<yourbot>?startchannel=<parameter> Add the bot to a channel the person owns, as an admin.

The apps open https://a-chat.app/b/<yourbot>?start=<parameter> in the bot’s chat, where Start sends /start <parameter>; a startgroup or startchannel link shows the person their groups or channels to pick from.

Inline mode

In inline mode, a person types @yourbot something in the message field of any chat. Your bot gets an inline_query update and answers with answerInlineQuery. The person taps a result, and it is sent into that chat as their own message, marked “via @yourbot”.

  1. Turn inline mode on in My bots or with /setinline in @achatbot (the inline switch, and an optional placeholder for the field). getMe then says supports_inline_queries: true.
  2. Handle inline_query updates. You have 5 seconds to answer.
  3. Call answerInlineQuery with up to 50 results.
{
  "inline_query_id": "9b2f...",
  "cache_time": 60,
  "results": [
    {
      "type": "article",
      "id": "1",
      "title": "Hello",
      "description": "Sends a greeting",
      "input_message_content": { "message_text": "Hello from my bot!" }
    }
  ]
}

A button can start inline mode for the person: switch_inline_query lets them pick a chat and puts @yourbot <query> in its field, and switch_inline_query_current_chat does that in the same chat.

Games

A bot can bring HTML5 games into chats: a card with the game’s cover, its title and description, a Play button, and a table of records for that card. A score that beats the table’s best is announced in the chat (in a chat of two, a new personal best). Games are free: nothing is bought inside a game.

Register a game

  1. The game’s page lives on a domain of a mini app linked to the bot that is live (Link a bot). Where the team requires domain verification, that domain must be verified too (Verify your domain).
  2. In @achatbot, send /newgame, pick the bot, and give the game’s short name (3 to 64 of a-z, 0-9 and _), its title, a description, its address (https), its age (0+, 12+, 16+ or 18+) and a cover: a picture (JPEG, PNG or WebP) or an animation (GIF or animated WebP), up to 5 MB and 1280 by 1280. An animation loops muted in the apps. Videos are not taken.
  3. The A-chat team reviews the game, as a mini app. @achatbot tells you the answer. /mygames and /setgame change a game (a change sends it to review again); /deletegame removes it.

A game waiting for review can be sent into your own chat with the bot, to try it.

Send it and keep the scores

// Your bot: send the game into a chat.
await api('sendGame', { chat_id: chatId, game_short_name: 'space_race' });

// A press of Play: answer with the address of the game (a level, a room...). Without it the registered address opens.
if (update.callback_query?.game_short_name) {
  await api('answerCallbackQuery', {
    callback_query_id: update.callback_query.id,
    url: 'https://play.example.com/space-race/',
  });
}

The page gets initData signed with your bot’s token. It sends it to your server with the score, and your server checks it and reports the score:

// The game's page.
const app = window.AChat.WebApp;
app.ready();

async function gameOver(score) {
  await fetch('/api/score', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ initData: app.initData, score }),
  });
}
// Your server (Node.js). checkInitData is the function of "Who opened the app", given the bot's token.
app.post('/api/score', async (req, res) => {
  const data = checkInitData(req.body.initData, process.env.BOT_TOKEN);
  if (!data) return res.status(401).end();
  const game = JSON.parse(data.game);
  const target = game.inline_message_id
    ? { inline_message_id: game.inline_message_id }
    : { chat_id: game.chat_id, message_id: game.message_id };
  await api('setGameScore', { user_id: data.user.id, score: Number(req.body.score), ...target });
  res.json({ ok: true });
});

Never trust a score the page reports without checks of your own: a person can send any number. Keep the state of a game on your server and work the score out there where you can.

Your bot can also offer the game in any chat through inline mode: a result {type: "game", id, game_short_name}. People find live games in Hub too, under Games, where they play without a table. See Games for every method and field.

Groups and channels

A bot can be a member or an admin of a group, and an admin of a channel. It acts there with the rights of its role, as a person would.

Adding a bot

Your bot gets a my_chat_member update when it is added, made an admin, removed or banned. @achatbot’s /setjoingroups turns adding off. A bot is never the owner of a group.

Privacy mode

Privacy mode is on by default. In a group, a bot with privacy mode on gets only:

An admin bot, or a bot with privacy mode off, gets every message. In a channel, a bot gets every post as channel_post. Turn privacy mode off with /setprivacy in @achatbot only when your bot must read everything.

What works in groups

sendMessage, the file methods, albums, places, contacts, edits, deletes, forwards, polls and reactions work in groups and channels as in a private chat. A group’s chat.id is negative; a public group or channel can also be named by its @username. Topics are message_thread_id. The full list is in the reference.

Admin bots can also, with the right a person would need:

Only the owner of a group makes admins: promoteChatMember is refused. setMyDefaultAdministratorRights sets the rights the apps propose when a person makes your bot an admin.

Files

A bot sends photos, videos, documents, voice messages, audio, animations and stickers with sendPhoto, sendVideo, sendDocument, sendVoice, sendAudio, sendAnimation and sendSticker. A file can be:

Files may be up to 50 MB. A bot downloads files up to 20 MB: call getFile, then fetch https://api.a-chat.app/file/bot<token>/<file_path>. Details are in the reference.

What a bot knows about a person

This is the whole list. Nothing else is ever given to a bot or a mini app.

The User object (in updates, getChat, from of every message, and initData.user of a mini app):

Never: the phone, the e-mail, the account id, the bio, the birthday, the avatar or its link, the last seen and the status, contacts, other chats, the person’s other bots and apps, the verification and badges, the Plus badge chosen, the IP or the device.

initData of a mini app: query_id, user (as above), auth_date, start_param (when given), bot (the linked bot’s @name), platform (one of ios, android, web, macos, windows, linux, or unknown), app_id and the signed hash. There is no chat_type or chat_instance yet.

A private chat (chat in updates, getChat): id (the person’s number), type "private", first_name, username.

A bot also gets what the person chooses to send it, such as a file. A file that the person sends “to be seen once” or with a timer is never given: the message only says has_media with its kind.

When a person deletes their account, every bot forgets them at once. When a person blocks a bot, the updates from them that were still waiting are removed. If your bot keeps data about people, delete it when they leave.

Statistics

The owner sees numbers about the bot in My bots → Statistics, or with /stats in @achatbot. They are numbers only: never a person’s name or a message.

Reports

People can report a bot from its profile, and any of its messages, as they report a person. Reasons include spam, scams, adult content and pretending to be someone else. The A-chat team reviews reports. A bot that breaks the rules can be frozen: every API call then answers 403 Forbidden: the bot is frozen by the team, and the owner gets a notice. A person can also simply block a bot.

Limits

A new bot starts with lower limits. They grow with its age and the number of people who started it:

Level When API calls Added to groups and channels
new Under 3 days old and under 100 people 30 a second 10 a day
growing Otherwise, under 30 days old and under 1,000 people 100 a second 50 a day
full Everything else 300 a second 200 a day

The A-chat team can give a bot the full level at once, or a higher number of calls. Service calls, which send nobody anything, are counted apart: Limits. The other limits are the same for every bot:

What Limit
Messages into one private chat 30 in 10 seconds
Messages into one group or channel 60 a minute
API calls from one IP address 60,000 a minute
Text of a message 4,096 characters
Caption of a file 1,024 characters
File you send 50 MB
File you download 20 MB
Request body 1 MB (51 MB for file methods)
getUpdates wait 50 seconds
Updates kept 24 hours
Answer to a button press, to show a toast 7 seconds
answerCallbackQuery accepted 15 minutes, once
Answer to an inline query 5 seconds
Webhook answer 10 seconds
Bots per person 20, and 5 new a day

Lengths are counted in UTF-16 code units. Over a limit, the API answers 429 with retry_after.

Next