Skip to content
Related Articles

Related Articles

How to Design a Weather Bot in Telegram using JavaScript ?
  • Last Updated : 12 Feb, 2021

Telegram bot can be used to know the complete weather details of any city, state, a country without going using another application. Telegram provides a bunch of API methods to perform different functions. You can use telegram bot API to create a Chatbot that returns the weather-based information about a city, state, or country based on the parameters and command sent to the bot.

Prerequisites:

  1. Knowledge of JavaScript and setting up a node environment.
  2. The latest version of Node (version > 10)
  3. The latest version of npm (version > 6)

Command to check if Node and npm are present in your system:

$ npm --v
6.14.5

$ node --version
v10.15.0

Creating Bot and getting API token:

  • Open the telegram app and search for @BotFather.
  • Click on the start button or send “/start”.
  • Then send “/newbot” message to set up a name and a username.
  • The BotFather will then give you an API token.

Getting Weather API key:



  • Go to the Open weather map website.
  • Create an account as per the limit.
  • You will receive your own API key.
  • Read the documentation if you want to use different parameters instead of the city name.

Modules Installation:

Install requests and node-telegram-bot-api (Node.js module to interact with the official Telegram Bot API)

$ npm install --save requests node-telegram-bot-api

Filename: weather.js

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Requiring modules
var TelegramBot = require('node-telegram-bot-api')
var request = require('request')
 
// Token obtained from bot father
var token = "YOUR_TELEGRAM_BOT_TOKEN"
 
var bot = new TelegramBot(token, { polling: true });
 
// Create a bot that uses 'polling' to
// fetch new updates
bot.on("polling_error", (err) => console.log(err));
 
// The 'msg' is the received Message from user and
// 'match' is the result of execution above
// on the text content
bot.onText(/\/city (.+)/, function (msg, match) {
 
    // Getting the name of movie from the message
    // sent to bot
    var city = match[1];
    var chatId = msg.chat.id
    var query =
        + city + '&appid=YOUR_WEATHER_API_KEY'
 
    // Key obtained from openweathermap API
    request(query, function (error, response, body) {
 
        if (!error && response.statusCode == 200) {
 
            bot.sendMessage(chatId,
                '_Looking for details of_ ' + city
                + '...', { parse_mode: "Markdown" })
                .then(msg) {
                res = JSON.parse(body)
                var temp = Math.round((parseInt(
                    res.main.temp_min) - 273.15), 2)
 
                // Kelvin to celsius and then round
                // off and conversion to atm
                var pressure = Math.round(parseInt(
                        res.main.pressure) - 1013.15)
 
                var rise = new Date(parseInt(
                        res.sys.sunrise) * 1000);
 
                var set = new Date(parseInt(
                        res.sys.sunset) * 1000);
                // Unix time to IST time conversion
 
                bot.sendMessage(chatId, '**** '
                    + res.name + ' ****\nTemperature: '
                    + String(temp) + '°C\nHumidity: ' +
                    res.main.humidity + ' %\nWeather: '
                    + res.weather[0].description +
                    '\nPressure: ' + String(pressure)
                    + ' atm\nSunrise: ' +
                    rise.toLocaleTimeString() +
                    ' \nSunset: ' +
                    set.toLocaleTimeString() +
                    '\nCountry: ' + res.sys.country)
            }
 
            // Sending back the response from
            // the bot to user. The response
            // has many other details also
            // which can be used or sent as
            // per requirement
        }
    })
})

chevron_right


Steps to run the program: Run weather.js file using the following command:

$ node weather.js

Go to your bot and type /city city-name and see the results.

Output:

Weather Information using Telegram bot

My Personal Notes arrow_drop_up
Recommended Articles
Page :