How to build a Telegram Bot: A Crypto Price Feed Notification Bot
Create your own Telegram bots with this 4 easy steps.
1. Install Python Wrapper for Telegram Bot API and dependencies
First, setup an environment for this project using
virualenv. Check this out for more info about virtualenv and why you should use them. This step is optional, you may skip this BUT keep in mind this is one of the best practices when dealing with multiple projects in python.
$ virtualenv --no-site-packages --python=python3 env
$ source env/bin/activate
The last command activates thevirtualenvwe just created.Install Python wrapper for Telegram bot API
$ pip install python-telegram-bot --upgrade
$ pip install requests
We will use pythonrequeststo pull price data on https://api.liqui.io/api/3/ticker/knc_btc . For this example, We will create a price notifier for KNC the cryptocurrency used in the Kyber Network.
2. Get Started
To get started, we need to create a bot account by asking @BotFather.
- Open Telegram and chat @BotFather enter
/newbotto create a bot account.
- Enter the name of your bot
- Enter the handle of your bot
- Take note of the access token
3. The Code
Now that you have created the bot account, configured and have the access token, let's start coding.
For simplicity, logging and error handling are removed from the code.
The code below defines the required modules and the global constants used in the program. Theaccess tokenwe got above from @BotFather is a required argument to theUpdaterclass which identifies our bot. We also define the URL of https://api.liqui.io/ where we pull the price feed of KNC
- Import modules and constants
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Telegram Bot to send crypto prices (KNC) as messages
# @precise
from telegram.ext import Updater, CommandHandler, Job
from telegram.ext import MessageHandler, Filters
import time, requests, json
updater = Updater("416634744:AAH6mGZsdhawD96wlITvFHBlepyLEuZRKls")
# Get the dispatcher to register handlers
dp = updater.dispatcher
KNC_URL = "https://api.liqui.io/api/3/ticker/knc_btc"
- Define the functions (methods)
For this example we define 4 simple handlers/methods/functions to get our bot up and running. These functions are called as a response to a user's input.
- The start function sends an instruction message to the telegram user on how to use this bot.
- The set function is called when the user inputs
/set secondscommand. The seconds argument specifies the interval between price feed notifications. - The **unset ** function is called when a user inputs
/unsetcommand which turns off the notification. - When a user inputs
/set secondscommand the set function creates a Job that is queued to send a message at a specified interval (seconds).
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
update.message.reply_text('Hi! Use /set seconds to set a timer')
def alarm(bot, job):
r = requests.get(KNC_URL)
data_json = json.loads(r.text)
output = "Last Price: {}\n".format(data_json['knc_btc']['last'])
output += "Buy: {}\n".format(data_json['knc_btc']['buy'])
output += "Sell: {}\n".format(data_json['knc_btc']['sell'])
output += "Volume (BTC): {} BTC\n".format(data_json['knc_btc']['vol'])
output += "Volume (KNC): {} KNC\n".format(data_json['knc_btc']['vol_cur'])
output += "High: {}\n".format(data_json['knc_btc']['high'])
output += "Low: {}\n".format(data_json['knc_btc']['low'])
output += "Ave. Price: {}\n".format(data_json['knc_btc']['avg'])
bot.sendMessage(job.context,text=output)
def set(bot, update, args, job_queue, chat_data):
chat_id = update.message.chat_id
try:
due = int(args[0])
if due < 0:
update.message.reply_text('Sorry we can not go back to future!')
return
job = Job(alarm, due, context=chat_id)
job_queue.put(job)
chat_data[chat_id] = job
update.message.reply_text('Timer successfully set!')
except (IndexError, ValueError):
update.message.reply_text('Usage: /set seconds ')
def unset(bot, update, chat_data):
update.message.reply_text('unsetting timer!')
chat_id = update.message.chat_id
if chat_id not in chat_data:
update.message.reply_text('You have no active timer')
return
job = chat_data[chat_id]
job.schedule_removal()
del chat_data[chat_id]
update.message.reply_text('Timer successfully unset!')
- Register Command Handlers and start the bot
The last part of the code is where we register the handlers/methods defined above to properly respond to a user's input. The bot process is run indefinitely and listen for connections until the process is stop.
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("set", set,
pass_args=True,
pass_job_queue=True,
pass_chat_data=True))
dp.add_handler(CommandHandler("unset", unset, pass_chat_data=True))
# Start the Bot
updater.start_polling()
# Block until you press Ctrl-C or the process receives SIGINT, SIGTERM or
# SIGABRT. This should be used most of the time, since start_polling() is
# non-blocking and will stop the bot gracefully.
updater.idle()
4. Run and Deploy
To run the bot place the above codes, combine them in a single file and name it as you wish. The file extension should be .py
Go back to your virtualenv and run the python script.
$ python my_simple_telegram_bot.py
You may run this as a background process in a server or your own computer using tmux, nohup, or screen
There you go, a very simple Telegram bot notifier for your favorite crypto! Have fun, tweak it and enjoy!
I code with purpose. I am
@precise.