Building a Simple Telegram Bot to Fetch Cryptocurrency Prices with Python

Building a Simple Telegram Bot to Fetch Cryptocurrency Prices with Python

Telegram bots have become a popular way to automate tasks, provide services, and interact with users. In this article, we will walk through the process of creating a Telegram bot that fetches cryptocurrency prices in real-time using Python. The bot will allow users to query the prices of various cryptocurrencies by using simple commands.

This article will cover the following:

1. Setting up a Telegram bot using BotFather.

2. Setting Up the Virtual Environment

3. Installing the necessary Python libraries.

4. Writing the Python code for the bot.

5. Deploying and running the bot.

By the end of this article, you will have a fully functional Telegram bot that can fetch cryptocurrency prices and respond to user queries.


Step 1: Setting Up a Telegram Bot Using BotFather

Before diving into the code, you need to set up a bot on Telegram. Telegram provides an official bot called BotFather to help developers create and manage bots.

Steps to Create a New Bot:

1. Search for BotFather:

Open Telegram and search for “BotFather.” This is the official bot management tool provided by Telegram.

2. Start a Chat with BotFather:

Click on the BotFather chat and type /start to begin.

3. Create a New Bot:

Type /newbot and follow the prompts. You will be asked to provide:

— A name for your bot (e.g., “CryptoPriceBot”).

— A unique username for your bot (e.g., “CryptoPriceBot123”).

4. Receive Your Bot Token:

Once the bot is created, BotFather will provide you with an API token (a long string of characters). This token is essential for interacting with Telegram’s API. Save it securely.

5. Customize Your Bot (Optional):

You can use commands like /setdescription, /setabouttext, and /setuserpic to customize your bot’s description, bio, and profile picture.


Step 2: Setting Up the Virtual Environment

To keep dependencies isolated, create a virtual environment:

python -m venv .venv        

Activate the virtual environment:

  • Windows:

.venv\Scripts\activate        

  • macOS/Linux:

source .venv/bin/activate        

Step 3: Installing Required Python Libraries

To build our bot, we’ll use the python-telegram-bot library for interacting with Telegram’s API and requests for fetching cryptocurrency prices from an external API.

Install the Libraries:

Run the following commands in your terminal or command prompt:

pip install python-telegram-bot
pip install requests        

The python-telegram-bot library simplifies the process of creating bots by providing an easy-to-use interface for handling commands, messages, and other interactions.


Step 4: Writing the Python Code

Now that we have our bot token and installed the necessary libraries, let’s dive into the code. Below is the complete Python script for our cryptocurrency price bot:

Code Breakdown:

import logging
import requests
from telegram import ForceReply, Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters        

Enable logging


logging.basicConfig(
 format=”%(asctime)s — %(name)s — %(levelname)s — %(message)s”, level=logging.INFO
)
logging.getLogger(“httpx”).setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# Define command handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 """Send a message when the command /start is issued."""
 user = update.effective_user
 await update.message.reply_html(
 rf"Hi {user.mention_html()}!",
 reply_markup=ForceReply(selective=True),
 )
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 """Send a message when the command /help is issued."""
 await update.message.reply_text("Use /price_currency (e.g., /price_btc) to get cryptocurrency prices.")
def get_crypto_price(symbol: str) -> str:
 """Fetch the latest price of the given cryptocurrency symbol."""
 url = f"https://api.coingecko.com/api/v3/simple/price?ids={symbol}&vs_currencies=usd"
 response = requests.get(url)
 if response.status_code == 200:
 data = response.json()
 if symbol in data:
 price = data[symbol]["usd"]
 return f"The current price of {symbol.upper()} is ${price}"
 else:
 return "Invalid currency symbol. Please try again!"
 else:
 return "Failed to retrieve price data. Try again later."
async def price_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 """Handles commands like /price_btc to fetch cryptocurrency prices."""
 command_text = update.message.text.lower()
 crypto_dict = {
 "btc": "bitcoin",
 "eth": "ethereum",
 "usdt": "tether",
 # Add more cryptocurrencies here…
 }
 if command_text.startswith("/price_"):
 currency = command_text.replace("/price_", "")
 price_info = get_crypto_price(crypto_dict[currency] if currency in crypto_dict else currency)
 await update.message.reply_text(price_info)
 else:
 await update.message.reply_text("Invalid command format. Use /price_currency (e.g., /price_btc)")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
 """Echo the user message."""
 await update.message.reply_text(update.message.text)
def main() -> None:
 """Start the bot."""
 application = Application.builder().token("YOUR_BOT_TOKEN").build()
 application.add_handler(CommandHandler("start", start))
 application.add_handler(CommandHandler("help", help_command))
 application.add_handler(MessageHandler(filters.Regex(r"^/price_\w+$"), price_command))
 application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
 application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
 main()        

Explanation of Key Components:

1. Logging:

The logging module is used to track events during program execution. We configure it to log messages at the INFO level.

2. Command Handlers:

— /start: Welcomes the user.

— /help: Provides guidance on how to use the bot.

— /price_currency: Fetches cryptocurrency prices based on user input.

3. Fetching Cryptocurrency Prices:

The get_crypto_price() function uses the CoinGecko API to fetch real-time prices of cryptocurrencies in USD.

4. Dynamic Price Commands:

Commands like /price_btc or /price_eth are handled dynamically by extracting the currency code from the command text.

5. Echo Handler:

If a user sends a message that isn’t a recognized command, the bot will echo it back.

6. Running the Bot:

The main() function initializes the bot using your API token (replace ”YOUR_BOT_TOKEN” with your actual token) and sets up handlers for commands and messages.


Step 5: Deploying and Running Your Bot

To run your bot locally:

1. Save your script as main.py.

2. Replace ”YOUR_BOT_TOKEN” with your actual bot token from BotFather.

3. Run the script using Python:

 python main.py        

Your bot will start running and listen for user commands on Telegram.


Enhancements and Customization

Here are some ideas to improve your bot:

1. Add More Cryptocurrencies:

Expand the crypto_dict dictionary in the code to include more symbols and their corresponding names.

2. Error Handling:

Improve error messages when users input invalid commands or when API requests fail.

3. Deploying Online:

Use platforms like Heroku or AWS Lambda to host your bot so it can run 24/7.

4. Additional Features:

Add commands for historical price data, market trends, or price alerts.


Conclusion

Creating a Telegram bot is a straightforward process with Python and the python-telegram-bot library. By integrating APIs like CoinGecko, you can build powerful tools that provide real-time information to users. This cryptocurrency price bot is just one example of what you can achieve with Telegram bots. With some creativity and additional features, you can make your bot even more useful and engaging!


For the complete code, please visit my GitHub repository: GitHub Repository.

要查看或添加评论,请登录

Hesam Alavi的更多文章