For the complete documentation index, see llms.txt. This page is also available as Markdown.

TBC Libraries (Libs)

Telebot Creator Documentation — Platform v7.1.2 · Telegram Bot API 10.1

Libraries, often called libs, in Telebot Creator (TBC) enhance the basic TPY functionalities by offering pre-built modules for specific tasks. These libraries make it easier and faster to add advanced features to your Telegram bots, such as handling payments, managing blockchain transactions, working with data, generating random values, and more. DEPRECATION NOTICE:

The following libraries are deprecated and removed:

libs.Polygon, libs.ARB, libs.TTcoin, libs.Tomochain.

Please migrate to libs.web3lib (sendETHER) which now supports all EVM chains, proxy support, and enhanced functionality.

New in 4.9.0:

  • Added native time.sleep() function with a maximum limit of 10 seconds

  • Direct HTTP module usage is now recommended over libs.customHTTP()

  • Code execution timeout increased from 60 to 120 seconds

  • Do not use import statements in your code

  • For handling inline queries and other update types, use the /handler_<update_type> command format

New in 5.0.0:

  • Commands can now run up to 160 seconds (increased from 120 seconds)

  • New stats tracking capabilities in Account and Bot classes

  • Data transfer functionality between bots

  • OpenRouter API support in openai_lib with extended timeouts

New in 7.1.2:

  • New libs.security library — HMAC, Ed25519 verification, AES encryption, hashing

  • Webhook commands now receive options.headers (HTTP headers) and options.ip (caller IP)

  • Full backward compatibility — existing bot code is not affected

5.1 Overview of Libraries

TBC libraries are grouped based on their functionalities to help you develop bots efficiently:

  • Payment Integrations: Automate payments using popular services.

  • Blockchain Transactions: Manage cryptocurrency transfers and transactions.

  • Data Handling: Work with data easily using CSV files.

  • Randomization: Generate random numbers or strings for games and giveaways.

  • Resource Management: Track points, credits, or other resources for users or globally.

7. libs.PremiumGift

Sends Telegram Premium gifts (paid for in Telegram Stars) to users via the bot's own token. The library ships with a built-in GIFTS catalog organised into Budget (15–25 Stars), Premium (50 Stars) and Luxury (100 Stars) tiers, and records every send to the bot's gift history for stats and auditing.

  • Catalog:

    • GIFTS: The built-in catalog dictionary (keys like "heart", "rose", "diamond", each with name, id, stars, category, emoji, description).

    • get_gift_catalog(category=None): Returns the catalog as a list, optionally filtered by "Budget", "Premium" or "Luxury".

    • get_gift_by_key(gift_key) / get_gift_by_id(gift_id): Look up a single gift.

    • get_gifts_by_category(): Returns gifts grouped by category.

    • search_gifts(query): Search by name, description or emoji.

    • get_gift_price_range(): Min/max/average Star prices.

  • Sending:

    • send_gift(user_id, gift_key, message=None, bot_token=None): Sends a catalog gift (by key) to user_id. Uses the current bot's token unless bot_token is supplied. Returns a dict with ok plus details.

    • send_gift_by_id(user_id, gift_id, message=None, bot_token=None): Sends a gift by its raw Telegram gift ID (works even for gifts not in the catalog).

  • History & Stats:

    • get_gift_history(limit=50, status=None, recipient_id=None): Recent sends for the current bot.

    • get_gift_stats(): Aggregate counts and total Stars sent.

  • Settings:

    • set_gift_setting(key, value), get_gift_setting(key, default=None), get_all_gift_settings().

Note: The recipient must allow gifts from your bot, and the bot's Stars balance must cover the gift price. Sending uses Telegram's sendGift Bot API method under the hood.

  • Example:

8. libs.MDxchange

