Introduction to BuilderEngine Docs

Welcome to the official documentation for BuilderEngine!

This documentation provides a comprehensive guide to help you understand, integrate, and make the most out of the BuilderEngine platform. Whether you are a new user getting started or an experienced developer looking for advanced configurations, you'll find valuable information here.

What is BuilderEngine?

BuilderEngine is a powerful platform designed to simplify the creation, deployment, and management of bots. With an intuitive interface and robust features, BuilderEngine empowers you to build sophisticated automated solutions with ease.

We are constantly updating our documentation to provide you with the latest information. If you have any questions or feedback, please don't hesitate to reach out to our Developer.


Getting Started

This guide will walk you through the initial steps to get up and running with BuilderEngine.

1. Sign Up for an Account

If you haven't already, you'll need to create a BuilderEngine account.

2. Log In to Your Account

Once your account is created and verified:

  • Go to the Login Page.
  • Enter your email and password.
  • You will be redirected to your dashboard.

3. Explore the Dashboard

The dashboard is your central hub for managing your bots. Here you can:

  • View a list of your existing bots.
  • Create new bots.
  • Access your profile, analytics, billing information, and settings.

4. Create Your First Bot

To create a new bot:

  • Click on the "Create New Bot" button on your dashboard.
  • You'll be prompted to provide a name and a token for your bot (description is optional).
  • Once created, you'll be taken to the bot editor page.

5. Using the Bot Editor

The bot editor allows you to:

  • Configure your bot's settings (name, description, token).
  • Manage files (HTML, CSS, JavaScript) associated with your bot.
  • Use the AI Bot Builder to get assistance with coding and configuration.
  • Set up a key-value based database for persistent storage.
  • Manage secrets for integrations with external services.
  • View logs to monitor your bot's activity.

Refer to the specific sections in this documentation for more details on each feature.

Happy building!


Bots

This page explains the fundamental concept of "Bots" within BuilderEngine & Telegram.

What is a Bot?

In Telegram, bots are small applications that run entirely within the Telegram app. Users interact with bots through flexible interfaces that can support any kind of task or service. The Telegram Bot Platform hosts more than 10 million bots and is free for both users and developers.

In BuilderEngine, a bot is an automated software application that performs tasks over the internet. You can design bots to:

  • Interact with users on messaging platforms (e.g., Telegram).
  • Automate web tasks or workflows.
  • Integrate with various APIs and third-party services.
  • Process data and provide insights.
  • Serve simple web content.

Components of a Bot in BuilderEngine

A typical bot in BuilderEngine consists of several key components that you manage through the Bot Editor:

  • Configuration:
    • Name & Description: Identifiable details for your bot.
    • Token: The primary authentication token required by the platform your bot integrates with (e.g., Telegram Bot Token).
    • API Hash: A unique hash for your bot to interact with BuilderEngine's internal APIs.
  • Files:
    • HTML, CSS, and JavaScript files that define the bot's logic, presentation (if serving web content), or command handlers.
    • Each JavaScript file can have an associated "command" (e.g., /start) that triggers its execution.
  • Database:
    • A simple key-value store for persistent data storage specific to the bot.
  • Secrets:
    • Secure storage for API keys, tokens, and other sensitive credentials your bot might need to interact with external services.
  • Logs:
    • Records of the bot's activity, errors, and informational messages for monitoring and debugging.
  • Users:
    • A list of platform-specific users who have interacted with your bot (e.g., Telegram users).
  • Libraries:
    • Read-only utility files (often JavaScript) provided by the platform that your bot can leverage.

Bot Status

A bot can be in one of several statuses:

  • Online: The bot is running and operational.
  • Offline: The bot is not running.
  • Compiling: The bot's code is currently being compiled or prepared for launch.
  • Error: The bot encountered an error and is not running correctly.

Creating and Managing Bots

You create and manage your bots through the BuilderEngine dashboard and the dedicated Bot Editor. Refer to the Getting Started guide to learn how to create your first bot.


Guide: Creating Your First Bot

This guide will walk you through the process of creating your very first bot using BuilderEngine. We'll cover the essential steps from setup to seeing your bot online.

Prerequisites

  • A BuilderEngine account. If you don't have one, please Sign Up.
  • A token for the platform you want your bot to integrate with Telegram Bot.

Steps

