Telegram Bot Integration
A step-by-step walkthrough for creating a Telegram bot that queries real data from the SAI protocol. No prior bot experience needed!
What You're About to Build
By the end of this guide, you'll have a working Telegram bot that:
Shows perpetual trades for any wallet address
Displays oracle prices for all tokens
Lets users search for specific token prices
Filters trades by asset (BTC only, ETH only, etc.)
Displays results with pagination (Next buttons)
Best part: No database needed! Everything pulls live data from SAI's GraphQL API.
Prerequisites Checklist
Before starting, make sure you have:
Software You'll Need
Python 3.10+ - Download here
Check your version: Open terminal and type
python3 --version
A code editor - Any of these work:
VS Code (recommended for beginners)
PyCharm
Sublime Text
Even Notepad will work!
Terminal/Command Line - You'll need to type a few commands
Accounts You'll Need
Telegram account - To test your bot
A Telegram bot token - We'll get this from BotFather (the official Telegram bot creator tool)
Knowledge Requirements
Basic Python understanding (if-statements, functions, dictionaries)
How to use terminal/command line (navigating folders, running commands)
No GraphQL knowledge needed - We'll explain everything!
Don't have Python installed? This is normal! Follow the download link above and choose your operating system. Python installation is straightforward.
Part 1: Get Your Telegram Bot Token (5 minutes)
Your bot needs a unique token to identify itself to Telegram. Here's how to get one:
Step 1: Open BotFather on Telegram
Open the Telegram app (phone, desktop, or web)
Search for
@BotFatherin the search barClick on it and start a conversation
You should see BotFather respond with a welcome message and commands.
Step 2: Create a New Bot
Send this command:
/newbotBotFather will ask: "Alright! New bot. How are we going to call it? Please choose a name for your bot."
Type something like:
My SAI Trading Bot(this is what appears in Telegram)
BotFather will ask: "Good. Now let's choose a username for your bot. It must end in bot."
Type something like:
my_sai_trading_bot(must end withbot)Example:
sai_price_bot,trading_bot_sai, etc.
Step 3: Copy Your Token
BotFather will send you a message like:
Important: This token is like your bot's password. Never share it publicly or commit it to GitHub!
Part 2: Prepare Your Computer (10 minutes)
Step 1: Create a Project Folder
Open your terminal/command prompt and create a folder for your project:
What this does:
Creates a new folder called
sai-telegram-botMoves you into that folder (you'll work from here)
Step 2: Create a Virtual Environment
A virtual environment is like a sandbox for your project. It keeps your bot's dependencies separate from other Python projects.
On Mac/Linux:
On Windows:
What should happen:
Your terminal prompt should now show
(venv)at the beginningExample:
(venv) user@computer sai-telegram-bot %
If you see (venv) ✅ - Perfect! You're in the virtual environment.
What's a virtual environment? Think of it like a separate Python installation just for this project. If you install packages here, they won't affect your other projects.
Step 3: Create Your Project Structure
Let's create the folders and files you'll need:
What this creates:
Part 3: Install Required Packages (2 minutes)
Packages are like plugins that give Python extra abilities. We need several for this bot.
Step 1: Create requirements.txt
requirements.txtOpen your code editor and create a file called requirements.txt with this content:
What each package does:
python-telegram-bot
Library for creating Telegram bots
requests
Makes HTTP requests to APIs
python-dotenv
Loads secret config from .env file
pytz
Handles timezones
Step 2: Install the Packages
In your terminal (make sure (venv) is showing), type:
This will download and install all the packages. You should see lots of text scrolling by. Wait for it to finish.
Success looks like:
Part 4: Set Up Your Secret Token (5 minutes)
We'll store your bot token in a special file so it's not exposed in your code.
Step 1: Create env.example
env.exampleThis file shows what secrets are needed (without actual values):
Step 2: Create .env
.envCopy the example file:
Now open .env in your editor and replace your_bot_token_here with your actual token from BotFather:
Security note: The .env file should NEVER be shared or committed to GitHub. If you use Git, add .env to your .gitignore file.
Part 5: Build the GraphQL Client (Intermediate)
The "GraphQL client" is code that talks to SAI's data API. Don't worry - we'll explain everything!
What is GraphQL?
GraphQL is a way to ask a server for specific data. Think of it like a restaurant menu:
REST API (old way): "Give me all the data about trades" (you get everything)
GraphQL (new way): "Give me only the trade ID, amount, and price" (you get exactly what you want)
Create bot/graphql.py
bot/graphql.pyThis file handles all communication with SAI's API. Here's the code:
Key concepts explained:
class SaiGQLClient:- A class is like a blueprint. It groups related functions together.def query():- The main function that sends queries to the APIfetch_trades():- Gets trade data for a walletfetch_prices():- Gets token pricesString variables like
$trader- These are placeholders that get filled in with real values
Part 6: Create the Bot's Brain (bot/main.py)
bot/main.py)This is where your bot comes alive! We'll build this in sections.
Section 1: Imports and Setup
Create bot/__init__.py (can be empty):
Create bot/main.py - Start with imports and setup:
What this does:
Imports libraries we installed earlier
Sets up logging so we can debug issues
Imports our GraphQL client
Section 2: Trade Formatting Functions
Add this to bot/main.py:
What this does:
format_trade_open()- Displays an open trade with profit/loss infoformat_trade_closed()- Displays a closed trade with entry/exit pricesThe division by
10^6converts from micro-units (how the API stores numbers) to regular dollars
Section 3: Price Formatting Functions
Add this to bot/main.py:
What this does:
format_prices()- Formats multiple prices with paginationformat_price_single()- Formats a single price nicelyPopular tokens (BTC, ETH, etc.) appear first
Section 4: Command Handlers
Add this to bot/main.py:
What this does:
/startcommand shows welcome message/helpshows the same message
Section 5: The Trades Command
Add this to bot/main.py:
Section 6: The Prices Commands
Add this to bot/main.py:
Section 7: Callback Handler (for buttons)
Add this to bot/main.py:
Section 8: Start the Bot
Add this to the end of bot/main.py:
Part 7: Test Your Bot! (5 minutes)
Step 1: Activate Virtual Environment
Make sure you're in the project folder and the virtual environment is active:
Step 2: Start the Bot
You should see:
This means your bot is running! Leave this terminal open.
Step 3: Test on Telegram
Open Telegram
Search for your bot (the username you created)
Send
/startYou should see the welcome message!
Try these commands:
/start
Shows welcome message
/help
Shows help message
/prices
Shows all token prices
/price BTC
Shows BTC price
/trades nibiru1abc123...
Shows trades (need real wallet address)
Step 4: Stop the Bot
When you're done testing, press Ctrl+C in the terminal to stop the bot.
Troubleshooting
Problem: "TELEGRAM_BOT_TOKEN not found"
Solution:
Check that
.envfile exists in your project rootOpen it and verify the token is there
Make sure there are no spaces:
TELEGRAM_BOT_TOKEN=123456789:ABC...
Problem: Bot doesn't respond to commands
Solution:
Check that the bot is still running (you should see
🚀 Bot is starting...in terminal)Try the
/startcommand firstCheck for errors in the terminal
Problem: "ModuleNotFoundError: No module named 'bot'"
Solution:
Problem: GraphQL errors or "No prices found"
Solution:
Check your internet connection
Verify the endpoint is correct in
.env:Test the endpoint manually in your browser (visit the URL)
How It All Works Together
Here's the flow when someone uses your bot:
Next Steps
Your bot is working! Now you can:
Level Up Your Bot
Add price alerts ("Notify me when BTC hits $100,000")
Add wallet monitoring ("Show me when this address opens a trade")
Add more markets or data sources
Deploy to Production
Run your bot 24/7 on a server (AWS, DigitalOcean, etc.)
Use
systemdor Docker to keep it running
Learn More
Congratulations! 🎉
You've built your first Telegram bot that:
Connects to the SAI protocol
Queries real live data
Displays prices and trades
Handles pagination
Filters by asset
You're now a bot developer!
Common Questions
Q: Can I share my bot with others? A: Yes! They can find it by searching your bot's username on Telegram and click "Start".
Q: Will my bot keep running if I close my computer? A: No. You'll need to deploy it to a server to run 24/7. See the "Deploy to Production" section.
Q: How do I update my bot with new features? A: Edit the Python files, then restart the bot (press Ctrl+C and run python -m bot.main again).
Q: Is it safe to share my bot token? A: No! Treat it like a password. Keep it in .env and never commit to GitHub.
Happy coding! 🚀
Last updated