On the event guildmemberupdate, I am trying to see if the event is in my server and if the role is a certain role. If all things are true, it will send a message. It does not send a message though
Here is the code
this.on('guildMemberUpdate', function (guild, oldMember, newMember) {
if(guild.id !== '#') {
return
} else {
const wc = new Discord.WebhookClient("#', 'lG-###-7RIXy3LIup80X");
if (oldMember.roles.cache.size !== newMember.roles.cache.size) {
if (!oldMember.roles.cache.has("851156630748921927") && newMember.roles.cache.has("851156630748921927")) {
wc.send(`yo !`);
}
}
}
})
It doesn't send 'test'
The guildMemberUpdate event requires the server members intent. You can enable it in the Discord Developer Portal, and within your client instantiation
const { Intents } = require("discord.js")
const client = new Client({intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS]})
//other intents may be added. Make sure it has server members intent (Intents.FLAGS.GUILD_MEMBERS)
Related
I've been working on this code for a discord bot that tracks a the voice channels of a server until a specific person joins which then the bot joins and then plays an audio. However whenever I start up my file, it keeps on saying
[nodemon] starting `node index.js`
[nodemon] clean exit - waiting for changes before restart
I have no clue why, I've looked online and I haven't seen any other people having the same issue as me, and if they did the answer didn't help.
Here is my code.
const { Client, GatewayIntentBits } = require('discord.js');
const { Lavalink } = require('discord.js-lavalink');
class MyBot {
// The Discord.js client object that represents our bot
client;
// The ID of the specific person we want to track
userIdToTrack;
// The audio file to play when the specific person joins
audioFile;
constructor(client, userIdToTrack, audioFile) {
// Save the client object and user ID and audio file for later use
this.client = "[bot token]";
this.userIdToTrack = '[discord id]';
this.audioFile = '[file name]';
}
onGuildVoiceJoin(event) {
// Get the member who just joined the voice channel
const member = event.member;
// If the member is the specific person we want to track...
if (member.id === this.userIdToTrack) {
// Get the voice channel that the member joined
const voiceChannel = event.channel;
// Join the voice channel with the bot
voiceChannel.guild.voice.channel.join();
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: '[file name]',
});
const client = new Client({
token: 'bot token]',
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
],
});
// Create a new instance of the Lavalink class and connect to the Lavalink nodes
const lavalink = new Lavalink({
client: client,
nodes: [
{ host: 'ratio-w', port: 2334, password: 'youshallnotpass' },
],
});
lavalink.connect();
client.on('ready', () => {
console.log('The bot is ready');
// Create a new instance of the bot, passing in the client object, user ID, and audio file
const bot = new MyBot("bot token", "user id", "file name");
// Listen for voice state update events, which are triggered when a user joins or leaves a voice channel
client.on('voiceStateUpdate', (oldState, newState) => {
// Check if the user we want to track has just joined a voice channel
if (newState.member.id === userIdToTrack && newState.channel) {
// Get the voice channel the user joined
const voiceChannel = newState.channel;
// Join the voice channel with the bot
voiceChannel.join().then(connection => {
// Play the audio file using Lavalink
lavalink.play(voiceChannel, {
track: audioFile,
});
});
}
});
client.on('messageCreate', message => {
if (message.content === 'ping') {
message.reply('hey <#user id>, you STINK!!!!111!');
}
});
client.on('messageCreate', message => {
if (message.content === 'shut up [redacted]') {
message.reply('yeah <#user id> shut up smelly');
}
});
client.on('messageCreate', message => {
if (message.content === 'stop being a nerd [redacted]') {
message.reply('<#user id> be like :nerd:');
}
});
});
process.on('unhandledRejection', (reason, promise) => {
console.log('Unhandled Rejection at:', reason.stack || reason)
// Recommended: send the information to sentry.io
// or whatever crash reporting service you use
})
client.login('[bot id]');}}}
I tried fixing any possible syntax errors, I've tried looking online but no help was found, I've properly started lavalink (I think), I've edited some of the code so that all possible parts are fixed. I've downloaded all possible directories like updating discord.js, node.js, lavalink.js, and more I think.
I am using Discord.js to make my bot.
I want to add a role to a user after they use a command.
The command is !attack it will "kill" the person you pinged.
I think it might have something to do with Intents but I'm not sure. Here are my Intents right now,
const client = new Discord.Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
}, {
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
Also, here is the code for the !attack command,
var user;
var rollNum;
var role;
module.exports = {
name: "attack",
category: "info",
permissions: [],
devOnly: false,
run: async ({client, message, args}) => {
user = message.content.toLowerCase().split(" ");
if(user[1] === `<#${message.author.id}>`){
message.reply("You are not allowed to kill yourself.")
}
else{
message.reply("Rolling...");
rollNum = Math.floor(Math.random() * 10);
if(rollNum >= 4){
message.reply(`${user[1]} could not be killed. They are too strong for you lol.`);
}
else{
message.reply(`${user[1]} is dead... R.I.P.`);
}
}
}
}
To give a user a role, you need the MANAGE_ROLES permission and the bot also cannot give a role which has a higher position than its own. Other than that, the syntax for adding a role is pretty simple. First, you have to fetch the role, then you can add it to the user. To fetch the role, you can use .get() if you have the role id or .find() if you have the role name. Your code might look something like this:
const role = message.guild.roles.cache.get('roleid') // Or message.guild.roles.cache.find(r => r.name === 'rolename')
message.member.roles.add(role.id).then(m => {
message.channel.send('Successfully added the role!')
}).catch(err => {
message.channel.send('There was an error while adding the role!')
})
I have this very basic code for a very basic discord bot
since the new discord.js version 13 you need to declare intents.
I tried doing that using the bitmap 32767 (basically declaring all intents), however the bot doesnt trigger the "messageCreate" event when a message is send
in the dms it only works in servers.
All privileged gateway intents on the developer site have been set to true.
What am I missing?
const Discord = require("discord.js");
const allIntents = new Discord.Intents(32767);
const client = new Discord.Client({ intents: allIntents });
require("dotenv").config();
const botName = "Miku";
client.once("ready", () => {
//gets executed once at the start of the bot
console.log(botName + " is online!");
});
client.on("messageCreate", (message) => {
console.log("got a message");
});
(async() => {
//bot connects with Discord api
client.login(process.env.TOKEN);
})();
You cannot listen for events in the Direct Messages unless they are direct responses/replies/reactions to the initial message.
For example, you can send a message to new members and wait for a response:
client.on('guildMemberAdd', member =>{
member.send("Welcome to the server!");
message.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then((collected) => {
//Now, write your code here that handles the reactions.
});
but there is no way to listen for events within the Direct Messages. As in, client.on... will never fire because of a DM event.
I have been doing my research in the past few days but I couldn't find literally anything. Same in python.
const Discord = require("discord.js")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
const member = client.guilds.cache.get("person_id") // person I want to check
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
if (msg.content === "ping") {
msg.reply("pong");
}
}) // everything worked to this moment
client.on("presenceUpdate", () => {
if (member.presence.status === 'online') {
client.channels.cache.get("channel_id").send("HELLO"); // message i want bot send to the channel if member goes online
}
});
client.login('***')
If I add the GUILD_PRESENCES intent, I receive the following error:
if (member.presence.status === 'online') {
^ TypeError: Cannot read properties of undefined (reading 'presence')
First, you'll need to enable the GUILD_PRESENCES intent if you want to use the presenceUpdate event.
Second, client.guilds.cache.get("person_id") doesn't return a member. guilds.cache is a collection of guilds, not members.
And last, presenceUpdate fires whenever a member's presence (e.g. status, activity) is changed. It means that their presence can be the same (e.g. online), yet the event still fires, so checking if (member.presence.status === 'online') won't work. What you can do instead is to compare the old and new presences. You can find the code below and I've added some comments to make it a bit clearer.
const Discord = require('discord.js');
const client = new Discord.Client({
intents: ['GUILDS', 'GUILD_MESSAGES', 'GUILD_PRESENCES'],
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
// if someone else has updated their status, just return
if (newPresence.userId !== 'person_id') return;
// if it's not the status that has changed, just return
if (oldPresence.status === newPresence.status) return;
// of if the new status is not online, again, just return
if (newPresence.status !== 'online') return;
try {
client.channels.cache.get('channel_id').send('HELLO');
} catch (error) {
console.log(error);
}
});
client.login('***');
I'm working on a command where when you do the command, d!woa the following happens
A webhook gets created with a certain name, Then a role gets created with the channel name, after that the bot watches if there's a webhook with that certain name for the channel, and just sees if anyone sends a message in that channel. If it does, then the bot will add that role with the certain name.
The problem is that there's this error : TypeError: Cannot read property 'guild' of undefined
The error will most likely appear at the end of the code provided.
I've tried rearranging the code, defining guild, and defining message. It does not seem to work even after trying all of this. I only want it to rely off of the ID instead of Name to be accurate for this command.
const Discord = require('discord.js');
const commando = require('discord.js-commando');
class woa extends commando.Command
{
constructor(client) {
super(client, {
name: 'watchoveradd',
group: 'help',
memberName: 'watchoveradd',
description: 'placeholder',
aliases: ['woa'],
})
}
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
else
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `...`;
const name2 = "name-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
specifiedchannel.send('test');
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
setTimeout(function(){
message.channel.send('Please wait...');
}, 10);
setTimeout(function(){
var role = message.guild.createRole({
name: `Name marker ${woaID.name} v1.0`,
color: 0xcc3b3b,}).catch(console.error);
if(role.name == "name marker") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(10)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
}, 20);
var sbwrID = member.guild.roles.find(`Synthibutworse marker ${woaID} v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
setTimeout(function(){
message.channel.send('Created Role... Please wait.');
}, 100);
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var member = client.user
var bot = message.client
bot.on('message', function(message) { {
if(message.channel.id == sbwrID.id) {
let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole);
}
}})
}};
module.exports = woa;
I expect a command without the TypeError, and the command able to create a role and a webhook (for a marker), and the role is automatically set so that the user that has the role won't be able to speak in the channel, and whoever speaks in the channel will get the role.
The actual output is a TypeError: Cannot read property 'guild' of undefined but a role and webhook are created.
You have var sbwrID = member.guild...
You did not define member. Use message.member.guild...
You can setup a linter ( https://discordjs.guide/preparations/setting-up-a-linter.html ) to find these problems automatically.