Role assignment gives announcement to specific channel - javascript

I'm using discord.js to try make a bot with the sole purpose of whenever a member is given a specific role (alpha, bravo, charlie, delta) it will send an announcement to a specific channel (#general) saying congratulations on becoming part of the faction! How would I go about doing this? (what I know is that it's part of the "GuildMembers" chunk)
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'NzUzNTY0NjA0MjM1MzgyODI1.X1oBug.E0GEmnakRtQMbOfg5IwllQsW_Ps';
client.on('ready', () => {
console.log('This bot is online!')
})
client.on("guildMemberUpdate", async(oldMember, newMember) => {
// On `guildMemberUpdate`
if (oldMember.roles.cache !== newMember.roles.cache) {
// Check if a role was updated
let newRole;
newMember.roles.cache.forEach((role) => {
if (oldMember.roles.cache.includes(role)) return;
// Check for the new role that was added
let roleNames = ["bobbies", "beebos", "babbos", "bobbios"];
if (roleNames.toLowerCase().includes(role.name.toLowerCase())) {
// Check for only `['bobbies', 'beebos', 'babbos', 'bobbios']`
newRole = role;
}
});
// Anything you want to run here with the `newRole` data.
const channel = oldMember.guild.channels.cache.find(
(channel) => channel.name === "general"
);
channel.send("Congratulations on becoming part of the faction!");
}
});
client.login(token);
This unfortunately returns with the error:
(node:6240) UnhandledPromiseRejectionWarning: TypeError: oldMember.roles.cache.includes is not a function
at C:\Users\sanderj\Desktop\Discord Bot\index.js:18:39
at Map.forEach (<anonymous>)
at Client.<anonymous> (C:\Users\sanderj\Desktop\Discord Bot\index.js:17:31)
at Client.emit (events.js:315:20)
at Object.module.exports [as GUILD_MEMBER_UPDATE] (C:\Users\sanderj\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\GUILD_MEMBER_UPDATE.js:25:16)
at WebSocketManager.handlePacket (C:\Users\sanderj\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\sanderj\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\sanderj\Desktop\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\sanderj\Desktop\Discord Bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:315:20)
(node:6240) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6240) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Check out Client#guildMemberUpdate which gets emitted when something about a member property gets changed (i.e. a role is added). Try adding this code to your bot:
client.on("guildMemberUpdate", async (oldMember, newMember) => {
// On `guildMemberUpdate`
if (!oldMember.roles.cache.equals(newMember.roles.cache)) {
// Check if a role was updated
let newRole;
newMember.roles.cache.forEach((role) => {
if (oldMember.roles.cache.includes(role)) return;
// Check for the new role that was added
let roleNames = ["alpha", "bravo", "charlie", "delta"];
if (roleNames.toLowerCase().includes(role.name.toLowerCase())) {
// Check for only `['alpha', 'bravo', 'charlie', 'delta']`
newRole = role;
}
});
// Anything you want to run here with the `newRole` data.
const channel = oldMember.guild.channels.cache.find(
(channel) => channel.name === "general"
);
channel.send("Congratulations on becoming part of the faction!");
}
});

Related

Mute role not working with time, UnhandledPromiseRejectionWarning

I'm making a mute and unmute command for our system bot, the mute should be timed by hours, but I have it as seconds just to test it, anyway, my problem is that when the command is used whether there is an args1 which is the time the mute will last in hours or not it sends an error and just uses the default time, anyone knows why?
My code:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'mute',
category: 'Owner',
aliases: ["t"],
description: 'Mute command.',
usage: 'mute <memeberid> <time>',
userperms: [],
botperms: [],
run: async (client, message, args) => {
if (!message.guild) return;
if (message.author.bot) return;
if (!message.member.roles.cache.has("916785912267034674")) return message.channel.send("You are not a staff member.").then(m => m.delete({timeout: 4000}))
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("I don't have permission to do this.").then(m => m.delete({timeout: 4000}))
let time = args[1]
let reason = args[2]
if (!reason) reason = "Violated server rules";
if (!time) time = "1"
const user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const muterole = message.guild.roles.cache.get("916963460540157962");
const embed = new MessageEmbed()
.setTitle('Member muted!')
.addField('User muted', '<#'+user+'>')
.addField('muted by', message.author)
.addField('Reason', reason)
.addField('For', time + " hour(s)")
.setFooter('Time muted', client.user.displayAvatarURL())
.setThumbnail('https://th.bing.com/th/id/R.3e3ee93bca49df93c9751dbb284d7ec8?rik=fKLepuY9WQQnew&riu=http%3a%2f%2fimage.flaticon.com%2ficons%2fpng%2f512%2f25%2f25632.png&ehk=mdsvAx56LxLhOmmktJkpp5Vbse%2fxjnaW8mxahrVoQeU%3d&risl=&pid=ImgRaw&r=0')
.setTimestamp()
if (!args[0]) return message.channel.send("Please mention a member or use an ID.")
if (!user) return message.channel.send("Error: Can't find that user.")
if (user.user.id == message.author.id) return message.channel.send("Uhh, why don't you just shut up like humans?")
if (user.user.id == client.user.id) return message.channel.send("You good bro?")
if (user == message.author.id) return message.channel.send("Uhh, why don't you just shut up like humans?")
if (user == client.user.id) return message.channel.send("You good bro?")
if (user.roles.cache.has("916963460540157962")) return message.channel.send("Chill, his already muted!")
if (user.roles.cache.has("916785912267034674")) return message.channel.send("You can't mute staff, idoit.")
message.channel.send(embed).catch(err => console.log("Error: " + err));
user.roles.add("916963460540157962").then(user.roles.remove("916963460540157962") ({timeout: time+"00000"})).catch(err => console.log("Error: " + err));
}
}
Error:
(node:1460) UnhandledPromiseRejectionWarning: TypeError: user.roles.remove(...) is not a function
at Object.run (/home/runner/DwaCraft-Main-bot/commands/owner/Mute.js:47:87)
at module.exports (/home/runner/DwaCraft-Main-bot/events/guild/message.js:52:11)
at Client.emit (events.js:314:20)
at MessageCreateAction.handle (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/DwaCraft-Main-bot/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:314:20)
(node:1460) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1460) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Thanks !
You are using user.roles.remove(id) ({timeout: time+"00000"}) which is obviously bad syntax. Also, role removal does not have a built in timeout. You will need to use setTimeout, or a database for larger times
await user.roles.add(id)
setTimeout(() => user.roles.remove(id), time * 1000) // *1000 for seconds
As I said before, it only works well with short times, use a database for longer times
The syntax seems to be incorrect, try with :
user.roles.add("916963460540157962").then(() => setTimeout(() => user.roles.remove("916963460540157962", +time))

Ticket command giving errors discord js

i need help with this for someone reason when i type !ticket it gives me a error the code and the error i tried what i could i couldent get it to work so i came here to ask please let me know if you could help. its probably a really simple issue and im dumb to realize it. i also cant get the emojis to work if you can help with that as well that would be nice
const Discord = require("discord.js")
const ms = require('ms');
module.exports = {
name: 'ticket',
usage: '%ticket <reason>',
description: 'makes a ticket',
async execute(client, message, args, cmd, discord) {
const channel = await message.guild.channels.create(`ticket: ${message.user.tag}`);
channel.setParent('855596395783127081');
channel.updateOverwrite(message.guild.id, {
SEND_MESSAGE: false,
VEIW_CHANNEL: false
})
channel.updateOverwrite(message.auther, {
SEND_MESSAGE: true,
VEIW_CHANNEL: true
})
const reactionMessage = await channel.send(`Thank you for contacting support! A staff member will be with you as soon as possible`);
try {
await reactionMessage.react(":lock:");
await reactionMessage.react(":no_entry:");
} catch (err) {
channel.send(`Error Sending Emojis`);
throw err;
}
const collector = reactionMessage.createReactionCollector((reaction, user) =>
message.guild.member.cache.find((member) => member.id === userid).hasPermission('ADMINISTRATOR'), { dispose: true }
);
collector.on('collect', (reaction, user) => {
switch (reaction.emoji.name) {
case ":lock:":
channel.updateOverwrite(message.auther, { SEND_MESSAGE: false });
break;
case ":no_entry:":
channel.send('Deleteing ticket in 5 seconds');
setTimeout(() => channel.delete(), 5000);
break;
}
});
message.channel.send(`We will be right withyou! ${channel}`).then((msg) => {
setTimeout(() => msg.delete(), 7000)
setTimeout(() => message.delete(), 7000)
})
}
}
Heres the error
PS C:\Users\lolzy\OneDrive\Desktop\discordbot> node .
Cbs slave is online!
(node:19284) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'tag' of undefined
at Object.execute (C:\Users\lolzy\OneDrive\Desktop\discordbot\commands\ticket.js:10:85)
at module.exports (C:\Users\lolzy\OneDrive\Desktop\discordbot\events\guild\message.js:10:26)
at Client.emit (events.js:376:20)
at MessageCreateAction.handle (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\lolzy\OneDrive\Desktop\discordbot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:376:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:19284) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:19284) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that
are not handled will terminate the Node.js process with a non-zero exit code.
In Message Object there is no properties that called .user it should be .author which is return User Object , docs here
So the right code will be
const channel = await message.guild.channels.create(`ticket: ${message.author.tag}`);

I want a Discord bot to enter voice channel and play a mp3 file

I suspect there is something wrong with my code but I don't know.
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
client.once('ready', () => {
console.log('Bot online!');
});
client.on('message', async message => {
if(message.content.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.playFile(require("path").join(__dirname, './audio.mp3'));
dispatcher.on('start', () => {
console.log('Now playing!');
});
dispatcher.on('finish', () => {
console.log('Finished playing!');
voiceChannel.leave();
});
dispatcher.on('error', console.error);
}
});
client.login(config.TOKEN);
I get error :
UnhandledPromiseRejectionWarning: TypeError: Cannot read property
'channel' of undefined
at Client. (C:\Users\djd18\Desktop\Bot\index.js:10:30)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\djd18\Desktop\Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\djd18\Desktop\Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\djd18\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\djd18\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\djd18\Desktop\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\djd18\Desktop\Bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\djd18\Desktop\Bot\node_modules\ws\lib\websocket.js:825:20)
(Use node --trace-warnings ... to show where the warning was
created) (node:16536) UnhandledPromiseRejectionWarning: Unhandled
promise rejection. This error originated either by throwing inside of
an async function without a catch block, or by rejecting a promise
which was not handled with .catch(). To terminate the node process on
unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:16536) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.

Discord JS V11 BAN COMMAND

Hello I have a ban command. Also I have a error. This is a code
I want solve. But I don't.
const Discord = require('discord.js')
module.exports = {
komut: "ban",
açıklama: "",
kategori: "moderasyon",
alternatifler: ["!ban", "!yasakla"],
kullanım: "!ban",
yetki: "BAN_MEMBERS"
}
module.exports.baslat = (message) => {
// if(!message.member.hasPermission(["BAN_MEMBERS"])) return message.channel.send("Ban atabilmek için yetkili olman gerek!")
let banMember = message.mention.members.first() || message.guild.member.get(args[0])
if(banMember) return message.channel.send("Lütfen banlamak istediğiniz kişiyi etiketleyin!")
let reason = args.slice(1).join(" ")
if (!reason) reason = "Lütfen bir sebep belirtiniz!"
// if(!message.guild.me.hasPermission(["BAN_MEMBERS" , "ADMINISTRATOR"])) return message.channel.send("Bu komutu kullanmak için yetkim yok")
message.delete()
banMember.send(`Merhaba, iyi günler dilerim. ${message.guild.name} adlı sunucudan ${reason} sebebiyle banlandın.`).then(() =>
message.guild.ban(banMember, {days : 1 , reason : reason})).catch(err => console.log(err))
message.channel.send(`**${banMember.user.tag}** banlandı.`)
let embed = new Discord.RichEmbed()
.setColor("RED")
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL)
.addField("Moderasyon :", "ban")
.addField("Kişi : ", banMember.user.username)
.addField("Banlayan Admin :", message.author.username)
.addField("Sebep : ", reason)
.addField("Date :", message.createdAt.toLocaleString())
let sChannel = message.guild.channels.find(c => c.name === "ban-log")
sChannel.send({embed:embed})
};
This is a terminal error :
(node:16116) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'members' of undefined
at Object.module.exports.baslat (C:\Users\RYZEN\Desktop\U4 BOT\komutlar\moderasyon\ban.js:16:33)
at AdvancedClient.<anonymous> (C:\Users\RYZEN\Desktop\U4 BOT\node_modules\discordjs-advanced\src\client.js:549:5)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:16116) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16116) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Please help me
Okey, don't see a
module.exports = {
komut: "ban",
açıklama: "",
kategori: "moderasyon",
alternatifler: ["!ban", "!yasakla"],
kullanım: "!ban",
yetki: "BAN_MEMBERS"
}
Note : I change members and users. Bot don't work again.
(Sorry for my bad english :) )
You are using message.mention.members.first() but it should be mentions -
message.mentions.members.first()

UnhandledPromiseRejectionWarning always showed up

im trying to make a discord bot using javascript. My bot is online and my commands are loaded. but whenever i typed a command, this text is showed up and my command didn't do anything
(node:4984) UnhandledPromiseRejectionWarning: TypeError: bot.commands.file is not a function
at Client.<anonymous> (C:\Users\user\Desktop\discord.js\useless bot\bot.js:37:36)
at Client.emit (events.js:314:20)
at MessageCreateAction.handle (C:\Users\user\Desktop\discord.js\useless bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\user\Desktop\discord.js\useless bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\user\Desktop\discord.js\useless bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (C:\Users\user\Desktop\discord.js\useless bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\Users\user\Desktop\discord.js\useless bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\Users\user\Desktop\discord.js\useless bot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:314:20)
at Receiver.receiverOnMessage (C:\Users\user\Desktop\discord.js\useless bot\node_modules\ws\lib\websocket.js:800:20)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:4984) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:4984) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
const Discord = require("discord.js");
const config = require("./config.json");
const bot = new Discord.Client({disableEveryone: true})
const fs = require("fs");
bot.commands = new Discord.Collection();
fs.readdir("./commands/", (err, files)=> {
if(err) console.log(err);
let jsfile = files.filter(f => f.split(".").pop() === "js")
if (jsfile.lenght <= 0){
console.log("no commands were found...")
return;
}
jsfile.forEach((f ,i) =>{
let props = require(`./commands/${f}`)
console.log(`${f} loaded!`)
bot.commands.set(props.help, props);
})
})
bot.on("ready", async ()=> {
console.log(`${bot.user.username} is online!`);
bot.user.setActivity("prefix is *", {type: "PLAYING"});
});
bot.on("message", async message =>{
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = config.prefix;
let messageArray = message.content.split(" ")
let cmd = messageArray [0];
let args = messageArray.slice (1);
let commandfile = bot.commands.file(cmd.slice(prefix.lenght));
if (commandfile) commandfile.run(bot, message, args);
})
bot.login(config.token)

Categories