So I was exploring Telegram APIs for a project someone asked me to work on it. The script was actually a cron job that would be sending messages on daily basis. While working on it I found that you could come up with your own commands that can pull data from some remote API and display the results to Telegram users. I found this an opportunity for my next blog post which I am writing here 🙂
Telegram is very much similar to WhatsApp for communication and it is quite popular among Crypto lovers. Many Crypto traders use both Telegram and Discord to send crypto and stock signals to their group members.
Telegram apps are called Bots. You create a bot and get an API/Token key used in your program to connect with Telegram servers. You can either create a bot that keeps sending messages itself without any user intervention or the one that takes command as input and responds accordingly. I am going to make a later one.
Creating a bot
The very first thing you have to do is to send a /start
message to the BotFather bot. This bot has a verified tick with it that separates it from other fake bots. When you send a /start
command it sends you a big menu of commands to manage your bot.
You will the /newbot
command and it will ask you to follow a few steps to generate your bot. In the end, it will also send you a message like the below:
Done! Congratulations on your new bot. You will find it at t.me/mybot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API:
2815346687:AAHZIr1IOcWSkEmg21-7Ilal4gH78jML3_4
Keep your token secure and store it safely, it can be used by anyone to control your bot.
Save this token key somewhere because this is the only way you could interact with your bot. In order to make your bot available for invitation from groups, you will have to send /setjoingroups
command. It will ask you to mention your bot name with @ sign. For instance, if my bot name is mybot
then I will write @mybot
and hit the ENTER key. It will show a dialog-like interface in which you will pick the Enable option.
Now you can easily invite your new bot to the group
Development
OK, so your bot is ready. Now you will have to write the code that’d automate this bot. In order to do that you will have to install the python library for telegram.
The very first thing I will do is setting the TOKEN KEY in a separate file. You may use a text/xml/JSON, whatever you want. I just created config.py
and set the token in TOKEN
constant.
Now I am going to create the main script file, called crypto.py
which will serve as a bot controller. In the file import things like the below:
from config import TOKEN from telegram.ext import Updater, CommandHandler USAGE = '/ticker <SYMBOL>: For example: /ticker BTC or /ticker ETH' def start(update, context): update.message.reply_text(USAGE) def main(): updater = Updater(TOKEN, use_context=True) dp = updater.dispatcher # on different commands - answer in Telegram dp.add_handler(CommandHandler("start", start)) # Start the Bot updater.start_polling() updater.idle()
When you run this script it will run in a loop. Go to your group where you added your bot and it sends the text set in the USAGE
variable. Pretty straightforward. You create a dispatch which is an object of Updater
class and then create CommandHandler
to deal with your custom commands. The first parameter of add_handler
is the command you want to send and the second is the function that will be invoked after receiving the command. Unknown commands are discarded by the script. start_polling
will start the script in a loop to accept commands from the bot. Try the /start
command and it should print the text you set in USAGE
variable.
OK, so we have tested our bot, now it is time to write the real code to fetch Crypto prices. I am using Yahoo Finance APIs for that purpose since they are free to use and pretty comprehensive. I create another file, called yf.py
which contains the following code:
Pretty straightforward. Now I am calling this function by doing an import like the below:
from yf import get_ticker_info
I am going to create a new function called ticker_command
which contains the following code:
Now the main()
function , ticker handler command will look like the below:
That’s it. If all goes well, this is how your bot will respond:
Cool, No? Before I conclude, you should notice this very command:
update.message.reply_text(msg, parse_mode='html', disable_web_page_preview=True)
Here I set the message format to HTML
. By default it is text. You may also use Markdown for text formatting. I also disabled the link preview I am also sending the URL for the main source for verification of the coin price
Conclusion
So you learned how simple it is to write a basic Telegram bot in Python. You may make it more complex by logging things in a database or other stuff. The basic structure will be the same. The code is available on Github.
PS: If you loved this post then you might show some love by supporting this blog. Your kind gesture will just help me to learn and share new stuff with awesome people like you.