Telegram price alerts in 50 lines of Python

python dev.to

I recently found myself needing to set up a system to notify me when the price of a particular cryptocurrency reached a certain threshold. I'm sure I'm not the only one who's ever sat watching the market, waiting for a specific price point to be hit. It's tedious and unnecessary, especially when you can automate the process. I decided to write a simple script to handle this for me, and it turned out to be a relatively straightforward task.

Setting up the basics

To start, I needed to choose a library to handle the Telegram notifications. I opted for python-telegram-bot, as it seems to be one of the most popular and well-maintained options. I also needed a way to get the current price of the cryptocurrency I was interested in. For this, I used the CoinGecko API, which provides a simple and free way to get current and historical price data for a wide range of cryptocurrencies.

The code

Here's a simplified version of the script I came up with:

import requests
import time
from telegram.ext import Updater, CommandHandler, MessageHandler

# Set up Telegram bot
TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
updater = Updater(TOKEN, use_context=True)

# Set up CoinGecko API
COINGECKO_API_URL = 'https://api.coingecko.com/api/v3/simple/price'
COIN_ID = 'bitcoin'
CURRENCY = 'usd'

def get_current_price():
    params = {'ids': COIN_ID, 'vs_currencies': CURRENCY}
    response = requests.get(COINGECKO_API_URL, params=params)
    data = response.json()
    return data[COIN_ID][CURRENCY]

def send_notification(price):
    updater.dispatcher.bot.send_message(chat_id='YOUR_CHAT_ID', text=f'Current price: {price}')

def main():
    target_price = 50000
    while True:
        current_price = get_current_price()
        if current_price >= target_price:
            send_notification(current_price)
        time.sleep(60)

if __name__ == '__main__':
    main()
Enter fullscreen mode Exit fullscreen mode

This script will continuously check the current price of the specified cryptocurrency and send a Telegram notification when it reaches the target price.

Expanding the functionality

As I was working on this script, I realized that I wanted to be able to set up multiple alerts for different cryptocurrencies and price points. I also wanted to be able to receive notifications via email or Discord, in addition to Telegram. This started to get a bit more complicated, and I ended up with a much larger script than I had initially anticipated. I actually packaged this into a tool called Crypto Price Alert Bot if you want the full working version, which you can find at https://lukegraggster.gumroad.com/l/crypto-price-alert?utm_source=devto&utm_medium=blog&utm_campaign=traffic_bot. It's been really useful for me, and I think it could be for you too.

Read Full Tutorial open_in_new
arrow_back Back to Tutorials