Simple Telegram Crypto Chart Bot using Coingecko

Alexander Vitanov
4 min readJul 6, 2021

Coins such as Doge, Shib and Hoge triggered a meme coin craze lasting for months. Every meme coin needs a community to create and maintain hype and such community is best kept thriving via Telegram groups. Telegram is well known for the useful bots you can interact with such as Captcha bots, Rose and many more. An integral part of every (meme?)coin group is the ability to view an up-to-date chart without leaving the chat. Today, we will learn how to bootstrap such a chart bot for your crypto project.

Goal: typing /chart into the chat will display the following:

Pulling price information from Coingecko

We will pull current coin information from Coingecko and use Python for the purpose. Referencing their free api it’s easy to pull 15-min point price info for the past 24hrs for a coin. I will use LunaDoge coin in this tutorial, so the code and url will look like this:

res = requests.get('https://api.coingecko.com/api/v3/coins/lunadoge/market_chart?vs_currency=usd&days=1')prices_res = res.json().get('prices')

Bootstrapping a Python Telegram project

Now that we know how to pull prices let’s create and connect to our new Telegram bot. First we need to create a Telegram bot:

  1. Open Telegram, then search @botfather
  2. Type /newbot command
  3. Type in a name, for example “LOGE Chart Bot”
  4. Type in a unique username, for example “loge_chart_bot”. It must end in “bot”
  5. Save the API token

Once we have the token we are ready to connect to our price bot from Python using python-telegram-bot. First install the packages:

pip install python-telegram-bot plotly pandas

Then add the needed skeleton:

import pandas as pd
import datetime as dt
import plotly.express as px
import plotly.graph_objects as go
import requests
from datetime import datetime, timezone
import os
from PIL import Image
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
telegram_bot_token = "YOUR_TOKEN_HERE"def save_chart():
pass
def chart(update, context):
chat_id = update.effective_chat.id
save_chart()
context.bot.send_photo(chat_id, photo=open('images/fig1.png', 'rb'))
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
# The chart function will be called when someone types /chart
dispatcher.add_handler(CommandHandler("chart", chart))
# Start listening for chat commands
updater.start_polling()

The flow begins inside chart function where we first fetch price, plot it on a chart, save it to a file images/fig1.png then send it as a response image into the chat. Now as we have the basic template, let’s fetch the price then save it to a chart image file:

def save_chart():
res = requests.get('https://api.coingecko.com/api/v3/coins/lunadoge/market_chart?vs_currency=usd&days=1')
prices_res = res.json().get('prices') for price in prices_res:
dt_object = datetime.utcfromtimestamp(price[0]/1000)
price[0] = dt_object.strftime("%H:%M:%S")

df = pd.DataFrame(dict(
time=[i[0] for i in prices_res],
price=[i[1] for i in prices_res],
))
if not os.path.exists("images"):
os.mkdir("images")
with Image.open("images/background.jpg") as bg_image:
fig = go.Figure()
fig.add_trace(go.Scatter(x=df['time'], y=df['price'], line=dict(width=6), mode='lines'))
fig.update_layout(
plot_bgcolor='#141721',
yaxis_title='Price',
xaxis_title='Last 24h',
xaxis_showgrid=False,
xaxis_showticklabels=False,
yaxis_gridcolor='#2f4a66',
yaxis_tickformat = '.12f',
yaxis_linecolor='#4a89ff',
height=512,
width=1052,
margin=dict(r=0, l=10, b=10, t=0),
font=dict(size=24)
)
fig.add_layout_image(
dict(
source=bg_image,
xref="paper",
yref="paper",
x=0,
y=1,
sizex=1,
sizey=1,
sizing="stretch",
opacity=0.3,
layer="below")
)
fig.write_image("images/fig1.png")

This is the updated save_chart function. We first fetch the prices from Coingecko API for the past 24 hrs, then make sure we format the UTC timestamps to a readable hour:minute:second format:

dt_object = datetime.utcfromtimestamp(price[0]/1000)
price[0] = dt_object.strftime("%H:%M:%S")

then create a panda dataframe to store the data points.

After we have our dataframe you will notice we access images/background.jpg file. This is the background image we use for our chart:

The lines that follow are chart initialization and configuration such as line color and width, background image position, labels, etc. which you can read more about in plotly docs.

Once we are happy with the way our chart looks, we save it to a file

fig.write_image("images/fig1.png")

This is the file we send to the Telegram chat for people to see.

Testing our chart

Now it’s time to test our chart in Telegram. Start the python server

python index.py

then open a chat with your Telegram bot and type /chart

And here we go! We have a simple chart bot to tell our user what the current price is without having to leave the chat!

--

--