bitcoin
bitcoin

$98681.852816 USD

5.90%

ethereum
ethereum

$3495.006624 USD

5.10%

tether
tether

$0.999544 USD

0.04%

xrp
xrp

$2.329640 USD

7.18%

bnb
bnb

$696.002832 USD

2.08%

solana
solana

$196.189362 USD

5.84%

dogecoin
dogecoin

$0.335499 USD

7.57%

usd-coin
usd-coin

$1.000137 USD

0.01%

cardano
cardano

$0.937165 USD

6.22%

tron
tron

$0.257804 USD

3.04%

avalanche
avalanche

$41.278493 USD

11.70%

chainlink
chainlink

$24.774196 USD

9.89%

toncoin
toncoin

$5.770074 USD

5.03%

shiba-inu
shiba-inu

$0.000023 USD

6.24%

sui
sui

$4.651562 USD

8.65%

Cryptocurrency News Articles

Build a Crypto Telegram Bot with Live Price Updates Using Python

Apr 17, 2024 at 12:01 pm

In this comprehensive guide, we embark on the creation of a Telegram bot using Python, empowering users with real-time crypto updates. This meticulously crafted bot delivers not only the latest prices for any chosen cryptocurrency but also a wealth of additional data. Dive into this guide to explore how it retrieves and displays crucial market metrics like 24-hour price variations, market capitalization, trading volumes, and historical crypto price data. With this vital information at your fingertips, you can navigate the crypto realm with confidence and make well-informed decisions.

Build a Crypto Telegram Bot with Live Price Updates Using Python

Building a Crypto Telegram Bot with Real-Time Price Updates Utilizing Python

In the rapidly evolving world of cryptocurrencies, staying abreast of market fluctuations and asset performance is paramount. To address this need, we present a comprehensive guide on constructing a Telegram bot that empowers users with real-time cryptocurrency updates. This bot not only provides instant access to current prices but also offers a wealth of additional information, such as market capitalization, trading volume, and historical price data.

Functionality Overview

Our Telegram Crypto Bot boasts an array of features designed to provide a comprehensive and real-time overview of the crypto market:

  • Real-Time Crypto Market Data Retrieval: The bot seamlessly fetches and displays real-time market data for various cryptocurrencies, including current price, market cap, volume, and price change percentage.
  • 24h High/Low Prices: Users can access the highest and lowest prices of a specific cryptocurrency over the past 24 hours, a crucial piece of information for active traders and investors.
  • Supply Information: The bot retrieves and presents the circulating supply and total supply of a selected cryptocurrency, offering insights into its scarcity.
  • Top Cryptocurrencies: To provide a quick overview of the leading cryptocurrencies, the bot displays the top 10 coins based on market cap.
  • On-Chain DEX Pool Data: This advanced feature enables users to explore on-chain Decentralized Exchange (DEX) crypto liquidity pools, providing valuable insights into the DEX market.

Prerequisites

Before embarking on this project, ensure that the following prerequisites are met:

  • Python 3.7 or higher installed on your system. Python is a versatile and beginner-friendly programming language that will serve as the foundation for our bot.
  • Telegram account. Telegram is a cloud-based instant messaging platform where our bot will reside.
  • Basic understanding of Python programming. While this guide will provide in-depth instructions, a foundational understanding of Python syntax and concepts will enhance your experience.
  • Text editor: Choose a text editor or Integrated Development Environment (IDE) of your choice, such as Visual Studio Code, Sublime Text, or Atom, to write your code.
  • CoinGecko API: We will leverage the CoinGecko API to fetch the necessary crypto market data. CoinGecko offers a free Demo plan, providing 30 calls per minute and a monthly cap of 10,000 calls. Register for a CoinGecko account and apply for the Demo plan to obtain your API key.

Step 1: Telegram Bot Setup

  1. Create a new bot on Telegram by searching for 'BotFather' and following the prompts. Provide a name and username for your bot.
  2. Upon successful creation, you will receive a token, which serves as your bot's authentication key for Telegram API requests.

Step 2: Installing Python Libraries

We will utilize two essential Python libraries:

  1. python-telegram-bot: This library facilitates interaction with the Telegram API.
  2. requests: This library empowers HTTP requests to the CoinGecko API.

Install these libraries using pip:

pip install python-telegram-bot requests

Step 3: Fetching Cryptocurrency Data

To access cryptocurrency data, we will employ the CoinGecko API, which provides comprehensive market insights beyond price information.

Step 4: Writing the Bot Code

Now that our bot is set up and the libraries are installed, let's delve into the Python code:

# Import necessary libraries
import telebot
from telebot import types
import requests
# Define your CoinGecko API key
cg_api_key = "YOUR_API_KEY_HERE"
# Define the main bot object
bot = telebot.TeleBot(cg_api_key)
# Define command handlers
@bot.message_handler(commands=['start'])
def start(message):
    # Welcome message
    bot.send_message(message.chat.id, "Welcome to the Crypto Telegram Bot! Type /help for a list of commands.")
@bot.message_handler(commands=['help'])
def help(message):
    # Help message
    bot.send_message(message.chat.id, "Available commands:\n/data [crypto-name]: Get current data for a specific cryptocurrency.\n/high_low [crypto-name]: Get highest and lowest prices of a specific cryptocurrency in the last 24 hours.\n/supply [crypto-name]: Get circulating and total supply of a specific cryptocurrency.\n/ranks: Get the top 10 cryptocurrencies.\n/search_pools [query] [network] [attributes]: Get on-chain DEX pool data.")
@bot.message_handler(commands=['data'])
def data(message):
    # Get current data for a specific cryptocurrency
    crypto_name = message.text.split()[1]
    data = get_crypto_data(crypto_name)
    if data:
        # Send the data to the user
        bot.send_message(message.chat.id, f"Current data for {crypto_name}:\nPrice: {data['current_price']} USD\nPrice Change (24h): {data['price_change_percentage_24h']}\nMarket Cap: {data['market_cap']} USD\nVolume (24h): {data['total_volume']} USD")
    else:
        # Handle errors
        bot.send_message(message.chat.id, "Invalid cryptocurrency name. Please try again.")
@bot.message_handler(commands=['high_low'])
def high_low(message):
    # Get highest and lowest prices of a specific cryptocurrency in the last 24 hours
    crypto_name = message.text.split()[1]
    data = get_high_low(crypto_name)
    if data:
        # Send the data to the user
        bot.send_message(message.chat.id, f"Highest and lowest prices of {crypto_name} in the last 24 hours:\nHighest Price: {data['high']} USD\nLowest Price: {data['low']} USD")
    else:
        # Handle errors
        bot.send_message(message.chat.id, "Invalid cryptocurrency name. Please try again.")
@bot.message_handler(commands=['supply'])
def supply(message):
    # Get circulating and total supply of a specific cryptocurrency
    crypto_name = message.text.split()[1]
    data = get_supply(crypto_name)
    if data:
        # Send the data to the user
        bot.send_message(message.chat.id, f"Supply data for {crypto_name}:\nCirculating Supply: {data['circulating_supply']}\nTotal Supply: {data['total_supply']}")
    else:
        # Handle errors
        bot.send_message(message.chat.id, "Invalid cryptocurrency name. Please try again.")
@bot.message_handler(commands=['ranks'])
def ranks(message):
    # Get the top 10 cryptocurrencies
    data = get_top_cryptos()
    if data:
        # Send the data to the user
        top_10 = "\n".join([f"{i + 1}. {crypto['name']}" for i, crypto in enumerate(data)])
        bot.send_message(message.chat.id, f"Top 10 Cryptocurrencies by Market Cap:\n{top_10}")
    else:
        # Handle errors
        bot.send_message(message.chat.id, "Unable to fetch the top 10 cryptocurrencies. Please try again later.")
# Define functions to get data from CoinGecko API
def get_crypto_data(crypto_name):
    # Get current data for a specific cryptocurrency
    response = requests.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=" + crypto_name)
    if response.status_code == 200:
        return response.json()[0]
    else:
        return None
def get_high_low(crypto_name):
    # Get highest and lowest prices of a specific cryptocurrency in the last 24 hours
    response = requests.get("https://api.coingecko.com/api/v3/coins/" + crypto_name + "/ohlc?vs_currency=usd&days=1")
    if response.status_code == 200:
        return response.json()[-1]
    else:
        return None
def get_supply(crypto_name):
    # Get circulating and total supply of a specific cryptocurrency
    response = requests.get("https://api.coingecko.com/api/v3/coins/" + crypto_name + "/market_chart?vs_currency=usd&days=1")
    if response.status_code == 200:
        return response.json()['total_supply_and_circulating_supply']
    else:
        return None
def get_top_cryptos():
    # Get the top 10 cryptocurrencies
    response = requests.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=10")

Disclaimer:info@kdj.com

The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!

If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.

Other articles published on Dec 25, 2024