createReceiver isn't a function - discord.js

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.

Related

Make a discord bot join a server automaticly

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);

How to use the awaitMessages function in discord.js

I have some code for discord.js that sends a user a DM when they join the server. They then have to enter the password given to them, and it will then give them a role that allows them access to channels.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.on('guildMemberAdd', guildMember => {
console.log("Joined");
guildMember.send("Welcome to the server! Please enter the password given to you to gain access to the server:")
.then(function(){
guildMember.awaitMessages(response => message.content, {
max: 1,
time: 300000000,
errors: ['time'],
})
.then((collected) => {
if(response.content === "Pass"){
guildMember.send("Correct password! You now have access to the server.");
}
else{
guildMember.send("Incorrect password! Please try again.");
}
})
.catch(function(){
guildMember.send('You didnt input the password in time.');
});
});
});
client.login("token");
The thing is, I don't really know how to use the awaitResponses function. I do not know how to call it, because all the tutorials I find use it with message.member.
When I run my code, I get these three errors:
UnhandledPromiseRejectionWarning: TypeError: guildMember.awaitMessages is not a function
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)
Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.
I do not know what lines these are referring to, so I am very confused.
Here's a quick rundown on how awaitMessages works:
First of all, the .awaitMessages() function extends GuildChannel, meaning you had already messed up a little bit by extending the GuildMember object instead. - You could easily fetch a channel using
const channelObject = guildMember.guild.channels.cache.get('Channel ID Here'); // Gets a channel object based on it's ID
const channelObject = guildMember.guild.channels.cache.find(ch => ch.name === 'channel name here') // Gets a channel object based on it's name
awaitMessages() also gives you the ability to add a filter for a certain condition an input must have.
Let's take the freshly new member as an example. We could simply tell the client to only accept input from members who have the same id as the guildMember object, so basically only the new Member.
const filter = m => m.author.id === guildMember.id
Now, finally, after we've gathered all of the resources needed, this should be our final code to await Messages.
const channelObject = guildMember.guild.channels.cache.get('Channel ID Here');
const filter = m => m.author.id === guildMember.id
channelObject.awaitMessages(filter, {
max: 1, // Requires only one message input
time: 300000000, // Maximum amount of time the bot will await messages for
errors: 'time' // would give us the error incase time runs out.
})
To read more about awaitMessages(), click here!

How do i send a DM to a user using discord.js?

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");
}
})

Error when trying to code a music player for Discord bot

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[...].

weird "count property undefined"

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

Resources