Covalent Telegram Bot

“One unified API. One billion possibilities.”This title appears on the Covalent homepage. It was exciting for me to test this API at work. The idea came to my mind to create a Telegram bot in Python, which, using the Covalent API, accesses any ETH electronic wallet (whatever you want) and checks its balance. Bots today are a multifunctional tool for business and entertainment. In this article, I will describe how to create such a bot.

Step 1: API key

Get a free API key at https://www.covalenthq.com/

Step 2: Bot Father

In the telegram search, you need to find Bot Father and create your bot using the command.

/newbot

Then enter the name and username. Please note that the username must end with bot As you can see, we were given a special API token to control your bot. You can remember your token, but I recommend writing it down.

Step 3: Code

We can start writing the code. The first thing we need to do is import the required libraries. We will import Telebot and Pandas Libraries for data processing. The Requests library is used for interacting with APIs.

import requests
import telebot
import pandas as pd

Next, create a URL variable, and set the Covalent API address as its value. For this step, it is important to note that: “my_key” variable is the Covalent API key associated with your Covalent account. Kindly replace “YOUR_COVALENT_API_KEY” with the key you received in the first step when you signed up on Covalent.

url = "https://api.covalenthq.com"
chain_id = "1"
my_key = "YOUR_COVALENT_API_KEY"

Next, Create the bot variable. Substitute “YOUR_TELEGRAM_BOT_TOKEN” assigned to the “telegram_token” variable, with your api token from step 2.

#CovalentBot
telegram_token = “YOUR TELEGRAM_BOT_TOKEN”
bot = telebot.TeleBot(telegram_token)

Next, we will create a keyboard that the bot will show you at startup. Create a variable “keyboard1”, and assign it the value :

telebot.types.ReplyKeyboardMarkup() 

This function calls the keyboard. So that the created buttons do not look large, you need to register True in ReplyKeyboardMarkup(). Well, if you want the keyboard to hide as soon as the user presses on it, then write a second True. Next, we will create rows, but remember that there can be no more than 12 rows! To create them, write keyboard1.row (). Then, put “💰Balance” and “Show adr”, “Add adr”, “Del adr” in parentheses.

keyboard1 = telebot.types.ReplyKeyboardMarkup(True, True)
keyboard1.row('💰Balance', 'Show adr')
keyboard1.row('Add adr', 'Del adr')

Let’s create a dictionary for users’ wallets.

users_addr = {}

Now, to call the keyboard, add reply_markup = keyboard1 to the function for sending a message at startup. Here’s what you should get:

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!', reply_markup=keyboard1)

Next, let’s set the following logic:

  • when you click on the “Add adr” button, our bot will request the address of your ETH wallet;
  • when you click on the “💰Balance” button, our bot using the Covalent API will request the balance of your wallet and display it on the screen;
  • when you click on the “Show adr” button, the address of the ETH wallet will be shown;
  • when you press the “Del adr” button, the address will be deleted.
@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text == '💰Balance':
        chat_id = message.chat.id
        if chat_id in users_addr:
            address = str(users_addr[chat_id])[2:-2]
            get_token_balances_for_address = f"/v1/{chain_id}/address/{address}/balances_v2/"
            result = requests.get(url+ get_token_balances_for_address).json()
            result = result.get('data').get('items')
            df = pd.DataFrame(result)
            df = df[['contract_decimals', 'contract_name', 'balance']].loc[df['balance'] != '0'].loc[df['contract_decimals'] != 0]
            df['balance'] = round(df['balance'].astype('float') / (10 ** df['contract_decimals']), 2).astype('str')

            for i in range(df.shape[0]):
                bot.send_message(message.chat.id, ''.join(df[['contract_name']].values[i]) + ' ' + ''.join(df[['balance']].values[i]))

        else:
            bot.send_message(message.chat.id, text='Set up your Eth address, please.')

    elif message.text == 'Show adr':
        chat_id = message.chat.id

        if chat_id in users_addr:
            bot.send_message(message.chat.id, text=users_addr[chat_id])
        else:
            bot.send_message(message.chat.id, text='Set up your Eth address, please.')

    elif message.text == 'Add adr':
        bot.send_message(message.chat.id, text='Input your Eth address:')
        bot.register_next_step_handler(message, add_adr)

    elif message.text == 'Del adr':
        chat_id = message.chat.id
        del users_addr[chat_id]
        bot.send_message(message.chat.id, text='Your Eth address has been deleted.')

def add_adr(message):
    adr = message.text
    chat_id = message.chat.id
    users_addr[chat_id] = [adr]

Now we will write bot.polling (). This is necessary so that the bot does not turn off immediately but works and checks if there is a new message on the server. You should put this at the end of the code.

bot.polling()

As a result, we have the following bot. There is only one coin on this wallet address used, but if there are many of them, then the balance is displayed for all coins. The most interesting moment in this program is the call to the Covalent API. Here I used the get_token_balances_for_address function, a detailed description can be found at https://www.covalenthq.com/docs/api/#get-/v1/ {chain_id }/address/ {address }/balances_v2/. As a result, after completing all the steps listed above, you can get a working bot with useful functions. It is also necessary to provide for the bot to be launched on some server for smooth operation.

In my opinion, it’s amazing how easy and fast you can get data from the blockchain using the Covalent API. As a result, there are incredible opportunities for data analysis and for creating various applications.

Last Updated: 5/29/2021, 9:55:36 AM