Integrates with the MDxchange payment/automation API for crypto deposits, payouts and Telegram Stars / Premium purchases.

  • Functions:

    • set_api_key(api_key): Stores your MDxchange API key for the current bot. Returns True/False.

    • get_api_key(): Returns the stored API key (or None).

    • deposit(currency, callback_url=None, api_key=None): Creates a deposit request and returns the API response (address/details).

    • payout(currency, amount, address, description="", callback_url=None, api_key=None): Sends a crypto payout to address.

    • buy_stars(username, currency, amount, callback_url=None, api_key=None): Buys Telegram Stars for a username (amount must be at least 50).

    • buy_premium(username, currency, duration, callback_url=None, api_key=None): Buys Telegram Premium for a username (duration must be 3, 6 or 12 months).

  • Example:

9. libs.Coinpayments

Thin wrapper around the CoinPayments API for crypto payment processing.

  • Functions:

    • setKeys(public_key, private_key): Stores your CoinPayments API credentials for the current bot. Returns {"ok": "success"}.

    • post(public_key=None, private_key=None): Returns a configured CoinPaymentsAPI client. If keys are omitted, the stored credentials are used.

  • Example:

Note: The returned client is an instance of CoinPaymentsAPI from the external coinpayments package; its methods are defined by that library, not by Telebot Creator.

10. libs.Webhook

The libs.Webhook library in Telebot Creator allows you to create and manage webhooks for seamless external integrations. Webhooks enable bots to respond to real-time updates from external systems, such as payment notifications or user actions.


Functions

  1. getUrlFor(command, user_id=None, chat_id=None, bot_id=None, api_key=None, **options)

    • Description: Generates a webhook URL for invoking a specific command, optionally tied to a specific user, chat, or another bot.

    • Function Syntax:

    • Parameters:

      • command (str): The command to be triggered by the webhook.

      • user_id (Optional[str]): The user ID associated with the webhook.

      • chat_id (Optional[str]): The chat ID associated with the webhook.

      • bot_id (Optional[str]): The ID of the bot for which the webhook is being generated. If provided, api_key is required.

      • api_key (Optional[str]): The API key of the bot owner. Used for validation when bot_id is specified.

      • **options: Additional options to customize the webhook behavior.

    • In webhook commands, the incoming response data is stored in options, not message. The options object includes the following keys:

      • data: The raw incoming data.

      • json: A parsed JSON object from the webhook payload.

      • headers: (New in 7.1.2) A dictionary of HTTP request headers (e.g., options.headers.get("X-Coinsway-Signature", "")).

      • ip: (New in 7.1.2) The IP address of the client that called the webhook.

    • Examples:

      Basic Webhook URL:

      Webhook for Another Bot:

      Webhook with Additional Options:


Use Cases

  • Payment Confirmation: Generate webhook URLs for real-time payment updates from external systems.

  • Bot-to-Bot Communication: Use bot_id and api_key to enable bots to trigger commands in each other.

  • Dynamic Event Handling: Pass additional options to customize webhook behavior based on the event.

11. libs.DateAndTime

Works with dates and times.

  • Functions:

    • utcnow(): Gets the current UTC date and time.

    • date_now(): Gets the current UTC date.

    • time(): Gets the current UNIX timestamp.

    • now(timezone_str): Gets the current date and time in a specific timezone.

  • Example:

12. libs.Oxapay

Integrates the Oxapay payment system for merchants.

  • Functions:

    • post(merchant_api_key): Initializes the Oxapay client with your API key.

  • Example:

13. libs.customHTTP

Performs HTTP requests with built-in size and timeout limits, SSRF protection, and rotating proxy support. The platform already exposes a ready-made HTTP object built on this class, but you can instantiate your own client when you need custom settings.

The defaults are:

  • Default timeout: 60 seconds (default_timeout=60).

  • Maximum timeout: 120 seconds (max_timeout=120). Requests exceeding this are rejected unless you pass a fallback_command (see below).

  • Maximum response size: 50 MB (max_data_size).

