Letgram Bot API

The Letgram Bot API allows you to build bots that interact with users through the Letgram messaging platform. Bots are special accounts operated by software, capable of responding to messages, managing groups, processing payments, running inline queries, and much more.

What are bots?

Bots are third-party applications that run inside Letgram. Users can interact with bots by sending them messages, commands, and inline requests. Bot developers can use the Letgram Bot API to send text messages, media, keyboards, and more in response.

Bots can:

How to create a bot

To create a new bot, start a conversation with @BotGod in Letgram. Send the command /newbot and follow the instructions. You will receive an API token that authenticates your bot and grants access to the Bot API.

Other useful commands for @BotGod:

Authentication

Each bot is identified by a unique token in the format:

123456789:ABCDefgh-IJKLmnop_QRSTuvwxyz1234567

The token is a string composed of the bot's numeric ID, a colon, and a random alphanumeric string. Keep your token secure — anyone with the token can control your bot.

Never share your bot token publicly or commit it to version control. If compromised, revoke it immediately via @BotGod.

Making Requests

All API requests are made via HTTPS POST or GET to:

https://api.letgram.ru/bot<token>/METHOD_NAME

Parameters can be passed as:

All method names are case-insensitive.

Example request

curl -X POST "https://api.letgram.ru/bot123456:ABC-DEF/sendMessage" \
  -H "Content-Type: application/json" \
  -d '{"chat_id": 12345, "text": "Hello from Letgram!"}'
import requests

TOKEN = "123456:ABC-DEF"
url = f"https://api.letgram.ru/bot{TOKEN}/sendMessage"

response = requests.post(url, json={
    "chat_id": 12345,
    "text": "Hello from Letgram!"
})
print(response.json())
const TOKEN = "123456:ABC-DEF";

const res = await fetch(
  `https://api.letgram.ru/bot${TOKEN}/sendMessage`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      chat_id: 12345,
      text: "Hello from Letgram!"
    })
  }
);
const data = await res.json();
console.log(data);

Response Format

All responses are JSON objects. A successful response has the following structure:

{
  "ok": true,
  "result": { ... }
}

An error response:

{
  "ok": false,
  "error_code": 400,
  "description": "Bad Request: chat not found"
}

The result field contains the response data. Its type depends on the method called. The error_code field corresponds to HTTP status codes.

Getting Updates

There are two ways to receive updates from Letgram: long polling via getUpdates, or webhooks via setWebhook. Only one method can be active at a time.

getUpdates

Use this method to receive incoming updates using long polling. Returns an Array of Update objects.

ParameterTypeRequiredDescription
offsetIntegerOptionalIdentifier of the first update to be returned. Must be greater than the highest update_id previously received. By default, updates starting with the earliest unconfirmed update are returned.
limitIntegerOptionalLimits the number of updates returned. Values between 1-100 accepted. Defaults to 100.
timeoutIntegerOptionalTimeout in seconds for long polling. Defaults to 0 (short polling). Should be positive for production use.
allowed_updatesArray of StringOptionalList of update types to receive. Specify an empty list to receive all update types except chat_member. Available: message, edited_message, channel_post, edited_channel_post, inline_query, chosen_inline_result, callback_query, shipping_query, pre_checkout_query, poll, poll_answer, my_chat_member, chat_member.
curl "https://api.letgram.ru/bot<token>/getUpdates?timeout=30&offset=0"
response = requests.get(f"https://api.letgram.ru/bot{TOKEN}/getUpdates", params={
    "timeout": 30,
    "offset": 0
})
const res = await fetch(
  `https://api.letgram.ru/bot${TOKEN}/getUpdates?timeout=30&offset=0`
);
const updates = await res.json();

setWebhook

Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update, Letgram will send an HTTPS POST request to the specified URL containing a JSON-serialized Update. Returns True on success.

ParameterTypeRequiredDescription
urlStringYesHTTPS URL to send updates to. Use an empty string to remove webhook integration.
certificateInputFileOptionalUpload your public key certificate for webhook verification.
ip_addressStringOptionalFixed IP address to send webhook requests to instead of resolving the URL via DNS.
max_connectionsIntegerOptionalMaximum allowed simultaneous HTTPS connections for update delivery. 1-100. Defaults to 40.
allowed_updatesArray of StringOptionalList of update types to receive. See getUpdates for available types.
drop_pending_updatesBooleanOptionalPass True to drop all pending updates.
secret_tokenStringOptionalA secret token (1-256 chars) to be sent in X-Letgram-Bot-Api-Secret-Token header for verification.

deleteWebhook

Use this method to remove webhook integration. Returns True on success.

ParameterTypeRequiredDescription
drop_pending_updatesBooleanOptionalPass True to drop all pending updates.

getWebhookInfo

Use this method to get current webhook status. Requires no parameters. Returns a WebhookInfo object.

The WebhookInfo object contains fields: url, has_custom_certificate, pending_update_count, ip_address, last_error_date, last_error_message, last_synchronization_error_date, max_connections, allowed_updates.

Update Object

This object represents an incoming update. At most one of the optional parameters can be present in any given update.

FieldTypeDescription
update_idIntegerThe update's unique identifier. Update identifiers start from a positive number and increase sequentially.
messageMessageNew incoming message of any kind.
edited_messageMessageNew version of a message that was edited.
channel_postMessageNew incoming channel post.
edited_channel_postMessageEdited channel post.
inline_queryInlineQueryNew incoming inline query.
chosen_inline_resultChosenInlineResultResult of an inline query chosen by the user.
callback_queryCallbackQueryNew incoming callback query.
shipping_queryShippingQueryNew incoming shipping query (payments only).
pre_checkout_queryPreCheckoutQueryNew incoming pre-checkout query (payments only).
pollPollNew poll state (stopped or received a new answer).
poll_answerPollAnswerA user changed their answer in a non-anonymous poll.
my_chat_memberChatMemberUpdatedBot's chat member status was updated.
chat_memberChatMemberUpdatedA chat member's status was updated.

Available Types

All types used in the Bot API are described below. Optional fields may not be present in every object.

User

This object represents a Letgram user or bot.

FieldTypeDescription
idIntegerUnique identifier for this user or bot.
is_botBooleanTrue, if this user is a bot.
first_nameStringUser's or bot's first name.
last_nameStringOptional. User's or bot's last name.
usernameStringOptional. User's or bot's username.
language_codeStringOptional. IETF language tag of the user's language.
is_premiumBooleanOptional. True, if this user has Letgram Premium.
can_join_groupsBooleanOptional. True, if the bot can be invited to groups. Returned only in getMe.
can_read_all_group_messagesBooleanOptional. True, if privacy mode is disabled for the bot. Returned only in getMe.
supports_inline_queriesBooleanOptional. True, if the bot supports inline queries. Returned only in getMe.

Chat

This object represents a chat.

