Telegram Bots 101
Telegram Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests.
Okay boring part is over. Let's get to making one?
Mission: Create a simple Telegram bot using Python
Prerequisites:
1. Computer with Python installed
2. Basic Python skills (I'll include some links at the end for those who want to learn Python)
In order to interact with the Telegram Bot API we need an API token. You can get one by creating a bot via @BotFather on Telegram. It's pretty straight forward. Send the command /newbot and follow the instructions. Once the bot is created you will get the bot token.
Before we get to coding, Install python-telegram-bot package via Python.
pip install python-telegram-bot
Let's get to coding. We are going to get a joke from an API and send it to as a message every 2 minutes. (Just for demonstration purposes. Don't go flooding yourself)
import telegram
import requests
import json
import time
#Replace with your API token and chat ID
bot_token = '899523772:AAGGzRMuQCBJU6o0AUZWOo2loUZBMgek6kE'
chatid = 'XXXXXXX'
while True:
#Get the joke as JSON from Chuck Norris API
req = requests.get('https://api.chucknorris.io/jokes/random').json()
#Get the joke as plain text from JSON
joke = req['value']
#Initializing bot with token
bot = telegram.Bot(token=bot_token)
#Sending the message
bot.send_message(chat_id=chatid, text=joke)
#Sleep for 120 seconds (2 minutes)
time.sleep(120)
To get your chatID, use /getid command on @myidbot
Open up a terminal and execute the script. Every 2 minutes, it will send a message until the script it stopped.
Note: You need to issue /start command on the bot first for it to recognize your chat and be able to send you messages.
Here are a few sites and books recommended for Python beginners.
1. https://www.python.org/
2. https://www.pythonforbeginners.com/basics/
3. https://www.learnpython.org/
4. https://stackabuse.com/the-best-python-books-for-all-skill-levels/
Contact me on Telegram (@PhoenixAtom) if you need help