Categories
Uncategorized

Creating a Discord Weather Bot

This is the first post here on my blog, so why not write it about something that can become very useful.

So I was creating a Discord server and was thinking, “wouldn’t it be helpful if I could make my server actually do something”. And from that I came to the idea of creating a weather bot.

I had never created a Discord bot before, so I had to do some research and learn how to make a bot, which deemed to be pretty simple. Adding weather functionality was a little bit more difficult, but not too complicated.

In this post, I will show you how you can create your own Discord weather bot, which you can use on your server(s).

To create your bot, you will need:

  • A Discord account
  • A computer with Node and PM2 installed (this will have to be on for your bot to work)

To begin, you need to login to the Discord Developer Portal. Click the New Application button and give your bot a name. Next, select the Bot option on the left hand side and click Add Bot. If you want other people to be able to use your bot, check Public Bot.

Now that your bot has been created, you can invite it to your server. To do this, you will need to use this URL format to authorise your bot: https://discordapp.com/oauth2/authorize?client_id=[client ID]&scope=bot&permissions=[permissions integer].

Now you are probably wondering, where do I get this client ID and permissions integer from? First of all, to get the client ID, you click General Information on the left and your Client ID will be displayed. The permissions integer is more complicated. To do this you go back to the Bot page, scroll down and select the permissions your bot needs, then your permissions integer will be displayed underneath. In the context of this weather bot, you will need to tick the Send Messages permission.

It’s now time to add your bot! Copy the URL above, changing the client ID with your client ID and the permissions integer with your permissions integer. Select your server from the list and click Authorise. Your bot should now show up on your server.

There he is!

Your bot now just sits there, doing nothing. To add weather functionality, you first need to get a free API key from OpenWeatherMap, then you can start writing the code.

On your computer, create a new directory for where you want your code to be saved. Create an ecosystem.json file for PM2. This will contain the token and your API key, so they do not have to be written in the source code. This file will have the following structure:

{
        "apps": [
                {
                        "script": "/path/to/your/bot/bot.js",
                        "watch": true,
                        "name": "besterbot",
                        "instances": 1,
                        "exec_mode": "fork",
                        "env": {
                                "TOKEN": "[Discord Bot token]",
                                "OPENWEATHERMAP_KEY": "[API key]"
                        }
                }
        ]
}

To get your Bot token, go to your Bot page and click Copy underneath Token. Next, you can create the bot.js file. In this file, write the following code:

var Discord = require('discord.io');
var request = require('request');

var bot = new Discord.Client({
    token: process.env.TOKEN,
    autorun: true
});

bot.on('disconnect', (errMsg, code) => {
	bot.connect();
});

bot.on('message', (user, userID, channelID, message, evt) => {
    if (message.substring(0, 1) == '!'){
        var args = message.substring(1).split(' ');
        var cmd = args[0].toLowerCase();

        switch(cmd){
            case "weather":
                var location = 'london';

                if(args[1] !== undefined){
                    location = args;
                    location.shift();
                    location = location.join(" ");
                }

                request('http://api.openweathermap.org/data/2.5/weather?q=' + location + '&units=metric&appid=' + process.env.OPENWEATHERMAP_KEY, (err, res, body) => {
                    if(err){
                        bot.sendMessage({
                            to: channelID,
                            message: 'Error getting weather information'
                        });
                    } else {
                        if(res.statusCode !== 200){
                            bot.sendMessage({
                                to: channelID,
                                message: 'Error getting weather information'
                            });
                        } else {
                            weather = JSON.parse(body);

                            bot.sendMessage({
                                to: channelID,
                                message: 'The temperature is ' + weather.main.temp + '°C, but it feels like ' + weather.main.feels_like + '°C'
                                        + '\nThe weather is ' + weather.weather[0].main
                                        + '\nThe pressure is ' + weather.main.pressure + 'hPa, and the humidity is ' + weather.main.humidity + '%'
                                        + '\nThe wind speed is ' + weather.wind.speed + 'm/s and is blowing at a direction of ' + weather.wind.deg + '°'
                                        + '\nThere is ' + weather.clouds.all + '% cloud coverage'
                            });
                        }
                    }
                });
                break;
        }
    }
});

Install the packages by typing npm install discord.io, npm install requests, and npm install https://github.com/woor/discord.io/tarball/gateway_v6. Type pm2 start ecosystem.json to run your bot. If everything is working correctly, you should be able to type !weather and your bot will respond with the current weather forecast in a default city, in this case it is London. You can also type !weather [city] to get the weather in a difference place.

“The weather is Clouds”!

So there you have it, how to make a simple weather Discord bot. If you have any problems with this or would liek to suggest some future posts or tutorials, feel free to leave a comment below and I’ll try to respond to as many as possible.

7 replies on “Creating a Discord Weather Bot”

Hello, I made a coment on having trouble getting the bot online earlier, but I managed to get it online. However, it seems to be having trouble getting weather information, the error message “Error getting weather information” is all that it prints. Any assistance? thank you.

This error appears if the bot cannot connect to the weather API, or if the API sends an invalid response. There’s a couple of things I would suggest trying:
1. I noticed in my code snippet it says & instead of just &, so first check if you’ve only got the single &.
2. Copy the URL and try it in your web browser, this could also be used to check your API token since it’ll tell you if it’s invalid. When I set up my bot, I had to wait a bit for the API token to work.
3. Check for any typos in your location.
I hope this helps.

This message is in relation to one of your suggestion. “1. I noticed in my code snippet it says & instead of just &, so first check if you’ve only got the single &.” Could you clarify where in the code because I’m seeing a lot of & symbols in the code displayed above. Thank you

Sorry, the code snippets have &, as in the HTML tag, so my comment was changed back to &. I don’t know why wordpress is displaying it as a HTML tag in the code snippets, but it should just be a single ampersand (&).

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.