FieldTypeDescription
idIntegerUnique identifier for this chat.
typeStringType of chat: private, group, supergroup, or channel.
titleStringOptional. Title for supergroups, channels, and group chats.
usernameStringOptional. Username for private chats, supergroups, and channels.
first_nameStringOptional. First name of the other party in a private chat.
last_nameStringOptional. Last name of the other party in a private chat.
photoChatPhotoOptional. Chat photo.
bioStringOptional. Bio of the other party in a private chat.
descriptionStringOptional. Description for groups, supergroups, and channels.
invite_linkStringOptional. Primary invite link.
pinned_messageMessageOptional. The most recent pinned message.
permissionsChatPermissionsOptional. Default chat permissions for groups and supergroups.
slow_mode_delayIntegerOptional. Minimum delay between consecutive messages sent by each unprivileged user (seconds).
message_auto_delete_timeIntegerOptional. Time after which all messages will be auto-deleted (seconds).
linked_chat_idIntegerOptional. Unique identifier of the linked chat.

Message

This object represents a message.

FieldTypeDescription
message_idIntegerUnique message identifier inside this chat.
fromUserOptional. Sender of the message. Empty for messages sent to channels.
sender_chatChatOptional. Sender of the message when sent on behalf of a chat.
dateIntegerDate the message was sent (Unix time).
chatChatConversation the message belongs to.
forward_fromUserOptional. Sender of the original message (for forwarded messages).
forward_from_chatChatOptional. For forwarded messages from channels, original channel.
forward_from_message_idIntegerOptional. For forwarded channel messages, original message identifier.
forward_dateIntegerOptional. For forwarded messages, date of the original message.
reply_to_messageMessageOptional. The message being replied to.
edit_dateIntegerOptional. Date the message was last edited (Unix time).
textStringOptional. Actual UTF-8 text of the message (0-4096 characters).
entitiesArray of MessageEntityOptional. Special entities in text (usernames, URLs, commands, etc.).
animationAnimationOptional. Message is an animation (GIF).
audioAudioOptional. Message is an audio file.
documentDocumentOptional. Message is a general file.
photoArray of PhotoSizeOptional. Message is a photo, available sizes.
stickerStickerOptional. Message is a sticker.
videoVideoOptional. Message is a video.
video_noteVideoNoteOptional. Message is a video note (round video).
voiceVoiceOptional. Message is a voice message.
captionStringOptional. Caption for animation, audio, document, photo, video (0-1024 chars).
caption_entitiesArray of MessageEntityOptional. Special entities in the caption.
contactContactOptional. Message is a shared contact.
diceDiceOptional. Message is a dice with random value.
pollPollOptional. Message is a native poll.
venueVenueOptional. Message is a venue.
locationLocationOptional. Message is a shared location.
new_chat_membersArray of UserOptional. New members added to the group or supergroup.
left_chat_memberUserOptional. A member was removed from the group.
new_chat_titleStringOptional. Group title was changed.
new_chat_photoArray of PhotoSizeOptional. Group photo was changed.
pinned_messageMessageOptional. A message was pinned.
web_app_dataWebAppDataOptional. Data sent from a Mini App.
reply_markupInlineKeyboardMarkupOptional. Inline keyboard attached to the message.

MessageEntity

This object represents one special entity in a text message (hashtag, username, URL, etc.).

FieldTypeDescription
typeStringType of the entity. One of: mention, hashtag, cashtag, bot_command, url, email, phone_number, bold, italic, underline, strikethrough, spoiler, code, pre, text_link, text_mention, custom_emoji.
offsetIntegerOffset in UTF-16 code units to the start of the entity.
lengthIntegerLength of the entity in UTF-16 code units.
urlStringOptional. URL that will be opened when the user taps on the entity (for text_link).
userUserOptional. Mentioned user (for text_mention).
languageStringOptional. Programming language of the entity text (for pre).
custom_emoji_idStringOptional. Unique identifier of the custom emoji (for custom_emoji).

Media Types

PhotoSize

FieldTypeDescription
file_idStringIdentifier for this file, which can be used to download or reuse the file.
file_unique_idStringUnique identifier for this file (same over time and for different bots, cannot be used to download).
widthIntegerPhoto width.
heightIntegerPhoto height.
file_sizeIntegerOptional. File size in bytes.

Audio

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
durationIntegerDuration of the audio in seconds.
performerStringOptional. Performer of the audio.
titleStringOptional. Title of the audio.
file_nameStringOptional. Original filename.
mime_typeStringOptional. MIME type.
file_sizeIntegerOptional. File size in bytes.
thumbnailPhotoSizeOptional. Thumbnail of the album cover.

Document

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
thumbnailPhotoSizeOptional. Document thumbnail.
file_nameStringOptional. Original filename.
mime_typeStringOptional. MIME type.
file_sizeIntegerOptional. File size in bytes.

Video

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
widthIntegerVideo width.
heightIntegerVideo height.
durationIntegerDuration in seconds.
thumbnailPhotoSizeOptional. Video thumbnail.
file_nameStringOptional. Original filename.
mime_typeStringOptional. MIME type.
file_sizeIntegerOptional. File size in bytes.

Animation

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
widthIntegerVideo width.
heightIntegerVideo height.
durationIntegerDuration in seconds.
thumbnailPhotoSizeOptional. Animation thumbnail.
file_nameStringOptional. Original filename.
mime_typeStringOptional. MIME type.
file_sizeIntegerOptional. File size in bytes.

Voice

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
durationIntegerDuration in seconds.
mime_typeStringOptional. MIME type.
file_sizeIntegerOptional. File size in bytes.

VideoNote

FieldTypeDescription
file_idStringIdentifier for this file.
file_unique_idStringUnique identifier for this file.
lengthIntegerVideo width and height (diameter of the circular video).
durationIntegerDuration in seconds.
thumbnailPhotoSizeOptional. Video note thumbnail.
file_sizeIntegerOptional. File size in bytes.

Contact, Location, Venue

Contact

FieldTypeDescription
phone_numberStringContact's phone number.
first_nameStringContact's first name.
last_nameStringOptional. Contact's last name.
user_idIntegerOptional. Contact's user identifier in Letgram.
vcardStringOptional. Additional data about the contact in vCard format.

Location

FieldTypeDescription
longitudeFloatLongitude as defined by sender.
latitudeFloatLatitude as defined by sender.
horizontal_accuracyFloatOptional. Radius of uncertainty for the location, meters (0-1500).
live_periodIntegerOptional. Time relative to the message sending date during which the location can be updated (seconds).
headingIntegerOptional. Direction in which the user is moving (degrees, 1-360).
proximity_alert_radiusIntegerOptional. Max distance for proximity alerts (meters).

Venue

FieldTypeDescription
locationLocationVenue location.
titleStringName of the venue.
addressStringAddress of the venue.
foursquare_idStringOptional. Foursquare identifier of the venue.
foursquare_typeStringOptional. Foursquare type of the venue.
google_place_idStringOptional. Google Places identifier of the venue.
google_place_typeStringOptional. Google Places type of the venue.

Poll

FieldTypeDescription
idStringUnique poll identifier.
questionStringPoll question (1-300 characters).
optionsArray of PollOptionList of poll options.
total_voter_countIntegerTotal number of users that voted.
is_closedBooleanTrue, if the poll is closed.
is_anonymousBooleanTrue, if the poll is anonymous.
typeStringPoll type: regular or quiz.
allows_multiple_answersBooleanTrue, if the poll allows multiple answers.
correct_option_idIntegerOptional. 0-based index of the correct option (quiz polls).
explanationStringOptional. Text shown when a user selects an incorrect answer (quiz polls).
open_periodIntegerOptional. Time in seconds the poll will be active after creation.
close_dateIntegerOptional. Unix timestamp when the poll will be automatically closed.

