DEV Community

loading...

How to make a Discord bot Creating An Announcement Discord Bot

shadowtime2000 profile image shadowtime2000 Updated on ・2 min read

A tutorial on creating a simple discord bots for announcements.

How it will work

Our bot will work in the following steps:

  1. Take announcement command e.g. !announce <announcement here>
  2. Check if user has announcer role
  3. 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"
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

Discussion (9)

pic
Editor guide
Collapse
infinitequinox profile image
InfinitEquinox

How would you turn on your bot?

Collapse
shadowtime2000 profile image
shadowtime2000 Author

You need NodeJS. You can run the bot with

$ node index.js
Enter fullscreen mode Exit fullscreen mode
Collapse
elcorporation1 profile image
E.L. Corporation

Where should I run that? Every time I get the same error.

C:\Users\leoth>node LeOS\index.js
node:internal/modules/cjs/loader:903
throw err;
^

Error: Cannot find module 'C:\Users\leoth\LeOS\index.js'
←[90m at Function.Module._resolveFilename (node:internal/modules/cjs/loader:900:15)←[39m
←[90m at Function.Module._load (node:internal/modules/cjs/loader:745:27)←[39m
←[90m at Function.executeUserEntryPoint as runMain←[39m
←[90m at node:internal/main/run_main_module:17:47←[39m {
code: ←[32m'MODULE_NOT_FOUND'←[39m,
requireStack: []
}

Thread Thread
shadowtime2000 profile image
shadowtime2000 Author

You should be inside the folder that you put the code in.

Collapse
katusha83 profile image
katusha83

is devvlopers poral ?

Collapse
shadowtime2000 profile image
shadowtime2000 Author

Sorry, but I don't understand what you mean by that question. Could you elaborate?

Collapse
nlmfr profile image
NLM-fr

Hey I was wondering if they was a way to make an announcement embed everytime ?

Collapse
dejf15 profile image
Dejf15 • Edited

I need help, every time I start my bot everything runs smoothly until i write the command !announce test, after writing the command, I always have this error in the console:

C:\Program Files\nodejs\node.exe .\index.js
Ready for action!
index.js:8
Uncaught TypeError: Cannot read property 'roles' of null
index.js:12
Debugger attached.
Waiting for the debugger to disconnect...
c:\Users\radad\node_modules\discord.js\index.js:12
if (!message.member.roles.cache.has(config["announcer-role"]) || !message.content.startsWith("!") || message.author.bot) return;
^

TypeError: Cannot read property 'roles' of null
at Client. (c:\Users\radad\node_modules\discord.js\index.js:12:23)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (c:\Users\radad\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports as MESSAGE_CREATE
at WebSocketManager.handlePacket (c:\Users\radad\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (c:\Users\radad\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (c:\Users\radad\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (c:\Users\radad\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (c:\Users\radad\node_modules\ws\lib\websocket.js:825:20)

Collapse
shadowtime2000 profile image
shadowtime2000 Author

Turning on the bot myself also causes this error now. I do not know why it is being caused, I will look at updating the tutorial once I have solved it.