Movatterモバイル変換


[0]ホーム

URL:


Telegram Mini Apps

WithMini Apps developers can useJavaScript to createinfinitely flexible interfaces that can be launched right inside Telegram — and can completely replaceany website.

Like bots,Mini Apps supportseamless authorization, payments via third-partypayment providers (withGoogle Pay andApple Pay out of the box), delivering tailored push notifications to users, andmuch more.

To see aMini App in action, try our sample@DurgerKingBot.


Recent changes

November 17, 2024

Bot API 8.0

This is thelargest update in the history of Telegram mini apps – adding more than10 new features and monetization options for developers. To read more about all these changes, check out thisdedicated blog post.

Full-screen Mode

  • Mini Apps are now able tobecome full-screen in both portrait andlandscape mode – allowing them to hostmore games, playwidescreen media and supportimmersive user experiences.
  • Added the methodsrequestFullscreen andexitFullscreen to toggle full-screen mode.
  • Added the fieldssafeAreaInset andcontentSafeAreaInset, allowing Mini Apps to ensure that their content properly respects the device's safe area margins.
  • Further added the fieldsisActive andisFullscreen to the classWebApp.
  • Added theeventsactivated,deactivated,safeAreaChanged,contentSafeAreaChanged,fullscreenChanged andfullscreenFailed.

Homescreen Shortcuts

  • Mini Apps can now be accessed viadirect shortcuts added to thehome screen of mobile devices.
  • Added the methodaddToHomeScreen to create a shortcut for users to add to their home screens.
  • Added the methodcheckHomeScreenStatus to determine the status and support of the home screen shortcut for the Mini App on the current device.
  • Added theeventshomeScreenAdded andhomeScreenChecked.

Emoji Status

  • Mini Apps can now prompt users to set theiremoji status – or request access to later sync it automatically with in-game badges, third-party APIs and more.
  • Added the methodsetEmojiStatus to let users manually confirm a custom emoji as their new status via a native dialog.
  • Added the methodrequestEmojiStatusAccess for obtaining permission to later update a user's emoji status via the Bot API methodsetUserEmojiStatus.
  • Added theeventsemojiStatusSet,emojiStatusFailed andemojiStatusAccessRequested.

Media Sharing and File Downloads

  • Users can nowshare media directly from Mini Apps – sendingreferral codes, custom memes, artwork and more toany chat or posting themas a story.
  • Added the methodshareMessage to share media from Mini Apps to Telegram chats. Also seePreparedInlineMessage.
  • Added the methoddownloadFile, introducing support for anative popup that prompts users to download files from the Mini App.
  • Added theeventsshareMessageSent,shareMessageFailed andfileDownloadRequested.

Geolocation Access

  • Mini Apps can now requestgeolocation access to users, allowing them to build virtually any location-based service, fromgames with dynamic points of interest tointeractive maps for events.
  • Added the fieldLocationManager to the classWebApp.
  • Added theeventslocationManagerUpdated andlocationRequested.

Device Motion Tracking

  • Mini Apps can now track detaileddevice motion data, allowing them to implement better productivity tools, immersiveVR experiences and more.
  • Added the fieldsisOrientationLocked,Accelerometer,DeviceOrientation andGyroscope to the classWebApp.
  • Added the methodslockOrientation andunlockOrientation to control the screen orientation.
  • Added theeventsaccelerometerStarted,accelerometerStopped,accelerometerChanged,accelerometerFailed,deviceOrientationStarted,deviceOrientationStopped,deviceOrientationChanged,deviceOrientationFailed,gyroscopeStarted,gyroscopeStopped,gyroscopeChanged,gyroscopeFailed.

Subscription Plans and Gifts for Telegram Stars

  • Mini Apps now supportpaid subscriptions powered byTelegram Starsmonetizing their efforts with multiple tiers of content and features.
  • Mini Apps can use their balance ofTelegram Stars tosend gifts to their users.
  • You can read more on implementing Paid Subscriptions and Gifts in ourBot API documentation.

Loading Screen Customization

  • Mini Apps can customize their loading screen, addingtheir own icon andspecific colors for light and dark themes.
  • You can access these customization settings in@BotFather via/mybots > Select Bot > Bot Settings > Configure Mini App > Enable Mini App

Hardware-specific Optimizations

  • Mini Apps running on Android can now receivebasic information about a device's processing hardware, allowing them tooptimize user experience based on the device's capabilities.
  • This information includes the OS, App and SDK's respective versions as well as the device's model and performance class.

General

  • The fieldphoto_url in the classWebAppUser is now available to all Mini Apps, allowing them to access a user's profile photo if their privacy settings allow for it.
  • Third parties (e.g., Mini App builders, external SDKs etc.) that receive or process data on behalf of Mini Apps are now able tovalidate it without knowing the App'sbot token.
  • Debuggingoptions have been expanded to include full support foriOS devices. You can use these tools to find app-specific issues in your Mini App.

September 6, 2024

Bot API 7.10

  • Added the fieldSecondaryButton to the classWebApp.
  • Added the eventsecondaryButtonClicked.
  • Renamed the classMainButton to the classBottomButton.
  • Added the fieldbottomBarColor and the methodsetBottomBarColor to the classWebApp.
  • Added the fieldbottom_bar_bg_color to the classThemeParams.

July 31, 2024

Bot API 7.8

  • Added the option for bots to set aMain Mini App, which can be previewed and launched directly from a button in the bot's profile or a link.
  • Added the methodshareToStory to the classWebApp.

July 7, 2024

Bot API 7.7

  • Added the fieldisVerticalSwipesEnabled and the methodsenableVerticalSwipes,disableVerticalSwipes to the classWebApp.
  • Added the eventscanQrPopupClosed.

July 1, 2024

Bot API 7.6

March 31, 2024

Bot API 7.2

  • Added the fieldBiometricManager to the classWebApp.

December 29, 2023

Bot API 7.0

  • Added the fieldSettingsButton to the classWebApp.
  • Added the fieldsheader_bg_color,accent_text_color,section_bg_color,section_header_text_color,subtitle_text_color,destructive_text_color to the classThemeParams.
  • Mini Apps no longer close when the methodWebApp.openTelegramLink is called.

September 22, 2023

Bot API 6.9

  • Added the fieldCloudStorage to the classWebApp.
  • Added the methodsrequestWriteAccess andrequestContact to the classWebApp.
  • Added the fieldsadded_to_attachment_menu andallows_write_to_pm to the classWebAppUser.
  • Added the eventswriteAccessRequested andcontactRequested.
  • Added the ability to set any header color using thesetHeaderColor method.

April 21, 2023

Bot API 6.7

  • Added support for launching Mini Apps from inline query results and from a direct link.
  • Added the methodswitchInlineQuery to the classWebApp.

December 30, 2022

Bot API 6.4

  • Added the fieldplatform, the optional parameteroptions to the methodopenLink and the methodsshowScanQrPopup,closeScanQrPopup,readTextFromClipboard to the classWebApp.
  • Added the eventsqrTextReceived,clipboardTextReceived.

August 12, 2022

Bot API 6.2

  • Added the fieldisClosingConfirmationEnabled and the methodsenableClosingConfirmation,disableClosingConfirmation,showPopup,showAlert,showConfirm to the classWebApp.
  • Added the fieldis_premium to the classWebAppUser.
  • Added the eventpopupClosed.

June 20, 2022

Bot API 6.1

  • Added the ability to use bots added to the attachment menu in group, supergroup and channel chats.
  • Added support fort.me links that can be used to select the chat in which the attachment menu with the bot will be opened.
  • Added the fieldsversion,headerColor,backgroundColor,BackButton,HapticFeedback and the methodsisVersionAtLeast,setHeaderColor,setBackgroundColor,openLink,openTelegramLink,openInvoice to the classWebApp.
  • Added the fieldsecondary_bg_color to the classThemeParams.
  • Added the methodoffClick to the classMainButton.
  • Added the fieldschat,can_send_after to the classWebAppInitData.
  • Added theeventsbackButtonClicked,settingsButtonClicked,invoiceClosed.

Designing Mini Apps

Color Schemes

Mini Apps always receive data about the user's currentcolor theme in real time, so you can adjust the appearance of your interfaces to match it. For example, when users switch betweenDay and Night modes or use variouscustom themes.

Jump to technical information

Design Guidelines

Telegram apps are known for being snappy, smooth and following a consistent cross-platform design. Your Mini App should ideally reflect these principles.

  • All elements should be responsive and designed with a mobile-first approach.
  • Interactive elements should mimic the style, behavior, and intent of UI components that already exist.
  • All included animations should be smooth, ideally 60fps.
  • All inputs and images should contain labels for accessibility purposes.
  • The app should deliver a seamless experience by monitoring thedynamic theme-based colors provided by the API and using them accordingly.
  • Ensure that the app’s interface respects thesafe area andcontent safe area to avoid overlapping with control elements, especially when using fullscreen mode.
  • For Android devices, consider the additional information in the User-Agent (seeUser-Agent details) and adjust for the device’s performance class, minimizing animations and visual effects on low-performance devices to ensure smooth performance.

Implementing Mini Apps

Telegram currently supports seven different ways of launching Mini Apps: the main Mini App from aprofile button, from akeyboard button, from aninline button, from thebot menu button, viainline mode, from adirect link – and even from theattachment menu.

Types of buttons

Keyboard Button Mini Apps

TL;DR: Mini Apps launched from aweb_app typekeyboard button can send data back to the bot in aservice message usingTelegram.WebApp.sendData. This makes it possible for the bot to produce a response without communicating with any external servers.

Users can interact with bots usingcustom keyboards,buttons under bot messages, as well as by sending freeformtext messages or any of theattachment types supported by Telegram: photos and videos, files, locations, contacts and polls. For even more flexibility, bots can utilize the full power ofHTML5 to create user-friendly input interfaces.

You can send aweb_app typeKeyboardButton that opens a Mini App from the specified URL.

To transmit data from the user back to the bot, the Mini App can call theTelegram.WebApp.sendData method. Data will be transmitted to the bot as a String in a service message. The bot can continue communicating with the user after receiving it.

Good for:

  • Сustom data input interfaces (a personalized calendar for selecting dates; selecting data from a list with advanced search options; a randomizer that lets the user “spin a wheel” and chooses one of the available options, etc.)
  • Reusable components that do not depend on a particular bot.

Inline Button Mini Apps

TL;DR: For more interactive Mini Apps like@DurgerKingBot, use aweb_app typeInline KeyboardButton, which gets basic user information and can be used to send a message on behalf of the user to the chat with the bot.

If receiving text data alone is insufficient or you need a more advanced and personalized interface, you can open a Mini App using aweb_app typeInline KeyboardButton.

From the button, a Mini App will open with the URL specified in the button. In addition to the user'stheme settings, it will receive basic user information (ID,name,username,language_code) and a unique identifier for the session,query_id, which allows messages on behalf of the user to be sent back to the bot.

The bot can call the Bot API methodanswerWebAppQuery to send an inline message from the user back to the bot and close the Mini App. After receiving the message, the bot can continue communicating with the user.

Good for:

  • Fully-fledged web services and integrations of any kind.
  • The use cases are effectivelyunlimited.

Launching Mini Apps from the Menu Button

TL;DR: Mini Apps can be launched from a customized menu button. This simply offers a quicker way to access the app and is otherwiseidentical tolaunching a mini app from an inline button.

By default, chats with bots always show a convenientmenu button that provides quick access to all listedcommands. WithBot API 6.0, this button can be used tolaunch a Mini App instead.

To configure the menu button, you must specify the text it should show and the Mini App URL. There are two ways to set these parameters:

  • To customize the button forall users, use@BotFather (the/setmenubutton command orBot Settings > Menu Button).
  • To customize the button for bothall users andspecific users, use thesetChatMenuButton method in the Bot API. For example, change the button text according to the user's language, or show links to different Mini Apps based on a user's settings in your bot.

Apart from this, Mini Apps opened via the menu button work in the exact same way as whenusing inline buttons.

@DurgerKingBot allows launching its Mini App both from an inline button and from the menu button.

Launching the main Mini App

TL;DR: If your bot is a mini app, you can add a prominentLaunch app button as well as high-quality demo videos and screenshots to the bot’s profile. To do this, go to@BotFather and set up your bot'sMain Mini App.

If your bot is a mini app, you can unlock a number of features that streamline and simplify the way in which users view and interact with it. To do this, go to@BotFather and set up your bot'sMain Mini App.

After setting a main mini app, you'll be able to upload detailedmedia preview demos to publicly highlight your app's key features on its profile. ALaunch app button will also appear, allowing users to open your app directly from its profile. Bots that enabled a main mini app will be displayed in theApps tab of the search for users who have launched them.

Media previews supportmultiple languages – so you can uploadtranslated versions of your previews that will be shown to users based on theirapp language.

A bot'smain Mini App can also be opened in the current chat by direct link in the formathttps://t.me/botusername?startapp. If a non-emptystartapp parameter is included in the link, it will be passed to the Mini App in thestart_param field and in the GET parametertgWebAppStartParam.

Examples

https://t.me/botusername?startapp
https://t.me/botusername?startapp=command
https://t.me/botusername?startapp=command&mode=compact

In this mode, Mini Apps can use thechat_type andchat_instance parameters to keep track of the current chat context. This introduces support forconcurrent andshared usage by multiple chat members – to create live whiteboards, group orders, multiplayer games and similar apps.

By default, the main Mini App opens to full-screen height, and users cannot reduce them to half-height. However, you can change this behavior via@BotFather or by including the parametermode=compact in the link to the Mini App, in which case it will open to half-screen height by default.

Good for:

  • Fully-fledged web services and integrations that any user can open in one tap.
  • Cooperative, multiplayer or teamwork-oriented services within a chat context.
  • The use cases are effectivelyunlimited.

Successful bots whichenable a main Mini App andaccept payments inTelegram Stars may be featured in the TelegramMini App Store. To increase the chances of being featured, we recommend uploading high-quality media showcasing your app on your bot's profile and following ourdesign guidelines.

Inline Mode Mini Apps

TL;DR: Mini Apps launched viaweb_app typeInlineQueryResultsButton can be used anywhere in inline mode. Users can create content in a web interface and then seamlessly send it to the current chat via inline mode.

You can use thebutton parameter in theanswerInlineQuery method to display a special 'Switch to Mini App' button either above or in place of the inline results. This button willopen a Mini App from the specified URL. Once done, you can call theTelegram.WebApp.switchInlineQuery method to send the user back to inline mode.

Inline Mini Apps haveno access to the chat – they can't read messages or send new ones on behalf of the user. To send messages, the user must be redirected toinline mode and actively pick a result.

Good for:

  • Fully-fledged web services and integrations in inline mode.

Direct Link Mini Apps

TL;DR: Mini App Bots can be launched from a direct link in any chat. They support astartapp parameter and are aware of the current chat context.

You can use direct links toopen a Mini App directly in the current chat. If a non-emptystartapp parameter is included in the link, it will be passed to the Mini App in thestart_param field and in the GET parametertgWebAppStartParam.

In this mode, Mini Apps can use thechat_type andchat_instance parameters to keep track of the current chat context. This introduces support forconcurrent andshared usage by multiple chat members – to create live whiteboards, group orders, multiplayer games and similar apps.

Mini Apps opened from a direct link haveno access to the chat – they can't read messages or send new ones on behalf of the user. To send messages, the user must be redirected toinline mode and actively pick a result.

Starting fromBot API 7.6, by default, Mini Apps of this type open to full-screen height, and users cannot reduce them to half-height. However, you can change this behavior by including the parametermode=compact in the link to the Mini App, in which case it will open to half-screen height by default.

Examples

https://t.me/botusername/appname
https://t.me/botusername/appname?startapp=command
https://t.me/botusername/appname?startapp=command&mode=compact

Good for:

  • Fully-fledged web services and integrations that any user can open in one tap.
  • Cooperative, multiplayer or teamwork-oriented services within a chat context.
  • The use cases are effectivelyunlimited.

Launching Mini Apps from the Attachment Menu

TL;DR: Mini App Bots can request to be added directly to a user's attachment menu, allowing them to be quickly launched from any chat. To try this mode, open thisattachment menu link for@DurgerKingBot, then use theAttach menu inany type of chat.

Mini App Bots can request to be added directly to a user's attachment menu, allowing them to be quickly launched fromany type of chat. You can configure in which types of chats your mini app can be started from the attachment menu (private, groups, supergroups or channels).

Attachment menu integration is currently only available for major advertisers on theTelegram Ad Platform. However,all bots can use it in thetest server environment.

To enable this feature for your bot, open@BotFatherfrom an account on the test server and send the/setattach command – or go toBot Settings > Configure Attachment Menu. Then specify the URL that will be opened to launch the bot's Mini App via its icon in the attachment menu.

You can add a 'Settings' item to the context menu of your Mini App using@BotFather. When users select this option from the menu, your bot will receive asettingsButtonClicked event.

In addition to the user'stheme settings, the bot will receive basic user information (ID,name,username,language_code,photo), as well as public info about the chat partner (ID,name,username,photo) or the chat info (ID,type,title,username,photo) and a unique identifier for the web view sessionquery_id, which allows messages of any type to be sent to the chat on behalf of the user that opened the bot.

The bot can call the Bot API methodanswerWebAppQuery, which sends an inline message from the user via the bot to the chat where it was launched and closes the Mini App.

You can read more about adding bots to the attachment menuhere.


Initializing Mini Apps

To connect your Mini App to the Telegram client, place the scripttelegram-web-app.js in the<head> tag before any other scripts, using this code:

<script src="https://telegram.org/js/telegram-web-app.js?56"></script>

Once the script is connected, awindow.Telegram.WebApp object will become available with the following fields:

FieldTypeDescription
initDataStringA string with raw data transferred to the Mini App, convenient forvalidating data.
WARNING:Validate data from this field before using it on the bot's server.
initDataUnsafeWebAppInitDataAn object with input data transferred to the Mini App.
WARNING: Data from this field should not be trusted. You should only use data frominitData on the bot's server and only after it has beenvalidated.
versionStringThe version of the Bot API available in the user's Telegram app.
platformStringThe name of the platform of the user's Telegram app.
colorSchemeStringThe color scheme currently used in the Telegram app. Either “light” or “dark”.
Also available as the CSS variablevar(--tg-color-scheme).
themeParamsThemeParamsAn object containing the current theme settings used in the Telegram app.
isActiveNEWBooleanBot API 8.0+True, if the Mini App is currently active.False, if the Mini App is minimized.
isExpandedBooleanTrue, if the Mini App is expanded to the maximum available height. False, if the Mini App occupies part of the screen and can be expanded to the full height using theexpand() method.
viewportHeightFloatThe current height of the visible area of the Mini App. Also available in CSS as the variablevar(--tg-viewport-height).

The application can display just the top part of the Mini App, with its lower part remaining outside the screen area. From this position, the user can “pull” the Mini App to its maximum height, while the bot can do the same by calling theexpand() method. As the position of the Mini App changes, the current height value of the visible area will be updated in real time.

Please note that the refresh rate of this value is not sufficient to smoothly follow the lower border of the window. It should not be used to pin interface elements to the bottom of the visible area. It's more appropriate to use the value of theviewportStableHeight field for this purpose.
viewportStableHeightFloatThe height of the visible area of the Mini App in its last stable state. Also available in CSS as a variablevar(--tg-viewport-stable-height).

The application can display just the top part of the Mini App, with its lower part remaining outside the screen area. From this position, the user can “pull” the Mini App to its maximum height, while the bot can do the same by calling theexpand() method. Unlike the value ofviewportHeight, the value ofviewportStableHeight does not change as the position of the Mini App changes with user gestures or during animations. The value ofviewportStableHeight will be updated after all gestures and animations are completed and the Mini App reaches its final size.

Note theeventviewportChanged with the passed parameterisStateStable=true, which will allow you to track when the stable state of the height of the visible area changes.
headerColorStringCurrent header color in the#RRGGBB format.
backgroundColorStringCurrent background color in the#RRGGBB format.
bottomBarColorStringCurrent bottom bar color in the#RRGGBB format.
isClosingConfirmationEnabledBooleanTrue, if the confirmation dialog is enabled while the user is trying to close the Mini App.False, if the confirmation dialog is disabled.
isVerticalSwipesEnabledBooleanTrue, if vertical swipes to close or minimize the Mini App are enabled.False, if vertical swipes to close or minimize the Mini App are disabled. In any case, the user will still be able to minimize and close the Mini App by swiping the Mini App's header.
isFullscreenNEWBooleanTrue, if the Mini App is currently being displayed in fullscreen mode.
isOrientationLockedNEWBooleanTrue, if the Mini App’s orientation is currently locked.False, if orientation changes freely based on the device’s rotation.
safeAreaInsetNEWSafeAreaInsetAn object representing the device's safe area insets, accounting for system UI elements like notches or navigation bars.
contentSafeAreaInsetNEWContentSafeAreaInsetAn object representing the safe area for displaying content within the app, free from overlapping Telegram UI elements.
BackButtonBackButtonAn object for controlling the back button which can be displayed in the header of the Mini App in the Telegram interface.
MainButtonBottomButtonAn object for controlling the main button, which is displayed at the bottom of the Mini App in the Telegram interface.
SecondaryButtonBottomButtonAn object for controlling the secondary button, which is displayed at the bottom of the Mini App in the Telegram interface.
SettingsButtonSettingsButtonAn object for controlling the Settings item in the context menu of the Mini App in the Telegram interface.
HapticFeedbackHapticFeedbackAn object for controlling haptic feedback.
CloudStorageCloudStorageAn object for controlling cloud storage.
BiometricManagerBiometricManagerAn object for controlling biometrics on the device.
AccelerometerNEWAccelerometerAn object for accessing accelerometer data on the device.
DeviceOrientationNEWDeviceOrientationAn object for accessing device orientation data on the device.
GyroscopeNEWGyroscopeAn object for accessing gyroscope data on the device.
LocationManagerNEWLocationManagerAn object for controlling location on the device.
isVersionAtLeast(version)FunctionReturns true if the user's app supports a version of the Bot API that is equal to or higher than the version passed as the parameter.
setHeaderColor(color)FunctionBot API 6.1+ A method that sets the app header color in the#RRGGBB format. You can also use keywordsbg_color andsecondary_bg_color.

Up toBot API 6.9 You can only passTelegram.WebApp.themeParams.bg_color orTelegram.WebApp.themeParams.secondary_bg_color as a color orbg_color,secondary_bg_color keywords.
setBackgroundColor(color)FunctionBot API 6.1+ A method that sets the app background color in the#RRGGBB format. You can also use keywordsbg_color andsecondary_bg_color.
setBottomBarColor(color)FunctionBot API 7.10+ A method that sets the app's bottom bar color in the#RRGGBB format. You can also use the keywordsbg_color,secondary_bg_color, andbottom_bar_bg_color. This color is also applied to the navigation bar on Android.
enableClosingConfirmation()FunctionBot API 6.2+ A method that enables a confirmation dialog while the user is trying to close the Mini App.
disableClosingConfirmation()FunctionBot API 6.2+ A method that disables the confirmation dialog while the user is trying to close the Mini App.
enableVerticalSwipes()FunctionBot API 7.7+ A method that enables vertical swipes to close or minimize the Mini App. For user convenience, it is recommended to always enable swipes unless they conflict with the Mini App's own gestures.
disableVerticalSwipes()FunctionBot API 7.7+ A method that disables vertical swipes to close or minimize the Mini App. This method is useful if your Mini App uses swipe gestures that may conflict with the gestures for minimizing and closing the app.
requestFullscreen()NEWFunctionBot API 8.0+ A method that requests opening the Mini App in fullscreen mode. Although the header is transparent in fullscreen mode, it is recommended that the Mini App sets the header color using thesetHeaderColor method. This color helps determine a contrasting color for the status bar and other UI controls.
exitFullscreen()NEWFunctionBot API 8.0+ A method that requests exiting fullscreen mode.
lockOrientation()NEWFunctionBot API 8.0+ A method that locks the Mini App’s orientation to its current mode (either portrait or landscape). Once locked, the orientation remains fixed, regardless of device rotation. This is useful if a stable orientation is needed during specific interactions.
unlockOrientation()NEWFunctionBot API 8.0+ A method that unlocks the Mini App’s orientation, allowing it to follow the device's rotation freely. Use this to restore automatic orientation adjustments based on the device orientation.
addToHomeScreen()NEWFunctionBot API 8.0+ A method that prompts the user to add the Mini App to the home screen. After successfully adding the icon, thehomeScreenAdded event will be triggered if supported by the device. Note that if the device cannot determine the installation status, the event may not be received even if the icon has been added.
checkHomeScreenStatus([callback])NEWFunctionBot API 8.0+ A method that checks if adding to the home screen is supported and if the Mini App has already been added. If an optionalcallback parameter is provided, thecallback function will be called with a single argumentstatus, which is a string indicating the home screen status. Possible values forstatus are:
-unsupported – the feature is not supported, and it is not possible to add the icon to the home screen,
-unknown – the feature is supported, and the icon can be added, but it is not possible to determine if the icon has already been added,
-added – the icon has already been added to the home screen,
-missed – the icon has not been added to the home screen.
onEvent(eventType, eventHandler)FunctionA method that sets the app event handler. Checkthe list of available events.
offEvent(eventType, eventHandler)FunctionA method that deletes a previously set event handler.
sendData(data)FunctionA method used to send data to the bot. When this method is called, a service message is sent to the bot containing the datadata of the length up to 4096 bytes, and the Mini App is closed. See the fieldweb_app_data in the classMessage.

This method is only available for Mini Apps launched via aKeyboard button.
switchInlineQuery(query[, choose_chat_types])FunctionBot API 6.7+ A method that inserts the bot's username and the specified inlinequery in the current chat's input field. Query may be empty, in which case only the bot's username will be inserted. If an optionalchoose_chat_types parameter was passed, the client prompts the user to choose a specific chat, then opens that chat and inserts the bot's username and the specified inline query in the input field. You can specify which types of chats the user will be able to choose from. It can be one or more of the following types:users,bots,groups,channels.
openLink(url[, options])FunctionA method that opens a link in an external browser. The Mini App willnot be closed.
Bot API 6.4+ If the optionaloptions parameter is passed with the fieldtry_instant_view=true, the link will be opened inInstant View mode if possible.

Note that this method can be called only in response to user interaction with the Mini App interface (e.g. a click inside the Mini App or on the main button)
openTelegramLink(url)FunctionA method that opens a telegram link inside the Telegram app. The Mini App willnot be closed after this method is called.