PollOption

FieldTypeDescription
textStringOption text (1-100 characters).
voter_countIntegerNumber of users that voted for this option.

Keyboards

InlineKeyboardMarkup

This object represents an inline keyboard that appears right next to the message it belongs to.

FieldTypeDescription
inline_keyboardArray of Array of InlineKeyboardButtonArray of button rows, each represented by an array of InlineKeyboardButton objects.

InlineKeyboardButton

FieldTypeDescription
textStringLabel text on the button.
urlStringOptional. HTTP/HTTPS URL to open when button is pressed.
callback_dataStringOptional. Data to be sent in a callback query when button is pressed (1-64 bytes).
web_appWebAppInfoOptional. Description of the Mini App to launch.
switch_inline_queryStringOptional. Pressing the button will prompt the user to select a chat and insert the bot's username and the specified inline query.
switch_inline_query_current_chatStringOptional. Pressing the button will insert the bot's username and the specified inline query in the current chat.
payBooleanOptional. Specify True to send a Pay button.

ReplyKeyboardMarkup

This object represents a custom keyboard with reply options.

FieldTypeDescription
keyboardArray of Array of KeyboardButtonArray of button rows.
is_persistentBooleanOptional. Requests the keyboard to always be shown.
resize_keyboardBooleanOptional. Requests clients to resize the keyboard vertically for optimal fit.
one_time_keyboardBooleanOptional. Requests clients to hide the keyboard after a button is pressed.
input_field_placeholderStringOptional. Placeholder text in the input field (1-64 chars).
selectiveBooleanOptional. Show the keyboard to specific users only.

KeyboardButton

FieldTypeDescription
textStringText of the button. If no optional fields are used, it will be sent as a message.
request_contactBooleanOptional. The user's phone number will be sent as a contact.
request_locationBooleanOptional. The user's current location will be sent.
request_pollKeyboardButtonPollTypeOptional. The user will be asked to create a poll.
web_appWebAppInfoOptional. Launch a Mini App.

ReplyKeyboardRemove

Removes the current custom keyboard and displays the default letter-keyboard.

FieldTypeDescription
remove_keyboardBooleanRequests clients to remove the custom keyboard. Always True.
selectiveBooleanOptional. Remove for specific users only.

CallbackQuery

FieldTypeDescription
idStringUnique identifier for this query.
fromUserSender.
messageMessageOptional. Message with the callback button that originated the query.
inline_message_idStringOptional. Identifier of the message sent via the bot in inline mode.
chat_instanceStringGlobal identifier, uniquely corresponding to the chat.
dataStringOptional. Data associated with the callback button (1-64 bytes).
game_short_nameStringOptional. Short name of a Game to be returned.

WebApp Types

WebAppInfo

FieldTypeDescription
urlStringAn HTTPS URL of a Mini App to be opened.

WebAppData

FieldTypeDescription
dataStringThe data. Can be an arbitrary string.
button_textStringText of the web_app keyboard button from which the Mini App was opened.

Available Methods

getMe

A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.

curl "https://api.letgram.ru/bot<token>/getMe"
response = requests.get(f"https://api.letgram.ru/bot{TOKEN}/getMe")
print(response.json())
const res = await fetch(`https://api.letgram.ru/bot${TOKEN}/getMe`);
const me = await res.json();

logOut

Use this method to log out from the cloud Bot API server. Returns True on success. You must log out the bot before running it locally.

close

Use this method to close the bot instance. Returns True on success. Use before moving a bot from one local server to another.

sendMessage

Use this method to send text messages. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier for the target chat or username of the target channel (e.g. @channelusername).
message_thread_idIntegerOptionalUnique identifier for the target message thread (topic) of the forum.
textStringYesText of the message to be sent (1-4096 characters).
parse_modeStringOptionalMode for parsing entities: MarkdownV2, HTML, or Markdown.
entitiesArray of MessageEntityOptionalList of special entities in the message text (instead of parse_mode).
disable_web_page_previewBooleanOptionalDisables link previews for links in this message.
disable_notificationBooleanOptionalSends the message silently. Users will receive a notification with no sound.
protect_contentBooleanOptionalProtects the contents of the sent message from forwarding and saving.
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message.
allow_sending_without_replyBooleanOptionalPass True if the message should be sent even if the specified replied-to message is not found.
reply_markupInlineKeyboardMarkup or ReplyKeyboardMarkup or ReplyKeyboardRemove or ForceReplyOptionalAdditional interface options (keyboards, force reply, etc.).
curl -X POST "https://api.letgram.ru/bot<token>/sendMessage" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": 12345678,
    "text": "Hello! This is a *bold* message with an [inline link](https://letgram.ru)",
    "parse_mode": "MarkdownV2"
  }'
import requests

TOKEN = "YOUR_BOT_TOKEN"
url = f"https://api.letgram.ru/bot{TOKEN}/sendMessage"

response = requests.post(url, json={
    "chat_id": 12345678,
    "text": "Hello! This is a bold message",
    "parse_mode": "HTML",
    "reply_markup": {
        "inline_keyboard": [[
            {"text": "Visit Letgram", "url": "https://letgram.ru"},
            {"text": "Click me", "callback_data": "btn_click"}
        ]]
    }
})
print(response.json())
const TOKEN = "YOUR_BOT_TOKEN";

const res = await fetch(`https://api.letgram.ru/bot${TOKEN}/sendMessage`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    chat_id: 12345678,
    text: "Hello! This is a bold message",
    parse_mode: "HTML",
    reply_markup: {
      inline_keyboard: [[
        { text: "Visit Letgram", url: "https://letgram.ru" },
        { text: "Click me", callback_data: "btn_click" }
      ]]
    }
  })
});
console.log(await res.json());

forwardMessage

Use this method to forward messages of any kind. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
from_chat_idInteger or StringYesChat where the original message was sent.
disable_notificationBooleanOptionalSends the message silently.
protect_contentBooleanOptionalProtects the message from forwarding and saving.
message_idIntegerYesMessage identifier in the chat specified in from_chat_id.

copyMessage

Use this method to copy messages of any kind. The method is analogous to forwardMessage, but the copied message doesn't have a link to the original. Returns the MessageId of the sent message.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
from_chat_idInteger or StringYesChat where the original message was sent.
message_idIntegerYesMessage identifier in the chat specified in from_chat_id.
captionStringOptionalNew caption for media (0-1024 chars).
parse_modeStringOptionalMode for parsing entities in the caption.
disable_notificationBooleanOptionalSends the message silently.
protect_contentBooleanOptionalProtects the message.
reply_to_message_idIntegerOptionalIf the message is a reply, ID of the original message.
reply_markupKeyboard markupOptionalAdditional interface options.

Send Media

sendPhoto

