How to Build a Crypto Telegram Bot (Easy Guide)

Share This Post


In today’s guide, we’ll cover how to build a crypto Telegram bot using Python, that delivers real-time updates on cryptocurrencies. This bot is engineered not only to furnish you with the latest price of any selected cryptocurrency but also to supply additional data. This includes, but is not limited to, changes in price over a 24-hour period, market capitalization, trading volume, and even historical crypto price data. This wealth of information at your fingertips can empower you to make well-informed decisions in your cryptocurrency ventures.

Let’s dive in!


Level of Functionality

In this section, we’ll break down the key functionalities of our crypto Telegram bot, and how these features will provide users with a comprehensive and real-time overview of the crypto market.

  • Fetching and displaying real-time crypto market data – Our bot is already equipped to fetch and display real-time market data for various cryptocurrencies. This includes data such as current price, market cap, volume, and price change percentage. We achieve this by making a GET request to the /coins/markets endpoint of the CoinGecko API.
  • Displaying the 24h highest and lowest prices – The bot can fetch and display the highest and lowest prices of a specific cryptocurrency in the last 24 hours. This information can be crucial for users who are actively trading or monitoring specific cryptocurrencies. We fetch this data from the same /coins/markets endpoint.
  • Fetching and displaying supply information – Our bot can fetch and display the circulating supply and totalidade supply of a specific cryptocurrency. This information can be useful for users who want to understand the scarcity of a pessoal cryptocurrency. Again, this data is fetched from the /coins/markets endpoint.
  • Fetching and Displaying Top Cryptocurrencies – The bot can fetch and display the top 10 cryptocurrencies based on market cap. This feature provides users with a quick overview of the leading cryptocurrencies in the market. We fetch this data by making a GET request to the same /coins/markets endpoint, but with specific parameters to order the results by market cap and limit the number of results.
  • Fetching and Displaying On-Chain DEX Pool Data – Our bot also includes the functionality to fetch and display on-chain DEX crypto liquidity pool data. This feature allows users to search for pools on a network, providing valuable insights into the decentralized exchange (DEX) market. We achieve this by making a GET request to the /onchain/search/pools endpoint.
💡 Pro-tip: Onchain endpoints are exclusively available for paid plan subscribers only. Unlock access to all 20 new /onchain endpoints for on-chain token and liquidity pool data for cryptocurrencies not listed on CoinGecko, by subscribing now

 

Prerequisites

Before we start, ensure you have the following:

  • Python 3.7 or higher installed on your system. Python is a powerful, easy-to-learn programming language that we will use to build our bot.
  • A Telegram account. Telegram is a cloud-based instant messaging app where our bot will live.
  • Basic understanding of Python programming. While this guide will be detailed, having a basic understanding of Python syntax and programming concepts will be beneficial.
  • A text editor: You will need a text editor or an Integrated Development Environment (IDE) to write your code. Some popular options include Visual Studio Code, Sublime Text, and Atom.
  • CoinGecko API: We will be using the CoinGecko API to fetch the crypto market data for cryptocurrencies. The CoinGecko API has a free Demo plan accessible to all users with a 30 calls/min rate limit and a monthly cap of 10,000 calls. Sign up for a CoinGecko account and apply for the Demo plan to get your complimentary Demo API key.
  • We will be using CoinGecko API to fetch the market chart data for cryptocurrencies. The CoinGecko API has a free Demo plan accessible to all users with a 30 calls/min rate limit and a monthly cap of 10,000 calls.

Note: The API key used in this guide is a placeholder and not a real API key. Please replace it with your own CoinGecko API key to make the code work.

 

Step 1: Setting Up Your Telegram Bot

First, you need to create a new bot on Telegram. Here’s how:

  1. Open the Telegram app and search for the ‘BotFather’ bot. BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.

  2. Start a chat and follow the prompts to create a new bot. You’ll need to provide a name and username for your bot.
    Setting Up Your Telegram Bot

  3. After the bot is created, you’ll receive a token. This token is your bot’s “password,” and you’ll need it to send requests to the Telegram API. Keep this token safe as we’ll use it later.

Step 2: Installing Required Python Libraries

We’ll use two Python libraries: python-telegram-bot for interacting with the Telegram API, and requests for making HTTP requests to the CoinGecko API.

Install them using pip:

pip install python-telegram-bot requests

  • python-telegram-bot is a library that provides a pure Python interface for the Telegram Bot API. It supports all types and methods of the API 4.8, and works with Python 3.7+.

  • requests is a simple, yet elegant HTTP library in Python, built for human beings. You’ll be using it to make requests to the CoinGecko API to fetch cryptocurrency data.

