I have a code, which is not working. I do not know how to finish it.
I need if user writing in one channel, his message sending in another, where admin can accept it or denie. So I have a lot of mistakes.
let rMember = message.id(message.id.get(args[0]));
const { RichEmbed } = require("discord.js");
module.exports.run = async (client, message, args) => {
if (message.channel.id !== "someid") return message.delete();
if(!message.member.hasPermission("KICK_MEMBERS")) return message.delete();
let rMember = message.id(message.id.get(args[0]));
if(!rMember) return await message.delete() && message.reply("nope.").then(m => m.delete(3000));
await message.delete().catch(O_o=>{});
const co = '1';
const a = '2';
const b = '3';
const c = '4';
const d = '5';
const e = '6';
const prohibited = ['someid'];
if (!message.member.roles.find(role => prohibited.includes(role.id))) return message.delete().catch(O_o=>{});
const filter = (reaction, user) => ['๐ฆ' ,'๐ง', '๐จ', '๐ฉ', '๐ช', '๐ซ'].includes(reaction.emoji.name) && user.id === message.author.id;
const embed = new RichEmbed()
.setTitle('nope:')
.setDescription(`
๐ฆ ${co.toString()}
๐ง ${a.toString()}
๐จ ${b.toString()}
๐ฉ ${c.toString()}
๐ช ${d.toString()}
๐ซ ${e.toString()}
`)
.setColor(0xdd9323)
.setFooter(`ID: ${rMember}`);
message.channel.send(embed).then(async msg => {
await msg.react('๐ฆ')
await msg.react('๐ง');
await msg.react('๐จ');
await msg.react('๐ฉ');
await msg.react('๐ช');
await msg.react('๐ซ');
msg.awaitReactions(filter, {
max: 1,
time: 30000,
errors: ['time']
}).then(collected => {
const reaction = collected.first();
switch (reaction.emoji.name) {
case '๐ฆ':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${co}**.`);
msg.delete()
break;
case '๐ง':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${a}**.`);
msg.delete()
break;
case '๐จ':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${b}**.`);
msg.delete()
break;
case '๐ฉ':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${c}**.`);
msg.delete()
break;
case '๐ช':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${d}**.`);
msg.delete()
break;
case '๐ซ':
message.client.channels.get(`someid`).send(`${message.member} ${rMember}: **${e}**.`);
msg.delete()
break;
}
}).catch(collected => {
return message.channel.send(`Error.`).then(m => m.delete(3000))
});
});
try{
await rMember.send(`${message.member} nope.`)
}catch(e){
}
}
module.exports.help = {
name: "denie"
}
So this is working code, which sends embed message
client.on('message', async message => {
if (message.channel.id == "someid") {
if (!message.member.roles.find(r => r.name === "role")) return await message.delete();
if (message.author.bot) return;
if (!message.content) return;
const embed = new RichEmbed()
.setTitle('woops:')
.setDescription(message.content)
.setColor(0xdd9323)
.setFooter(`MessageID: ${message.id}`);
await message.client.channels.get(`someid`).send(embed)
}
try{
}catch(e){
}
})
(node:6544) UnhandledPromiseRejectionWarning: TypeError:
message.id.get is not a function
I need for the command to work with[ a ]message [ID] .... as [an] argument.
To retrieve a Message by its ID, you can use the TextChannel.fetchMessage() method. Keep in mind that it returns a Promise. Consider the following examples.
// Attaching a 'then()' method...
const id = '189855563893571595';
const channel = message.channel;
channel.fetchMessage(id)
.then(fetchedMessage => {
// Use 'fetchedMessage'
})
.catch(console.error);
// Using the 'await' keyword (async context required)...
const fetchedMessage = await channel.fetchMessage(id);
// Use 'fetchedMessage'
Implementing this in your command is relatively straightforward.
try {
// Stop if the argument is missing
if (!args[0]) return await message.channel.send(':x: Provide a message ID.');
// Define the channel to fetch the message in
const channel = message.guild.channels.get('idHere');
// Fetch the message
const fetchedMessage = await channel.fetchMessage(args[0]);
// Stop if the message doesn't exist
if (!fetchedMessage) return await message.channel.send(':x: Invalid message ID.');
// Insert code using 'fetchedMessage' here...
} catch(err) {
// Log any errors from rejected promises
console.error(err);
}
Related
I am aware that this problem has been discussed already, but I don't seem to fit the solutions found into my code. I've created some commands to this bot and they seem to work, although they are only basic slash commands (e.g. /ping). This problem came in when I try to run a moderation command or a play command.
This is the code with the error
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.execute(interaction, client);
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
None of the fixes that I found seem to fit, at least to my rather unexperienced eye.
The command I try to run is this:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const { QueryType } = require("discord-player")
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("Asculta muzica")
.addSubcommand((subcommand)=>
subcommand
.setName("song")
.setDescription("Incarca o singura melodie printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul melodiei").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("playlist")
.setDescription("Incarca un playlist printr-un url")
.addStringOption((option) => option.setName("url").setDescription("url-ul playlist-ului").setRequired(true)))
.addSubcommand((subcommand) =>
subcommand
.setName("search")
.setDescription("Cauta o melodie pe baza cuvintelor-cheie")
.addStringOption((option) =>
option.setName("searchterms").setDescription("the search keywords").setRequired(true))),
run: async ({ client, interaction }) => {
if (interaction.member.voice.channel)
return interaction.editReply("Trebuie sa fii pe un voice channel pentru a folosi aceasta comanda!")
const queue = await client.player.createQueue(interaction.guild)
if (!queue.connection) await queue.connect(interaction.member.voice.channel)
let embed = new MessageEmbed()
if (interaction.options.getSubcommand() === "song"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_VIDEO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
} else if (interaction.options.getSubcommand() === "playlist"){
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_PLAYLIST
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const playlist = result.tracks
await queue.addTrack(result.tracks)
embed
.setDescription(`**${result.tracks.length} melodii din [${playlist.title}](${playlist.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${playlist.duration}`})
} else if (interaction.options.getSubcommand() === "search"){
let url = interaction.options.getString("seatchterms")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
})
if (result.tracks.length === 0)
return interaction.editReply("Niciun rezultat")
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})**a fost adaugata`)
.setFooter({ text: `Durata: ${song.duration}`})
}
if (!queue.playing) await queue.play()
await interaction.editReply({
embeds: [embed]
})
}
}
and the corresponding error:
TypeError: command.execute is not a function
at Object.execute (C:\Users\shelby\Bot\src\events\interactionCreate.js:15:27)
at Client.<anonymous> (C:\Users\shelby\Bot\src\functions\handelEvents.js:8:58)
at Client.emit (node:events:513:28)
at InteractionCreateAction.handle (C:\Users\shelby\Bot\node_modules\discord.js\src\client\actions\InteractionCreate.js:97:12)
at module.exports [as INTERACTION_CREATE] (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
at WebSocketManager.handlePacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:352:31)
at WebSocketShard.onPacket (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:489:22)
at WebSocketShard.onMessage (C:\Users\shelby\Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:328:10)
at callListener (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:290:14)
at WebSocket.onMessage (C:\Users\shelby\Bot\node_modules\ws\lib\event-target.js:209:9)
You should be using command.run() instead of command.execute(), as your exported Slash Command uses this property name to store the core function.
const { Interaction } = require("discord.js");
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return
try{
await command.run({ interaction, client });
} catch (error) {
console.log(error);
await interaction.reply({
content: 'A aparut o eroare cu aceasta comanda!',
ephemeral: true
});
}
},
};
Additionally, you have to use an object that contains your interaction and client to run the function instead of using two arguments.
Basically, i'm coding a discord bot and i'm trying to code a music bot / command. On line 14 whenever ?play is run (the command) i get TypeError: Cannot read property 'voice' of undefined (NOTE: i AM in a voice channel when i run this command) Im using discord js v.12.4 not sure how to check :/ I've gone over some stack overflow questions and they're all saying to update message.member.voiceChannel to message.member.voice.channel. btw i have tried message.member.voiceChannel it returns the same error.
code:
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 10,
description: 'Advanced music bot',
async execute(message, args, cmd, client, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`๐ **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`๐ถ Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue ๐`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}```
I'm working on my music bot for my discord server. So my code from a technical perspective works, it can play music, and it has queues, but I'm trying to add embeds to the messages, but I keep getting an error message that my message, channel, author is not defined. How do correctly define properties that I need for my embeds to work?
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ('skip', 'stop'),
cooldown: 0,
description: 'Advanced music bot',
async execute(client, message, args, cmd, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
const Discord = require('discord.js');
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
newEmbed = new Discord.MessageEmbed()
.setTitle("**Now adding...**")
.setDescription(`${song.title}\n\`Requested by:\` ${message.author}`)
.setColor("#ff0000")
.setThumbnail('https://i.pinimg.com/474x/db/cd/d0/dbcdd0a38ebdb5f7f32cfda2f671dede.jpg')
return message.channel.send
message.channel.send(newEmbed);
}
}
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
const Discord = require('discord.js');
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send
newEmbed = new Discord.MessageEmbed()
.setTitle("**Now playing...**")
.setDescription(`${song.title}\n\`Requested by:\` ${message.author}`)
.setColor("#ff0000")
.setThumbnail('https://i.pinimg.com/236x/a1/57/2c/a1572c4306f27fd644ab62199def8aab.jpg')
message.channel.send(newEmbed);
}
I think you are missing the const before the "newEmbed" and you also can't have "newEmbed" twice, as it will return an error. Change it. E.g.
const newEmbed = new Discord.MessageEmbed()
Or you can have
const songList = new Discord.MessageEmbed()
The songList can be anything but just not the same for the other embeds you want.
I am trying to make a my bot play music, and so when I run my command, it doesn't show any error or joining the vc. however when I'm not in the vc it does send me a message telling me to execute this command after joining the vc. I do have Ytdl and YtSearch installed ofcourse, but I can't figure out how to fix this. I'm using repl btw. I'm using Aliases for the skip and stop command.
The code is below.
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
description: 'Plays music',
async execute(message, args, cmd, client, Discord){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`๐ **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`๐ถ Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue ๐`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}
I am trying to code a role reaction for my discord bot. Currently, right now I am stuck on how to make it so multiple people can react to the message to receive a role(s) or remove role(s). I would also like the embed message to be a constant message.
Any guidance would be helpful as I have been trying to code this for several days and I just cant get it.
This is my current code:
const Discord = require("discord.js");
const colors = require("../colors");
const botconfig = require("../botconfig")
module.exports.run = async (bot, message, args) => {
const eRole = message.guild.roles.get('688477690344374283'); // Events
const uRole = message.guild.roles.get('688477558982836344'); // Updates
const pRole = message.guild.roles.get('688477868078137369'); // Polls
const smRole = message.guild.roles.get('687498488295981069'); // Social Media
const qRole = message.guild.roles.get('688477467840872452'); // QOTD
const filter = (reaction, user) => ['โค๏ธ', '๐งก', '๐', '๐','๐'].includes(reaction.emoji.name) && user.id === message.author.id;
let embed = new Discord.RichEmbed()
.setTitle('Pinged Roles')
.setDescription(`
โค๏ธ ${eRole.toString()}
๐งก ${uRole.toString()}
๐ ${pRole.toString()}
๐ ${smRole.toString()}
๐ ${qRole.toString()}
`)
.addField("**TIP:**", "Double react to remove a role")
.setColor(colors.aqua)
.setTimestamp()
.setFooter(`mc.advancius.net`,bot.user.displayAvatarURL)
message.channel.send(embed).then(async msg => {
await msg.react('โค๏ธ');
await msg.react('๐งก');
await msg.react('๐');
await msg.react('๐');
await msg.react('๐');
msg.awaitReactions(filter, {
max:1,
}).then(collected => {
const reaction = collected.first();
switch (reaction.emoji.name) {
case 'โค๏ธ':
if (message.member.roles.has(eRole.id)) {
return message.channel.send('You are already in this role!').then(m => m.delete(3000));
}
message.member.addRole(eRole).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role: **${err.message}**.`);
});
message.channel.send(`You have been added to the **${eRole.name}** role!`).then(m => m.delete(3000));
break;
case '๐งก':
if (message.member.roles.has(uRole.id)) {
return message.channel.send('You are already in this role!').then(m => m.delete(3000));
}
message.member.addRole(uRole).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role: **${err.message}**.`);
});
message.channel.send(`You have been added to the **${uRole.name}** role!`).then(m => m.delete(3000));
break;
case '๐':
if (message.member.roles.has(pRole.id)) {
return message.channel.send('You are already in this role!').then(m => m.delete(3000));
}
message.member.addRole(pRole).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role: **${err.message}**.`);
});
message.channel.send(`You have been added to the **${pRole.name}** role!`).then(m => m.delete(3000));
break;
case '๐':
if (message.member.roles.has(smRole.id)) {
return message.channel.send('You are already in this role!').then(m => m.delete(3000));
}
message.member.addRole(smRole).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role: **${err.message}**.`);
});
message.channel.send(`You have been added to the **${smRole.name}** role!`).then(m => m.delete(3000));
break;
case '๐':
if (message.member.roles.has(qRole.id)) {
return message.channel.send('You are already in this role!').then(m => m.delete(3000));
}
message.member.addRole(qRole).catch(err => {
console.log(err);
return message.channel.send(`Error adding you to this role: **${err.message}**.`);
});
message.channel.send(`You have been added to the **${qRole.name}** role!`).then(m => m.delete(3000));
break;
};
});
})
};
exports.help = {
name: 'roles2'
};
Instead of a collector, I would advise to save that message's object or ID to a JSON and, listen for messageReactionAdd and messageReactionRemove event to check the emoji used to add and remove role.
Example:
bot.on("messageReactionAdd", (reaction, user) => {
if (reaction.message.id != "stored_msg_id") return; // or you can compare the message objects
const eRole = message.guild.roles.get('688477690344374283');
switch (reaction.emoji.name) {
case "โค๏ธ": reaction.message.guild.member(user).addRole(eRole); break;
// etc.
}
});
Things might change depending on your version of discord.js version