Use this method to send photos. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
photoInputFile or StringYesPhoto to send. Pass a file_id as String to send a photo that exists on the Letgram servers, pass an HTTP URL to send a photo from the Internet, or upload a new photo using multipart/form-data.
captionStringOptionalPhoto caption (0-1024 characters).
parse_modeStringOptionalMode for parsing entities in the caption.
has_spoilerBooleanOptionalPass True if the photo needs to be covered with a spoiler animation.
disable_notificationBooleanOptionalSends the message silently.
protect_contentBooleanOptionalProtects the message.
reply_to_message_idIntegerOptionalIf the message is a reply.
reply_markupKeyboard markupOptionalAdditional interface options.
# Send photo by URL
curl -X POST "https://api.letgram.ru/bot<token>/sendPhoto" \
  -H "Content-Type: application/json" \
  -d '{"chat_id": 12345678, "photo": "https://example.com/photo.jpg", "caption": "Beautiful photo!"}'

# Upload photo file
curl -X POST "https://api.letgram.ru/bot<token>/sendPhoto" \
  -F "chat_id=12345678" \
  -F "photo=@/path/to/photo.jpg" \
  -F "caption=Uploaded photo!"
# Send by URL
requests.post(f"https://api.letgram.ru/bot{TOKEN}/sendPhoto", json={
    "chat_id": 12345678,
    "photo": "https://example.com/photo.jpg",
    "caption": "Beautiful photo!"
})

# Upload file
with open("photo.jpg", "rb") as f:
    requests.post(f"https://api.letgram.ru/bot{TOKEN}/sendPhoto",
        data={"chat_id": 12345678, "caption": "Uploaded!"},
        files={"photo": f}
    )
// Send by URL
await fetch(`https://api.letgram.ru/bot${TOKEN}/sendPhoto`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    chat_id: 12345678,
    photo: "https://example.com/photo.jpg",
    caption: "Beautiful photo!"
  })
});

sendAudio

Use this method to send audio files (mp3 format, up to 50 MB). On success, the sent Message is returned. For voice messages, use sendVoice instead.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
audioInputFile or StringYesAudio file to send.
captionStringOptionalAudio caption (0-1024 chars).
parse_modeStringOptionalMode for parsing entities in the caption.
durationIntegerOptionalDuration of the audio in seconds.
performerStringOptionalPerformer.
titleStringOptionalTrack name.
thumbnailInputFile or StringOptionalThumbnail of the file.
reply_markupKeyboard markupOptionalAdditional interface options.

sendDocument

Use this method to send general files (up to 50 MB). On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
documentInputFile or StringYesFile to send.
thumbnailInputFile or StringOptionalThumbnail of the file.
captionStringOptionalDocument caption (0-1024 chars).
parse_modeStringOptionalMode for parsing entities.
disable_content_type_detectionBooleanOptionalDisables automatic server-side content type detection for uploaded files.
reply_markupKeyboard markupOptionalAdditional interface options.

sendVideo

Use this method to send video files (up to 50 MB). On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
videoInputFile or StringYesVideo to send.
durationIntegerOptionalDuration in seconds.
widthIntegerOptionalVideo width.
heightIntegerOptionalVideo height.
thumbnailInputFile or StringOptionalThumbnail of the video.
captionStringOptionalVideo caption (0-1024 chars).
parse_modeStringOptionalMode for parsing entities.
has_spoilerBooleanOptionalPass True for a spoiler animation cover.
supports_streamingBooleanOptionalPass True if the video is suitable for streaming.
reply_markupKeyboard markupOptionalAdditional interface options.

sendAnimation

Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound, up to 50 MB). On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
animationInputFile or StringYesAnimation to send.
durationIntegerOptionalDuration in seconds.
widthIntegerOptionalAnimation width.
heightIntegerOptionalAnimation height.
captionStringOptionalAnimation caption (0-1024 chars).
has_spoilerBooleanOptionalPass True for spoiler cover.
reply_markupKeyboard markupOptionalAdditional interface options.

sendVoice

Use this method to send audio files as a playable voice message (OPUS in OGG container, up to 50 MB). On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
voiceInputFile or StringYesAudio file to send as voice.
captionStringOptionalVoice message caption (0-1024 chars).
durationIntegerOptionalDuration in seconds.
reply_markupKeyboard markupOptionalAdditional interface options.

sendVideoNote

Use this method to send video messages (round videos, up to 1 minute). On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
video_noteInputFile or StringYesVideo note to send.
durationIntegerOptionalDuration in seconds.
lengthIntegerOptionalVideo width and height (diameter).
thumbnailInputFile or StringOptionalThumbnail of the video note.
reply_markupKeyboard markupOptionalAdditional interface options.

sendSticker

Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
stickerInputFile or StringYesSticker to send.
emojiStringOptionalEmoji associated with the sticker.
reply_markupKeyboard markupOptionalAdditional interface options.

sendMediaGroup

Use this method to send a group of photos, videos, documents, or audios as an album. On success, an Array of Messages is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
mediaArray of InputMediaYesArray describing messages to be sent. Must include 2-10 items.
disable_notificationBooleanOptionalSends messages silently.
protect_contentBooleanOptionalProtects the messages.
reply_to_message_idIntegerOptionalIf the messages are a reply.

sendLocation

Use this method to send a point on the map. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
latitudeFloatYesLatitude of the location.
longitudeFloatYesLongitude of the location.
horizontal_accuracyFloatOptionalRadius of uncertainty (0-1500 meters).
live_periodIntegerOptionalPeriod in seconds for live location (60-86400).
headingIntegerOptionalDirection of movement (1-360 degrees).
proximity_alert_radiusIntegerOptionalMax distance for proximity alerts (meters).
reply_markupKeyboard markupOptionalAdditional interface options.

sendVenue

Use this method to send information about a venue. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
latitudeFloatYesLatitude of the venue.
longitudeFloatYesLongitude of the venue.
titleStringYesName of the venue.
addressStringYesAddress of the venue.
foursquare_idStringOptionalFoursquare identifier of the venue.
google_place_idStringOptionalGoogle Places identifier of the venue.
reply_markupKeyboard markupOptionalAdditional interface options.

sendContact

Use this method to send phone contacts. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
phone_numberStringYesContact's phone number.
first_nameStringYesContact's first name.
last_nameStringOptionalContact's last name.
vcardStringOptionalAdditional data in vCard format (0-2048 bytes).
reply_markupKeyboard markupOptionalAdditional interface options.

sendPoll

Use this method to send a native poll. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
questionStringYesPoll question (1-300 characters).
optionsArray of StringYesList of answer options (2-10 strings, 1-100 chars each).
is_anonymousBooleanOptionalTrue for anonymous poll. Defaults to True.
typeStringOptionalPoll type: quiz or regular. Defaults to regular.
allows_multiple_answersBooleanOptionalTrue if the poll allows multiple answers (regular polls only).
correct_option_idIntegerOptional0-based index of the correct answer (quiz polls, required for quiz).
explanationStringOptionalText shown after user selects an incorrect answer (0-200 chars).
open_periodIntegerOptionalTime in seconds the poll will be active (5-600).
close_dateIntegerOptionalUnix timestamp when the poll will be closed.
reply_markupKeyboard markupOptionalAdditional interface options.

sendDice

Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
emojiStringOptionalEmoji on which the dice throw animation is based. Currently one of: dice, darts, basketball, football, bowling, slot machine. Defaults to dice.
reply_markupKeyboard markupOptionalAdditional interface options.

sendChatAction

Use this method to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
actionStringYesType of action: typing, upload_photo, record_video, upload_video, record_voice, upload_voice, upload_document, choose_sticker, find_location, record_video_note, upload_video_note.

