Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.servflow.io/llms.txt

Use this file to discover all available pages before exploring further.

Build a fully functional Telegram bot that allows users to interact with their Binance accounts through natural language. The bot uses an AI agent to understand user requests and execute trading operations on their behalf — all configured through the ServFlow dashboard without writing code.
What you’ll build:
  • A Telegram bot that responds to messages via webhook
  • Secure per-user credential storage in MongoDB
  • AI-powered natural language processing for trading commands
  • Dynamic Binance integration using stored credentials
  • Account balance checking and price history tools

Import & Run

Get started immediately by importing the complete workflow:
1

Download the Configuration

Download the workflow from the ServFlow Cookbook
2

Import into ServFlow

In the ServFlow dashboard, click Import in the Files panel and select the downloaded YAML file
3

Configure Integrations

Set up the required integrations:
  • mongo-main — MongoDB for storing user credentials
  • open-ai-main — OpenAI for the AI agent
4

Add Your Bot Token

Go to SettingsSecrets and add:
NameValue
TELEGRAM_BOT_TOKENYour bot token from BotFather
5

Set the Telegram Webhook

Tell Telegram where to send messages:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-servflow-domain.com/telegram"}'
6

Test Your Bot

Open your bot in Telegram and try:
  • /save_creds your_api_key your_secret_key — Save Binance credentials
  • “What’s my account balance?” — Check your balance
  • “Show me BTC price history for the last 12 hours” — Get price data
For local development, use ngrok to expose your local ServFlow instance to the internet.

How It Works

The rest of this guide explains how the imported workflow is structured and what each component does.
Telegram bot workflow flowchart showing message processing logic
The workflow follows this decision tree:
  1. New message arrives → Check if user has stored Binance credentials
  2. If credentials exist → Send typing indicator → Process with AI agent → Send response
  3. If no credentials → Check if message is a /save_creds command
  4. If save command → Store credentials → Confirm to user
  5. If not save command → Tell user how to save credentials

Workflow Entry Point

The workflow listens for Telegram webhook requests via an HTTP POST endpoint.
SettingValuePurpose
Listen Path/telegramThe URL path Telegram sends messages to
HTTP MethodPOSTTelegram webhooks use POST requests
Telegram sends webhook payloads as JSON containing message details. The key fields are message.chat.id, message.from.id, and message.text.

Telegram Field Presets

Throughout this workflow, you’ll see references to Telegram message data. ServFlow automatically detects Telegram webhooks and provides convenient presets in the content editor. When editing any field, open the content editor and expand Popular VariablesTelegram:
Content editor showing Telegram preset variables including User ID, Message Body, and Chat ID
PresetTemplate SyntaxDescription
User ID{{ body "message.from.id" }}Unique identifier of the message sender
Message Body{{ body "message.text" }}The text content of the message
Chat ID{{ body "message.chat.id" }}The chat/conversation identifier
Click any preset to insert it automatically — no need to memorize the syntax!

Action: Fetch Credentials

Type: fetch This action checks if the user has already stored their Binance API credentials in the database.
FieldValuePurpose
Integration IDmongo-mainThe MongoDB integration to query
TablecredentialsCollection storing user credentials
Single Result✅ EnabledReturn one document instead of an array
Should Fail✅ EnabledTrigger fail path if query fails
Fail If Empty✅ EnabledTreat no results as a failure

Filter Configuration

FieldOperationComparator
user_id==User ID preset

Routing

PathDestinationWhen
NextIs typingUser has stored credentials
Failparse_commandNo credentials found

Action: Parse Command

Type: javascript When a user doesn’t have credentials, this action parses the incoming message to check if they’re sending a /save_creds command.

Script Logic

function servflowRun(vars) {
  const text = "{{ body \"message.text\"}}";
  const match = text.trim().match(/^\/(\w+)\s*(.*)$/);

  if (!match || match[1].toLowerCase() !== "save_creds") {
    return { command: "", args: [] };
  }

  const command = "/" + match[1];
  const args = match[2]?.trim() ? match[2].trim().split(/\s+/) : [];
  
  return { command, args };
}

Output

FieldDescription
.parse_command.commandThe parsed command (e.g., /save_creds) or empty string
.parse_command.argsArray of arguments (e.g., ["api_key", "secret_key"])

Conditional: Is Save Credentials

Type: conditional Checks if the parsed command is /save_creds.
FieldValue
Expression{{ eq .parse_command.command "/save_creds" }}

Routing

PathDestinationWhen
Truesave_credsUser is saving credentials
FalseAdd credentialsUser needs instructions

Action: Save Credentials

Type: store Stores the user’s Binance API credentials in MongoDB.
FieldValuePurpose
Integration IDmongo-mainMongoDB integration
TablecredentialsCollection to store in

Fields Stored

Field NameValuePurpose
user_idUser ID presetLinks credentials to Telegram user
api_key{{ index .parse_command.args 0 }}First argument from command
api_secret{{ index .parse_command.args 1 }}Second argument from command
saved_at{{ now }}Timestamp for record-keeping

Action: Credentials Saved (HTTP)

Type: http Sends a confirmation message to the user via Telegram.
FieldValue
HTTP MethodPOST
URLhttps://api.telegram.org/bot{{ secret "TELEGRAM_BOT_TOKEN" }}/sendMessage

Request Body

FieldValue
chat_idChat ID preset
textCredentials saved successfully

