I'm started to learn discord.js library and trying to make event when user joins special voice channel and bot creates a new one and moves user. Now bot can create channel, but when it tries to move user it have an error "Cannot read properties of undefined (reading 'setChannel')"
Here is my code:
const {Collection} = require('discord.js')
let privateVoice = new Collection()
config = require('../config.json');
module.exports = async (bot, oldState, newState)=>{
const user = await bot.users.fetch(newState.id)
const member = newState.guild.members.fetch(user)
if(!oldState.channel && newState.channel.id === (config.createChannel)){
const channel = await newState.guild.channels.create(user.tag,{
type: "GUILD_VOICE",
parent: newState.channel.parent
})
member.voice.setChannel(channel);
privateVoice.set(user.id, channel.id)
}
};
You are trying to fetch a member by their user object and you aren't even awaiting it. .fetch is a Promise and you use their ID, not their user object.
Instead of using this to get their member object:
const member = newState.guild.members.fetch(user)
Use VoiceState.member
const { member } = newState //object destructuring for cleaner syntax. 'const member = newState.member' is also fine
But this can be null since it gets them from the member cache (see here). If you really want to fetch them, make sure to await it and use their ID
const member = await newState.guild.members.fetch(user.id)
Related
I'm pretty new to javascript or discord.js but my guess was something like this:
client.on('channelCreate', channel =>
{
message.channel.send('test');
})
I'm guessing 'channelCreate' doesn't exist.
Your guess is right.
According to the discord.js documentation, you can listen to a channelCreate event to trigger something when a channel is created.
To know who created a channel, your bot need to access the audit logs and the first entry of it.
client.on("channelCreate", async (channel) => {
if (!channel.guild) return;
// Fetch the audit logs of CHANNEL_CREATE events.
const audit_logs = await channel.guild.fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE"
});
if (!audit_logs.entries.first()) {
console.error("No entry found.");
return;
}
const entry = audit_logs.entries.first();
const executor = entry.executor;
// The executor property is type User,
// so you can easily check if it's a bot by doing...
const is_bot = executor.bot;
// `is_bot` will be boolean.
});
Resources
https://discord.js.org/#/docs/discord.js/13.7.0/class/Guild?scrollTo=fetchAuditLogs
https://discord.js.org/#/docs/discord.js/13.7.0/class/GuildAuditLogsEntry?scrollTo=executor
https://discord.js.org/#/docs/discord.js/13.7.0/class/User?scrollTo=bot
so im trying to have the bot run a command that checks the roles of everyone in the database every hour or so. pretty sure i need it to be async for the database portion of this if i remember correctly. i cant figure out how to properly word this to get it to work.
i know how to make an async function normally but im making a functions folder to keep my code clean and from there i dont know how to turn one into a function because normal syntax does not work. most things i find when i google/look here is stuff for inside the code or inside the message handler not for inside a functions folder.
the question being. how can i properly word this to become an async function?
const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
module.exports = {
// we need to declare the name first, then add the function
autoRoleCheck: function (message) {
// find id of user who sent message
let userId = await message.member.id;
//find owner of the guild the message was sent in
let owner = message.guild.ownerID
// Guild the user needs to have the role in
let myGuild = bot.guilds.fetch(process.env.BOT_GUILD);
console.log(myGuild);
}
// here we can add more functions, divided by a comma
}
// if you want to export only one function
// declare it normally and then export it
module.exports = autoRoleCheck;
I don't know why you have the function wrapped in the module.exports, and then export it again later.
Try defining the function first, and then exporting it. Something more like
const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
// we need to declare the name first, then add the function
async function autoRoleCheck(message) {
// find id of user who sent message
let userId = await message.member.id;
//find owner of the guild the message was sent in
let owner = await message.guild.ownerID
// Guild the user needs to have the role in
let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
console.log(myGuild);
}
// if you want to export only one function
// declare it normally and then export it
module.exports = { autoRoleCheck };
I've added the awaits to everything within the function, because I have no idea what's actually accessing the database here. You actually shouldn't need to await anything with the message, because you are passing it in to the function when you call it. (Unless you're passing a promise along, at which point, those awaits will be handy).
Just add the async keyword in front of your function to make it asynchronous. You should then be able to use await syntax.
autoRoleCheck: async function(message) {
const Discord = require('discord.js');
require('dotenv').config();
const mysql = require('mysql2');
let connection;
module.exports = {
// we need to declare the name first, then add the function
autoRoleCheck: async function(message) { // <-- change made here
// find id of user who sent message
let userId = await message.member.id;
//find owner of the guild the message was sent in
let owner = message.guild.ownerID
// Guild the user needs to have the role in
let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
console.log(myGuild);
}
// here we can add more functions, divided by a comma
}
// if you want to export only one function
// declare it normally and then export it
module.exports = autoRoleCheck;
The best way to define a function in an object is by using this syntax:
let someObj = {
someFunction(arg1, arg2) {
//code
},
async someAsyncFn(arg1, arg2) {
//async code
}
}
The execution is super easy to do:
someObj.someFunction(arg1, arg2)
someObj.someAsyncFunction(arg1, arg2)
I'm trying to get all users from my server with a bot using discord.js, I wrote this code but it's not working, it's telling me : TypeError: client.guilds.get is not a function. Here is my code :
'use strict';
const Discord = require('discord.js');
const client = new Discord.Client();
const list = client.guilds.get("myServerID");
list.members.forEach(member => console.log(member.user.username));
client.login('myTokenID');
Thanks
Since discord.js v12 you now need to access the guilds collection using .cache and I can also see that you're trying to access the members collection so your solution would be:
'use strict';
const Discord = require('discord.js');
const client = new Discord.Client();
const list = client.guilds.cache.get("myServerID");
list.members.cache.forEach(member => console.log(member.user.username));
client.login('myTokenID');
just use .fetch()
const guild = await client.guilds.fetch('your_id')
const members = await guild.members.fetch() // returns Collection
i am trying to convert my old discord bot from node js 6.x.x to 8.x.x, i am also putting the commands in a separate folder to make it look cleaner, the command works on my old bot but not with this bot, i get
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'id' of null
UPDATED CODE STILL RETURNS THE SAME:
var settings = '../settingsConfig/settings.json';
var file = require(settings)
const SteamTotp = require('steam-totp');
const Discord = require('discord.js');
const configS = require('../settingsConfig/ConfigSammy.json');
const configJ = require('../settingsConfig/ConfigJack.json');
const configB = require('../settingsConfig/ConfigBen.json');
module.exports.run = async (bot, message, args) => {
function myFunc(){
var JackCode = SteamTotp.getAuthCode(configJ.sharedSecret);
var BenCode = SteamTotp.getAuthCode(configB.sharedSecret);
var SammyCode = SteamTotp.getAuthCode(configS.sharedSecret);
var codess = new Discord.RichEmbed()
.addField("__**Bens Code:**__", BenCode)
.addField("__**Jacks Code:**__", JackCode)
.addField("__**Sammys Code:**__", SammyCode)
.setColor(0x00FF00)
message.author.send(codess)
}
new myFunc();
};
module.exports.help = {
name: "codes"
}
Looks like the error comes from having message.guild not being defined, there for calling message.guild.id yields the error
The reason you're getting this specific error is since you are using the async keyword, which basically means you are using a promise, but you don't provide a reject method for it, hence UnhandledPromiseRejectionWarning
The error may occur because your MongoDB would not be connected. Try to repair it while installing MongoDB.
Hello I'm trying to deafen a particular person in discord but I keep getting the following error:
TypeError: message.setDeaf is not a function
The discord js docs state that you should deafen members like this.
.setDeaf(deaf)
Deafen/undeafen a user.
I'm unsure as to why I'm getting this error, below is my code;
var Discord = require("discord.js");
var client = new Discord.Client();
var user = "30898500862111287"
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', function(message) {
if (message.content === '$deafen') {
message.setDeaf(user);
}
});
setDeaf() is a function derived from GuildMember, not Message. Since Message does not contain a function called setDeaf(), it gave you that error.
In order to get GuildMember, which is the user you want to deafen/undeafen, you can first get the user from the Message, in your case, it will be message.author, which will return the user who sent that message.
Now, on Guild, there is a FetchMember() function that returns a GuildMember datatype. For that function's argument, all you have to do is just to put in your user that you want to target.
(Your Guild will of course be the guild where the message is in! Message.Guild should do the trick.)
Last step is just to deafen/undeafen the user.
You're using setDeaf() on a Message and not a GuildMember (SetDeaf() is a GuildMember method).
Additionally, you're passing an unexisting value user to setDeaf(). I'm guessing you were trying to pass the message.author, but setDeaf() takes a boolean and an optional reason string, not a User.
You can achieve what you're looking for with this:
if(message.content == "$deafen")
message.member.setDeaf(true);
Alternatively, add a reason:
if(message.content == "$deafen")
message.member.setDeaf(true, "reason");
References:
Message Object
GuildMember Object
you cannot invoke a Server Deaf on Message. You can do it on Guild_Member.
If you want to get the first mentioned member:
let mMember = message.mentions.members.first()
mMember.setDeaf(true)
You can also invoke it on the message_author with a member property.
message.member.setDeaf(true)
But you cannot set a Server Deaf on a Message.
It looks like they've changed the code for this a little bit, instead of:
member.setDeaf(true);
You now use:
member.voice.setDeaf(true);
The code below is solution:
const user = message.mentions.members.first()
if(!args[1]) {
message.channel.send('send me a user to mute in voice')
} else {
user.voice.setDeaf(true, `${args[2]}`)
}
Seeing as you may only deafen guild members a useful approach could be getting the guild member.
You pass the set deaf an id, this would in short throw a logic error because you passed an invalid argument type.
The following should achieve what you were going for.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
const guild = client.guilds.cache.get("YOUR GUILD ID");
const user = guild.members.cache.get("30898500862111287");
client.on('message', message => {
if (message.content === '$deafen') {
user.voice.setDeaf(true);
}
});
However, if you instead want to deafen a mentioned member you could take this approach.
var Discord = require("discord.js");
var client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
let mentioned = message.mentions.members.first();
if (message.content === '$deafen') {
mentioned.voice.setDeaf(true);
}
});
(On a side note I'd recommend the use of constants for your discord and client object so they may not be mutated)
const Discord = require("discord.js");