Step 3: Fetching Cryptocurrency Data

We’ll use the CoinGecko API to fetch cryptocurrency data. CoinGecko provides a fundamental analysis of the crypto market. In addition to tracking price, volume and market capitalization, CoinGecko tracks community growth, open-source code development, major events and on-chain metrics.

Step 4: Writing the Bot Code

Now that we have our bot set up and our libraries installed, let’s start writing the code for our bot. We’ll be using the python-telegram-bot library to interact with the Telegram API and the requests library to make HTTP requests to the CoinGecko API.

Here’s the complete Python code for our bot:

Step 5: Understanding the Bot Code

In this section, we’ll break down the Python code for our Telegram Crypto Bot to understand each part and its role in the overall functionality of the bot:

  1. Importing Necessary Libraries and Modules: The first step in our code is to import the necessary libraries and modules. These include telegram, telegram.ext, and requests. These libraries provide the tools we need to interact with the Telegram API and make HTTP requests to the CoinGecko API.

  2. Defining the CoinGecko API Key: We define our CoinGecko API key, which is used to authenticate our requests to the CoinGecko API. This key is essential for accessing the cryptocurrency data that our bot will provide.

  3. Defining the get_crypto_data Function: This function fetches data for a specific cryptocurrency from the CoinGecko API. It makes a GET request to the /coins/markets endpoint of the CoinGecko API and returns the data for the specified cryptocurrency.

  4. Defining the get_top_cryptos Function: This function fetches data for the top 10 cryptocurrencies from the CoinGecko API. It makes a GET request to the /coins/markets endpoint of the CoinGecko API with specific parameters to order the results by market cap and limit the number of results.

  5. Defining the get_dex_pools: This function is responsible for fetching on-chain Decentralized Exchange (DEX) pool data from the CoinGecko API. It takes four parameters: query (the name of the pool), network (the network it operates on), include (the specific attributes you want to include in the response), and page (for paginated results). The function sends a GET request to the CoinGecko API with these parameters and returns the response data. If there’s an error during the request, the function will print an error message.

  6. Defining the search_pools: This is an asynchronous function that handles the ‘/search_pools’ command in the Telegram bot. When this command is triggered by a user, the function gets the query, network, and include parameters from the user’s input, calls the get_dex_pools function with these parameters, and sends the returned data back to the user. If the get_dex_pools function doesn’t return any data, the function will send an error message to the user.

  7. Defining the Bot Commands: We define several commands that the bot can respond to. Each command is a function that takes an update and context as arguments. The update argument contains information about the incoming message, and the context argument contains information about the current state of the bot.

  8. Creating an Instance of the ApplicationBuilder Class: We create an instance of the ApplicationBuilder class, passing in our Telegram bot token. This instance is used to register our command handlers and start the bot.

  9. Adding Handlers for Our Commands: We add handlers for our commands using the add_handler method of our ApplicationBuilder instance. Each handler is an instance of the CommandHandler class, which takes the name of the command and the function to be called when the command is received.

  10. Starting the Bot: Finally, we call the run_polling method of our ApplicationBuilder instance to start the bot. This method starts a long polling process that checks for new updates from the Telegram server.

Step 6: Testing the Bot

To test the bot, follow these steps:

  1. Run the Python script in your terminal using python <your_file>.py, in this case python bot.py
    Run the Python script in your terminal

  2. Open the Telegram app and search for your bot using the username you provided when creating the bot. In our case it is crypto-gecko-bot.

  3. Start a chat with your bot and try out the commands. Here are the commands you can use:

    1. /start: Starts the bot.

    2. /data <crypto-name>: Gets the current data for a specific cryptocurrency. For example, you can type /data bitcoin to get the current data for Bitcoin.

    3. /high_low <crypto-name>: Gets the highest and lowest prices of a specific cryptocurrency in the last 24 hours.

    4. /supply <crypto-name>: Gets the circulating supply and totalidade supply of a specific cryptocurrency.

    5. /ranks: Gets the top 10 cryptocurrencies.

    6. /search_pools:  This command fetches and displays on-chain Decentralized Exchange (DEX) pool data.

Eg: Lets try /data bitcoin

/data bitcoin in your Telegram bot

Once we type /data bitcoin in your Telegram bot, the bot will fetch data for Bitcoin from the CoinGecko API using the get_crypto_data function in the Python program.

The bot will then send a message back to you with the current price of Bitcoin, the price change in the last 24 hours, the market cap, and the totalidade volume in the last 24 hours.