1. Navigate to Your Dashboard

After logging into BuilderEngine, you'll land on your dashboard. This is where you can see all your existing bots and create new ones.

2. Initiate Bot Creation

  • Click the prominent "Create New Bot" button.
  • You'll be taken to a simple form asking for initial bot details.

3. Provide Basic Bot Information

  • Bot Name: Choose a descriptive name for your bot. This is how you'll identify it in your dashboard.
  • Bot Token: This is a compulsory field. Enter the API token provided by the messaging platform your bot will use (e.g., Telegram, Discord).
    • Why is this compulsory? The token is essential for BuilderEngine to authenticate and communicate with the respective platform on behalf of your bot.
    • For testing purposes you can enter some random text.
  • Description (Optional): Add a short description of what your bot does. This is helpful for your own reference.

Click "Create Bot & Continue to Editor".

4. Explore the Bot Editor

You'll now be in the Bot Editor for your newly created bot. This is where you'll define its functionality. Key areas include:

  • Configuration: Review and update your bot's name, description, and token. You'll also see a view-only API Hash generated by BuilderEngine for internal use.
  • Files: This is where you'll add your HTML, CSS, and JavaScript files to make your bot do things.
  • AI Bot Builder: Get assistance from an AI to write code or configure your bot.
  • Database: A key-value store if your bot needs to remember information.
  • Secrets: Securely store any other API keys or sensitive data your bot might need.
  • Logs: Monitor your bot's activity.

5. Create a Simple "Hello World" Bot

Let's create a basic command.

  • Go to the Files tab.

  • File Name: Enter abc.js

  • Command: Enter *

  • Click "Add File".

  • The abc.js file will be selected, and the editor will appear.

  • Enter the following JavaScript code:

    // This script will be executed when any message is recived. await Api.sendMessage({ chat_id: update.message.chat.id, text: "Hello there! i am alive" })
  • Click "Save".

6. Launch Your Bot

  • Navigate to the Configuration tab in the Bot Editor.
  • Under "Bot Controls", click the "Launch" button.
  • Make sure to use a active bot token from telegram.
  • The bot's status should change from "offline" to "compiling" and then to "online".

7. Test Your Bot

How you test depends on the platform:

  • Telegram: Go to your Telegram app, find your bot (using the username you set up when getting the token), and send any message.

Next Steps

Congratulations! You've created and launched a basic bot. From here, you can:

  • Explore adding HTML and CSS files if your bot needs a web interface.
  • Learn about using the Database and Secrets management.
  • Dive deeper into writing more complex JavaScript logic for your bot's commands.

Refer to other sections in this documentation for more detailed guides and API references.


Subscription Plans

BuilderEngine offers a variety of plans to suit your needs, from individual hobbyists to large enterprises.

Plan Tiers

FeatureFree TierPro PlanUltra Plan
Price₹0/month₹79/month₹149/month
Bots2020Unlimited
Data Traffic/month5MB25MBUnlimited
Database/month2 MB5 MB10 MB
AI Tokens1040100
Execution timeout5sec8sec10sec
SupportBasicPriorityDedicated
Community BotStoreYesYesYes
HostingSharedSharedDedicated

Choosing the Right Plan

  • Free Tier: Perfect for getting started, exploring the platform, and small personal projects.
  • Pro Plan: Ideal for developers and small businesses looking to build and deploy multiple bots with higher usage limits and priority support.
  • Ultra Plan: Designed for large organizations with specific needs, offering unlimited resources , and dedicated support.

How to Upgrade

You can manage your subscription and upgrade your plan from the Billing section of your dashboard. For Enterprise plans, please contact our sales team.

For more details on current usage and plan options, please visit the Billing Page in your account dashboard after logging in.


Understanding the Bot Editor

The BuilderEngine Bot Editor is your primary interface for configuring, coding, and managing individual bots. This guide provides an overview of its main sections and functionalities.

Accessing the Bot Editor

You can access the Bot Editor in two ways:

  1. After Creating a New Bot: You are automatically redirected here.
  2. From the Dashboard: Click the "Manage Bot" button on any bot card in your list of bots.

Main Tabs

The Bot Editor is organized into several tabs for clarity:

1. Configuration

