TypeError: Cannot read property 'send' of undefined discord.js v12 - discord.js

i have this reaction role system everything works up to the last part where the coulour slection happens
async run(message, client, con) {
await message.channel.send("Give the color for the embed.")
answer = await message.channel.awaitMessages(answer => answer.author.id === message.author.id,{max: 1});
var color = (answer.map(answers => answers.content).join()).toUpperCase()
if(color.toUpperCase()==='CANCEL') return (message.channel.send("The Process Has Been Cancelled!"))
function embstr(){
var finalString = '';
for(var i =0;i<n;i++){
finalString += b[i]+ ' - '+a[i] +'\n';
}
return finalString;
}
const botmsg = message.client.channels.cache.get(channel => channel.id === reactChannel)
const embed = new MessageEmbed()
.setTitle(embtitle)
.setColor(color)
.setDescription(embstr());
botmsg.send(embed);
message.channel.send("Reaction Role has been created successfully")
here is the error message
{
"stack": "TypeError: Cannot read property 'send' of undefined
at SlowmodeCommand.run (B:\\stuff\\Downloads\\Admeeeeeen bot\\src\\commands\\reactionroles\\createreactionrole.js:100:22)
at processTicksAndRejections (node:internal/process/task_queues:93:5)"
}

The .get() method takes in a snowflake as its parameter. AKA an ID of a certain object. It is not an iterator, meaning that what you're currently attempting to do is not right JavaScript wise.
Instead of passing in a parameter to represent a channel object, we'll just want to pass in the ID of the channel that we'd like to get. Alternatively, you could replace .get() with .find() there, which is in fact an iterator that uses this form of a callback, although it's insufficient in our case considering we can just use .get() which is more accurate when it comes to IDs.
/**
* Insufficient code:
* const botmsg = message.client.channels.cache.find(channel => channel.id === reactChannel)
*/
const botmsg = message.client.channels.cache.get(reactChannel /* assuming that reactChannel represents a channel ID */)

Related

TypeError: this is undefined in rect js while passing BigNumber in solana RPC Request

i am getting this is undefined at BN while making RPC request to a function in solana smart contract
'''
let token1Amount = BN(token1_amount);
let token2Amount = BN(token2_amount)
const add_liquidity = await router_program.rpc.addLiquidity(
token1Amount,
token2Amount,
{
accounts: {
// poolAccount: pool_Account.publicKey, //account which stores the individual pair data
userToken1Account: usetoken1_account,
userToken2Account: usetoken2_account,
poolToken1Account: new PublicKey(tokenaccount_1),
poolToken2Account: new PublicKey(tokenaccount_2),
owner: provider.wallet.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
// systemProgram : SystemProgram.programId ,
// associatedTokenProgram: spl.ASSOCIATED_TOKEN_PROGRAM_ID,
// rent: anchor.web3.SYSVAR_RENT_PUBKEY,
tokensProgram: TOKEN_ID,
// poolProgram: pair.programId,
// pairAccount: pairAccount.publicKey
},
// signers: [provider]
}
);
'''
This is a shot in the dark, but I think you need new so that your BNs have a this context, so instead try:
let token1Amount = new BN(token1_amount);
let token2Amount = new BN(token2_amount);

Discord bot join/leave channel change separately per guild

I am trying to find out how to make a command that detects a channel from separate guilds (etc. $setwelcome #channel). I have made the command but, instead of setting it for one guild its setting it for all guilds. this is my code
client.on('guildMemberAdd', member => {
console.log("New member joined.");
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel){
console.log("The joinChannel does not exist.");
}else{
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
member.roles.add(member.guild.roles.cache.find(i => i.name === 'member'));
}
});
/*const channel = member.guild.channels.cach.find((ch) => {
console.log(ch.name);
return ch.name === joinChannel;*/
client.on('guildMemberRemove', member =>{
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Goodbye ${member}, we will miss you :cry:`);
})
client.on("message", message => {
if (!message.author.bot){
const content = message.content;
if (content.toLowerCase().startsWith(`${prefix}setwelcome`)){
joinChannel = content.substring((`${prefix}setwelcome`).length).trim();
console.log(`Join channel changed to ${joinChannel}`);
}
}
});
I guess you could use JSON, best in a database, or different file:
//how the JSON should look like
{
"G123456789012345678": "123456789012345678"
}
//first part is the guild ID, second, is the id the channel you choose
Now you have to somehow modify this data, for this I will use fs, which assumes that this is in the file system. I’ll reference it as if it was in the same folder, and is named: welcomeChannels.json
const fs = require('fs');
//maybe other "requires"
client.on('message', msg => {
//checking message content etc
let ChansString = fs.readFileSync('./welcomeChannels.json');
let chans = JSON.parse(ChansString);
//you can get the channel for the guild with chans['G'+guild.id]
chans['G'+msg.guild.id] = msg.mentions.channels.first().id || msg.channel.id;
fs.writeFileSync('./welcomeChannels.json', JSON.stringify(chans));
})
//use chans[`G${guild.id}`] to get the welcome channel id
Warning: this could fill up your storage. You should use a database instead.

discord.js can not read property'id' of undefined when bulk delete messages

I have been working on a bulk delete message logs, but for whatever reason it can not get the ID of the channel from the guild in a seperate file. so it returns that ID is undefined.
THE CODE
module.exports = async (bot, messages) => {
const length = messages.array().length
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
let mEmbed = new MessageEmbed()
.setAuthor(messages.guild.name, messages.guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
In the index file I specified the
messageDeleteBulk
When trying to send the message to the messageChannel it does not send because 'id' is undefined. Is there something I am missing?
So, the command works fine all I forgot was that earlier when I defined length I used
messages.first()so where I just put messages I have to add .first()
THE NEW CODE
module.exports = async (bot, messages) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.first().guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
const length = messages.array().length;
let mEmbed = new MessageEmbed()
.setAuthor(messages.first().guild.name, messages.first().guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.first().channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
Now it logs the bulk deleted messages and does not return any errors.

TypeError: Cannot read property 'fetchMembers' of undefined

i got this erroe even the command is working fine
(node:1907) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'fetchMembers' of undefined
client.on('message', async message => {
let guild = await message.guild.cache.fetchMembers();
let roleID= '644235497169748037';
let roleID1= '615852982734684181';
let roleID2= '615852983330013212';
let roleID3= '615852992230588427';
let roleID4= '722513324151144552';
let memberCount = guild.roles.get(roleID).members.size;
let memberCount1 = guild.roles.get(roleID1).members.size;
let memberCount2 = guild.roles.get(roleID2).members.size;
let memberCount3 = guild.roles.get(roleID3).members.size;
let memberCount4 = guild.roles.get(roleID4).members.size;
let memberCountChannel = guild.channels.get("733035179756486737")
let memberCountChannel1 = guild.channels.get("732530240420839464")
let memberCountChannel2 = guild.channels.get("732530312713863178")
let memberCountChannel3 = guild.channels.get("732530713898909746")
let memberCountChannel4 = guild.channels.get("732530791686602833")
memberCountChannel.setName("Guild Members: " + memberCount)
memberCountChannel1.setName("Wizard: " + memberCount1)
memberCountChannel2.setName("Witch: " + memberCount2)
memberCountChannel3.setName("Shai: " + memberCount3)
memberCountChannel4.setName("Compass: " + memberCount4)
});
Discord JS v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for a cache on a manager before trying to use collection methods.
You need to change:
guild.roles.get(roleID)
// to
guild.roles.cache.get(roleID)
and:
guild.channels.get(channelID)
// to
guilds.channels.cache.get(channelID)
Another error I saw in your code is that you are trying to access the property cache of Guild, which is nonexistent (message.guild.cache.fetchMembers()).
You'll have to use:
message.guild.members.fetch()

"checkwarns" command giving me this error

Whenever I use my checkwarns command to check the number of warns a user has it gives me this error:
2019-03-20T23:55:35.590941+00:00 app[worker.1]: (node:4)
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'warns' of
undefined
2019-03-20T23:55:35.590958+00:00 app[worker.1]: at
Object.module.exports.run (/app/commands/checkwarns.js:10:35)
I don't know how to fix this I can't find any problems with my code.
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async(bot, message, args) => {
if (!message.member.hasPermission("MANAGE_MESSAGES")) return
message.reply("You don't have permssion to use this command");
let wUser = message.guild.member(message.mentions.users.first()) ||
message.guild.members.get(args[0])
if (!wUser) return message.reply("Couldn't find that user");
let warnlevel = warns[wUser.id].warns;
if (!warns[wUser.id]) warns[wUser.id] = {
warns: 0
};
message.delete().catch();
let warnembed = new Discord.RichEmbed()
.setTitle("**warns**")
.setColor("#0xff80ff")
.addField("User Warns", warnlevel, true);
message.channel.send(warnembed);
}
module.exports.help = {
name: "checkwarns"
}
I'm using Heroku to host the bot.
Your issue might be occuring here:
let warnlevel = warns[wUser.id].warns;
If the key wUser.id doesn't exist, the value of warns[wUser.id] would be undefined, which doesn't contain any user-defined properties. Hence, you get an error trying to read the value of warns (a user-defined property) in undefined.
To get around this, you want to check whether an object at warns[wUser.id] actually exists first. An easy way to do this is by doing the following:
var warnLevel;
if (warns[wUser.id] != undefined) {
warnLevel = warns[wUser.id].warns
}
else {
// Do something else to initialize either warnLevel or warns[wUser.id] here
}

Resources