Note: As of version 4.9.0, it's recommended to use the standard HTTP module for most requests; instantiate libs.customHTTP() only when you need a separate client with custom options.

  • Class:

    • CustomHTTP(default_timeout=60, max_data_size=52428800, use_proxy=True): Creates an HTTP client. (52428800 = 50 MB.)

  • Methods:

    • get(url, **kwargs): Performs a GET request.

    • post(url, **kwargs): Performs a POST request.

    • put(url, **kwargs): Performs a PUT request.

    • delete(url, **kwargs): Performs a DELETE request.

    • head(url, **kwargs): Performs a HEAD request.

    • options(url, **kwargs): Performs an OPTIONS request.

    • patch(url, **kwargs): Performs a PATCH request.

    • close(): No-op kept for API compatibility (the shared requests session is reused).

fallback_command (long-running requests): Any request method accepts a fallback_command keyword. If the requested timeout exceeds the 120-second maximum, the request is offloaded to a background worker and the response is delivered to the named TBC command via a webhook when it completes. The call then returns immediately with a {"task_id", "status": "processing", "message": ...} dict instead of the response. Without fallback_command, a timeout over 120 s raises an error.

Security: customHTTP only allows http/https URLs and blocks requests that resolve to internal, loopback, reserved or cloud-metadata addresses (SSRF guard), as well as .gov domains.

  • Example — simple request:

  • Example — offload a slow request:

14. TonLib

New in 4.9.0

