Easy Code Share > Python > Basics > Telegram Bot API Send Weather Message by Python

Telegram Bot API Send Weather Message by Python


Based on the example of a Telegram weather bot, let us learn how Python scripts send messages to apps by using Telegram API. The procedural steps are made up of registering a bot, creating a daemon process for the bot, and handling requests with the help of web crawling skills.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 9 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Install Python on Windows by clicking Python Downloads, or search a Python setup pack for Linux.
  • The installation package for Windows also contains pip install, which allow you to obtain more Python libraries in the future.
 DOWNLOAD SOURCE

 

SECTION 1
Register a Telegram Bot

At the first beginning, let us walk through the steps of bot registration, bot design, and setting up developing environment for your bot. We also show official sites for you to get coding references.

 

Register a Bot from The BotFather

For your comfortable developing environment, you should install Telegram Desktop in your Mac or PC in the beginning.

Once installed, you can register a bot from BotFather, importantly, to get your token. When calling Telegram bot API in Python, the Telegram site will check the token and decide whether you are authorized or not.

BotFather is the one bot to rule them all. Use it to create new bot accounts and manage your existing bots.

Based on our example bot, let us guide you step by step to register a Telegram bot.

  1. Click BotFather, and press the START button to start the bot management.
  2. Use the command /newbot, and set a NAME or TITLE for your bot, for example, Weather Query.
  3. Follow BotFather’s steps to define your USERNAME, for example, EasyCodeShareBot, which should be unique. Then you can get it at https://telegram.me/EasyCodeShareBot. If you have installed Telegram app in your mobile phone, search for @EasyCodeShareBot or Weather Query.
  4. When your USERNAME has been approved, keep the replied YOUR_TOKEN safely. If someone get it, he will be able to access to the HTTP API to control your bot.
  5. Type /help for a list of commands that can add a description, about section and profile picture for your bot.

 

Design Your Telegram Bot

After the BotFather allows you to create an account associated with a bot, you should design what the bot will serve and what commands your bot can handle in advance. Let’s design Telegram commands in the example as below.

  • /help replies with how to use the bot and, optionally, the bot description.
  • /start responds to users with a welcome message and also the help content. Note that clicking START button to join the bot is equal to make a request with this command.
  • /temp location_name replies with the result of scraped weather information from websites.

 

Setup Developing Environment

Install Python library by using the pip command line. Your can find more details about python-telegram-bot in PyPI – python-telegram-bot.

$ pip install python-telegram-bot

If you want some reference manual and guide, they are in the site of Python Telegram Bot’s documentation. In the next section, we will bring you to learn the developing process by means of our example.

 

The Relationship of Bot, Telegram Host and Mobile App

We illustrate the relation about entities as the picture below. Bot is implemented by Python scripts with Telegram bot api library, and acts as a daemon process in Linux hosts. The bot continues polling Telegram official hosts for requests to serve.

How Bot Interact with Telegram Host and Mobile App

When requests come, Python scripts in the bot handle them and send back a proper weather message through Telegram api.

 

SECTION 2
Customize the Telegram Bot

In the section, you will learn about building a bot server on your own Linux host. The bot server executes under Python and calls Telegram bot api to receive requests from and send messages to Telegram apps in mobile phones.

 

What Should You Do for the Telegram Bot?

Under the Python Telegram API, what we should implement for the bot is creating a daemon process. A daemon process indicates the server program running on the Linux host, and listening requests to serve.

The following scripts in the daemon process describe the primary actions of polling Telegram host site for any request to handle. Don’t forget to replace the YOUR_TOKEN with your bot’s token.

You have to add a callback handler to each command. Optionally, setting pass_args=True allows you to accept arguments after the command. the option tell the Telegram to pass arguments to your handlers.

weatherbot.py
 from telegram import Update
 from telegram.ext import Updater, CommandHandler, CallbackContext
 # Daemon start
 if __name__ == "__main__":
    print("=== Weather Bot Started ===")
    updater = Updater('YOUR_TOKEN')
    dp = updater.dispatcher
    # Add handlers
    dp.add_handler( CommandHandler('start', handle_help) )
    dp.add_handler( CommandHandler('help', handle_help) )
    dp.add_handler( CommandHandler('temp', handle_temperature, pass_args=True) )
    # Listen requests to serve
    updater.start_polling()
    updater.idle()

At last, the daemon process continues polling the Telegram site for requests, and turns to idle.

In Linux, you can run the daemon server in the foreground. Thus you will see the executing events that are helpful on the developing mode.

$ python3 weatherbot.py
=== Weather Bot Started ===
/start
/help
/temp New York
['2:26 AM', 'New York', '8°C']
/temp Mumbai
['12:57 PM', 'Mumbai', '32°C']
/temp ムンバイ
['12:57', 'ムンバイ', '32°C']
/temp 東京
['PM4:28', '東京', '16°C']
/temp Київ
['9:29 AM', 'Київ', '-3°C']
/temp München
['8:29 AM', 'München', '0°C']

Once being on production, you may want to run it in the background. Moreover, set the error log file using Linux shell commands if you hope to investigate exceptions under any specific condition.

Also, it is necessary to stop the daemon server when there is any version upgrade.