Up toBot API 7.0 The Mini Appwill be closed after this method is called.
openInvoice(url[, callback])FunctionBot API 6.1+ A method that opens an invoice using the linkurl. The Mini App will receive theeventinvoiceClosed when the invoice is closed. If an optionalcallback parameter was passed, thecallback function will be called and the invoice status will be passed as the first argument.
shareToStory(media_url[, params])FunctionBot API 7.8+ A method that opens the native story editor with the media specified in themedia_url parameter as an HTTPS URL. An optionalparams argument of the typeStoryShareParams describes additional sharing settings.
shareMessage(msg_id[, callback])NEWFunctionBot API 8.0+ A method that opens a dialog allowing the user to share a message provided by the bot. If an optionalcallback parameter is provided, thecallback function will be called with a boolean as the first argument, indicating whether the message was successfully sent. The message id passed to this method must belong to aPreparedInlineMessage previously obtained via the Bot API methodsavePreparedInlineMessage.
setEmojiStatus(custom_emoji_id[, params, callback])FunctionBot API 8.0+ A method that opens a dialog allowing the user to set the specified custom emoji as their status. An optionalparams argument of typeEmojiStatusParams specifies additional settings, such as duration. If an optionalcallback parameter is provided, thecallback function will be called with a boolean as the first argument, indicating whether the status was set.

Note: this method opens a native dialog and cannot be used to set the emoji status without manual user interaction. For fully programmatic changes, you should instead use the Bot API methodsetUserEmojiStatus after obtaining authorization to do so via the Mini App method requestEmojiStatusAccess.
requestEmojiStatusAccess([callback])NEWFunctionBot API 8.0+ A method that shows a native popup requesting permission for the bot to manage user's emoji status. If an optionalcallback parameter was passed, thecallback function will be called when the popup is closed and the first argument will be a boolean indicating whether the user granted this access.
downloadFile(params[, callback])NEWFunctionBot API 8.0+ A method that displays a native popup prompting the user to download a file specified by theparams argument of typeDownloadFileParams. If an optionalcallback parameter is provided, thecallback function will be called when the popup is closed, with the first argument as a boolean indicating whether the user accepted the download request.
showPopup(params[, callback])FunctionBot API 6.2+ A method that shows a native popup described by theparams argument of the typePopupParams. The Mini App will receive theeventpopupClosed when the popup is closed. If an optionalcallback parameter was passed, thecallback function will be called and the fieldid of the pressed button will be passed as the first argument.
showAlert(message[, callback])FunctionBot API 6.2+ A method that showsmessage in a simple alert with a 'Close' button. If an optionalcallback parameter was passed, thecallback function will be called when the popup is closed.
showConfirm(message[, callback])FunctionBot API 6.2+ A method that showsmessage in a simple confirmation window with 'OK' and 'Cancel' buttons. If an optionalcallback parameter was passed, thecallback function will be called when the popup is closed and the first argument will be a boolean indicating whether the user pressed the 'OK' button.
showScanQrPopup(params[, callback])FunctionBot API 6.4+ A method that shows a native popup for scanning a QR code described by theparams argument of the typeScanQrPopupParams. The Mini App will receive theeventqrTextReceived every time the scanner catches a code with text data. If an optionalcallback parameter was passed, thecallback function will be called and the text from the QR code will be passed as the first argument. Returningtrue inside this callback function causes the popup to be closed. Starting fromBot API 7.7, the Mini App will receive thescanQrPopupClosed event if the user closes the native popup for scanning a QR code.
closeScanQrPopup()FunctionBot API 6.4+ A method that closes the native popup for scanning a QR code opened with theshowScanQrPopup method. Run it if you received valid data in theeventqrTextReceived.
readTextFromClipboard([callback])FunctionBot API 6.4+ A method that requests text from the clipboard. The Mini App will receive theeventclipboardTextReceived. If an optionalcallback parameter was passed, thecallback function will be called and the text from the clipboard will be passed as the first argument.

Note: this method can be called only for Mini Apps launched from the attachment menu and only in response to a user interaction with the Mini App interface (e.g. a click inside the Mini App or on the main button).
requestWriteAccess([callback])FunctionBot API 6.9+ A method that shows a native popup requesting permission for the bot to send messages to the user. If an optionalcallback parameter was passed, thecallback function will be called when the popup is closed and the first argument will be a boolean indicating whether the user granted this access.
requestContact([callback])FunctionBot API 6.9+ A method that shows a native popup prompting the user for their phone number. If an optionalcallback parameter was passed, thecallback function will be called when the popup is closed and the first argument will be a boolean indicating whether the user shared its phone number.
ready()FunctionA method that informs the Telegram app that the Mini App is ready to be displayed.
It is recommended to call this method as early as possible, as soon as all essential interface elements are loaded. Once this method is called, the loading placeholder is hidden and the Mini App is shown.
If the method is not called, the placeholder will be hidden only when the page is fully loaded.
expand()FunctionA method that expands the Mini App to the maximum available height. To find out if the Mini App is expanded to the maximum height, refer to the value of theTelegram.WebApp.isExpanded parameter
close()FunctionA method that closes the Mini App.

ThemeParams

Mini Apps canadjust the appearance of the interface to match the Telegram user's app in real time. This object contains the user's current theme settings:

FieldTypeDescription
bg_colorStringOptional. Background color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-bg-color).
text_colorStringOptional. Main text color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-text-color).
hint_colorStringOptional. Hint text color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-hint-color).
link_colorStringOptional. Link color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-link-color).
button_colorStringOptional. Button color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-button-color).
button_text_colorStringOptional. Button text color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-button-text-color).
secondary_bg_colorStringOptional.Bot API 6.1+ Secondary background color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-secondary-bg-color).
header_bg_colorStringOptional.Bot API 7.0+ Header background color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-header-bg-color).
bottom_bar_bg_colorStringOptional.Bot API 7.10+ Bottom background color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-bottom-bar-bg-color).
accent_text_colorStringOptional.Bot API 7.0+ Accent text color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-accent-text-color).
section_bg_colorStringOptional.Bot API 7.0+ Background color for the section in the#RRGGBB format. It is recommended to use this in conjunction withsecondary_bg_color.
Also available as the CSS variablevar(--tg-theme-section-bg-color).
section_header_text_colorStringOptional.Bot API 7.0+ Header text color for the section in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-section-header-text-color).
section_separator_colorStringOptional.Bot API 7.6+ Section separator color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-section-separator-color).
subtitle_text_colorStringOptional.Bot API 7.0+ Subtitle text color in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-subtitle-text-color).
destructive_text_colorStringOptional.Bot API 7.0+ Text color for destructive actions in the#RRGGBB format.
Also available as the CSS variablevar(--tg-theme-destructive-text-color).

StoryShareParams

This object describes additional sharing settings for the native story editor.

FieldTypeDescription
textStringOptional. The caption to be added to the media, 0-200 characters for regular users and 0-2048 characters forpremium subscribers.
widget_linkStoryWidgetLinkOptional. An object that describes a widget link to be included in the story. Note that onlypremium subscribers can post stories with links.

StoryWidgetLink

This object describes a widget link to be included in the story.

FieldTypeDescription
urlStringThe URL to be included in the story.
nameStringOptional. The name to be displayed for the widget link, 0-48 characters.

ScanQrPopupParams

This object describes the native popup for scanning QR codes.

FieldTypeDescription
textStringOptional. The text to be displayed under the 'Scan QR' heading, 0-64 characters.

PopupParams

This object describes the native popup.

FieldTypeDescription
titleStringOptional. The text to be displayed in the popup title, 0-64 characters.
messageStringThe message to be displayed in the body of the popup, 1-256 characters.
buttonsArray ofPopupButtonOptional. List of buttons to be displayed in the popup, 1-3 buttons. Set to[{“type”:“close”}] by default.

PopupButton

This object describes the native popup button.

FieldTypeDescription
idStringOptional. Identifier of the button, 0-64 characters. Set to empty string by default.
If the button is pressed, itsid is returned in the callback and thepopupClosed event.
typeStringOptional. Type of the button. Set todefault by default.
Can be one of these values:
-default, a button with the default style,
-ok, a button with the localized text “OK”,
-close, a button with the localized text “Close”,
-cancel, a button with the localized text “Cancel”,
-destructive, a button with a style that indicates a destructive action (e.g. “Remove”, “Delete”, etc.).
textStringOptional. The text to be displayed on the button, 0-64 characters. Required iftype isdefault ordestructive. Irrelevant for other types.

EmojiStatusParams

This object describes additional settings for setting an emoji status.

FieldTypeDescription
durationIntegerOptional. The duration for which the status will remain set, in seconds.

DownloadFileParams

This object describes the parameters for the file download request.

Note: To ensure consistent file download behavior across platforms, it is recommended to include the HTTP headerContent-Disposition: attachment; filename="<file_name>" in the server response. This header helps prompt the download action and suggests a file name for the downloaded file, especially on web platforms where forced downloads cannot always be guaranteed.

FieldTypeDescription
urlStringThe HTTPS URL of the file to be downloaded.
file_nameStringThe suggested name for the downloaded file.

SafeAreaInset

This object represents the system-defined safe area insets, providing padding values to ensure content remains within visible boundaries, avoiding overlap with system UI elements like notches or navigation bars.

FieldTypeDescription
topIntegerThe top inset in pixels, representing the space to avoid at the top of the screen. Also available as the CSS variablevar(--tg-safe-area-inset-top).
bottomIntegerThe bottom inset in pixels, representing the space to avoid at the bottom of the screen. Also available as the CSS variablevar(--tg-safe-area-inset-bottom).
leftIntegerThe left inset in pixels, representing the space to avoid on the left side of the screen. Also available as the CSS variablevar(--tg-safe-area-inset-left).
rightIntegerThe right inset in pixels, representing the space to avoid on the right side of the screen. Also available as the CSS variablevar(--tg-safe-area-inset-right).

