When checking invites is the following - javascript

If I create a new express invitation to the server when the bot is turned on, an error occurs. In other cases, it works
const invites = {};
const wait = require('util').promisify(setTimeout);
client.on('ready', () => {
wait(1000);
g.fetchInvites().then(guildInvites => {
invites[g.id] = guildInvites;
});
});
});
client.on('guildMemberAdd', member => {
member.guild.fetchInvites().then(guildInvites => {
const ei = invites[member.guild.id];
invites[member.guild.id] = guildInvites;
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);
const inviter = client.users.get(invite.inviter.id);
const logChannel = member.guild.channels.find(channel => channel.name === "join-logs");
logChannel.send(`${member.user.tag} joined using invite code ${invite.code} from ${inviter.tag}. Invite was used ${invite.uses} times since its creation.`);
});
});
Errors:
2019-07-07T09:49:20.363359+00:00 app[worker.1]: Unhandled Rejection:
2019-07-07T09:49:20.363377+00:00 app[worker.1]: TypeError: Cannot read property 'uses' of undefined
2019-07-07T09:49:20.363378+00:00 app[worker.1]: at guildInvites.find.i (./bot.js:398:57)
2019-07-07T09:49:20.363380+00:00 app[worker.1]: at Map.find (./node_modules/discord.js/src/util/Collection.js:160:13)
2019-07-07T09:49:20.363381+00:00 app[worker.1]: at member.guild.fetchInvites.then.guildInvites (./bot.js:398:33)
2019-07-07T09:49:20.363382+00:00 app[worker.1]: at process._tickCallback (internal/process/next_tick.js:68:7)
398 deadline
const invite = guildInvites.find(i => ei.get(i.code).uses < i.uses);

The invite used is new, and isn't yet in the cache. However, ei.get(i.code).uses assumes it is, and tries to use a property of it when it doesn't exist.
This revised predicate function will return the invite that isn't cached, or the invite that increased in uses.
const invite = guildInvites.find(i => !ei.get(i.code) || ei.get(i.code).uses < i.uses);

Related

events `messageUpdate` and `messageDelete` doesn't "work" after bot restart

Well, events messageUpdate and messageDelete doesn't "work" after restarting the bot
I mean, they don't respond to messages that were sent before the restart
I added MESSAGE to partials
Now the events works, but there is a problem with the if (newMessage.author.bot) return and if (message.author.bot) return and generally with message|newMessage.author|member etc.
Here are the error:
TypeError: Cannot read properties of null (reading 'bot')
at module.exports.run (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\events\messageDelete.js:14:28)
at Slodziak.<anonymous> (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\aslodziak.js:40:43)
at Slodziak.emit (node:events:527:28)
at Slodziak.emit (node:domain:475:12)
at MessageDeleteAction.handle (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\actions\MessageDelete.js:24:16)
at Object.module.exports [as MESSAGE_DELETE] (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_DELETE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketManager.js:346:31) at WebSocketShard.onPacket (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:478:22)
at WebSocketShard.onMessage (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\discord.js\src\client\websocket\WebSocketShard.js:317:10)
at WebSocket.onMessage (C:\Users\ALL\Desktop\Slodziak\Slodziak13vCanary\node_modules\ws\lib\event-target.js:199:18)
Can someone help? I need these partials MESSAGE to messageUpdate because the bot did not respond to messages that were sent after restart. More specifically, to the automod, i.e. that it deletes invitations if someone has edited the message and has no permissions
messageUpdate
module.exports = class {
constructor(client) {
this.client = client;
}
async run(oldMessage, newMessage) {
const data = {};
const client = this.client;
data.config = client.config;
if (newMessage.author.bot) return;
if (!newMessage.editedAt) return;
code that deleted invites if member has not permissions
}
};
messageDelete
module.exports = class {
constructor(client) {
this.client = client;
}
async run(message) {
const data = {};
const client = this.client;
data.config = client.config;
if (message.author.bot) return;
Code that snipes deleted message
}
}
The error means that newMessage.author is null. You already knew that you would need to use the MESSAGE partials.
The problem is that you don't check if the received message is a partial only.
A partial message will not contain all of the original Message parameters. The id, the channelId, and the guildId will be present, but others, like author, can be null.
To solve this, you'll need to check if your message is partial only, and if it is, you can fetch it and use it as usual:
module.exports = class {
constructor(client) {
this.client = client;
}
async run(oldMessage, newMessage) {
const data = {};
const client = this.client;
data.config = client.config;
if (oldMessage.partial) oldMessage = await oldMessage.fetch();
if (newMessage.partial) newMessage = await newMessage.fetch();
if (newMessage.author.bot) return;
if (!newMessage.editedAt) return;
// code that deleted invites if the member has no permissions
}
};