$ python3 weatherbot.py > /dev/null 2> error.log &
$ ps -ef | grep weatherbot.py
user01     13018 12774  4 15:34 pts/2    00:00:01 python3 weatherbot.py
$ kill 13018

 

Command Handler

First, let’s study the handler for command /help in the daemon process. The essential parameters passed to handlers are Update and CallbackContext. You can get most information from them including the whole command line update.effective_message.text, for example, /help and /temp New York.

weatherbot.py
def handle_help(update: Update, context: CallbackContext) :
    # For commands of /start and /help
    text = update.effective_message.text
    print(text)
    # Show welcome only for command /start
    if text.split(" ")[0] == "/start" :
        # Get id of the chat room.
        chat_id = update.effective_chat.id
        url = "https://freepngimg.com/thumb/welcome/26893-3-welcome-free-download-thumb.png"
        context.bot.send_photo(chat_id, photo=url)
    # Reply help descryption
    update.message.reply_text("/temp location_name\n\nYou can get current temperature everywhere.\n\nFor example, \n\t\t\t/temp Berlin\n\t\t\t/temp New York")

When users join the Telegram bot by searching for it and clicking on a START button at the bottom, the daemon process receive a request. Pressing the button is identical to issue command /start, and then you will see the hello screen from the daemon process.

The Weather Bot using Python Telegram API

We show the welcome picture by an url address. Alternatively, you can show it by the opened file id such as the examples below.

context.bot.send_photo(chat_id, photo=url)

or

context.bot.send_photo(chat_id, photo=open("welcome.png", "rb"))

Mostly, transmitted data are text. The bot can send a text message to the chat room by using Python Telegram API update.message.reply_text().

 

Python Telegram Weather Bot

Another command handler indicate that the bot can crawl websites to provide more rich content. The weather bot will get the current temperature everywhere in the world, according to the location you specified.

weatherbot.py
def handle_temperature(update: Update, context: CallbackContext) :
    # For command /temp
    text = update.effective_message.text
    print(text)
    # Get arguments as location names
    if len(context.args) == 0 :
        update.message.reply_text("/temp location_name\n\nMust has arguments.")
        return
    loc = " ".join(context.args)
    # Send message to Telegram users.
    rlist = get_weather(loc)
    print(rlist)
    update.message.reply_text("\t\t\t".join(rlist))

Look at the following examples, we refer to all arguments after command /temp as the location name. No matter languages you entered are Japanese, Chinese, Ukrainian, Russian, Germany and so on, the weather bot can recognized it.

Report Temperatures from Every Location in the World

Then the bot scrape the accuweather website for current temperature. For example, to locate the Ukrainian city, Kiev, both Київ(Ukrainian language) and Киев(Russian language) will query the same weather result. And the location name ムンバイ will represent the Indian city, Mumbai, and returned temperatures are both 27°C.

 

The Bot Control Invalid Data

If users send command /temp without arguments, the kindly notification will display to tell users that there should be a specified location name.

Kindly Notify If Users Send Invalid Requests

Perhaps the location name is dummy. In such a condition, users will get a non-available temperature, N/A.

 

SECTION 3
Crawl Weather

A simple tricky weather scraping method is introduced here. It’s Python crawling functions satisfy our presentation in the Telegram weather bot. The tricks leverage the Google’s capability of result searching and language interpreting.

 

An Introduction to Weather Scraping

The temperature scraping process consists of three stages. First, searching for weather information on Google generates a web page, which contains several links to the accuweather website. Next, find out the only one candidate link by filtering. Fianlly, analyze the complete weather content in accuweather to just retrieve the local time and the result temperature.

weatherbot.py
import requests
from bs4 import BeautifulSoup
def get_weather(location) :
    # Get the content of web page
    the_url = "https://www.google.com/search?q=weather+accuweather+{}".format(location)
    r_text = get_webpage(the_url)
    # Crawl and analyze
    # Get the url of accuweather from Google results
    soup = BeautifulSoup(r_text, "html.parser")
    google_results  = soup.find_all(href=re.compile("https://www.accuweather.com/"))
    # Get content from the url of accuweather
    weather_page = ""
    for a in google_results :
        if a['href'].find('https://www.accuweather.com/') == 0 and '/weather-forecast/' in a['href'] :
            # e.g https://www.accuweather.com/en/de/berlin/10178/weather-forecast/178087
            the_url = a['href']
            weather_page = get_webpage(the_url)
            break
    # Ignore invalid location
    if weather_page == "" :
        #return {"current": "N/A", "location": location, "temp" : "N/A"}
        return ["N/A", location, "N/A"]
    # Crawl and analyze the web page of accuweather
    soup = BeautifulSoup(weather_page, "html.parser")
    wcard = soup.find("a", attrs={"class" : "cur-con-weather-card"})
    current = soup.find("p", attrs={"class" : "cur-con-weather-card__subtitle"}).text
    temperature = wcard.find("div", attrs={"class" : "temp"}).text
    return [current.strip(), location, temperature]

More details about crawling and BeautifulSoup are in our previous post Python Web Scraping using BeautifulSoup in 3 Steps

 

FINAL
Conclusion

This article primarily reveals how Telegram bot works among Linux hosts, Telegram official websites, and Telegram apps. The programming stuff are not complex, but more advanced references can be found in the official site. If interested in the topic, taking practices on advanced bot functions will lead you to be an expert.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

Leave a Comment