Action: Add Credentials (HTTP)

Type: http Tells users without credentials how to save them.
FieldValue
HTTP MethodPOST
URLhttps://api.telegram.org/bot{{ secret "TELEGRAM_BOT_TOKEN" }}/sendMessage

Request Body

FieldValue
chat_idChat ID preset
textPlease add credentials first with /save_creds <api_key> <secret_key>

Action: Is Typing (HTTP)

Type: http Sends a “typing” indicator so users know the bot is processing their request.
FieldValue
HTTP MethodGET
URLhttps://api.telegram.org/bot{{ secret "TELEGRAM_BOT_TOKEN" }}/sendChatAction?chat_id={{ body "message.chat.id" }}&action=typing

Action: Agent LLM

Type: agent The AI agent that understands natural language and decides which tools to use.
FieldValuePurpose
Integration IDopen-ai-mainOpenAI integration
Conversation IDChat ID presetMaintains context across messages
Return Last Message❌ DisabledReturn full agent response

System Prompt

You are a helpful telegram bot for performing actions on behalf of a user. You have access to tools to help you achieve your request.

User Prompt

Message Body preset — the actual message text from the user.

Tool: Price Difference

Allows the agent to fetch price history data.
FieldValue
Typeworkflow
Nameprice_difference
DescriptionGets price history ticks for a period. The period is the number of 1hr intervals (e.g., 12), the symbol is the pair (e.g., BTCUSDT)
Parametersperiod, symbol
Start ActionBinance Price Difference
Return Value{{ escape (jsonout .get_price_difference) }}

Tool: Account Balance

Allows the agent to check the user’s Binance balance.
FieldValue
Typeworkflow
Nameaccount_balance
DescriptionFetches the account balance of the user
Parameters(none)
Start Actionfetch account balance
Return Value{{ .get_account_balance }}

Action: Binance Price Difference

Type: binance/pricedifference Called by the agent’s price_difference tool.
FieldValuePurpose
Integration IDtelegram_bot_cred_storage_binanceDynamic Binance integration
Interval1hCandlestick interval
Period{{ tool_param "period" }}From agent tool call
Symbol{{ tool_param "symbol" }}From agent tool call
The tool_param function accesses parameters passed by the AI agent when it calls this tool.

Action: Fetch Account Balance

Type: binance/accountbalance Called by the agent’s account_balance tool.
FieldValuePurpose
Integration IDtelegram_bot_cred_storage_binanceDynamic Binance integration
Futures❌ DisabledQuery spot account
Symbol(empty)Return all balances

Action: Telegram Reply (HTTP)

Type: http Sends the AI agent’s response back to the user.
FieldValue
HTTP MethodPOST
URLhttps://api.telegram.org/bot{{ secret "TELEGRAM_BOT_TOKEN" }}/sendMessage

Request Body

FieldValue
chat_idChat ID preset
text{{ .agent_llm | escape }}
The escape function ensures special characters in the AI response don’t break the JSON payload.

Dynamic Binance Integration

The key to supporting multiple users is the lazy-loaded integration that uses each user’s stored credentials.
FieldValuePurpose
IDtelegram_bot_cred_storage_binanceReferenced by Binance actions
TypebinanceBinance exchange integration
Lazy Load✅ EnabledOnly initialize when first used

Dynamic Credentials

FieldValueSource
API Key{{ .fetch_credentials.api_key }}From MongoDB query
Secret Key{{ .fetch_credentials.api_secret }}From MongoDB query
Testnet❌ DisabledUse production (enable for testing)
Timeout30Request timeout in seconds
Lazy Load means the integration initializes only when an action uses it. At that point, the credentials from the fetch_credentials action are available, allowing each user’s Binance operations to use their own stored API keys.

Response Definitions

Success Response

FieldValue
Namesuccess
Status Code200
Response Fieldmessage: Reply sent via Telegram

Error Response

FieldValue
Nameerror
Status Code500
Response Fielderror: {{ .error }}

Testing

Use ServFlow’s test mode to simulate requests without setting up the Telegram webhook.
Test run button location in the ServFlow dashboard
Click the Play button in the top-right corner and enter a sample payload:
{
  "message": {
    "message_id": 123,
    "from": {
      "id": 12345678,
      "first_name": "Test",
      "username": "testuser"
    },
    "chat": {
      "id": 12345678,
      "type": "private"
    },
    "text": "What is my account balance?"
  }
}

Security Considerations

Important security notes:
  1. Never share your bot token — Anyone with the token can control your bot
  2. Use HTTPS — Always deploy with SSL to protect credentials in transit
  3. Consider encryption — For production, encrypt stored API credentials at rest
  4. Rate limiting — Consider adding rate limiting to prevent abuse
  5. API key permissions — Use Binance API keys with minimal required permissions

Extending the Bot

Now that you understand how the bot works, consider adding:
  • More Binance tools — Spot/futures trading, order management
  • Price alerts — Scheduled checks that notify users of price movements
  • Trade logging — Store trades to MongoDB for user history
  • Multi-exchange support — Add integrations for other exchanges
ServFlow workflow showing all configured actions

Next Steps

AI Agents

Learn more about configuring AI agents and tools.

Binance Trading

Explore all available Binance actions.

Data Operations

Master MongoDB and database operations.

Secrets Management

Securely manage API tokens and credentials.