i getting error Cannot read property 'channels' of undefined

I'm getting an error Cannot read property 'channels' of undefined
(node:2632) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property 'channels' of undefined
at updateMembers (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:5:31)
at module.exports (C:\Users\Asus\Desktop\Episode 50\commands\Main-Commands\Mod\member-count.js:13:5)
at Client. (C:\Users\Asus\Desktop\Episode 50\index.js:48:5)
at Object.onceWrapper (events.js:421:28)
at Client.emit (events.js:315:20)
at WebSocketManager.triggerClientReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (C:\Users\Asus\Desktop\Episode
50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:415:10)
at WebSocketShard. (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (C:\Users\Asus\Desktop\Episode 50\node_modules\discord.js\src\client\websocket\WebSocketShard.js:475:12)
Here is my code:
module.exports = (client) => {
const membercountchannel = '811119579580465182'
const updateMembers = (guild) => {
const channel = guild.channels.cache.get(membercountchannel)
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`)
}
client.on('guildMemberAdd', (member) => updateMembers(member.guild))
client.on('guildMemberRemove', (member) => updateMembers(member.guild))
const guild = client.guilds.cache.get('787083837833871400')
updateMembers(guild)
}
If you check the stack trace, you can see that your updateMembers function receives a guild that is undefined (member-count.js:5:31). On the next line you can see that it's coming from the last line (member-count.js:13:5): updateMembers(guild).
As you define guild one line above, it means client.guilds.cache.get('787083837833871400') returns undefined. Make sure the guild ID is correct. If it is correct, you can try to fetch the guild instead.
One more thing, you should never add event handlers inside event handlers. I think you're already in client.on('message'). Every time someone's using your command to update the member count, you create two new event listeners (client.on('guildMemberAdd') and client.on('guildMemberRemove')) and it will cause issues (memory leaks). You need to handle these somewhere else, outside of your commands.
module.exports = async (client) => {
const updateMembers = (guild) => {
const memberCountChannel = '811119579580465182';
const channel = guild.channels.cache.get(memberCountChannel);
channel.setName(`Member:- ${guild.memberCount.toLocaleString()}`);
};
try {
const guild = await client.guilds.fetch('787083837833871400');
updateMembers(guild);
} catch (error) {
console.log(error);
}
};

How can I fix this ReferenceError when using .setSelfDeaf()?

I'm trying to use .setSelfDeaf() in my code but I couldn't figure it out. Every way I tried ended up crashing the bot when executed.
Could someone help me to use it? I want is the bot the deafen itself every time it joins a voice channel.
Edit: added the error I am getting and the updated code upon request.
The error I am getting:
2021-03-04T06:25:06.238627+00:00 app[worker.1]: /app/code.js:53
2021-03-04T06:25:06.238628+00:00 app[worker.1]: connection.voice.setSelfDeaf(true);
2021-03-04T06:25:06.238629+00:00 app[worker.1]: ^
2021-03-04T06:25:06.238629+00:00 app[worker.1]:
2021-03-04T06:25:06.238629+00:00 app[worker.1]: ReferenceError: connection is not defined
2021-03-04T06:25:06.238630+00:00 app[worker.1]: at Client.<anonymous> (/app/code.js:53:5)
2021-03-04T06:25:06.238630+00:00 app[worker.1]: at Client.emit (events.js:327:22)
2021-03-04T06:25:06.238631+00:00 app[worker.1]: at VoiceStateUpdate.handle (/app/node_modules/discord.js/src/client/actions/VoiceStateUpdate.js:40:14)
2021-03-04T06:25:06.238632+00:00 app[worker.1]: at Object.module.exports [as VOICE_STATE_UPDATE] (/app/node_modules/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js:4:35)
2021-03-04T06:25:06.238632+00:00 app[worker.1]: at WebSocketManager.handlePacket (/app/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
2021-03-04T06:25:06.238633+00:00 app[worker.1]: at WebSocketShard.onPacket (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
2021-03-04T06:25:06.238633+00:00 app[worker.1]: at WebSocketShard.onMessage (/app/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at WebSocket.onMessage (/app/node_modules/ws/lib/event-target.js:132:16)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at WebSocket.emit (events.js:315:20)
2021-03-04T06:25:06.238634+00:00 app[worker.1]: at Receiver.receiverOnMessage (/app/node_modules/ws/lib/websocket.js:825:20)
2021-03-04T06:25:06.279643+00:00 heroku[worker.1]: Process exited with status 1
2021-03-04T06:25:06.340294+00:00 heroku[worker.1]: State changed from up to crashed
The updated code:
const Discord = require('discord.js'),
DisTube = require('distube'),
client = new Discord.Client(),
config = {
prefix: "em!",
token: process.env.TOKEN || "[insert discord bot token]"
};
const distube = new DisTube(client, { searchSongs: true, emitNewSongOnly: true });
client.on('ready', () => {
console.log(`e-Music is up and running`);
client.user.setActivity(`em!play`)
});
client.on("message", async (message) => {
if (message.author.bot) return;
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift();
if (command == "play")
distube.play(message, args.join(" "));
if (["repeat", "loop"].includes(command))
distube.setRepeatMode(message, parseInt(args[0]));
if (command == "stop") {
distube.stop(message);
message.channel.send("Stopped the music!");
}
if (command == "skip")
distube.skip(message);
if (command == "queue") {
let queue = distube.getQueue(message);
message.channel.send('Current queue:\n' + queue.songs.map((song, id) =>
`**${id + 1}**. ${song.name} - \`${song.formattedDuration}\``
).slice(0, 10).join("\n"));
}
if ([`3d`, `bassboost`, `echo`, `karaoke`, `nightcore`, `vaporwave`].includes(command)) {
let filter = distube.setFilter(message, command);
message.channel.send("Current queue filter: " + (filter || "Off"));
}
});
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
connection.voice.setSelfDeaf(true);
};
});
const status = (queue) => `Volume: \`${queue.volume}%\` | Filter: \`${queue.filter || "Off"}\` | Loop: \`${queue.repeatMode ? queue.repeatMode == 2 ? "All Queue" : "This Song" : "Off"}\` | Autoplay: \`${queue.autoplay ? "On" : "Off"}\``;
distube
.on("playSong", (message, queue, song) => message.channel.send(
`Playing \`${song.name}\` - \`${song.formattedDuration}\`\nRequested by: ${song.user}\n${status(queue)}`
))
.on("addSong", (message, queue, song) => message.channel.send(
`Added ${song.name} - \`${song.formattedDuration}\` to the queue by ${song.user}`
))
.on("playList", (message, queue, playlist, song) => message.channel.send(
`Play \`${playlist.name}\` playlist (${playlist.songs.length} songs).\nRequested by: ${song.user}\nNow playing \`${song.name}\` - \`${song.formattedDuration}\`\n${status(queue)}`
))
.on("addList", (message, queue, playlist) => message.channel.send(
`Added \`${playlist.name}\` playlist (${playlist.songs.length} songs) to queue\n${status(queue)}`
))
.on("searchResult", (message, result) => {
let i = 0;
message.channel.send(`**Choose an option from below**\n${result.map(song => `**${++i}**. ${song.name} - \`${song.formattedDuration}\``).join("\n")}\n*Enter anything else or wait 60 seconds to cancel*`);
})
.on("searchCancel", (message) => message.channel.send(`Searching canceled`))
.on("error", (message, e) => {
console.error(e)
message.channel.send("An error encountered: " + e);
});
client.login(config.token);
If you read the error ReferenceError: connection is not defined, it tells you what is wrong. connection in the following code is not a variable:
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
connection.voice.setSelfDeaf(true);
};
});
There is a connection property on newVoiceState though, although that isn't what you want in this scenario. You would want to use the .setSelfDeaf method from VoiceState:
client.on("voiceStateUpdate", (oldVoiceState, newVoiceState) => {
if (newVoiceState.id == client.user.id) {
newVoiceState.setSelfDeaf(true);
};
});

TypeError: value.split is not a function

I'm creating a discord.js bot v12 and I get this error on line 2 when I use the purge command in discord and I'm assuming value.split is not a function and wondering if I should be doing something else since I'm using v12 of discord.js:
Uncaught Promise Error:
TypeError: args.split is not a function or its return value is not iterable
at Object.module.exports.run (c:\Users\Kazzu\Desktop\src\commands\prune.js:2:34)
at module.exports (c:\Users\Kazzu\Desktop\src\events\message.js:33:9)
at Client.emit (events.js:323:22)
at MessageCreateAction.handle (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Kazzu\Desktop\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Kazzu\Desktop\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:311:20)
This is my code:
module.exports.run = async (client, message, args) => {
let [ userId, limit ] = args.split(/\s+/);
if(!userId && !limit) {
let deletedMessages = await message.channel.bulkDelete();
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
if(!userId || !limit) return message.channel.send('Please provide the correct arguments.');
let r = new RegExp(/^\d+$/);
if(!r.test(userId)) return message.channel.send('Please provide a valid user id.');
if(isNaN(limit)) return message.channel.send('Please provide a numeric value for limit');
if(limit > 100) return message.channel.send('Limit must be less than or equal to 100.');
try {
let fetchedMessages = await message.channel.messages.fetch({ limit });
let filteredMessages = fetchedMessages.filter(message => message.author.id === userId);
let deletedMessages = await message.channel.bulkDelete(filteredMessages);
message.channel.send(`${deletedMessages.size} messages were deleted.`);
}
catch(err) {
console.log(err);
}
}
module.exports.help = {
name: "purge",
description: "Deletes a number of messages from a user in a channel."
}
module.exports.requirements = {
userPerms: [],
clientPerms: [],
ownerOnly: false
}
It seems that args is not type of string. When you call .split() for something other than a string, JavaScript runtime cannot find the .split() method for that type. So, make sure you are passing a string to your function or try something like that:
if (typeof string === args) {
var str = args.toString();
}
Turns out I needed to replace value.split to value.slice

discord.js TypeError: Cannot read property 'name' of undefined

const botconfig = require("./botconfig.json");
const tokenfile = require("./token.json");
const Discord = require("discord.js");
const fs = require("fs");
const bot = new Discord.Client({disableEveryone: true});
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.length <= 0){
console.log("Couldn't find commands.");
return;
}
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
});
bot.on("ready", async () => {
console.log(`${bot.user.username} is online on ${bot.guilds.size} servers!`);
bot.user.setActivity("!help | website.xyz", {type: "WATCHING"});
//bot.user.setGame("on SourceCade!");
});
bot.on("message", async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
let prefix = botconfig.prefix;
let messageArray = message.content.split(" ");
let cmd = messageArray[0];
let args = messageArray.slice(1);
let commandfile = bot.commands.get(cmd.slice(prefix.length));
if(commandfile) commandfile.run(bot,message,args);
});
bot.login(tokenfile.token);
This is my index folder, when I try to run the bot I get this error. I've tried everything but I'm not the best at this as I am still learning so any help would be greatly appreciated! Thanks
C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:21
bot.commands.set(props.help.name, props);
^
TypeError: Cannot read property 'name' of undefined
at jsfile.forEach (C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:21:33)
at Array.forEach (<anonymous>)
at fs.readdir (C:\Users\Luca\Desktop\DiscordJS\RedHQ-Bot\index.js:18:10)
at FSReqWrap.oncomplete (fs.js:135:15)
[nodemon] app crashed - waiting for file changes before starting...
your commands handler does not have
exports.conf = {
aliases: ['Stuff', 'AlsoStuff']
};
exports.help = {
name: "More Stuff", description: "SillyStuff.", usage: ".SeriousStuff"
}
This is why you are returned the name not found error. Because in the code where it is looking, it doesn't exist.
There is a problem with props.help because it returns undefined (the key "help" does not exist in props) as the error states. You should probably check exactly what you are assigning to props.
When you are accessing a property's property, you should add check for the first property.
Your props.help is undefined. undefined is not a Javascript object and name property lookup on undefined will fail.
If you try looking up the properties of undefined, you will get a TypeEror
Object.getOwnPropertyNames(undefined)
// prints 'Uncaught TypeError: Cannot convert undefined or null to object'
Especially since you are reading multiple files and accessing the fields in those files, you should take care of the case where the file is not in the right format, or file was not read correctly, etc.
jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
if (props.help && props.help.name) {
bot.commands.set(props.help.name, props);
} else {
console.error(`file ${f} does not have .help or .help.name property!`);
});

Categories

Resources