Creating An Announcement Discord Bot
shadowtime2000
Posted on July 20, 2020
A tutorial on creating a simple discord bots for announcements.
How it will work
Our bot will work in the following steps:
- Take announcement command e.g.
!announce <announcement here>
- Check if user has announcer role
- Post announcement through Discord webhook
Setting up
First, enter a blank folder an set it up with npm init
. Then, install discord.js
with npm i discord.js --save
. Then, head towards the Discord Developer Portal and create a new application. You can name it whatever you want, but you should probably name it something like Announcement Bot. Then, open the bot page and click create a bot. Inside your development folder create a file named config.json
, and in it write this:
{
"token":"put your discord token here",
"announcer-role": "announcer role Id",
"webhookToken": "webhook token",
"webhookID": "webhook ID"
}
Fill in the Discord bot token in the token
field.
You can invite your bot to a test server with the link: https://discord.com/oauth2/authorize?client_id=APPID&scope=bot, but fill in the APPID
with the ID of your Discord application.
In your server, create a role called Announcer
and copy the role ID. You can get the ID if you turn on developer mode in the Appearance section of Discord's settings. Fill in the announcer-role
field of config.json
. Also, create a channel for announcements and create a webhook for that channel. Fill in the webhook fields accordingly.
Now lets get started with the programming!
Coding the bot
Create a file named index.js
and fill in the following code:
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client();
const webhookClient = new Discord.WebhookClient(config.webhookID, config.webhookToken);
client.once("ready", () => {
console.log("Ready for action!");
});
client.on("message", (message) => {
if (!message.member.roles.cache.has(config["announcer-role"]) || !message.content.startsWith("!") || message.author.bot) return;
const args = message.content.slice(1).trim().split(' ');
const command = args.shift().toLowerCase();
if (command == "announce") {
var announcement = "";
for (const word in args) {
announcement = announcement + args[word] + " ";
}
webhookClient.send(announcement)
}
})
client.login(config.token);
Next Steps
So you have done it! You have successfully made a Discord announcement bot!
A couple things you could do:
- This bot is built to work with only one server. Try customizing it so it could work on multiple servers
- Allow customization of prefix in the
config.json
file - Currently, the bot is just repeating whatever someone says with the command, which isn't that useful. Try getting it to send announcements in a better format
The source code for this tutorial is uploaded on Github
Posted on July 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.