ContentSafeAreaInset

This object represents the content-defined safe area insets, providing padding values to ensure content remains within visible boundaries, avoiding overlap with Telegram UI elements.

FieldTypeDescription
topIntegerThe top inset in pixels, representing the space to avoid at the top of the content area. Also available as the CSS variablevar(--tg-content-safe-area-inset-top).
bottomIntegerThe bottom inset in pixels, representing the space to avoid at the bottom of the content area. Also available as the CSS variablevar(--tg-content-safe-area-inset-bottom).
leftIntegerThe left inset in pixels, representing the space to avoid on the left side of the content area. Also available as the CSS variablevar(--tg-content-safe-area-inset-left).
rightIntegerThe right inset in pixels, representing the space to avoid on the right side of the content area. Also available as the CSS variablevar(--tg-content-safe-area-inset-right).

BackButton

This object controls theback button, which can be displayed in the header of the Mini App in the Telegram interface.

FieldTypeDescription
isVisibleBooleanShows whether the button is visible. Set tofalse by default.
onClick(callback)FunctionBot API 6.1+ A method that sets the button press event handler. An alias forTelegram.WebApp.onEvent('backButtonClicked', callback)
offClick(callback)FunctionBot API 6.1+ A method that removes the button press event handler. An alias forTelegram.WebApp.offEvent('backButtonClicked', callback)
show()FunctionBot API 6.1+ A method to make the button active and visible.
hide()FunctionBot API 6.1+ A method to hide the button.

All these methods return the BackButton object so they can be chained.

BottomButton

This object controls the button that is displayed at the bottom of the Mini App in the Telegram interface.

FieldTypeDescription
typeStringReadonly. Type of the button. It can be eithermain for the main button orsecondary for the secondary button.
textStringCurrent button text. Set toContinue for the main button andCancel for the secondary button by default.
colorStringCurrent button color. Set tothemeParams.button_color for the main button andthemeParams.bottom_bar_bg_color for the secondary button by default.
textColorStringCurrent button text color. Set tothemeParams.button_text_color for the main button andthemeParams.button_color for the secondary button by default.
isVisibleBooleanShows whether the button is visible. Set tofalse by default.
isActiveBooleanShows whether the button is active. Set totrue by default.
hasShineEffectBooleanBot API 7.10+ Shows whether the button has a shine effect. Set tofalse by default.
positionStringBot API 7.10+ Position of the secondary button. Not defined for the main button. It applies only if both the main and secondary buttons are visible. Set toleft by default.
Supported values:
-left, displayed to the left of the main button,
-right, displayed to the right of the main button,
-top, displayed above the main button,
-bottom, displayed below the main button.
isProgressVisibleBooleanReadonly. Shows whether the button is displaying a loading indicator.
setText(text)FunctionA method to set the button text.
onClick(callback)FunctionA method that sets the button's press event handler. An alias forTelegram.WebApp.onEvent('mainButtonClicked', callback)
offClick(callback)FunctionA method that removes the button's press event handler. An alias forTelegram.WebApp.offEvent('mainButtonClicked', callback)
show()FunctionA method to make the button visible.
Note that opening the Mini App from theattachment menu hides the main button until the user interacts with the Mini App interface.
hide()FunctionA method to hide the button.
enable()FunctionA method to enable the button.
disable()FunctionA method to disable the button.
showProgress(leaveActive)FunctionA method to show a loading indicator on the button.
It is recommended to display loading progress if the action tied to the button may take a long time. By default, the button is disabled while the action is in progress. If the parameterleaveActive=true is passed, the button remains enabled.
hideProgress()FunctionA method to hide the loading indicator.
setParams(params)FunctionA method to set the button parameters. Theparams parameter is an object containing one or several fields that need to be changed:
text - button text;
color - button color;
text_color - button text color;
has_shine_effect -Bot API 7.10+ enable shine effect;
position - position of the secondary button;
is_active - enable the button;
is_visible - show the button.

All these methods return the BottomButton object so they can be chained.

SettingsButton

This object controls theSettings item in the context menu of the Mini App in the Telegram interface.

FieldTypeDescription
isVisibleBooleanShows whether the context menu item is visible. Set tofalse by default.
onClick(callback)FunctionBot API 7.0+ A method that sets the press event handler for the Settings item in the context menu. An alias forTelegram.WebApp.onEvent('settingsButtonClicked', callback)
offClick(callback)FunctionBot API 7.0+ A method that removes the press event handler from the Settings item in the context menu. An alias forTelegram.WebApp.offEvent('settingsButtonClicked', callback)
show()FunctionBot API 7.0+ A method to make the Settings item in the context menu visible.
hide()FunctionBot API 7.0+ A method to hide the Settings item in the context menu.

All these methods return theSettingsButton object so they can be chained.

HapticFeedback

This object controls haptic feedback.

FieldTypeDescription
impactOccurred(style)FunctionBot API 6.1+ A method tells that an impact occurred. The Telegram app may play the appropriate haptics based on style value passed. Style can be one of these values:
-light, indicates a collision between small or lightweight UI objects,
-medium, indicates a collision between medium-sized or medium-weight UI objects,
-heavy, indicates a collision between large or heavyweight UI objects,
-rigid, indicates a collision between hard or inflexible UI objects,
-soft, indicates a collision between soft or flexible UI objects.
notificationOccurred(type)FunctionBot API 6.1+ A method tells that a task or action has succeeded, failed, or produced a warning. The Telegram app may play the appropriate haptics based on type value passed. Type can be one of these values:
-error, indicates that a task or action has failed,
-success, indicates that a task or action has completed successfully,
-warning, indicates that a task or action produced a warning.
selectionChanged()FunctionBot API 6.1+ A method tells that the user has changed a selection. The Telegram app may play the appropriate haptics.

Do not use this feedback when the user makes or confirms a selection; use it only when the selection changes.

All these methods return the HapticFeedback object so they can be chained.

CloudStorage

This object controls the cloud storage. Each bot can store up to 1024 items per user in the cloud storage.

FieldTypeDescription
setItem(key, value[, callback])FunctionBot API 6.9+ A method that stores a value in the cloud storage using the specified key. The key should contain 1-128 characters, onlyA-Z,a-z,0-9,_ and- are allowed. The value should contain 0-4096 characters. You can store up to 1024 keys in the cloud storage. If an optionalcallback parameter was passed, thecallback function will be called. In case of an error, the first argument will contain the error. In case of success, the first argument will benull and the second argument will be a boolean indicating whether the value was stored.
getItem(key, callback)FunctionBot API 6.9+ A method that receives a value from the cloud storage using the specified key. The key should contain 1-128 characters, onlyA-Z,a-z,0-9,_ and- are allowed. In case of an error, thecallback function will be called and the first argument will contain the error. In case of success, the first argument will benull and the value will be passed as the second argument.
getItems(keys, callback)FunctionBot API 6.9+ A method that receives values from the cloud storage using the specified keys. The keys should contain 1-128 characters, onlyA-Z,a-z,0-9,_ and- are allowed. In case of an error, thecallback function will be called and the first argument will contain the error. In case of success, the first argument will benull and the values will be passed as the second argument.
removeItem(key[, callback])FunctionBot API 6.9+ A method that removes a value from the cloud storage using the specified key. The key should contain 1-128 characters, onlyA-Z,a-z,0-9,_ and- are allowed. If an optionalcallback parameter was passed, thecallback function will be called. In case of an error, the first argument will contain the error. In case of success, the first argument will benull and the second argument will be a boolean indicating whether the value was removed.
removeItems(keys[, callback])FunctionBot API 6.9+ A method that removes values from the cloud storage using the specified keys. The keys should contain 1-128 characters, onlyA-Z,a-z,0-9,_ and- are allowed. If an optionalcallback parameter was passed, thecallback function will be called. In case of an error, the first argument will contain the error. In case of success, the first argument will benull and the second argument will be a boolean indicating whether the values were removed.
getKeys(callback)FunctionBot API 6.9+ A method that receives the list of all keys stored in the cloud storage. In case of an error, thecallback function will be called and the first argument will contain the error. In case of success, the first argument will benull and the list of keys will be passed as the second argument.

All these methods return theCloudStorage object, so they can be chained.

BiometricManager

This object controls biometrics on the device. Before the first use of this object, it needs to be initialized using theinit method.