This is where you manage the core settings of your bot.

  • Bot Name: The display name of your bot.
  • Description: A brief description of your bot's purpose.
  • Bot Token: The primary API token from the platform your bot integrates with (e.g., Telegram Bot Token).
  • API Hash (View Only): A unique hash generated by BuilderEngine, used for internal API interactions. You cannot edit this, but you can revoke it to generate a new one if needed.
  • Bot Controls:
    • Launch: Starts your bot.
    • Stop: Stops your bot.
    • Go to Bot (Conditional): If your bot has a direct platform link, this button will appear to take you there.
    • Delete Bot: Permanently removes your bot and all its associated data. This action requires confirmation.
  • Save Configuration: Click this to save any changes made to the name, description, or token.

2. Files

This tab is for managing the code that powers your bot.

  • File Manager:
    • Add New File: Create HTML, CSS, or JavaScript files.
      • File Name: Must include a valid extension (.html, .css, .js).
      • Command (for .js files only): A required field for JavaScript files. This is the command (e.g., /start) that will trigger this script when received by the bot.
    • File List: Shows all your bot's files. Click a file to open it in the editor. You can also delete files from here.
  • Code Editor:
    • Appears when a file is selected.
    • Provides syntax highlighting for HTML, CSS, and JavaScript.
    • Format Code: Uses Prettier to automatically format the code in the editor.
    • Save: Saves the current content of the selected file. The button is disabled if no changes have been made.
    • Displays file language, last modified date, and command (if applicable).
    • All your code will run for upto 6 second and it will be forced to hard kill after that.
    • Upgrade your plan to acces for network and storage access.

3. AI Bot Builder

An interactive chat interface to help you build your bot.

  • Chat Pane: Displays your conversation with the AI assistant. Messages are scrollable.
  • Input Area: Type your requests or questions for the AI.
  • Tokens Left: Shows an estimate of your remaining AI interaction tokens for the current cycle (if applicable to your plan).
  • The AI can help with:
    • Generating code snippets or full bot codes.
    • Explaining concepts.
    • Suggesting configurations.
    • Modifying files on your behalf (it will describe the changes it plans to make).

4. Libraries

View read-only utility files provided by the BuilderEngine platform.

  • Library File List: Click a file to view its content.
  • Viewer: Displays the content of the selected library file with syntax highlighting. You cannot edit these files.

5. Users

Lists users who have interacted with your bot on its platform.

  • Displays user's avatar (initials), full name (if available), username, and platform ID.
  • This list is typically populated by the backend as users interact with your live bot.

6. Database

A simple key-value store for your bot's persistent data.

  • Add/Update Item:
    • Key: The unique identifier for your data entry. Cannot be changed once an item is created.
    • Value: The data you want to store (can be a string, number, JSON string, etc.).
    • Click "Add Item" to create a new entry or "Update Value" if you've selected an existing item to edit.
  • Stored Items: Lists all existing key-value pairs. You can edit the value or delete items.

7. Secrets

Securely manage sensitive information like API keys or tokens that your bot needs.

  • Add/Update Secret:
    • Secret Key: The name of your secret (e.g., STRIPE_API_KEY). Cannot be changed once created.
    • Secret Value: The actual secret data. This is stored securely by the backend.
    • Click "Add Secret" or "Update Value".
  • Stored Secrets: Lists your secrets.
    • Values are masked by default. Click the "eye" icon to reveal/hide the value.
    • You can edit the value or delete secrets.

8. Logs

View real-time and historical logs generated by your bot.

  • Log Viewer: Displays log messages, including their type (info, critical, normal).
    • INFO messages are often highlighted (e.g., yellow).
    • ERROR messages are highlighted (e.g., red).
    • NORMAL messages are standard text.
  • Refresh Logs: Manually fetches the latest logs auto logs are not updated in live tail.

General Tips

  • Save Frequently: Always save your file changes and configuration updates.
  • Export Backup: Keep a piece of bot codes in backup.
  • Check Logs: When troubleshooting, the Logs tab is your best friend.
  • Use AI Builder: Don't hesitate to ask the AI for help if you're stuck or need ideas.

This overview should help you navigate and utilize the Bot Editor effectively. Happy building!


Files in BuilderEngine

BuilderEngine operates based on a file system, where each file determines how your bot behaves. Understanding how files work is essential for building responsive bots.

FileName

  • FileName is a unique identifier used to name your file—this helps you quickly recognize its purpose.
    • Examples: Start.js, Help.js, Welcome.html
  • Allowed file extensions:
    • .js → JavaScript logic
    • .html → Web apps or Telegram WebView UIs
    • .css → Styling for HTML files
  • 🔒 Note: Two files cannot have the same name.
  • 🧠 The file name itself doesn’t affect command matching, unless the file defines the special function answerCallback().

Commands

  • A Command is a trigger from user input—either text message or callback data—that determines which file is executed.
  • The system matches commands based on prefixes (not exact match):
    • Example: If a file has the command hi, it will match messages like:
      • "hi"
      • "hithere"
      • "hi hello"
  • Commands must be defined in the file using a comma-separated list:
    • Example: "/start, home, /back" → this file will be called when user sends /start, home, or /back.

Commands

Special CommandTrigger TypeDescriptionNotes
*Unhandled MessageRuns when no other command matches.Timeout: ⏱ 3 seconds. Other command files still execute.
@All Update TypesRuns on every update (text, photo, callback, etc.) excute next command only after finished executionTimeout: ⏱ 2 seconds. Other command files still execute.
@@All Update TypesRuns on every update (text, photo, callback, etc.).In background with other file.Timeout: ⏱ 2 seconds. Other command files still execute.

⚠️ Case-Sensitive Matching:

  • Commands are case-sensitive → "Hi""hi"
  • Commands are case-sensitive → "/start""start"

File Contents

Each file contains logic or interface code:

✅ JavaScript Files (.js)

  • Used to define bot logic and handle user commands.
  • Fully supports modern asynchronous JavaScript (async/await, Promises).
  • Execution is limited by a timeout:
    • Standard: 3 seconds
    • Global Commands (@, *): extra 3 seconds

🌐 HTML Files (.html) + 🎨 CSS Files (.css)

  • Used for Telegram Web Apps, custom UIs, forms, or interactive layouts.
  • Can include full HTML5/CSS3.
  • Best for building rich, responsive experiences inside Telegram.

🧠 Key Takeaways

  • Each file in BuilderEngine is command-driven.
  • Use .js for logic, .html for UI, and .css for styles.
  • The system is flexible with partial matching and global command types.
  • Always structure files clearly and avoid command or filename duplication.

For deeper coding help, refer to the coding documentation.


Coding (JavaScript)

BuilderEngine runs your bot logic using modern JavaScript, including support for async/await, Promises, and ES6+ features. Each .js file represents a handler that responds to specific commands or Telegram updates.

JavaScript Support

BuilderEngine uses an asynchronous JavaScript engine, giving you access to:

  • async/await
  • ✅ Promises
  • ✅ Modern syntax (arrow functions, destructuring, template literals)
  • ✅ Full access to Telegram API via Api.xxxx()

File Template

Each JavaScript file must have proper error handlings.

// Example: Start.js await Bot.sendMessage(`Hello, ${update.message?.from?.first_name || "there"}! 👋`);

When the matching command is triggered (e.g., /start), this function runs.

Available Variables

Your function gets passed a context object with the following fields:

FieldDescription
updateIncoming updates object
userA json object with detials of user
chatA json object with detials of chat
Bot.Class of quick telegram actions
Api.Class of all telegram api methods
HTTPAccess internet with external apis and urls
osAccess server objects and secrets
StorageAccess our official key-value database
ResourceA wrapper build around database for storing users balances

Common Mistakes

  • Forgetting await on asynchronous calls.
  • Trying to use blocking/slow code — stay under timeout!
  • Case mismatch on commands (they're case-sensitive).

Best Practices

  • Structure logic clearly and modularly.
  • Handle both message and callback gracefully.
  • Always validate update by update variable.
  • Use Api. for Telegram-specific tasks like media or formatting.

Need More?

  • Check the Files page to learn how commands link to files.
  • Refer to Telegram Bot API Docs for full method reference.
  • Test your files using /start or by triggering the commands directly.

JavaScript is the brain of your bot—write smart, async-powered logic!


Libraries

Supercharge your bots with our ready-to-use, prebuilt libraries! Whether you're handling data, making HTTP requests, or adding advanced logic, our libraries are designed to make bot development faster, easier, and a lot more fun.

🔧 Why Use Our Libraries?

  • Plug & Play: Just import and go — no boilerplate required.
  • Battle-Tested: Built with performance, stability, and real-world needs in mind.
  • Developer-Friendly: Clean APIs, helpful utilities, and consistent patterns.

✨ What’s Included?

  • HTTP: Simplify external API calls with elegant methods like .get(), .post(), and more.
  • Storage: Lightweight key-value data storage per bot or user instance.
  • More Coming Soon: We're constantly adding new tools to help you build smarter, faster, and cleaner bots.

Whether you're creating a support assistant, game bot, or custom automation — our libraries let you focus on logic, not low-level plumbing.


HTTP Module

The HTTP class provides a simplified interface for making HTTPS requests in Node.js. It supports common HTTP methods such as GET, POST, PUT, DELETE, HEAD, and OPTIONS. Each method returns a promise that resolves with the response body and headers.

All responses follow a unified format with the following structure:

{ body: <string | null>, // Response body as a string (null for HEAD requests) headers: <object>, // HTTP headers as an object error?: <string> // Optional error message if the request fails }

Usage Examples

1. get(url, headers = {})

Sends a GET request to the given URL.

const res = await HTTP.get('https://api.example.com/data'); console.log(res.body);

2. post(url, body, headers = {})

Sends a POST request. The body can be a raw string or an object (automatically stringified).

const res = await HTTP.post('https://api.example.com/data', { name: 'John' }, {'Content-Type': 'application/json'} ); console.log(res.body);

3. put(url, body, headers = {})

Sends a PUT request with a string or object as the request body.

const res = await HTTP.put('https://api.example.com/item/123', { status: 'active' }, { 'Content-Type': 'application/json' }); console.log(res.body);

4. delete(url, headers = {})

Sends a DELETE request.

const res = await HTTP.delete('https://api.example.com/item/123'); console.log(res.body);

5. head(url, headers = {})

Sends a HEAD request. Only headers will be returned, body will be null.

const res = await HTTP.head('https://api.example.com/data'); console.log(res.headers);

6. options(url, headers = {})

Sends an OPTIONS request to determine available HTTP methods and server capabilities.

const res = await HTTP.options('https://api.example.com/data'); console.log(res.headers);

Notes

  • Automatically stringifies objects for POST and PUT requests.
  • Handles request errors gracefully and returns an error field in the result if any issue occurs.
  • Does not throw; always resolves the promise to avoid unhandled rejections.

Storage Module (DataBase)

The Storage class provides a structured interface for storing key-value pairs scoped to a specific entity (e.g., a bot, user, or session). It supports reading, writing, and removing individual or all values in a persistent, queryable format.

⚠️ Important:

  • Both key and value must be strings.
  • The total number of stored properties may be limited by your plan quota. Exceeding this limit may prevent new entries from being saved.

Methods

1. get(key)

Retrieves the value for a given key.

Parameters:

  • key (string): The key to look up.

Returns:

  • string | undefined: The value, or undefined if the key does not exist.

Example:

const language = Storage.get('language');

2. exists(key)

Checks if a specific key exists.

Parameters:

  • key (string): The key to check.

Returns:

  • boolean: true if the key exists, false otherwise.

Example:

if (Storage.exists('theme')) { console.log('Theme is set.'); }

3. set(key, value)

Creates or updates a key-value pair.

Parameters:

  • key (string): The key to store.
  • value (string): The value to associate with the key.

Returns:

  • true: Indicates success.

Example:

Storage.set('mode', 'dark');

⚠️ Note:

  • Both key and value must be strings.
  • The total number of stored properties may be capped based on your subscription plan.

4. delete(key)

Removes a key-value pair.

Parameters:

  • key (string): The key to delete.

Returns:

  • true: Indicates success.

Example:

Storage.delete('mode');

5. clear()

Removes all key-value pairs.

Returns:

  • true: Indicates success.

Example:

Storage.clear();

6. getAll()

Returns all key-value pairs.

Returns:

  • Array<{ key: string, value: string, createdAt: number, updatedAt: number }>: A deep copy of all stored properties.

Example:

const entries = Storage.getAll(); entries.forEach(item => console.log(`${item.key}: ${item.value}`));

Best Practices

  • Always validate that key and value are strings before calling set().
  • Use exists() before using get() when unsure if a key is present.
  • Avoid storing sensitive or large payloads; storage is intended for lightweight configurations.
  • Monitor your usage if on a limited plan.

Example Usage

// Set key-value pairs Storage.set('language', 'en'); Storage.set('theme', 'light'); // Get a stored value console.log(Storage.get('language')); // 'en' // Check if a key exists if (Storage.exists('theme')) { console.log('Theme is:', Storage.get('theme')); } // Get all key-value pairs console.log(Storage.getAll()); // Delete a specific key Storage.delete('theme'); // Clear all entries Storage.clear();

The Storage class is a robust utility for managing scoped, string-based key-value pairs. It is subject to platform-level limits and should be used according to plan allowances.

Here's a well-structured documentation for the Resource and Balance classes, following the format and tone of your Storage module:


Resource Module (User Balances)

The Resource class provides a structured interface to manage per-user resource balances (e.g., coins, credits, points). It uses a single Storage key per user to store a dictionary of all resource types and their balances.

⚠️ Important:

  • All resource types must be non-empty strings.
  • Amounts must be numbers and can be positive or negative.
  • Balance storage is limited per user under a single key and may be subject to quota.

Methods

1. res(resourceType)

Creates a Balance instance scoped to a specific resource (e.g., coins, credits).

Parameters:

  • resourceType (string): The name of the resource.

Returns:

  • Balance: A balance interface for the resource.

Example:

let res = Resource.res("coins") res.add(100);

2. getAllBalances()

Retrieves all balances stored for the user.

Returns:

  • Record<string, number>: A dictionary of all resource types and their balances.

Example:

console.log(Resource.getAllBalances()); // { coins: 100, gems: 50 }

3. clearAllBalances()

Deletes all balances for the user.

Returns:

  • true: Indicates success.

Example:

Resource.clearAllBalances();

class Balance

Manages an individual resource type (e.g., coins, tokens) for a specific user.

Constructor

Not used directly; use Resource.res(resourceType) instead.

Methods

1. add(amount)

Adds (or subtracts) from the current balance. Automatically deletes the key if the result is zero.

Parameters:

  • amount (number): Amount to add (or subtract if negative).

Returns:

  • true: Indicates success.

Example:

let coins = Resource.res("coins") coins.add(50); // Increases coins by 50 coins.add(-10); // Decreases coins by 10

2. getBalance()

Fetches the current balance.

Returns:

  • number: The current balance (defaults to 0 if not set).

Example:

let coins = Resource.res("coins") const balance = coins.getBalance(); console.log(`Coins: ${balance}`);

3. hasBalance()

Checks if any balance exists for the resource.

Returns:

  • boolean: true if a balance exists, false otherwise.

Example:

let coins = Resource.res("coins") if (coins.hasBalance()) { console.log('User has coins'); }

4. clearBalance()

Removes the resource from the user’s balances.

Returns:

  • true: Indicates success.

Example:

let coins = Resource.res("coins") coins.clearBalance();

5. transfer(targetResourceType, amount, conversionRate)

Transfers an amount from the current resource to another, applying a conversion rate.

Parameters:

  • targetResourceType (string): Destination resource type.
  • amount (number): Amount to transfer from the current resource.
  • conversionRate (number): Rate to convert amount to target resource.

Returns:

  • true: Indicates success.

Example:

let coins = Resource.res("coins") coins.transfer('gems', 100, 0.5); // Converts 100 coins into 50 gems

Example Usage

// Add 100 dollars Resource.res('dollar').add(100); // Get balance console.log(Resource.res('dollar').getBalance()); // 100 // Transfer 50 dollars to coins (1 dollar = 10 coins) Resource.res('dollar').transfer('coins', 50, 10); // View all balances console.log(Resource.getAllBalances()); // { dollar: 50, coins: 500 } // Clear all balances Resource.clearAllBalances();

Best Practices

  • Always validate resourceType before use.
  • Use res() to encapsulate resource logic instead of manipulating raw storage.
  • Use getAllBalances() to audit or sync user states.
  • Avoid storing a large number of unused or zero-value resources.

Telegram "Api"

The Api object is a global interface to the Telegram Bot API. It allows you to call any Telegram method directly using async/await. No setup or initialization is required — it's ready to use.

Basic Usage

You can directly call any Telegram Bot API method using Api.<methodName>(params):

Example

const response = await Api.sendMessage({ chat_id: 123456789, text: 'Hello from Api!' }); if (response.ok) { console.log('Message sent:', response.result); } else { console.error('Failed to send message:', response.error); }

Supported Methods

Any method listed in the Telegram Bot API Docs is supported automatically. Here are some common examples:

Get Bot Info

const me = await Api.getMe(); console.log(me);

Send a Message

await Api.sendMessage({ chat_id: 123456789, text: 'Hello World!', parse_mode: 'Markdown' });

Send a Photo

await Api.sendPhoto({ chat_id: 123456789, photo: 'https://example.com/image.jpg', caption: 'Check this out!' });

Batch Api Requests

You can send multiple requests in parallel using:

const results = await Api.batchRequests([ { method: 'sendMessage', params: { chat_id: 123, text: 'Hello' } }, { method: 'getMe', params: {} }, ]); for (const result of results) { if (result.ok) { console.log(result.result); } else { console.error('API Error:', result.error); } }

Usage Data Usage Tracking

The Api instance tracks how much data has been used (in kilobytes):

const res = await Api.sendMessage({ chat_id: 123, text: 'Ping' }); console.log(res.usage) // to get used data in this method // It will a float in kilobytes

⚠️ Note: You may have a data usage limit depending on your plan. Avoid sending large payloads or too many requests to stay within your limit.

Api Error Handling

Always check if the response is successful:

const res = await Api.sendMessage({ chat_id: 123, text: 'Ping' }); if (!res.ok) { console.error('API Error:', res.error); }

Notes

  • Method names must match exactly with the official Telegram API (e.g., sendMessage, getMe, forwardMessage).
  • All keys and values passed in parameters must be strings or serializable values.
  • Data usage may be restricted as per your plan — keep requests optimized.

Telegram API Reference

Refer to the official Telegram Bot API to see a full list of methods and expected parameters.


Secrets (Enviornments)

Use os.secrets to securely access sensitive data such as API keys, tokens, or credentials in your bot logic.

Access Syntax

const apiKey = os.secrets.API_KEY;
  • Replace API_KEY with the name of your configured secret.
  • All secret keys must be valid identifiers (A–Z, 0–9, and underscores).

Example

const token = os.secrets.OPENAI_KEY; if (!token) { await Api.sendMessage({ chat_id: update.message.from.id, text: "OpenAI key is missing from secrets." }); return; } // Use the token in your API call

Use Cases

  • os.secrets.TOKEN – Store some token
  • os.secrets.DB_PASSWORD – Database access credentials
  • os.secrets.OPENAI_KEY – AI service API key
  • os.secrets.STRIPE_SECRET – Payment service keys

Best Practices of Secrets

✅ Recommended🚫 Avoid
Use os.secrets for all sensitive dataDon’t hardcode secrets in your scripts
Use descriptive and scoped namesDon’t log full secret values
Validate secret existence before useDon’t assume secrets are always present

Advantages

  • Secure – Secrets are not exposed in logs or user-facing output.
  • Flexible – Can be configured per environment (e.g., dev vs. prod).
  • Maintainable – Makes bot logic clean and deployment-ready.

Notes

  • If a secret key does not exist, os.secrets.KEY returns undefined.
  • You can’t dynamically list or loop over all secrets — access them by name.

Common Bot Logic Patterns

Below are short, ready-to-use patterns that appear in almost every production bot. Each example uses Api for Telegram calls and Bot.answerCallback() for the next-step handler.

Wait for Answer

The Bot.answerCallback method is used to set a file that will be executed on the user's next message. You can optionally pass a string payload that will be available in that file.

Usage Syntax

Bot.answerCallback(file_name, payload);
  • file name (string) – Name of the file (with .js) to be executed next.
  • payload (string, optional) – Optional string data passed into the next file as payload.

Behavior

  • Executes the specified file when the same user sends the next message.
  • The payload variable is available in that file.
  • Must complete execution within your plan’s time limits.

Notes

  • Both file name and payload must be strings.
  • The callback is one-time and clears after execution.
  • Keep execution time within limits based on your plan.

Example: Ask → Wait → Handle

askName.js

await Api.sendMessage({ chat_id: update.message.from.id, text: "What is your name?" }); Bot.answerCallback("handleName.js");

handleName.js

const name = update.message.text; await Api.sendMessage({ chat_id: update.message.from.id, text: `Nice to meet you, ${name}.` });