User & Files

getUserProfilePhotos

Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.

ParameterTypeRequiredDescription
user_idIntegerYesUnique identifier of the target user.
offsetIntegerOptionalSequential number of the first photo to be returned.
limitIntegerOptionalLimits the number of photos to be retrieved (1-100). Defaults to 100.

getFile

Use this method to get basic information about a file and prepare it for downloading. The file can then be downloaded from https://api.letgram.ru/file/bot<token>/<file_path>. Files up to 20 MB in size can be downloaded.

ParameterTypeRequiredDescription
file_idStringYesFile identifier to get information about.
# Step 1: Get file path
curl "https://api.letgram.ru/bot<token>/getFile?file_id=AgACAgIA..."

# Step 2: Download the file
curl "https://api.letgram.ru/file/bot<token>/photos/file_0.jpg" -o downloaded.jpg
# Get file info
file_info = requests.get(f"https://api.letgram.ru/bot{TOKEN}/getFile",
    params={"file_id": "AgACAgIA..."}).json()

# Download
file_path = file_info["result"]["file_path"]
file_data = requests.get(f"https://api.letgram.ru/file/bot{TOKEN}/{file_path}")
with open("downloaded.jpg", "wb") as f:
    f.write(file_data.content)
// Get file info
const info = await fetch(
  `https://api.letgram.ru/bot${TOKEN}/getFile?file_id=AgACAgIA...`
).then(r => r.json());

// Download
const filePath = info.result.file_path;
const fileData = await fetch(
  `https://api.letgram.ru/file/bot${TOKEN}/${filePath}`
).then(r => r.blob());

Chat Administration

banChatMember

Use this method to ban a user in a group, supergroup, or channel. The bot must be an administrator with the appropriate rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
user_idIntegerYesUnique identifier of the target user.
until_dateIntegerOptionalUnix timestamp when the user will be unbanned. If less than 366 days, the user is banned for that duration. If more than 366 days or 0, the user is banned forever.
revoke_messagesBooleanOptionalPass True to delete all messages from the user in the chat.

unbanChatMember

Use this method to unban a previously banned user in a supergroup or channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
user_idIntegerYesUnique identifier of the target user.
only_if_bannedBooleanOptionalDo nothing if the user is not banned.

restrictChatMember

Use this method to restrict a user in a supergroup. The bot must be an administrator with can_restrict_members rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
user_idIntegerYesUnique identifier of the target user.
permissionsChatPermissionsYesJSON-serialized object for new user permissions.
until_dateIntegerOptionalUnix timestamp when restrictions will be lifted.

promoteChatMember

Use this method to promote or demote a user in a supergroup or channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
user_idIntegerYesUnique identifier of the target user.
is_anonymousBooleanOptionalPass True if the administrator's presence should be hidden.
can_manage_chatBooleanOptionalPass True if the administrator can access the chat event log, statistics, etc.
can_post_messagesBooleanOptionalPass True if the administrator can post messages (channels only).
can_edit_messagesBooleanOptionalPass True if the administrator can edit messages (channels only).
can_delete_messagesBooleanOptionalPass True if the administrator can delete messages of other users.
can_manage_video_chatsBooleanOptionalPass True if the administrator can manage video chats.
can_restrict_membersBooleanOptionalPass True if the administrator can restrict, ban, or unban members.
can_promote_membersBooleanOptionalPass True if the administrator can add new administrators.
can_change_infoBooleanOptionalPass True if the administrator can change the chat title, photo, etc.
can_invite_usersBooleanOptionalPass True if the administrator can invite new users.
can_pin_messagesBooleanOptionalPass True if the administrator can pin messages (supergroups only).
can_post_storiesBooleanOptionalPass True if the administrator can post stories.
can_edit_storiesBooleanOptionalPass True if the administrator can edit stories.
can_delete_storiesBooleanOptionalPass True if the administrator can delete stories.

setChatTitle

Use this method to change the title of a chat. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
titleStringYesNew chat title (1-128 characters).

setChatDescription

Use this method to change the description of a group, supergroup, or channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
descriptionStringOptionalNew chat description (0-255 characters).

setChatPhoto

Use this method to set a new profile photo for the chat. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
photoInputFileYesNew chat photo (must be uploaded as multipart/form-data).

pinChatMessage

Use this method to add a message to the list of pinned messages in a chat. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
message_idIntegerYesIdentifier of a message to pin.
disable_notificationBooleanOptionalPass True to silently pin the message.

unpinChatMessage

Use this method to remove a message from the list of pinned messages. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
message_idIntegerOptionalIdentifier of a message to unpin. If not specified, the most recent pinned message is unpinned.

Chat Info

leaveChat

Use this method for your bot to leave a group, supergroup, or channel. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.

getChat

Use this method to get up-to-date information about the chat. Returns a Chat object.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.

getChatAdministrators

Use this method to get a list of administrators in a chat (non-bots). Returns an Array of ChatMember objects.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.

getChatMemberCount

Use this method to get the number of members in a chat. Returns Integer.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.

getChatMember

Use this method to get information about a member of a chat. Returns a ChatMember object.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
user_idIntegerYesUnique identifier of the target user.

Bot Commands

setMyCommands

Use this method to change the list of the bot's commands. Returns True on success.

ParameterTypeRequiredDescription
commandsArray of BotCommandYesList of bot commands (up to 100). Each BotCommand has command (1-32 chars) and description (1-256 chars).
scopeBotCommandScopeOptionalScope of users for which the commands are relevant.
language_codeStringOptionalTwo-letter ISO 639-1 language code.
curl -X POST "https://api.letgram.ru/bot<token>/setMyCommands" \
  -H "Content-Type: application/json" \
  -d '{
    "commands": [
      {"command": "start", "description": "Start the bot"},
      {"command": "help", "description": "Show help message"},
      {"command": "settings", "description": "Open settings"}
    ]
  }'
requests.post(f"https://api.letgram.ru/bot{TOKEN}/setMyCommands", json={
    "commands": [
        {"command": "start", "description": "Start the bot"},
        {"command": "help", "description": "Show help message"},
        {"command": "settings", "description": "Open settings"}
    ]
})
await fetch(`https://api.letgram.ru/bot${TOKEN}/setMyCommands`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    commands: [
      { command: "start", description: "Start the bot" },
      { command: "help", description: "Show help message" },
      { command: "settings", description: "Open settings" }
    ]
  })
});

getMyCommands

Use this method to get the current list of the bot's commands. Returns an Array of BotCommand.

ParameterTypeRequiredDescription
scopeBotCommandScopeOptionalScope of users for which the commands are relevant.
language_codeStringOptionalTwo-letter ISO 639-1 language code.

deleteMyCommands

Use this method to delete the list of the bot's commands for the given scope and language. Returns True on success.

ParameterTypeRequiredDescription
scopeBotCommandScopeOptionalScope of users for which the commands are relevant.
language_codeStringOptionalTwo-letter ISO 639-1 language code.

Editing Messages

