I am currently making a music Discord Bot. My problem is at the fist lines of the command : even when the user is in a voice channel, voiceChannel is marked as undefined and the bot return "You have to be in a voice channel to use this command"
client.on("message", async message => {
if(message.author.bot) return;
const serverQueue = queue.get(message.guild.id);
if(message.content.indexOf(PREFIX) !== 0) return;
const args = message.content.slice(PREFIX.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "play" || command === "p") {
const args = message.content.split(" ");
const searchString = args.slice(1).join(" ");
const url = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
const serverQueue = queue.get(message.guild.id);
const voiceChannel = message.member.voiceChannel;
if (!voiceChannel) return message.channel.send("You have to be in a voice channel to use this command");
}
});
have a look here
message.member.voiceChannel;
doesn't exist in discord.js version 12 and up
you need to use
message.member.voice.channel.
Related
I am trying to make a system that makes a user enter a code(like a verification code sent to the dms) before doing the action. I am trying to understand how my code can wait for the code to be entered, and I came across the awaitMessages tag. I am trying to understand how I can use it properly in my code. Here is my code.
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! This message had a latency of ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
message.channel.awaitMessage(code) {
message.channel.send('confirmed. Doing the action.')
}
}
});
client.login(config.BOT_TOKEN)
To wait for a response from the user, you can use a collector.
You can create a filter to see if the user sending the code is the same as the one who executed the command and if the code sent is correct
const filter = (msg) => msg.author.id === message.author.id && msg.content === code;
const collector = message.channel.createMessageCollector({
filter,
time: 60000,
});
collector.on('collect', (collectedMessage) => {
collector.stop('success');
message.channel.send('confirmed. Doing the action.')
});
collector.on('end', (collected, reason) => {
if (reason === 'success') return;
else message.channel.send('Timeout or error');
});
How assign role to user in discord by slash command?
This is my discord code by node.js using discord.js module.
After finish this code, I want add role on ready event.
Please fixt:
This small code doesn't working.
else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
in below.
const Discord = require("discord.js");
const config = require("./config.json");
const {
Client,
Intents,
MessageEmbed,
MessageAttachment,
} = require("discord.js");
const { MessageActionRow, MessageButton } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.on("messageCreate", function (message) {
let guild = message.guild;
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(" ");
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (command === "sum") {
const numArgs = args.map((x) => parseFloat(x));
const sum = numArgs.reduce((counter, x) => (counter += x));
message.reply(`The sum of all the arguments you provided is ${sum}!`);
} else if (command === "channel") {
// Create a new text channel
guild.channels
.create("nft-checking", { reason: "Needed a cool new channel" })
.then(console.log)
.catch(console.error);
} else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
});
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(ping! This message had a latency of ${timeTaken}ms.);
Replace these line with this
Or
Just correct the spelling of from pong to ping.
Want a bot to play a predetermined audio file when a word is written in a text channel of my personal server. Having trouble, as it is reading the message, running the code, but not finding that im in a voice channel when I really am. has permissions to join, have no idea why its not working.
Edit: New Code
var Discord = require('discord.js');
const { waitForDebugger } = require('inspector');
var bot = new Discord.Client();
var isReady = true;
const path = require('path');
const ytdl = require('ytdl-core');
bot.on('guildMemberAdd', guildMember =>{
let welcomeRole = guildMember.guild.roles.cache.find(role => role.name === 'Average Bread');
guildMember.roles.add(welcomeRole);
console.log('Role Assigned');
});
bot.once('ready', () => {
console.log('Bot is Online');
});
bot.on('message', message => {
const args = message.content.split(/ +/);
const command = args.shift().toLowerCase();
var VC = message.member.voice.channel;
if (command === "join") {
if (!VC) return message.reply("You are not in a voice channel.")
VC.join()
.then(connection => {
message.channel.send('Joining Channel');
var stream = ytdl('https://www.youtube.com/watch?v=U06jlgpMtQs')
connection.play(stream, {seek: 0, volume: 1});
console.log('Joining')
})
.catch(console.error);
}
else if (command === "leave") {
VC.leave()
message.channel.send('Leaving channel');
console.log('Leaving');
}});
bot.login('token');
I am trying to make a command to clear messages in my discord and I receive the error message is not defined. Above the error inside of the terminal there is one specific portion under my return for the first line with it, there is an arrow pointing up to it.
Here is my code for the main portion
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '!';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Codelyon is online!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command == 'ping') {
client.commands.get('ping').execute(message, args);
}
else if(command == 'ouryoutube') {
client.commands.get('youtube').execute(message, args);
}
else if(command == 'clear') {
client.commands.get('clear').execute(message, args);
}
});
Here is my code for the command
module.exports = {
name: 'clear',
description: "Clear Messages",
execute(messages, args) {
if(!args[0]) return message.reply("You must enter the number of messages you want to clear");
if(isNaN(args[0])) return message.reply("Please Enter a Real Number.");
if(args[0] > 100) return message.reply("You can't delete more then 100 messages");
if(args[0] < 1) return message.reply("You must delete at least one message");
}
}
Thank you any help is appreciated! :)
You have a typo in execute(messages, args) {...}. The first argument should be message.
execute(message, args) {
// code
}
Hi I Coded A Bot But I Want To limit Bot's One Exact Event in One Channel This is Code
No Errors Just Need To Lock This Event in one channel
module.exports = async (client, message) => {
if (message.author.bot) return
if (message.channel.type === "dm") {
const guild = client.guilds.cache.get("736112465678565437")
const channel = guild.channels.cache.find(c => c.name === "modmail-messages")
const embed = new Discord.MessageEmbed()
.setAuthor(`${message.author.tag} | ${message.author.id}`, message.author.displayAvatarURL())
.addField("Message", message.content)
.setFooter("Sent")
.setTimestamp()
.setColor("PURPLE")
await message.author.send("Sending To Staff...")
await channel.send(embed)
}
if (message.channel.type !== "dm" && message.guild.channels.cache.find(c => c.name === "modmail-messages")) {
const user = message.mentions.members.first()
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
let response = args.slice(1).join(' ')
if (!response)
return message.reply("please provide a response to the user!")
if (!user)
return message.reply("please specify a user!")
await user.send(`**(•Hyper Staff)** ${message.member.displayName}: ${response}`)
}
if (message.content.indexOf(process.env.PREFIX) !== 0) return
const args = message.content.slice(process.env.PREFIX.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = client.commands.get(command)
if (!cmd) return
cmd.run(client, message, args)
}```
What do you mean by "locking the event in one channel"? You want the bot to send a message in a specific channel?