FieldTypeDescription
isInitedBooleanShows whether biometrics object is initialized.
isBiometricAvailableBooleanShows whether biometrics is available on the current device.
biometricTypeStringThe type of biometrics currently available on the device. Can be one of these values:
-finger, fingerprint-based biometrics,
-face, face-based biometrics,
-unknown, biometrics of an unknown type.
isAccessRequestedBooleanShows whether permission to use biometrics has been requested.
isAccessGrantedBooleanShows whether permission to use biometrics has been granted.
isBiometricTokenSavedBooleanShows whether the token is saved in secure storage on the device.
deviceIdStringA unique device identifier that can be used to match the token to the device.
init([callback])FunctionBot API 7.2+ A method that initializes the BiometricManager object. It should be called before the object's first use. If an optionalcallback parameter was passed, thecallback function will be called when the object is initialized.
requestAccess(params[, callback])FunctionBot API 7.2+ A method that requests permission to use biometrics according to theparams argument of typeBiometricRequestAccessParams. If an optionalcallback parameter was passed, thecallback function will be called and the first argument will be a boolean indicating whether the user granted access.
authenticate(params[, callback])FunctionBot API 7.2+ A method that authenticates the user using biometrics according to theparams argument of typeBiometricAuthenticateParams. If an optionalcallback parameter was passed, thecallback function will be called and the first argument will be a boolean indicating whether the user authenticated successfully. If so, the second argument will be a biometric token.
updateBiometricToken(token, [callback])FunctionBot API 7.2+ A method that updates the biometric token in secure storage on the device. To remove the token, pass an empty string. If an optionalcallback parameter was passed, thecallback function will be called and the first argument will be a boolean indicating whether the token was updated.
openSettings()FunctionBot API 7.2+ A method that opens the biometric access settings for bots. Useful when you need to request biometrics access to users who haven't granted it yet.

Note that this method can be called only in response to user interaction with the Mini App interface (e.g. a click inside the Mini App or on the main button)

All these methods return theBiometricManager object so they can be chained.

BiometricRequestAccessParams

This object describes the native popup for requesting permission to use biometrics.

FieldTypeDescription
reasonStringOptional. The text to be displayed to a user in the popup describing why the bot needs access to biometrics, 0-128 characters.

BiometricAuthenticateParams

This object describes the native popup for authenticating the user using biometrics.

FieldTypeDescription
reasonStringOptional. The text to be displayed to a user in the popup describing why you are asking them to authenticate and what action you will be taking based on that authentication, 0-128 characters.

Accelerometer

This object provides access to accelerometer data on the device.

FieldTypeDescription
isStartedBooleanIndicates whether accelerometer tracking is currently active.
xFloatThe current acceleration in the X-axis, measured in m/s².
yFloatThe current acceleration in the Y-axis, measured in m/s².
zFloatThe current acceleration in the Z-axis, measured in m/s².
start(params[, callback])FunctionBot API 8.0+ Starts tracking accelerometer data usingparams of typeAccelerometerStartParams. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully started.
stop([callback])FunctionBot API 8.0+ Stops tracking accelerometer data. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully stopped.

All these methods return theAccelerometer object so they can be chained.

AccelerometerStartParams

This object defines the parameters for starting accelerometer tracking.

FieldTypeDescription
refresh_rateIntegerOptional. The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Set to1000 by default. Note thatrefresh_rate may not be supported on all platforms, so the actual tracking frequency may differ from the specified value.

DeviceOrientation

This object provides access to orientation data on the device.

FieldTypeDescription
isStartedBooleanIndicates whether device orientation tracking is currently active.
absoluteBooleanA boolean that indicates whether or not the device is providing orientation data in absolute values.
alphaFloatThe rotation around the Z-axis, measured in radians.
betaFloatThe rotation around the X-axis, measured in radians.
gammaFloatThe rotation around the Y-axis, measured in radians.
start(params[, callback])FunctionBot API 8.0+ Starts tracking device orientation data usingparams of typeDeviceOrientationStartParams. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully started.
stop([callback])FunctionBot API 8.0+ Stops tracking device orientation data. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully stopped.

All these methods return theDeviceOrientation object so they can be chained.

DeviceOrientationStartParams

This object defines the parameters for starting device orientation tracking.

FieldTypeDescription
refresh_rateIntegerOptional. The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Set to1000 by default. Note thatrefresh_rate may not be supported on all platforms, so the actual tracking frequency may differ from the specified value.
need_absoluteBooleanOptional. Passtrue to receive absolute orientation data, allowing you to determine the device's attitude relative to magnetic north. Use this option if implementing features like a compass in your app. If relative data is sufficient, passfalse. Set tofalse by default.

Note: Keep in mind that some devices may not support absolute orientation data. In such cases, you will receive relative data even ifneed_absolute=true is passed. Check theDeviceOrientation.absolute parameter to determine whether the data provided is absolute or relative.

Gyroscope

This object provides access to gyroscope data on the device.

FieldTypeDescription
isStartedBooleanIndicates whether gyroscope tracking is currently active.
xFloatThe current rotation rate around the X-axis, measured in rad/s.
yFloatThe current rotation rate around the Y-axis, measured in rad/s.
zFloatThe current rotation rate around the Z-axis, measured in rad/s.
start(params[, callback])FunctionBot API 8.0+ Starts tracking gyroscope data usingparams of typeGyroscopeStartParams. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully started.
stop([callback])FunctionBot API 8.0+ Stops tracking gyroscope data. If an optionalcallback parameter is provided, thecallback function will be called with a boolean indicating whether tracking was successfully stopped.

All these methods return theGyroscope object so they can be chained.

GyroscopeStartParams

This object defines the parameters for starting gyroscope tracking.

FieldTypeDescription
refresh_rateIntegerOptional. The refresh rate in milliseconds, with acceptable values ranging from 20 to 1000. Set to1000 by default. Note thatrefresh_rate may not be supported on all platforms, so the actual tracking frequency may differ from the specified value.

LocationManager

This object controls location access on the device. Before the first use of this object, it needs to be initialized using theinit method.

FieldTypeDescription
isInitedBooleanShows whether the LocationManager object has been initialized.
isLocationAvailableBooleanShows whether location services are available on the current device.
isAccessRequestedBooleanShows whether permission to use location has been requested.
isAccessGrantedBooleanShows whether permission to use location has been granted.
init([callback])FunctionBot API 8.0+ A method that initializes the LocationManager object. It should be called before the object's first use. If an optionalcallback parameter is provided, thecallback function will be called when the object is initialized.
getLocation(callback)FunctionBot API 8.0+ A method that requests location data. Thecallback function will be called withnull as the first argument if access to location was not granted, or an object of typeLocationData as the first argument if access was successful.
openSettings()FunctionBot API 8.0+ A method that opens the location access settings for bots. Useful when you need to request location access from users who haven't granted it yet.

Note that this method can be called only in response to user interaction with the Mini App interface (e.g., a click inside the Mini App or on the main button).

All these methods return theLocationManager object so they can be chained.

LocationData

This object contains data about the current location.

FieldTypeDescription
latitudeFloatLatitude in degrees.
longitudeFloatLongitude in degrees.
altitudeFloatAltitude above sea level in meters.null if altitude data is not available on the device.
courseFloatThe direction the device is moving in degrees (0 = North, 90 = East, 180 = South, 270 = West).null if course data is not available on the device.
speedFloatThe speed of the device in m/s.null if speed data is not available on the device.
horizontal_accuracyFloatAccuracy of the latitude and longitude values in meters.null if horizontal accuracy data is not available on the device.
vertical_accuracyFloatAccuracy of the altitude value in meters.null if vertical accuracy data is not available on the device.
course_accuracyFloatAccuracy of the course value in degrees.null if course accuracy data is not available on the device.
speed_accuracyFloatAccuracy of the speed value in m/s.null if speed accuracy data is not available on the device.

WebAppInitData

This object contains data that is transferred to the Mini App when it is opened. It is empty if the Mini App was launched from akeyboard button or frominline mode.

FieldTypeDescription
query_idStringOptional. A unique identifier for the Mini App session, required for sending messages via theanswerWebAppQuery method.
userWebAppUserOptional. An object containing data about the current user.
receiverWebAppUserOptional. An object containing data about the chat partner of the current user in the chat where the bot was launched via the attachment menu. Returned only for private chats and only for Mini Apps launched via the attachment menu.
chatWebAppChatOptional. An object containing data about the chat where the bot was launched via the attachment menu. Returned for supergroups, channels and group chats – only for Mini Apps launched via the attachment menu.
chat_typeStringOptional. Type of the chat from which the Mini App was opened. Can be either “sender” for a private chat with the user opening the link, “private”, “group”, “supergroup”, or “channel”. Returned only for Mini Apps launched from direct links.
chat_instanceStringOptional. Global identifier, uniquely corresponding to the chat from which the Mini App was opened. Returned only for Mini Apps launched from a direct link.
start_paramStringOptional. The value of thestartattach parameter, passedvia link. Only returned for Mini Apps when launched from the attachment menu via link.

The value of thestart_param parameter will also be passed in the GET-parametertgWebAppStartParam, so the Mini App can load the correct interface right away.
can_send_afterIntegerOptional. Time in seconds, after which a message can be sent via theanswerWebAppQuery method.
auth_dateIntegerUnix time when the form was opened.
hashStringA hash of all passed parameters, which the bot server can use tocheck their validity.
signatureNEWStringA signature of all passed parameters (excepthash), which the third party can use tocheck their validity.

WebAppUser

This object contains the data of the Mini App user.