editMessageText

Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptional*Required if inline_message_id is not specified. Target chat.
message_idIntegerOptional*Required if inline_message_id is not specified. Identifier of the message to edit.
inline_message_idStringOptional*Required if chat_id and message_id are not specified. Identifier of the inline message.
textStringYesNew text of the message (1-4096 characters).
parse_modeStringOptionalMode for parsing entities in the text.
disable_web_page_previewBooleanOptionalDisables link previews.
reply_markupInlineKeyboardMarkupOptionalAn inline keyboard.

editMessageCaption

Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptional*Required if inline_message_id is not specified.
message_idIntegerOptional*Required if inline_message_id is not specified.
inline_message_idStringOptional*Required if chat_id and message_id are not specified.
captionStringOptionalNew caption (0-1024 characters).
parse_modeStringOptionalMode for parsing entities.
reply_markupInlineKeyboardMarkupOptionalAn inline keyboard.

editMessageReplyMarkup

Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringOptional*Required if inline_message_id is not specified.
message_idIntegerOptional*Required if inline_message_id is not specified.
inline_message_idStringOptional*Required if chat_id and message_id are not specified.
reply_markupInlineKeyboardMarkupOptionalAn inline keyboard.

deleteMessage

Use this method to delete a message. The bot must have the appropriate rights. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
message_idIntegerYesIdentifier of the message to delete.

answerCallbackQuery

Use this method to send answers to callback queries sent from inline keyboards. On success, True is returned.

ParameterTypeRequiredDescription
callback_query_idStringYesUnique identifier for the query to be answered.
textStringOptionalText of the notification (0-200 characters). If not specified, nothing will be shown.
show_alertBooleanOptionalPass True to show an alert instead of a notification at the top of the chat screen.
urlStringOptionalURL that will be opened by the user's client.
cache_timeIntegerOptionalMaximum time in seconds that the result may be cached. Defaults to 0.
curl -X POST "https://api.letgram.ru/bot<token>/answerCallbackQuery" \
  -H "Content-Type: application/json" \
  -d '{"callback_query_id": "123456789", "text": "Button clicked!", "show_alert": false}'
requests.post(f"https://api.letgram.ru/bot{TOKEN}/answerCallbackQuery", json={
    "callback_query_id": callback_query.id,
    "text": "Button clicked!",
    "show_alert": False
})
await fetch(`https://api.letgram.ru/bot${TOKEN}/answerCallbackQuery`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    callback_query_id: callbackQuery.id,
    text: "Button clicked!",
    show_alert: false
  })
});

Inline Mode

Bots can be called from any chat via inline queries. Users type @botusername query in the text input field, and the bot receives the query and returns results that appear in a dropdown above the text field. When the user selects a result, it is sent to the chat.

To enable inline mode, send the /setinline command to @BotGod and provide a placeholder text that will be shown in the input field when the user types the bot's name.

InlineQuery

This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results.

FieldTypeDescription
idStringUnique identifier for this query.
fromUserSender.
queryStringText of the query (up to 256 characters).
offsetStringOffset of the results to be returned (for pagination).
chat_typeStringOptional. Type of the chat from which the inline query was sent: sender, private, group, supergroup, or channel.
locationLocationOptional. Sender location (only for bots that request user location).

answerInlineQuery

Use this method to send answers to an inline query. No more than 50 results per query are allowed. Returns True on success.

ParameterTypeRequiredDescription
inline_query_idStringYesUnique identifier for the answered query.
resultsArray of InlineQueryResultYesArray of results for the inline query (max 50).
cache_timeIntegerOptionalMaximum time in seconds the result may be cached. Defaults to 300.
is_personalBooleanOptionalResults may be cached on the server side only for the user that sent the query.
next_offsetStringOptionalOffset for pagination. Pass the offset that a client should send in the next query to receive more results.
switch_pm_textStringOptionalA button displayed above inline query results to switch to a private chat with the bot.
switch_pm_parameterStringOptionalDeep-linking parameter for the /start message sent to the bot.
curl -X POST "https://api.letgram.ru/bot<token>/answerInlineQuery" \
  -H "Content-Type: application/json" \
  -d '{
    "inline_query_id": "query123",
    "results": [
      {
        "type": "article",
        "id": "1",
        "title": "Result Title",
        "input_message_content": {
          "message_text": "This is the result message"
        },
        "description": "A short description"
      }
    ]
  }'
requests.post(f"https://api.letgram.ru/bot{TOKEN}/answerInlineQuery", json={
    "inline_query_id": inline_query.id,
    "results": [
        {
            "type": "article",
            "id": "1",
            "title": "Result Title",
            "input_message_content": {
                "message_text": "This is the result message"
            },
            "description": "A short description"
        }
    ],
    "cache_time": 60
})
await fetch(`https://api.letgram.ru/bot${TOKEN}/answerInlineQuery`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    inline_query_id: inlineQuery.id,
    results: [{
      type: "article",
      id: "1",
      title: "Result Title",
      input_message_content: {
        message_text: "This is the result message"
      },
      description: "A short description"
    }],
    cache_time: 60
  })
});

InlineQueryResult Types

The following types of InlineQueryResult are supported:

All InlineQueryResult types share common fields: type (String), id (String, up to 64 bytes), and optionally reply_markup (InlineKeyboardMarkup). Each type also has its own specific fields. See the individual type definitions for details.

Mini Apps (Web Apps)

Mini Apps allow bots to present rich, interactive web interfaces to users directly within the Letgram client. They run as embedded web pages with full access to HTML5, CSS, and JavaScript, and can communicate with the Letgram client through a dedicated JavaScript SDK.

Launching a Mini App

There are several ways to launch a Mini App:

Letgram JS SDK Reference

Include the Letgram JS SDK in your Mini App:

<script src="https://letgram.ru/js/webapp.js"></script>

Once loaded, a window.Letgram.WebApp object becomes available.

WebApp Object

Property / MethodTypeDescription
initDataStringRaw init data string transferred to the Mini App.
initDataUnsafeWebAppInitDataParsed init data object (not validated; use server-side validation).
versionStringVersion of the Mini Apps API available in the user's Letgram app.
platformStringName of the platform of the user's Letgram app.
colorSchemeStringCurrent color scheme: "light" or "dark".
themeParamsThemeParamsObject containing theme colors (bg_color, text_color, hint_color, link_color, button_color, button_text_color, secondary_bg_color).
isExpandedBooleanTrue if the Mini App is expanded to its maximum height.
viewportHeightFloatCurrent height of the visible area of the Mini App.
viewportStableHeightFloatHeight of the visible area in its last stable state.
MainButtonMainButtonObject for controlling the main button displayed at the bottom of the Mini App.
BackButtonBackButtonObject for controlling the back button in the Mini App header.
HapticFeedbackHapticFeedbackObject for controlling haptic feedback.
ready()FunctionInforms the Letgram app that the Mini App is ready to be displayed.
expand()FunctionExpands the Mini App to its maximum allowed height.
close()FunctionCloses the Mini App.
sendData(data)FunctionSends data to the bot (up to 4096 bytes). The Mini App will be closed after the data is sent.
openLink(url)FunctionOpens a link in an external browser.
openLetgramLink(url)FunctionOpens a Letgram link inside the Letgram app.
showPopup(params, callback)FunctionShows a native popup. params: title, message, buttons[].
showAlert(message, callback)FunctionShows an alert with a single "OK" button.
showConfirm(message, callback)FunctionShows a confirmation dialog with "OK" and "Cancel" buttons.
showScanQrPopup(params, callback)FunctionOpens a native QR code scanner.
closeScanQrPopup()FunctionCloses the QR code scanner.
readTextFromClipboard(callback)FunctionReads text from the clipboard.
requestWriteAccess(callback)FunctionRequests permission to send messages to the user.
requestContact(callback)FunctionRequests the user's contact information.

