How To Make A Telegram Crypto Bot: A Beginners’ guide

Telegram Crypto Bot

Building a bot for your crypto telegram community is not a tough job. You can have an operational Telegram Crypto Bot with a little Python knowledge and some free tools. In this guide, I’ll guide you through the process step-by-step, don’t worry if you’re new; I’ll keep the guide simple explaining the code with live examples.

What Can a Telegram Crypto Bot Do?

Let’s see what you can do with a telegram bot:

  • Fetch Live Prices: You can allow telegram users to check the recent crypto prices with a command. For example, if you want to see Bitcoin’s price today, you can simply ask the bot and get real-time data from the web.
  • Set Alerts: You can set functions, which will allow you to notify your community when a price of a coin reaches a certain limit.
  • Share Market News and Insights: You can integrate different APIs and fetch real-time updates from leading crypto platforms
  • Manage Community Discussions: You can allow your bots to remove spam from the community and keep that fresh. Besides, you can input common FAQs in the programme to reply automatically.

What You’ll Need for a Telegram Crypto Bot?

A Telegram Account: You need a Telegram account to connect with the bot creation tool.

BotFather Access: Telegram’s “BotFather” bot will allow you to create and manage your new bot. You will get an API token with this.

Python Installed: Make sure you have Python 3.6+ installed on your system. If you’re on Windows, download it from the official website. On macOS or Linux, Python often comes preinstalled.

A Text Editor or IDE: You can use Visual Studio Code, PyCharm, or even a plain text editor if you want.

Python Libraries:

  • python-telegram-bot to interact with Telegram’s API.
  • requests to fetch crypto data from external APIs.

You can install them by running the following command:

pip install python-telegram-bot requests

Crypto API Source:

We’ll use CoinGecko’s public API in this guide. It’s totally free and doesn’t seek any API key for basic price data.

Step-by-Step: Building Your First Telegram Crypto Bot

Step 1: Create Your Bot with BotFather

Open Telegram and Find BotFather:
In the search bar, type “BotFather” and start a chat with it.

Create a New Bot:
Type /newbot and follow the directions. BotFather will ask a name and a username (the username must end with “_bot”).

Get Your API Token:
After finishing the setup, BotFather will give you a long token (a set of letters and numbers). Save this token somewhere safe. We’ll add it to our code soon for developing our Telegram Crypto Bot.

Step 2: Set Up Your Python Environment

Create a new folder for your project, open your terminal there, and install the libraries.

pip install python-telegram-bot requests

Step 3: Fetching Crypto Data

We’ll keep the Telegram Crypto Bot simple and just fetch a single coin’s price from CoinGecko. For example, to get Bitcoin’s price in USD, we can hit this URL:

https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd

This returns a JSON object with Bitcoin’s current price in USD.

Create a file named crypto_bot.py and paste the following code:

import logging

from telegram import Update

from telegram.ext import Updater, CommandHandler, CallbackContext

import requests

# Enable logging for debugging

logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)

logger = logging.getLogger(__name__)

# Replace 'YOUR_TELEGRAM_BOT_TOKEN' with the token you got from BotFather

TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"

def start(update: Update, context: CallbackContext) -> None:

update.message.reply_text("Hey there! I’m your crypto bot. Type /price to get the current price. For example: /price bitcoin")

def get_crypto_price(coin: str) -> str:

url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd"

response = requests.get(url)

if response.status_code == 200:

data = response.json()

price = data.get(coin, {}).get('usd')

if price is not None:
return f"The current price of {coin.capitalize()} is ${price}."

else:
return f"Sorry, I couldn’t find data for {coin}."

else:
return "Unable to fetch data at the moment."

def price(update: Update, context: CallbackContext) -> None:

args = context.args

if len(args) == 0:

update.message.reply_text("Please specify a coin. For example: /price ethereum")

return
coin = args[0].lower()

result = get_crypto_price(coin)

update.message.reply_text(result)

def main():

updater = Updater(TELEGRAM_BOT_TOKEN, use_context=True)

dispatcher = updater.dispatcher

# Commands
dispatcher.add_handler(CommandHandler("start", start))

dispatcher.add_handler(CommandHandler("price", price))

# Start the bot

updater.start_polling()

updater.idle()

if __name__ == '__main__':

main()

What This Code Does:

  • Imports: We bring the python-telegram-bot, requests, and logging.
  • Logging: It helps to identify any issues if something isn’t working properly.
  • start Handler: When a user types /start, the Telegram Crypto Bot greets them.
  • price Handler: When a user types /price bitcoin, it fetches Bitcoin’s price and answers with the result.
  • get_crypto_price Function: This function asks CoinGecko’s API to get the price and returns a message.
  • main Function: Sets up the updater with your token, adds the command handlers, and starts the bot’s event loop.

Step 5: Running and Testing the Telegram Crypto Bot

  1. Run the Bot:python crypto_bot.py
  2. Test in Telegram:
    • Go to your bot’s chat (use the username BotFather provided you).
    • Type /start. You should see a greeting message.
    • Type /price bitcoin. If you have set everything properly, you’ll get the latest BTC price.

If something doesn’t work, check your terminal for error messages. Sometimes it’s a token issue or a missing library.

Step 6: Adding More Features

Now that you know the basics, you can do a lot more:

  • Multiple Coins: Update your /price command to accept different coins at once. For example, /price bitcoin ethereum dogecoin.
  • Alerts: Store user opinions (in a database or a local file) and set up due tasks to alert them when a coin’s price hits a certain mark.
  • News and Updates: Use another API to fetch crypto news headlines and share them with your community.
  • Inline Commands: Let users get prices without leaving the chat.

Tips for a Better Telegram Crypto Bot:

  1. Error Handling:
    Keep your API calls in try-except blocks, and if something goes wrong, send a error message instead of letting the bot crash.
  2. Configurable Settings:
    Store your API tokens and configurable data (like default coins or alert thresholds) in a different .env file.
  3. Testing with Friends:
    Send yourTelegram Crypto Bot to some of your friends for testing and take feedback.

More Advanced Ideas

Trading Integration:
You can connect your bot to a trading platform’s API and allow users place real (or test) trades from your Telegram channel. Be careful because this needs secure managing of keys and may be more complicated codes.

Portfolio Tracking:
You can allow users to save their holdings and trace the total value of the portfolio. They can type /portfolio add btc 0.5 to store half a Bitcoin, and /portfolio to see its total worth.

Educating Users:
Add a /learn command at your Telegram Crypto Bot to share any random fact about blockchain, or /faq that responds questions about your token.

Real Example: Enhancing the /price Command

Want to show more than just the price? Let’s add the 24-hour percentage change:

def get_crypto_price(coin: str) -> str:
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd&include_24hr_change=true"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if coin in data:
price = data[coin].get('usd', 'N/A')
change = data[coin].get('usd_24h_change', 'N/A')
return f"{coin.capitalize()}: ${price:.2f} (24h change: {change:.2f}%)"
else:
return f"Sorry, no data for {coin}."
else:
return "Unable to fetch data at the moment."

Now, typing /price bitcoin might yield something like:

Bitcoin: $34000.25 (24h change: -1.23%)

This extra info gives your community more context

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top