Now lets try /ranks

live crypto prices in telegram bot | crypto data api

When you type /ranks in your Telegram bot, the bot will fetch data for the top 10 cryptocurrencies from the CoinGecko API using the get_top_cryptos function in the Python program.

The bot will then send a message back to you with a list of the top 10 cryptocurrencies. 

 Now let’s try /search_pools weth eth base_token command

search for dex pools in telegram crypto bot | crypto dex api

When we run the /search_pools weth eth dex command, the bot fetches on-chain DEX pool data from CoinGecko for the specified query, network, and attributes. In this case, it searches for pools related to ‘weth’ on the ‘eth’ network. The bot then formats this data into a more human-readable format and displays it in the chat. This includes details such as the Pool ID, Pool Name, Base Token Price (USD), Quote Token Price (USD), and Totalidade Liquidity. Additionally, it provides the price change percentage in the last 5 minutes, 1 hour, 6 hours, and 24 hours. This feature gives users valuable insights into the decentralized exchange (DEX) market, enhancing the bot’s capabilities and offering a more comprehensive view of the crypto market landscape.

Do note that this is a basic implementation and does not include error handling or robustness that a production-level bot might require. Always ensure to handle exceptions and edge cases when writing your own bot.

Advanced Functionalities and Useful Endpoints

While the guide above covers the basic development of a crypto tracker bot, developers who might want to expand the bot’s functionalities can consider the following:

  • Crypto Market Data
    Provide the user with various market data such as market cap, volume, liquidity, dominance, and sentiment on the dashboard using the /global and /coins/markets endpoints. This data can give users a comprehensive overview of the current state of the crypto market.

  • Crypto Asset Tracking
    Implement functionality to track a wider range of crypto assets. This could involve integrating with CoinGecko’s /coins/list endpoint to fetch a comprehensive list of all available cryptocurrencies. This feature can help users keep track of a diverse portfolio of crypto assets.

  • Real-Time Price Updates
    Allow users to receive real-time price updates for their specified crypto assets. This would involve interacting with the /simple/price endpoint. Real-time price updates can help users make timely investment decisions.

  • News, Trends & Sentiment
    Integrate /search/trending and social media analysis for sentiment-based alerts, and display the latest news, trending coins, and popular categories from the crypto space on the dashboard using the /search/trending and /coins/categories/list endpoints. Staying updated with the latest news and trends can help users make informed investment decisions.

  • Fetching and Displaying Portfolio Details
    Adding a portfolio management feature to your bot can provide users with real-time overviews of their crypto investments. This includes totalidade portfolio value, individual asset values, and changes over time. It can also track performance, diversification, and risk, helping users make informed decisions. This feature would require integration with additional APIs or services that provide access to user portfolio data.

💡Pro-tip: Developing advanced features requires familiarizing yourself with the API documentation, understanding the various endpoints you’ll be interacting with, and the specific data each endpoint provides. Always prioritize the accuracy of your bot’s data and adhere to best practices in the crypto industry.

Coin Gecko API plans and pricing


Conclusion

And there you have it! You’ve just built a basic Telegram bot that provides real-time cryptocurrency price updates. This bot can be a handy tool for crypto enthusiasts who want to stay updated with the latest crypto prices. You can add more features like alerts for significant price changes, portfolio tracking, and more.

We hope you found this guide informative and helpful. Stay tuned for more guides on exciting tech topics, and happy coding!


Interested in similar how-to guides using CoinGecko API? Check out this low-code tutorial where we cover how to build an AI crypto chatbot with Flowise.

Tell us how much you like this article!

Rollend Xavier

Rollend Xavier

Rollend is a Microsoft Certified Cloud Architect with 16 years of experience. He is the author of the book “Automate Your Life: Streamline Your Daily Tasks with Python: 30 Powerful Ways to Streamline Your Daily Tasks with Python”.
Follow the author on Twitter @RollendXavier



Related Posts

Jack Dorsey says he’s no longer on the Bluesky board

It sounds like Bluesky’s most prominent backer is...

Azuki NFT Sets Records Despite Crypto Market Slump

Even though the crypto market is facing challenges,...

Farewell, dunks? Threads launches quote controls for all users

Threads users can now exert more control over...

BDAG’s 10 New Payment Options vs. DOGE & Solana (SOL) Price Prediction

As cryptocurrency markets grapple with fluctuations, BlockDAG distinguishes...

BlockDAG’s X1 Miner App Beta Launch Set for June | Cardano Developments

BlockDAG is set to release the beta version of...