Provides comprehensive integration with The Open Network (TON) blockchain. With TonLib, you can create wallets, check balances, send TON, work with jettons (TON's tokens), and integrate TON Connect for user wallet connections.

  • Wallet Management:

    • generateWallet(): Creates a new TON wallet and returns its address and mnemonic phrase.

    • setKeys(mnemonics): Stores a mnemonic phrase for later use.

    • getWalletAddress(mnemonics=None): Retrieves the wallet address from stored keys or specified mnemonics.

  • TON Operations:

    • getBalance(address, api_key=None, endpoint=None): Checks the TON balance of an address.

    • sendTON(to_address, amount, comment=None, mnemonics=None, api_key=None, endpoint=None, is_testnet=False): Sends TON to another address.

    • checkTONTransaction(address, api_key=None, endpoint=None, limit=10): Gets recent transactions for an address.

  • TON Connect Integration:

    • create_ton_connect_session(user_id, expiry_seconds=86400): Creates a session for wallet connection.

    • verify_ton_connect_session(session_id): Checks if a wallet has connected to the session.

    • register_ton_connect_wallet(session_id, wallet_address): Marks a session as connected and stores the connected wallet address (used by your callback after the user approves).

    • create_ton_connect_payload(callback_url, items=None, return_url=None): Builds a raw TON Connect payload / deep link for custom request flows.

    • request_ton_transaction(to_address, amount, comment=None, callback_url="", return_url=None): Requests a TON transfer from a connected wallet.

  • Jetton Operations:

    • get_jetton_metadata(jetton_master_address, api_key=None, endpoint=None): Retrieves information about a Jetton (token).

    • get_jetton_wallet_address(owner_address, jetton_master_address, api_key=None, endpoint=None): Resolves the Jetton wallet address for an owner on a given Jetton master.

    • get_jetton_balance(owner_address, jetton_master_address, api_key=None, endpoint=None): Checks a Jetton balance.

    • request_jetton_transfer(to_address, jetton_master_address, amount, comment=None, callback_url="", return_url=None): Requests a Jetton transfer.

  • Example:

For detailed documentation, see TON Library Documentation.

15. libs.web3lib

Overview: This library is designed to interact with all supported EVM chains. It offers functions to send native coins and tokens (ERC‑20) using advanced features such as automatic gas estimation, retry logic, and optional proxy support. This library is published on Telebot Creator in TPY language.

Supported Networks (31 Total):

  • Ethereum (chainId: 1)

  • BSC (chainId: 56)

  • Polygon (chainId: 137)

  • Avalanche (chainId: 43114)

  • Fantom (chainId: 250)

  • Arbitrum (chainId: 42161)

  • Optimism (chainId: 10)

  • Harmony (chainId: 1666600000)

  • Cronos (chainId: 25)

  • Moonriver (chainId: 1285)

  • Moonbeam (chainId: 1284)

  • Celo (chainId: 42220)

  • Heco (chainId: 128)

  • Okexchain (chainId: 66)

  • Xdai (chainId: 100)

  • KCC (chainId: 321)

  • Metis (chainId: 1088)

  • Aurora (chainId: 1313161554)

  • Base (chainId: 8453)

  • ZKSync (chainId: 324)

  • Scroll (chainId: 534352)

  • Linea (chainId: 59144)

  • Boba (chainId: 288)

  • Kava (chainId: 2222)

  • Fuse (chainId: 122)

  • Evmos (chainId: 9001)

  • Canto (chainId: 7700)

  • Astar (chainId: 592)

  • Telos (chainId: 40)

  • Rootstock (chainId: 30)

  • TTcoin (chainId: 22023)

Key Functions:

  • get_supported_networks() -> Dict[str, Dict[str, Any]] Provides a list of all supported networks with their chain IDs and RPC endpoints.

  • setKeys(private_Key: str) -> str Stores the sender's private key (linked to your current bot ID) in the MongoDB collection.

  • sendNativeCoin(...) -> str Sends native coins (like ETH) on the selected EVM chain. Features include automatic gas estimation, retry logic, and optional proxy support.

  • sendETHER(..., decimals=None) -> str When provided with a token contract address, this function sends ERC‑20 tokens via the contract's transfer method. It supports the same features as sendNativeCoin. Tokens are assumed to have 18 decimals; for tokens that use a different precision (e.g. USDT/USDC with 6 decimals) pass decimals=6. Valid range is 018.

  • getBalance(address, rpc_url=None, network=None, unit="ether") -> float Returns the native coin balance of an address. unit may be "wei", "gwei" or "ether". Alias: get_balance.

  • getTokenBalance(address, contract_address, rpc_url=None, network=None, decimals=None, raw=False) -> float Returns the ERC‑20 token balance of an address. decimals is auto-detected from the contract when omitted (falling back to 18); pass raw=True to get the unscaled on-chain integer. Alias: get_token_balance.

Additionally, the following aliases are available for token transfers: send_ether, sendether, and sendEther (all reference the same function as sendETHER). For more details please read https://help.telebotcreator.com/crypto-libraries-documentation.


Usage Examples

In TPY language on Telebot Creator, you define your function alias like this:

Below are several examples demonstrating how to use these functions:

Example 1: Sending a Native Coin Transfer (ETH)

Example 2: Sending an ERC‑20 Token Transfer

Example 3: Using Network Parameter Only (No Explicit RPC URL)


Summary:

  • This library supports 31 EVM networks with default RPC endpoints.

  • It offers robust functionality with automatic gas estimation, retry logic, and proxy support.

  • Aliases like send_ether, sendether, and sendEther are provided for convenience.

  • It is published on Telebot Creator and written in TPY language.

5.3 Example Use Cases for Libraries

Here are some real-world scenarios where these libraries can be applied:

Payment Automation

Automate payments for subscriptions or services using payment libraries.

  • Example:

User Data Tracking

Manage user data for referral systems or leaderboards with the CSV library.

  • Example:

Crypto Payment Bots

Handle cryptocurrency transactions for services or rewards using libs.web3lib (all EVM chains).

  • Example:

Random Giveaways

Use the Random library to create giveaways or dynamic responses.

  • Example:

Webhook Integrations

Connect your bot with external services using the Webhook library.

  • Example:

16. libs.openai_lib

Provides a client for interacting with OpenAI's API and OpenRouter API, enabling AI-powered features in your bot.

  • Classes:

    • OpenAIClient: Core client for interacting with OpenAI API or OpenRouter API.

    • AIAssistant: Higher-level class for working with OpenAI Assistants or direct chat completions.

  • Error Classes:

    • OpenAIError: Base exception class for OpenAI errors.

    • OpenAITimeoutError: Error for request timeouts.

    • OpenAIAPIError: Error for API-specific issues.

  • Key Methods in OpenAIClient:

    • create_chat_completion: Generates text completions using OpenAI or OpenRouter models.

    • create_assistant: Creates a new OpenAI Assistant (OpenAI API only).

    • create_thread: Creates a new conversation thread (OpenAI API only).

    • create_message: Adds a message to a conversation thread (OpenAI API only).

    • create_run: Runs an assistant on a thread to generate a response (OpenAI API only).

  • Key Methods in AIAssistant:

    • start_conversation: Starts a new conversation thread.

    • send_message: Sends a message and returns the assistant's response.

    • get_conversation_history: Retrieves the history of messages in a thread.

  • New in 5.0.0:

    • Extended timeout support up to 160 seconds

    • OpenRouter API integration with access to various models like Llama

    • Enhanced error handling and retries

  • Example - Chat Completion with OpenAI:

  • Example - Using OpenAI Assistant:

  • Example - Using OpenRouter API:

17. libs.gemini_lib

Provides a client for interacting with Google's Gemini AI models, offering an OpenAI-compatible interface.

Note: The Gemini client caps every request at a 40-second timeout (MAX_TIMEOUT = 40). Any larger timeout value you pass is clamped down to 40 seconds.

  • Classes:

    • GeminiClient: Core client for interacting with Gemini API.

    • GeminiAIAssistant: Higher-level class for working with Gemini in an assistant-like way.

  • Error Classes:

    • GeminiError: Base exception class for Gemini errors.

    • GeminiTimeoutError: Error for request timeouts.

    • GeminiAPIError: Error for API-specific issues.

  • Key Methods in GeminiClient:

    • create_chat_completion: Generates text completions using Gemini models.

    • create_assistant: Creates a new assistant-like interface.

    • create_thread: Creates a new conversation thread.

    • create_message: Adds a message to a conversation thread.

    • create_run: Runs an assistant on a thread to generate a response.

  • Key Methods in GeminiAIAssistant:

    • start_conversation: Starts a new conversation thread.

    • send_message: Sends a message and returns the assistant's response.

    • get_conversation_history: Retrieves the history of messages in a thread.

  • Example - Chat Completion:

  • Example - Using Assistant:


libs.Random

Utility functions for generating random values — handy for games, giveaways, codes and tokens. All functions are also available in lowercase (e.g. randomint, randomchoice).

  • Numbers:

    • randomInt(min, max): Random integer in [min, max] (inclusive). Alias: randomInteger.

    • randomFloat(min, max): Random float in [min, max].

    • randomRange(start, stop, count): count unique integers sampled from [start, stop].

    • randomGaussian(mean, stddev): Random float from a Gaussian (normal) distribution.

  • Strings & bytes:

    • randomStr(length, charSet=None): Random alphanumeric string (or from a custom charSet). Alias: randomString.

    • randomAscii(length): Random string of ASCII letters.

    • randomHex(length): Random hex string of the given length.

    • randomBytes(length): Random bytes object.

    • randomUUID(): A random UUID4 string.

    • randomPassword(length, use_digits=True, use_specials=True): Random password with optional digits and special characters.

  • Collections:

    • randomChoice(data): One random element from data.

    • randomSample(data, k): k unique random elements from data.

    • randomShuffle(data): A new shuffled copy of data (original is left unchanged).

    • randomWeightedChoice(data, weights): One element chosen according to weights.

  • Misc:

    • randomBoolean(): Random True/False.

  • Example:

5.4 Summary of Libraries

Library

Purpose

Key Functions

libs.Resources

Managing user, global and account resources

value, add, cut, set, reset, getAllData, fetchAllResources, fetchAllResourcesOfUser, deleteSingleUserData, deleteAllUsersData, clearAllUserOrAccountData

libs.Coinbase

Coinbase payment integration

setKeys, post

libs.Coinpayments

CoinPayments crypto payment integration

setKeys, post

libs.MDxchange

MDxchange deposits, payouts, Stars & Premium

set_api_key, deposit, payout, buy_stars, buy_premium

libs.PremiumGift

Sending Telegram Stars premium gifts

send_gift, send_gift_by_id, get_gift_catalog, get_gift_history, get_gift_stats, GIFTS

libs.Crypto

Cryptocurrency conversions and pricing

convert, get_price, fetch_price, get_coin_info

libs.Random

Generating random numbers, strings and more

randomInt, randomStr, randomFloat, randomAscii, randomChoice, randomShuffle, randomSample, randomBoolean, randomHex, randomBytes, randomUUID, randomRange, randomGaussian, randomWeightedChoice, randomPassword

libs.CSV

Data management with CSV files

create_csv, add_row, edit_row, get, delete

libs.Webhook

Creating and managing webhooks

genRandomId, getUrlFor

libs.DateAndTime

Working with dates and times

utcnow, date_now, time, now

libs.Oxapay

Oxapay payment integration

post

libs.customHTTP

Performing HTTP requests with constraints

get, post, put, delete, head, options, patch, close

libs.TonLib

TON blockchain, jettons and TON Connect

generateWallet, getBalance, sendTON, get_jetton_balance, create_ton_connect_session

libs.web3lib

EVM-compatible blockchain transactions & balances

setKeys, sendETHER, sendNativeCoin, getBalance, getTokenBalance, get_supported_networks

libs.OpenCV

Image processing (OpenCV/NumPy)

read_image_from_bytes, resize, detect_faces, apply_filter, to_bytes

libs.Pillow

Image editing (PIL)

open_from_bytes, resize, draw_text, add_watermark, to_bytes

libs.openai_lib

OpenAI API integration for AI capabilities

OpenAIClient, AIAssistant, create_chat_completion

libs.gemini_lib

Google Gemini API integration for AI capabilities

GeminiClient, GeminiAIAssistant, create_chat_completion

libs.security

Cryptographic toolkit — HMAC, Ed25519, AES, hashing

hmac_sign, hmac_verify, ed25519_verify, encrypt, decrypt

5.6 Real-World Applications of Libraries

Here are some practical examples of how you can use these libraries in your bots:

Crypto Payment Bots

Handle cryptocurrency payments for services or rewards.

  • Example:

Referral and Loyalty Systems

Manage user points or rewards for referrals and other actions.

  • Example:

Data-Driven Decisions

Log and analyze user data or create leaderboards using CSV files.

  • Example:

Automated Payments

Use Coinbase, Coinpayments, Oxapay or MDxchange libraries to automate payment transfers.

  • Example:

Random Giveaways

Create random giveaways or generate unique codes.

  • Example:

OpenAI Integration

Use the OpenAI library to add AI capabilities to your bot.

  • Example - Chat Completion:

Gemini Integration

Use the Gemini library to add AI capabilities to your bot.

  • Example - Chat Completion:


18. libs.security

New in 7.1.2

A cryptographic toolkit providing HMAC signatures, Ed25519 asymmetric signature verification, AES encryption/decryption, and hashing functions.

  • HMAC (Symmetric Signatures):

    • hmac_sign(secret, data, algorithm="sha256"): Create an HMAC signature. Returns hex string.

    • hmac_verify(secret, data, signature, algorithm="sha256"): Verify an HMAC signature (timing-safe). Returns True/False.

  • Ed25519 (Asymmetric Verification):

    • ed25519_verify(public_key_hex, signature_hex, data): Verify an Ed25519 signature using a public key. Returns True/False.

    • verify_coinsway_webhook(public_key_hex, signature_hex, raw_body): Convenience method for verifying Coinsway webhook signatures.

  • AES Encryption (Fernet):

    • generate_key(): Generate a new Fernet encryption key.

    • encrypt(plaintext, key): Encrypt a string. Returns encrypted token.

    • decrypt(token, key): Decrypt a Fernet token. Returns plaintext.

  • Hashing:

    • sha256(data): SHA-256 hash. Returns hex string.

    • sha512(data): SHA-512 hash. Returns hex string.

    • md5(data): MD5 hash. Returns hex string.

  • Example — Verify a webhook signature:

  • Example — Encrypt user data:

  • Example — HMAC webhook verification:

For detailed documentation, see Version 7.1.2 Update.


19. libs.OpenCV

An image-processing toolkit built on OpenCV (cv2) and NumPy. Images are handled as NumPy arrays: read incoming photo bytes with read_image_from_bytes, process them, then convert back to bytes with to_bytes before sending. (Telebot Creator sandboxes the filesystem, so always work with in-memory bytes — never local file paths.)

  • I/O:

    • read_image_from_bytes(image_bytes): Decode raw bytes into an image array.

    • to_bytes(image, format=".jpg", params=None): Encode an image array to a BytesIO buffer.

    • create_blank(width, height, color=(255, 255, 255)): Create a blank canvas.

  • Geometry & color:

    • resize(image, width=None, height=None), rotate(image, angle), perspective_transform(image, src_points, dst_points).

    • convert_color(image, conversion_type), threshold(image, thresh_value=127, max_value=255, ...), adaptive_threshold(image, max_value=255, ...).

  • Filters & effects:

    • apply_filter(image, filter_type), detect_edges(image, threshold1=100, threshold2=200), morph_operations(image, operation, kernel_size=5), blend_images(image1, image2, alpha=0.5).

  • Drawing:

    • draw_text(image, text, position, ...), draw_rectangle(image, pt1, pt2, ...), find_contours(image, ...), draw_contours(image, contours, ...).

  • Faces:

    • detect_faces(image): Returns a list of (x, y, w, h) face boxes.

    • draw_faces(image, faces, ...): Draws boxes around detected faces.

  • Example — resize a photo the user sent:

  • Example — detect and box faces:


20. libs.Pillow

An image-editing toolkit built on Pillow (PIL). Like libs.OpenCV, it works entirely with in-memory bytes: open_from_bytes to load and to_bytes to export.

  • I/O:

    • open_from_bytes(image_bytes): Load an image from raw bytes.

    • to_bytes(image, format="JPEG", **params): Export an image to a BytesIO buffer.

    • create_image(width, height, color=(255, 255, 255)), create_gradient(width, height, start_color, end_color, ...).

  • Transform:

    • resize(image, width=None, height=None, resample=...), crop(image, box), rotate(image, angle, expand=False), mirror(image, direction="horizontal").

  • Adjustments & filters:

    • adjust_brightness(image, factor), adjust_contrast(image, factor), adjust_color(image, factor), adjust_sharpness(image, factor), apply_filter(image, filter_type), invert(image).

  • Composition:

    • composite(image1, image2, mask=None), paste(base_image, image_to_paste, ...), blend(image1, image2, alpha=0.5), add_border(image, border, color="black"), add_watermark(image, watermark, ...), apply_mask(image, mask).

  • Drawing:

    • draw_text(image, text, position, ...), draw_rectangle(image, xy, ...), draw_circle(image, xy, ...), draw_line(image, xy, ...).

  • Channels & modes:

    • convert_mode(image, mode), split_channels(image), merge_channels(r, g, b).

  • Example — add a caption and border:

  • Example — build a gradient banner:


By using these libraries, you can significantly extend the capabilities of your Telegram bots, making them more interactive, efficient, and feature-rich. Whether you need to handle payments, manage data, or integrate with blockchain technologies, TBC's libraries provide the tools you need to build powerful bots with ease.

4. libs.Resources

The libs.Resources library in Telebot Creator provides a simple and efficient way to track and manage numeric values in your bot. These can represent points, credits, scores, or any other numerical resource.

Resource Classes

userRes

Create and manage resources for specific users.

Parameters:

  • name (Required): The name of the resource.

  • user (Optional): User ID to associate with this resource. Defaults to the current user.

  • bot_id / api_key (Optional): Target another bot's resources (see Cross-bot access below).

globalRes

Create and manage global resources that apply across all users.

Parameters:

  • name (Required): The name of the resource.

  • bot_id / api_key (Optional): Target another bot's resources (see Cross-bot access below).

anotherRes

Create and manage resources for a specific user (even if not the current user).

Parameters:

  • name (Required): The name of the resource.

  • user (Required): User ID to associate with this resource.

  • bot_id / api_key (Optional): Target another bot's resources (see Cross-bot access below).

adminRes

Create and manage resources with administrative privileges. Required for the bulk/fetch/delete methods below.

Parameters:

  • name (Required): The name of the resource.

  • user (Optional): User ID to scope the admin operations.

  • bot_id / api_key (Optional): Target another bot's resources (see Cross-bot access below).

accountRes

Create and manage account-level resources that persist across all bots.

Parameters:

  • name (Required): The name of the resource.

Cross-bot access (bot_id / api_key)

userRes, globalRes, anotherRes and adminRes accept optional bot_id and api_key arguments. Pass them together to read or modify the resources of another bot you own — api_key (the owner's account API key) is validated against bot_id before access is granted. When both are omitted, operations target the current bot.

Resource Methods

All resource classes support the value methods (value, add, cut, set, reset). The data-export and bulk-delete methods (getAllData, fetchAllResources, fetchAllResourcesOfUser, deleteSingleUserData, deleteAllUsersData, clearAllUserOrAccountData) require an adminRes instance (or accountRes for account-level data); calling them on a non-admin resource raises a PermissionError.

value()

Gets the current value of the resource.

Returns: The current numeric value of the resource.

add(value)

Adds the specified amount to the resource.

Parameters:

  • value (Required): The amount to add.

Returns: The new value after addition.

cut(value)

Subtracts the specified amount from the resource.

Parameters:

  • value (Required): The amount to subtract.

Returns: The new value after subtraction.

set(value)

Sets the resource to a specific value.

Parameters:

  • value (Required): The value to set.

Returns: The new value.

reset()

Resets the resource value to zero.

Returns: The new value (always 0).

getAllData(length)

Returns the top entries for this resource, sorted by value (descending). Useful for leaderboards.

Parameters:

  • length (Required): Maximum number of entries to return.

fetchAllResources(output_format)

Exports all resource records for the bot (or the whole account, for accountRes) as a downloadable file. Requires adminRes or accountRes.

Parameters:

  • output_format (Required): "csv" or "json".

Returns: A BytesIO file object.

fetchAllResourcesOfUser(user, output_format)

Exports all of a single user's resource records as a file. Requires adminRes.

Parameters:

  • user (Required): The user ID to export.

  • output_format (Required): "csv" or "json".

deleteSingleUserData(user, data=None, all_data=False)

Deletes one user's data. Requires adminRes.

Parameters:

  • user (Required): The user ID.

  • data (Optional): Resource name to delete (defaults to the instance's name).

  • all_data (Optional): If True, delete every resource belonging to the user.

deleteAllUsersData(data=None, all_data=False)

Deletes a resource across all users of the bot. Requires adminRes.

Parameters:

  • data (Optional): Resource name (defaults to the instance's name).

  • all_data (Optional): If True, delete every resource for the bot.

clearAllUserOrAccountData(data=None)

Clears all records for a named resource (bot scope) or all account-level records (accountRes). Requires adminRes or accountRes.

Parameters:

  • data (Optional): Resource name (defaults to the instance's name).

Examples

User-specific resources:

Global resources:

Managing another user's resources:

Administrative tasks:

Account-level resources:

Last updated