FieldTypeDescription
idIntegerA unique identifier for the user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. It has at most 52 significant bits, so a 64-bit integer or a double-precision float type is safe for storing this identifier.
is_botBooleanOptional.True, if this user is a bot. Returns in thereceiver field only.
first_nameStringFirst name of the user or bot.
last_nameStringOptional. Last name of the user or bot.
usernameStringOptional. Username of the user or bot.
language_codeStringOptional.IETF language tag of the user's language. Returns inuser field only.
is_premiumTrueOptional.True, if this user is a Telegram Premium user.
added_to_attachment_menuTrueOptional.True, if this user added the bot to the attachment menu.
allows_write_to_pmTrueOptional.True, if this user allowed the bot to message them.
photo_urlStringOptional. URL of the user’s profile photo. The photo can be in .jpeg or .svg formats.

WebAppChat

This object represents a chat.

FieldTypeDescription
idIntegerUnique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
typeStringType of chat, can be either “group”, “supergroup” or “channel”
titleStringTitle of the chat
usernameStringOptional. Username of the chat
photo_urlStringOptional. URL of the chat’s photo. The photo can be in .jpeg or .svg formats. Only returned for Mini Apps launched from the attachment menu.

Validating data received via the Mini App

To validate data received via the Mini App, one should send the data from theTelegram.WebApp.initData field to the bot's backend. The data is a query string, which is composed of a series of field-value pairs.

You can verify the integrity of the data received by comparing the receivedhash parameter with the hexadecimal representation of theHMAC-SHA-256 signature of thedata-check-string with the secret key, which is theHMAC-SHA-256 signature of thebot's token with the constant stringWebAppData used as a key.

Data-check-string is a chain of all received fields, sorted alphabetically, in the formatkey=<value> with aline feed character ('\n', 0x0A) used as separator – e.g.,'auth_date=<auth_date>\nquery_id=<query_id>\nuser=<user>'.

The full check might look like:

data_check_string = ...secret_key = HMAC_SHA256(<bot_token>, "WebAppData")if (hex(HMAC_SHA256(data_check_string, secret_key)) == hash) {  // data is from Telegram}

To prevent the use of outdated data, you can additionally check theauth_date field, which contains a Unix timestamp of when it was received by the Mini App.

Once validated, the data may be used on your server. Complex data types are represented as JSON-serialized objects.

Validating data for Third-Party Use

NEW If you need to share the data with a third party, they can validate the data without requiring access to yourbot's token. Simply provide them with the data from theTelegram.WebApp.initData field and yourbot_id.

The integrity of the data can be verified by validating the receivedsignature parameter, which is the base64url-encoded representation of theEd25519 signature of thedata-check-string. The verification is performed using the public key provided by Telegram.

Data-check-string is constructed as follows:
1. Prepend thebot_id, followed by: and the constant stringWebAppData.
2. Add aline feed character ('\n', 0x0A).
3. Append all received fields (excepthash andsignature), sorted alphabetically, in the formatkey=<value>.
4. Separate each key-value pair with a line feed character ('\n', 0x0A).

Example:
'12345678:WebAppData\nauth_date=<auth_date>\nquery_id=<query_id>\nuser=<user>'

The verification process might look like this:

data_check_string = ...public_key = "<Telegram_public_key>"if (Ed25519_verify(public_key, data_check_string, signature)) {  // data is valid and originated from Telegram}

Telegram provides the followingEd25519 public keys for signature verification:

Test environment:40055058a4ee38156a06562e52eece92a771bcd8346a8c4615cb7376eddf72ec (hex)
Production:e7bf03a2fa4602af4580703d88dda5bb59f32ed8b02a56c187fe7d34caed242d (hex)

To prevent the use of outdated data, the third party should additionally validate theauth_date field. This field contains a Unix timestamp indicating when the data was received by the Mini App.

Once validated, the data may be used. Complex data types are represented as JSON-serialized objects.

Events Available for Mini Apps

The Mini App can receive events from the Telegram app, onto which a handler can be attached using theTelegram.WebApp.onEvent(eventType, eventHandler) method. InsideeventHandler thethis object refers toTelegram.WebApp, the set of parameters sent to the handler depends on the event type. Below is a list of possible events:

eventTypeDescription
activatedNEWBot API 8.0+ Occurs when the Mini App becomes active (e.g., opened from minimized state or selected among tabs).
eventHandler receives no parameters.
deactivatedNEWBot API 8.0+ Occurs when the Mini App becomes inactive (e.g., minimized or moved to an inactive tab).
eventHandler receives no parameters.
themeChangedOccurs whenever theme settings are changed in the user's Telegram app (including switching to night mode).
eventHandler receives no parameters, new theme settings and color scheme can be received viathis.themeParams andthis.colorScheme respectively.
viewportChangedOccurs when the visible section of the Mini App is changed.
eventHandler receives an object with the single fieldisStateStable. IfisStateStable is true, the resizing of the Mini App is finished. If it is false, the resizing is ongoing (the user is expanding or collapsing the Mini App or an animated object is playing). The current value of the visible section’s height is available inthis.viewportHeight.
safeAreaChangedNEWBot API 8.0+ Occurs when the device's safe area insets change (e.g., due to orientation change or screen adjustments).
eventHandler receives no parameters. The current inset values can be accessed viathis.safeAreaInset.
contentSafeAreaChangedNEWBot API 8.0+ Occurs when the safe area for content changes (e.g., due to orientation change or screen adjustments).
eventHandler receives no parameters. The current inset values can be accessed viathis.contentSafeAreaInset.
mainButtonClickedOccurs when themain button is pressed.
eventHandler receives no parameters.
secondaryButtonClickedBot API 7.10+ Occurs when thesecondary button is pressed.
eventHandler receives no parameters.
backButtonClickedBot API 6.1+ Occurrs when theback button is pressed.
eventHandler receives no parameters.
settingsButtonClickedBot API 6.1+ Occurrs when the Settings item in context menu is pressed.
eventHandler receives no parameters.
invoiceClosedBot API 6.1+ Occurrs when the opened invoice is closed.
eventHandler receives an object with the two fields:url – invoice link provided andstatus – one of the invoice statuses:
-paid – invoice was paid successfully,
-cancelled – user closed this invoice without paying,
-failed – user tried to pay, but the payment was failed,
-pending – the payment is still processing. The bot will receive a service message about asuccessful payment when the payment is successfully paid.
popupClosedBot API 6.2+ Occurrs when the opened popup is closed.
eventHandler receives an object with the single fieldbutton_id – the value of the fieldid of the pressed button. If no buttons were pressed, the fieldbutton_id will benull.
qrTextReceivedBot API 6.4+ Occurs when the QR code scanner catches a code with text data.
eventHandler receives an object with the single fielddata containing text data from the QR code.
scanQrPopupClosedBot API 7.7+ Occurs when the QR code scanner popup is closed by the user.
eventHandler receives no parameters.
clipboardTextReceivedBot API 6.4+ Occurrs when thereadTextFromClipboard method is called.
eventHandler receives an object with the single fielddata containing text data from the clipboard. If the clipboard contains non-text data, the fielddata will be an empty string. If the Mini App has no access to the clipboard, the fielddata will benull.
writeAccessRequestedBot API 6.9+ Occurs when the write permission was requested.
eventHandler receives an object with the single fieldstatus containing one of the statuses:
-allowed – user granted write permission to the bot,
-cancelled – user declined this request.
contactRequestedBot API 6.9+ Occurrs when the user's phone number was requested.
eventHandler receives an object with the single fieldstatus containing one of the statuses:
-sent – user shared their phone number with the bot,
-cancelled – user declined this request.
biometricManagerUpdatedBot API 7.2+ Occurs whenever BiometricManager object is changed.
eventHandler receives no parameters.
biometricAuthRequestedBot API 7.2+ Occurs whenever biometric authentication was requested.
eventHandler receives an object with the fieldisAuthenticated containing a boolean indicating whether the user was authenticated successfully. IfisAuthenticated is true, the fieldbiometricToken will contain the biometric token stored in secure storage on the device.
biometricTokenUpdatedBot API 7.2+ Occurs whenever the biometric token was updated.
eventHandler receives an object with the single fieldisUpdated, containing a boolean indicating whether the token was updated.
fullscreenChangedNEWBot API 8.0+ Occurs whenever the Mini App enters or exits fullscreen mode.
eventHandler receives no parameters. The current fullscreen state can be checked viathis.isFullscreen.
fullscreenFailedNEWBot API 8.0+ Occurs if a request to enter fullscreen mode fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – Fullscreen mode is not supported on this device or platform.
ALREADY_FULLSCREEN – The Mini App is already in fullscreen mode.
homeScreenAddedNEWBot API 8.0+ Occurs when the Mini App is successfully added to the home screen.
eventHandler receives no parameters.
homeScreenCheckedNEWBot API 8.0+ Occurs after checking the home screen status.
eventHandler receives an object with the fieldstatus, which is a string indicating the current home screen status. Possible values forstatus are:
-unsupported – the feature is not supported, and it is not possible to add the icon to the home screen,
-unknown – the feature is supported, and the icon can be added, but it is not possible to determine if the icon has already been added,
-added – the icon has already been added to the home screen,
-missed – the icon has not been added to the home screen.
accelerometerStartedNEWBot API 8.0+ Occurs when accelerometer tracking has started successfully.
eventHandler receives no parameters.
accelerometerStoppedNEWBot API 8.0+ Occurs when accelerometer tracking has stopped.
eventHandler receives no parameters.
accelerometerChangedNEWBot API 8.0+ Occurs with the specified frequency after calling thestart method, sending the current accelerometer data.
eventHandler receives no parameters, the current acceleration values can be received viathis.x,this.y andthis.z respectively.
accelerometerFailedNEWBot API 8.0+ Occurs if a request to start accelerometer tracking fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – Accelerometer tracking is not supported on this device or platform.
deviceOrientationStartedNEWBot API 8.0+ Occurs when device orientation tracking has started successfully.
eventHandler receives no parameters.
deviceOrientationStoppedNEWBot API 8.0+ Occurs when device orientation tracking has stopped.
eventHandler receives no parameters.
deviceOrientationChangedNEWBot API 8.0+ Occurs with the specified frequency after calling thestart method, sending the current orientation data.
eventHandler receives no parameters, the current device orientation values can be received viathis.alpha,this.beta andthis.gamma respectively.
deviceOrientationFailedNEWBot API 8.0+ Occurs if a request to start device orientation tracking fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – Device orientation tracking is not supported on this device or platform.
gyroscopeStartedNEWBot API 8.0+ Occurs when gyroscope tracking has started successfully.
eventHandler receives no parameters.
gyroscopeStoppedNEWBot API 8.0+ Occurs when gyroscope tracking has stopped.
eventHandler receives no parameters.
gyroscopeChangedNEWBot API 8.0+ Occurs with the specified frequency after calling thestart method, sending the current gyroscope data.
eventHandler receives no parameters, the current rotation rates can be received viathis.x,this.y andthis.z respectively.
gyroscopeFailedNEWBot API 8.0+ Occurs if a request to start gyroscope tracking fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – Gyroscope tracking is not supported on this device or platform.
locationManagerUpdatedNEWBot API 8.0+ Occurs whenever LocationManager object is changed.
eventHandler receives no parameters.
locationRequestedNEWBot API 8.0+ Occurs when location data is requested.
eventHandler receives an object with the single fieldlocationData of typeLocationData, containing the current location information.
shareMessageSentNEWBot API 8.0+ Occurs when the message is successfully shared by the user.
eventHandler receives no parameters.
shareMessageFailedNEWBot API 8.0+ Occurs if sharing the message fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – The feature is not supported by the client.
MESSAGE_EXPIRED – The message could not be retrieved because it has expired.
MESSAGE_SEND_FAILED – An error occurred while attempting to send the message.
USER_DECLINED – The user closed the dialog without sharing the message.
UNKNOWN_ERROR – An unknown error occurred.
emojiStatusSetNEWBot API 8.0+ Occurs when the emoji status is successfully set.
eventHandler receives no parameters.
emojiStatusFailedNEWBot API 8.0+ Occurs if setting the emoji status fails.
eventHandler receives an object with the single fielderror, describing the reason for the failure. Possible values forerror are:
UNSUPPORTED – The feature is not supported by the client.
SUGGESTED_EMOJI_INVALID – One or more emoji identifiers are invalid.
DURATION_INVALID – The specified duration is invalid.
USER_DECLINED – The user closed the dialog without setting a status.
SERVER_ERROR – A server error occurred when attempting to set the status.
UNKNOWN_ERROR – An unknown error occurred.
emojiStatusAccessRequestedNEWBot API 8.0+ Occurs when the write permission was requested.
eventHandler receives an object with the single fieldstatus containing one of the statuses:
-allowed – user granted emoji status permission to the bot,
-cancelled – user declined this request.
fileDownloadRequestedNEWBot API 8.0+ Occurs when the user responds to the file download request.
eventHandler receives an object with the single fieldstatus containing one of the statuses:
-downloading – the file download has started,
-cancelled – user declined this request.

Adding Bots to the Attachment Menu

Attachment menu integration is currently only available for major advertisers on theTelegram Ad Platform. However,all bots can use it in thetest server environment. Talk to Botfather on the test server toset up the integration.

A special link is used to add bots to the attachment menu:

https://t.me/botusername?startattach
or
https://t.me/botusername?startattach=command

For example, open thisattachment menu link for@DurgerKingBot, then use theAttach menu in anyprivate chat.

Opening the link prompts the user to add the bot to their attachment menu. If the bot has already been added, the attachment menu will open in the current chat and redirect to the bot there (if the link is opened from a 1-on-1 chat). If a non-emptystartattach parameter was included in the link, it will be passed to the Mini App in thestart_param field and in the GET parametertgWebAppStartParam.

The following link formats are also supported:

https://t.me/username?attach=botusername
https://t.me/username?attach=botusername&startattach=command
https://t.me/+1234567890?attach=botusername
https://t.me/+1234567890?attach=botusername&startattach=command

These links open the Mini App in the attachment menu in the chat with a specific user. If the bot wasn't already added to the attachment menu, the user will be prompted to do so. If a non-emptystartattach parameter was included in the link, it will be passed to the Mini App in thestart_param field and in the GET parametertgWebAppStartParam.

Bot API 6.1+ supports a new link format:

https://t.me/botusername?startattach&choose=users+bots
https://t.me/botusername?startattach=command&choose=groups+channels

Opening such a link prompts the user to choose a specific chat and opens the attachment menu in that chat. If the bot wasn't already added to the attachment menu, the user will be prompted to do so. You can specify which types of chats the user will be able to choose from. It can be one or more of the following types:users,bots,groups,channels separated by a+ sign. If a non-emptystartattach parameter was included in the link, it will be passed to the Mini App in thestart_param field and in the GET parametertgWebAppStartParam.

Additional Data in User-Agent

When the Mini App is running on Android, additional information is appended to the User-Agent string to provide more context about the app environment. This information includes the app version, device model, Android version, SDK version, and device performance class, formatted as follows:

Telegram-Android/{app_version} ({manufacturer} {model}; Android {android_version}; SDK {sdk_version}; {performance_class})

where:

  • {app_version} is the version of the Telegram app (e.g.,11.3.3),
  • {manufacturer} {model} represents the device’s manufacturer and model (e.g.,Google sdk_gphone64_arm64),
  • {android_version} is the Android OS version running on the device (e.g.,14),
  • {sdk_version} indicates the Android SDK version (e.g.,34),
  • {performance_class} specifies the device performance class asLOW,AVERAGE, orHIGH, indicating the device's performance capacity.

Example
Mozilla/5.0 (Linux; Android 14; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.5672.136 Mobile Safari/537.36 Telegram-Android/11.3.3 (Google sdk_gphone64_arm64; Android 14; SDK 34; LOW)

We recommend using this information to optimize your Mini App based on the device's capabilities. For instance, you can adjust animations and visual effects in games on low-performance devices to ensure a smooth experience for all users, regardless of device specifications.

Testing Mini Apps

Using bots in the test environment

To log in to the test environment, use either of the following:

  • iOS: tap 10 times on the Settings icon > Accounts > Login to another account > Test.
  • Telegram Desktop: open ☰ Settings > Shift + Alt + Right click ‘Add Account’ and select ‘Test Server’.
  • macOS: click the Settings icon 10 times to open the Debug Menu, ⌘ + click ‘Add Account’ and log in via phone number.

The test environment is completely separate from the main environment, so you will need to create anew user account and anew bot with @BotFather.

After receiving your bot token, you can send requests to the Bot API in this format:

https://api.telegram.org/bot<token>/test/METHOD_NAME

Note: When working with the test environment, you may use HTTP links without TLS to test your Mini App.

Debug Mode for Mini Apps

Use these tools to find app-specific issues in your Mini App:

iOS

  • In Telegram tap 10 times on the Settings icon and toggle onAllow Web View Inspection.
  • Connect your phone to your computer using a USB cable.
  • Open Safari on your Mac, then go toDevelop > [Your Device Name] in the menu bar.
  • Launch your Mini App on the iOS device – it will appear in theDevelop menu under your device.

Android

  • Enable USB-Debugging on your device.
  • In Telegram Settings, scroll all the way down, press and hold on theversion number two times.
  • ChooseEnable WebView Debug in the Debug Settings.
  • Connect your phone to your computer and openchrome://inspect/#devices in Chrome – you will see your Mini App there when you launch it on your phone.

Telegram Desktop on Windows and Linux

  • Download and launch theBeta Version of Telegram Desktop onWindows orLinux (not supported on Telegram Desktop for macOS yet).
  • Go toSettings > Advanced > Experimental settings > Enable webview inspection.
  • Right click in the WebView and chooseInspect.

Telegram macOS

  • Download and launch theBeta Version of Telegram macOS.
  • Quickly click 5 times on the Settings icon to open the debug menu and enable “Debug Mini Apps”.
  • Right click in the Mini App and chooseInspect Element.
Telegram
Telegram is a cloud-based mobile and desktop messaging app with a focus on security and speed.
About
Mobile Apps
Desktop Apps
Platform
About
Blog
Press
Moderation

[8]ページ先頭

©2009-2025 Movatter.jp