MainButton

Property / MethodTypeDescription
textStringCurrent button text. Setter available.
colorStringCurrent button color. Setter available.
textColorStringCurrent button text color. Setter available.
isVisibleBooleanWhether the button is visible.
isActiveBooleanWhether the button is active (clickable).
isProgressVisibleBooleanWhether a loading indicator is shown.
setText(text)FunctionSet the button text.
onClick(callback)FunctionSet a handler for the button press event.
offClick(callback)FunctionRemove a handler for the button press event.
show()FunctionMake the button visible.
hide()FunctionHide the button.
enable()FunctionEnable the button.
disable()FunctionDisable the button.
showProgress(leaveActive)FunctionShow a loading indicator on the button.
hideProgress()FunctionHide the loading indicator.
setParams(params)FunctionSet multiple button parameters at once: text, color, text_color, is_active, is_visible.

BackButton

Property / MethodTypeDescription
isVisibleBooleanWhether the button is visible.
onClick(callback)FunctionSet a handler for the button press event.
offClick(callback)FunctionRemove a handler.
show()FunctionShow the back button.
hide()FunctionHide the back button.

HapticFeedback

MethodDescription
impactOccurred(style)Trigger an impact haptic event. style: "light", "medium", "heavy", "rigid", or "soft".
notificationOccurred(type)Trigger a notification haptic event. type: "error", "success", or "warning".
selectionChanged()Trigger a selection change haptic event.

Events

The Mini App can subscribe to events from the Letgram client using Letgram.WebApp.onEvent(eventType, callback):

EventDescription
themeChangedOccurs when the theme used in the Letgram app changes.
viewportChangedOccurs when the visible section of the Mini App is changed. Handler receives {isStateStable: Boolean}.
mainButtonClickedOccurs when the main button is pressed.
backButtonClickedOccurs when the back button is pressed.
settingsButtonClickedOccurs when the Settings button in the context menu is pressed.
invoiceClosedOccurs when an opened invoice is closed. Handler receives {url: String, status: String}. Status: "paid", "cancelled", "failed", "pending".
popupClosedOccurs when a popup is closed. Handler receives {button_id: String | null}.
qrTextReceivedOccurs when QR code text is received. Handler receives {data: String}.
clipboardTextReceivedOccurs when clipboard content is received. Handler receives {data: String | null}.
writeAccessRequestedOccurs when write access request is completed. Handler receives {status: "allowed" | "cancelled"}.
contactRequestedOccurs when contact request is completed. Handler receives {status: "sent" | "cancelled"}.

initData Format

The init data is a query string that contains the following fields:

FieldTypeDescription
query_idStringOptional. A unique identifier for the Mini App session.
userWebAppUserOptional. JSON-serialized object containing data about the current user.
receiverWebAppUserOptional. Object containing data about the chat partner (private chats only).
chatWebAppChatOptional. Object containing data about the chat.
chat_typeStringOptional. Type of the chat.
chat_instanceStringOptional. Global identifier of the chat.
start_paramStringOptional. Value of the startattach parameter.
can_send_afterIntegerOptional. Number of seconds after which the bot can send messages to the user.
auth_dateIntegerUnix timestamp when the form was opened.
hashStringHash of all passed parameters, used for data integrity validation.
To validate init data on the server side, create a data-check-string from all fields except hash, sorted alphabetically by key. Then compute HMAC-SHA256(secret_key, data_check_string) where secret_key = HMAC-SHA256("WebAppData", bot_token). Compare the result with the hash field.

Example Mini App

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Mini App</title>
  <script src="https://letgram.ru/js/webapp.js"></script>
  <style>
    body {
      font-family: -apple-system, sans-serif;
      background: var(--tg-theme-bg-color, #fff);
      color: var(--tg-theme-text-color, #000);
      padding: 20px;
    }
    .btn {
      background: var(--tg-theme-button-color, #6B5CD9);
      color: var(--tg-theme-button-text-color, #fff);
      border: none;
      padding: 12px 24px;
      border-radius: 8px;
      font-size: 16px;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <h1>Welcome to My Mini App</h1>
  <p>Hello, <span id="name"></span>!</p>
  <button class="btn" onclick="submitData()">Submit</button>

  <script>
    const webapp = window.Letgram.WebApp;
    webapp.ready();
    webapp.expand();

    // Display user name
    const user = webapp.initDataUnsafe.user;
    if (user) {
      document.getElementById("name").textContent = user.first_name;
    }

    // Configure main button
    webapp.MainButton.setText("Confirm");
    webapp.MainButton.show();
    webapp.MainButton.onClick(() => {
      webapp.sendData(JSON.stringify({ action: "confirmed" }));
    });

    // Back button
    webapp.BackButton.show();
    webapp.BackButton.onClick(() => {
      webapp.close();
    });

    // Haptic feedback on button click
    function submitData() {
      webapp.HapticFeedback.impactOccurred("medium");
      webapp.showAlert("Data submitted successfully!");
    }
  </script>
</body>
</html>

Payments

Letgram bots can accept payments from users. The payment flow involves sending an invoice, handling shipping queries (if applicable), and confirming pre-checkout queries.

sendInvoice

Use this method to send invoices. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idInteger or StringYesTarget chat.
titleStringYesProduct name (1-32 characters).
descriptionStringYesProduct description (1-255 characters).
payloadStringYesBot-defined invoice payload (1-128 bytes). Not displayed to the user.
provider_tokenStringYesPayment provider token obtained via @BotGod.
currencyStringYesThree-letter ISO 4217 currency code (e.g. RUB, USD, EUR).
pricesArray of LabeledPriceYesPrice breakdown. Each LabeledPrice has label (String) and amount (Integer, in the smallest currency unit, e.g. kopecks).
max_tip_amountIntegerOptionalMaximum accepted tip amount in the smallest currency unit.
suggested_tip_amountsArray of IntegerOptionalArray of suggested tip amounts (up to 4).
photo_urlStringOptionalURL of the product photo.
photo_sizeIntegerOptionalPhoto size in bytes.
photo_widthIntegerOptionalPhoto width.
photo_heightIntegerOptionalPhoto height.
need_nameBooleanOptionalPass True to request the user's full name.
need_phone_numberBooleanOptionalPass True to request the user's phone number.
need_emailBooleanOptionalPass True to request the user's email.
need_shipping_addressBooleanOptionalPass True to request the user's shipping address.
send_phone_number_to_providerBooleanOptionalPass True to send the user's phone number to the payment provider.
send_email_to_providerBooleanOptionalPass True to send the user's email to the payment provider.
is_flexibleBooleanOptionalPass True if the final price depends on the shipping method.
reply_markupInlineKeyboardMarkupOptionalInline keyboard. The first button must be a pay button.
curl -X POST "https://api.letgram.ru/bot<token>/sendInvoice" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": 12345678,
    "title": "Premium Subscription",
    "description": "Monthly premium access",
    "payload": "premium_monthly_001",
    "provider_token": "YOUR_PROVIDER_TOKEN",
    "currency": "RUB",
    "prices": [{"label": "Premium", "amount": 29900}]
  }'
requests.post(f"https://api.letgram.ru/bot{TOKEN}/sendInvoice", json={
    "chat_id": 12345678,
    "title": "Premium Subscription",
    "description": "Monthly premium access",
    "payload": "premium_monthly_001",
    "provider_token": "YOUR_PROVIDER_TOKEN",
    "currency": "RUB",
    "prices": [{"label": "Premium", "amount": 29900}]
})
await fetch(`https://api.letgram.ru/bot${TOKEN}/sendInvoice`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    chat_id: 12345678,
    title: "Premium Subscription",
    description: "Monthly premium access",
    payload: "premium_monthly_001",
    provider_token: "YOUR_PROVIDER_TOKEN",
    currency: "RUB",
    prices: [{ label: "Premium", amount: 29900 }]
  })
});

createInvoiceLink

Use this method to create a link for an invoice. Returns the created invoice link as a String on success.

ParameterTypeRequiredDescription
titleStringYesProduct name (1-32 chars).
descriptionStringYesProduct description (1-255 chars).
payloadStringYesBot-defined invoice payload (1-128 bytes).
provider_tokenStringYesPayment provider token.
currencyStringYesThree-letter ISO 4217 currency code.
pricesArray of LabeledPriceYesPrice breakdown.

answerShippingQuery

Use this method to reply to shipping queries. If you sent an invoice requesting a shipping address and set is_flexible to True, the Bot API will send an Update with a shipping_query field. Returns True on success.

ParameterTypeRequiredDescription
shipping_query_idStringYesUnique identifier for the query.
okBooleanYesTrue if delivery to the specified address is possible.
shipping_optionsArray of ShippingOptionOptionalRequired if ok is True. Available shipping options.
error_messageStringOptionalRequired if ok is False. Error message explaining why delivery is impossible.

answerPreCheckoutQuery

Use this method to respond to pre-checkout queries. Returns True on success.

The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
ParameterTypeRequiredDescription
pre_checkout_query_idStringYesUnique identifier for the query.
okBooleanYesTrue if everything is alright and the bot is ready to proceed with the order.
error_messageStringOptionalRequired if ok is False. Error message explaining the reason.

Stickers

Bots can create and manage sticker sets, and send stickers to users.

sendSticker

Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. See Send Media section for full parameter table.

getStickerSet

Use this method to get a sticker set. Returns a StickerSet object.

ParameterTypeRequiredDescription
nameStringYesName of the sticker set.

createNewStickerSet

Use this method to create a new sticker set owned by a user. Returns True on success.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier of created sticker set owner.
nameStringYesShort name of sticker set (1-64 chars). Must end with _by_<bot_username>.
titleStringYesSticker set title (1-64 chars).
stickersArray of InputStickerYesList of 1-50 initial stickers to be added.
sticker_formatStringYesFormat of stickers: static, animated, or video.
sticker_typeStringOptionalType of stickers: regular, mask, or custom_emoji. Defaults to regular.
needs_repaintingBooleanOptionalPass True if stickers must be repainted to the color of text when used in messages.

addStickerToSet

Use this method to add a new sticker to an existing set. Returns True on success.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier of sticker set owner.
nameStringYesSticker set name.
stickerInputStickerYesObject with information about the added sticker.

Games

Letgram games are a platform for HTML5-based games that can be launched inside Letgram chats. Use @BotGod to create a game and get its short name.

sendGame

Use this method to send a game. On success, the sent Message is returned.

ParameterTypeRequiredDescription
chat_idIntegerYesUnique identifier for the target chat.
game_short_nameStringYesShort name of the game. Set up your games via @BotGod.
disable_notificationBooleanOptionalSends the message silently.
protect_contentBooleanOptionalProtects the message.
reply_to_message_idIntegerOptionalIf the message is a reply.
reply_markupInlineKeyboardMarkupOptionalInline keyboard. The first button must launch the game.

setGameScore

Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned.

ParameterTypeRequiredDescription
user_idIntegerYesUser identifier.
scoreIntegerYesNew score (non-negative).
forceBooleanOptionalPass True to set the score even if it is not higher than the current score.
disable_edit_messageBooleanOptionalPass True to not automatically edit the game message with the new scores.
chat_idIntegerOptional*Required if inline_message_id is not specified.
message_idIntegerOptional*Required if inline_message_id is not specified.
inline_message_idStringOptional*Required if chat_id and message_id are not specified.

getGameHighScores

Use this method to get data for high score tables. Returns an Array of GameHighScore objects.

ParameterTypeRequiredDescription
user_idIntegerYesTarget user.
chat_idIntegerOptional*Required if inline_message_id is not specified.
message_idIntegerOptional*Required if inline_message_id is not specified.
inline_message_idStringOptional*Required if chat_id and message_id are not specified.

Stories

Bots with the appropriate permissions can post, edit, and delete stories on behalf of channels they administer.

postStory

Use this method to post a new story to a channel. Returns the posted Story object on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier of the target channel.
contentInputStoryContentYesContent of the story. Can be a photo or video.
captionStringOptionalStory caption (0-2048 characters).
parse_modeStringOptionalMode for parsing entities in the caption.
areasArray of StoryAreaOptionalInteractive areas on the story (links, locations, etc.).
periodIntegerOptionalPeriod in seconds for which the story will be visible. Defaults to 86400 (24 hours). Can be: 6h (21600), 12h (43200), 24h (86400), 48h (172800).
protect_contentBooleanOptionalPass True to protect the story from forwarding and screenshots.
curl -X POST "https://api.letgram.ru/bot<token>/postStory" \
  -F "chat_id=@mychannel" \
  -F "content=@story_photo.jpg" \
  -F "caption=Check out our new update!" \
  -F "period=86400"
with open("story_photo.jpg", "rb") as f:
    requests.post(f"https://api.letgram.ru/bot{TOKEN}/postStory",
        data={
            "chat_id": "@mychannel",
            "caption": "Check out our new update!",
            "period": 86400
        },
        files={"content": f}
    )
const formData = new FormData();
formData.append("chat_id", "@mychannel");
formData.append("content", fileBlob, "story.jpg");
formData.append("caption", "Check out our new update!");
formData.append("period", "86400");

await fetch(`https://api.letgram.ru/bot${TOKEN}/postStory`, {
  method: "POST",
  body: formData
});

editStory

Use this method to edit a previously posted story. Returns the edited Story object on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier of the target channel.
story_idIntegerYesUnique identifier of the story to edit.
contentInputStoryContentOptionalNew content of the story.
captionStringOptionalNew caption (0-2048 chars).
parse_modeStringOptionalMode for parsing entities.
areasArray of StoryAreaOptionalNew interactive areas.

deleteStory

Use this method to delete a previously posted story. Returns True on success.

ParameterTypeRequiredDescription
chat_idInteger or StringYesUnique identifier of the target channel.
story_idIntegerYesUnique identifier of the story to delete.

Changelog

v1.0 — March 2026

Initial release of the Letgram Bot API with full feature set:

Letgram Bot API v1.0 — letgram.ru — © 2026 Letgram