I need help with this, honestly, I've given up on this, 'cause it should work. I don't know if it's a discord.js bug or something but I couldn't find where the issue is.
const Discord = require('discord.js');
const live = "👍";
const rmke = "👎";
module.exports.run = async(bot, message, args) => {
let msg = await message.channel.send("Vote! LIVE 👍 RMK 👎");
await msg.react(live);
await msg.react(rmke);
const reactions = await msg.awaitReactions(reaction => reaction.emoji.name === live || reaction.emoji.name === rmke, {
time: 15000
});
let embed = new Discord.RichEmbed()
.setTitle("Ready")
.setDescription("Results")
.addField("LIVE!", `${live}: ${reactions.get(live).count -1 }`)
.addField("RMK!", `${rmke}: ${reactions.get(rmke).count -1 }`);
message.channel.send({
embed: embed
});
}
module.exports.help = {
name: "vta"
}
(node:8592) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'count' of undefined
at Object.module.exports.run (C:\Users\user\Documents\Mod9z\commands\vota.js:16:60)
(node:8592) 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(). (rejection id: 1)
(node:8592) [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.
If nobody reacts reactions.get(live) and reactions.get(rmke) will be undefined because your bot reacts before the awaitReactions and so that one won't be counted.
The easiest way to deal with this would be:
reactions.get(live) ? reactions.get(live).count : 0
Related
I need some help. The bot joins the voice channel but then crashes when I speak into the voice channel. I am trying to receive voice packets then tell the console that I received packets. The error that I get when speaking is:
(node:1394) UnhandledPromiseRejectionWarning: TypeError: voiceConnection.createReceiver is not a function
(node:1394) 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:1394) [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.
My code is here:
if (command == 'record') {
message.member.voice.channel.join().then((voiceConnection) => {
const { Readable } = require('stream');
const SILENCE_FRAME = Buffer.from([0xF8, 0xFF, 0xFE]);
class Silence extends Readable {
_read() {
this.push(SILENCE_FRAME);
}
}
// Plays silence infinitely
voiceConnection.play(new Silence(), { type: 'opus' });
const receiver = voiceConnection.createReceiver();
voiceConnection.on("speaking",
(user, speaking) => {
if (speaking) {
const audioStream = receiver.createStream(user);
audioStream.on('data',
(chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
}
});
});
}
In discord.js v12, VoiceConnection#createReciever() was removed in favor of VoiceConnection#reciever. I imagine this is because they wanted to limit you to one receiver instead of letting you create however many you want, but I'm not certain. I'm sure you can find a reason in the release notes.
Recently I saw another question that had a answer but it doesn't fully satisfy me. I would like to use the bot in the usage of /invite [invitelink]
Found this code that works using puppeteer but I would like it instead of setting the url by hand in code to use a var or something. I tried just changing the url to a var called url but that just gives a error
>(node:32664) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: invite is not defined
at __puppeteer_evaluation_script__:3:62
at ExecutionContext._evaluateInternal (E:\Folders\DiscordBot\v2\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:218:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async ExecutionContext.evaluate (E:\Folders\DiscordBot\v2\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:107:16)
at async invite4 (E:\Folders\DiscordBot\v2\app.js:91:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:32664) 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:32664) [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.
The code I use is:
const invite = async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://discord.com/');
await page.evaluate(async () => {
const x = new XMLHttpRequest();
x.open('POST', `https://discord.com/api/v6/invites/${invite}`);
x.setRequestHeader('Authorization', token);
x.send();
});
//Maybe good idea to close browser after executing
};
Got the code from here: How do I make a selfbot join a server?
Can anyone help me?
So in the Error is stated, that evaluation failed, because invite is not defined. Evaluation is the part of the code, that gets injected into the website you're trying to access.
>(node:32664) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: invite is not defined
at __puppeteer_evaluation_script ...
You need to pass the inviteCode to the page.evaluate() function. In your case, you also need to pass the token to the function.
To pass variables inside the page.evaluate() function in puppeteer, I found an answer here:
How can I pass variable into an evaluate function?
So for your example, it'd look like that:
const invite = async (inviteCode, token) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://discord.com/');
await page.evaluate(({inviteCode, token}) => {
const x = new XMLHttpRequest();
console.log(inviteCode);
x.open('POST', `https://discord.com/api/v6/invites/${inviteCode}`);
x.setRequestHeader('Authorization', token);
x.send();
},{inviteCode, token});
//Maybe good idea to close browser after executing
};
Like that, you can pass the arguments directly to your function like that: invite(inviteCode, token);
So this command worked just a second ago then the next a error came out of nowhere. Is there a fix to this?
Here is the code
run: async (client, message, args) => {
const cooldown = cooldowns.get(message.author.id);
if (cooldown) {
const remaining = humanizeDuration(cooldown - Date.now(),{ units: ['m', 's'],round: true });
let cEmbed = new MessageEmbed()
.setColor("RANDOM")
.setTitle("Slow down, cmon!")
.setDescription(`You will be able to work in \`${remaining}\` just you wait!\n\nWhile you wait why not follow our [Twitter](https://twitter.com/switchoffical)`)
return message.channel.send(cEmbed)
.catch(console.error);
} else {
let member = message.mentions.users.first() || client.users.cache.get(args[0]);
let user = message.mentions.members.first()
let targetuser = await db.fetch(`money_${user.id}`) // fetch mentioned users balance
let author = await db.fetch(`money_${message.author.id}`) // fetch authors balance
let uBalance = balance[member.id].balance;
let TuBalance = balance[user.id].balance;
let random = Math.floor(Math.random() * 200) + 1; // random number 200-1, you can change 200 to whatever you'd like
let curBal = balance[message.author.id].balance
balance[message.author.id].balance = curBal + random;
let crurBal = balance[message.author.id].balance
balance[user.id].balance = crurBal - random;
if (!user) {
return message.channel.send('Sorry, you forgot to mention somebody.')
if (uBalance < 500) { // if the authors balance is less than 250, return this.
return message.channel.send(':x: You need at least 500$ to rob somebody.')
}
if (TuBalance < 0) { // if mentioned user has 0 or less, it will return this.
return message.channel.send(`:x: ${user.user.username} does not have anything to rob.`)
}
message.channel.send(`${message.author} you robbed ${user} and got away with ${random}!`)
cooldowns.set(message.author.id, Date.now() + 900000);
setTimeout(() => cooldowns.delete(message.author.id), 900000);
db.subtract(`money_${user.id}`, random)
db.add(`money_${message.author.id}`, random)
}
}
}
The error that is made is
(node:7574) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined
at Object.run (/app/commands/economy/rob.js:37:47)
at module.exports (/app/events/guild/message.js:10:33)
at Client.emit (events.js:196:13)
at MessageCreateAction.handle (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketManager.js:386:31)
at WebSocketShard.onPacket (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketShard.js:436:22)
at WebSocketShard.onMessage (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
at WebSocket.onMessage (/rbd/pnpm-volume/5936e237-314d-4884-9101-9ef8b43cdb53/node_modules/.registry.npmjs.org/discord.js/12.2.0/node_modules/discord.js/node_modules/ws/lib/event-target.js:125:16)
at WebSocket.emit (events.js:196:13)
(node:7574) 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(). (rejection id: 1)
(node:7574) [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.
Now to my next question for the fail system I want it to subtract $500 away from the author and give the 500 to whom they were robbing from. I have the code but it broke the command and there is just too much going on in the code where the system will not fit that I have. SO I completely trashed the fail portion. For the fail rate it is pretty high and there is about a 10% chance you will actually rob someone. is there a efficient way to do this with the big code I have.
There are 2 issues here :
Issue 1:
By using
let user = message.mentions.members.first()`
The variable user can be undefined if there are no mentions in the message.
You were right to check for !user, however, you forgot to move the line just before :
let user = message.mentions.members.first()`
// [...]
balance[user.id].balance = crurBal - random;
if (!user) {
Should be :
let user = message.mentions.members.first()`
// [...]
if (!user) {
balance[user.id].balance = crurBal - random;
Issue 2:
Keep in mind that a message does not always have an author. A webhook message has no author, as you can see in the documentation with the return type being ?User (? here means that it can also be null). Here is the related code.
So you also need to check for an author to the recieved message.
I've put a silly bot together that will join a voice channel when prompted and play a clip of Gordon Ramsay. The voice feature works great after some trial and error. Currently I'm trying to have it DM a list of the mp3's available to play but I'm running into an error. I think my if statement to DM the user is interacting with my logic to play a random mp3 in voice channel. I'm still quite new to this.
client.on('message', async message => {
if(message.member.voice.channel && message.content === `${prefix}list`) {
message.author.send('placeholder');
}
if (message.member.voice.channel && message.content === `${prefix}gordon`) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play(mp3[Math.floor(Math.random() * mp3.length)]);
dispatcher.on('start', () => {
console.log('Audio is now playing!\n Deleting command in chat.');
message.delete();
});
dispatcher.on('finish', () => {
console.log('Audio has finished playing!');
connection.disconnect();
});
dispatcher.on('error', console.error);
}});
It successfully sends the DM but it has errors.
```(node:14168) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of null
at Client.<anonymous> (c:\Users\Havok\Desktop\GordonBot\index.js:53:20)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Havok\Desktop\GordonBot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:310:20)
at Receiver.receiverOnMessage
(node:14168) 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:14168) [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.
When the bot receives a DM message, message.member will be null (because it can't be a guild member; it wasn't sent in a guild).
Check if the message was sent in a guild first before attempting use message.member.voice or playing music:
client.on('message', async message => {
if (!message.guild) return;
// rest of code...
})
dm user
message.user.send("msg");
client.on('message', async message => {
if(message.member.voice.channel && message.content === `${prefix}list`) {
messsge.user.send("Message");
}
})
So I am trying to code a Discord bot via discord.js-commando in Visual Studio Code. I am trying to code the music player, and I am able to get the bot to join the voice channel. When inputting the URL I want it to play, though, the terminal gives me this error:
(node:17316) DeprecationWarning: Collection#filterArray: use
Collection#filter instead
(node:17316) UnhandledPromiseRejectionWarning: TypeError: Cannot read
property '524399562249601026' of undefined
at Play
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:6:24)
at message.member.voiceChannel.join.then.connection
(C:\Users\Vincent\Documents\AstralBot\commands\music\join_channel.js:48:25)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:17316) 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(). (rejection id: 1)
(node:17316) [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.
This is the code:
const commando = require('discord.js-commando');
const YTDL = require('ytdl-core');
function Play(connection, message)
{
var server = server[message.guild.id]
server.dispatcher = connection.playStream(YTDL(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function(){
if(server.queue[0])
{
Play(connection, message);
}
else
{
connection.disconnect();
}
});
}
class JoinChannelCommand extends commando.Command
{
constructor(client)
{
super(client,{
name: 'play',
group: 'music',
memberName: 'play',
description: 'Plays whatever you link from YouTube.'
});
}
async run(message, args)
{
if(message.member.voiceChannel)
{
if(!message.guild.voiceConnection)
{
if(!servers[message.guild.id])
{
servers[message.guild.id] = {queue: []}
}
message.member.voiceChannel.join()
.then(connection =>{
var server = servers[message.guild.id];
message.reply("Successfully joined!")
server.queue.push(args);
Play(connection, message);
})
}
else
{
message.reply("You must first join a voice channel before inputting the command.")
}
}
}
}
module.exports = JoinChannelCommand;
I'm a little new to this so any help would be appreciated, thank you.
The issue occurs at var server = server[message.guild.id] saying it can't read property 524399562249601026 of undefined. So in this context server is undefined.
Looking at more snippets of your code, I think you made a typo in that it should be servers[...] instead of server[...].