From b0188483ac3432a4c8fb0464da14000831330eb7 Mon Sep 17 00:00:00 2001 From: SileNce5k Date: Sun, 3 Dec 2023 21:12:21 +0100 Subject: [PATCH] Add weather command --- commands/misc/weather.js | 27 +++++++++++++++++++++++++++ util/getWeather.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 commands/misc/weather.js create mode 100644 util/getWeather.js diff --git a/commands/misc/weather.js b/commands/misc/weather.js new file mode 100644 index 0000000..f2c991e --- /dev/null +++ b/commands/misc/weather.js @@ -0,0 +1,27 @@ +const getWeather = require('../../util/getWeather') + +module.exports = { + name: "weather", + description: "Returns what the weather is for the specified location", + async execute({message, args}) { + if(args.length < 1){ + message.channel.send(`You have to provide a location`) + return; + } + let location = args.join() + let weather = await getWeather(location).catch((err) => { + console.log(err); + }); + + // convert °C to °F and add it after C temperature in parentheses + let tempRegex = /(-?\d+)(?=°C)/g; + if(weather.success){ + let tempInCelsius = weather.weather.match(tempRegex)[0]; + let tempInFahrenheit = `(${Math.round(tempInCelsius * 1.8 + 32)}°F)`; + let splitWeather = weather.weather.split("°C"); + weather.weather = `${splitWeather[0]}°C ${tempInFahrenheit} ${splitWeather[1]}` + } + message.channel.send(weather.weather); + } + +} \ No newline at end of file diff --git a/util/getWeather.js b/util/getWeather.js new file mode 100644 index 0000000..e41b396 --- /dev/null +++ b/util/getWeather.js @@ -0,0 +1,30 @@ +const https = require('https'); + +module.exports = async function (location) { + const url = `https://wttr.in/${location}?format=4&M` // 4 = one line, M = metric wind speed + let success = false; + let weather = await new Promise((resolve, reject) => { + https.get(url, (res) => { + let data = ''; + res.on('data', (chunk) => { + data += chunk; + }); + res.on('end', () => { + if(res.statusCode === 404){ + reject(`Couldn't find weather for ${location}`); + return; + }else if(res.statusCode != 200){ + reject(`Something went wrong while getting the weather for ${location}`); + } else{ + resolve(data); + success = true; + } + + }); + }).on("error", (err) => { + reject(err); + }); + }) + return {success: success, weather: weather}; + +} \ No newline at end of file