Skip to content

Instantly share code, notes, and snippets.

@timothyis
Created November 23, 2018 16:30
Show Gist options
  • Save timothyis/514024768d5dab59d27c97087cb3c169 to your computer and use it in GitHub Desktop.
Save timothyis/514024768d5dab59d27c97087cb3c169 to your computer and use it in GitHub Desktop.
A Now v2 Node-Server Telegram bot for getting the temperature of a city, using Node.js and Express (based on https://scotch.io/tutorials/how-to-build-a-telegram-bot-using-nodejs-and-now)
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
require("now-env")
const axios = require("axios");
let telegram_url = "https://api.telegram.org/bot" + process.env.TELEGRAM_API_TOKEN +"/sendMessage";
let openWeatherUrl = process.env.OPENWEATHER_API_URL;
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.post("/start_bot", function(req, res) {
const { message } = req.body;
let reply = "Welcome to telegram weather bot";
let city_check = message.text.toLowerCase().indexOf('/');
if (message.text.toLowerCase().includes('hi')) {
sendMessage(telegram_url, reply, message, res);
} else if ((message.text.toLowerCase().includes('check')) && (city_check !== -1 )) {
city = message.text.split('/')[1];
get_forecast(city).then( response => {
sendMessage(telegram_url, response, message, res)
});
} else {
reply = "request not understood, please review and try again.";
sendMessage(telegram_url, message, reply, res);
return res.end();
}
});
function sendMessage(url, reply, message, res) {
axios.post(url, {
chat_id: message.chat.id,
text: reply
}).then(response => {
console.log("Message posted");
res.end("ok");
}).catch(error =>{
console.log(error);
});
}
function get_forecast(city){
let new_url = openWeatherUrl + city+"&appid="+process.env.OPENWEATHER_API_KEY;
return axios.get(new_url).then(response => {
let temp = response.data.main.temp;
//converts temperature from kelvin to celsuis
temp = Math.round(temp - 273.15);
let city_name = response.data.name;
let resp = "It's "+temp+" degrees in "+city_name;
return resp;
}).catch(error => {
console.log(error);
});
}
app.listen(3000, function() {
console.log('Telegram app listening on port 3000!')
})
{
"version": 2,
"builds": [
{ "src": "index.js", "use": "@now/node-server" }
],
"env": {
"OPENWEATHER_API_KEY": "YOUR_OPENWEATHER_API_KEY",
"OPENWEATHER_API_URL": "http://api.openweathermap.org/data/2.5/weather?q=",
"TELEGRAM_API_TOKEN": "YOUR_TELEGRAM_API_KEY"
},
"routes": [
{ "src": "^/(.*)", "dest": "/" }
]
}
{
"name": "telegram-weather-bot",
"description": "A telegram bot made for Now v2 to get the temperature of a city",
"dependencies": {
"axios": "^0.18.0",
"body-parser": "^1.18.3",
"express": "^4.16.4",
"now-env": "^3.1.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment