discord.js reaction for play function - javascript

I am pretty sure it means message is not defined but why I think I defined it does anyone know what is the problem? I tried everything I can. it sends this error (There was an error connecting to the voice channel: TypeError: Cannot read property 'react' of undefined)
function play(guild, song, client, message) {
const serverQueue = client.queue.get(guild.id)
const loop = client.loop.get(guild.id)
console.log(loop)
if (!song) {
serverQueue.voiceChannel.leave()
client.queue.delete(guild.id)
return
}
const dispatcher = serverQueue.connection.play(ytdl(song.url))
.on('finish', () => {
if (loop === undefined) {
serverQueue.songs.shift()
}
play(guild, serverQueue.songs[0], client, message)
})
.on('error', error => {
console.log(error)
})
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5)
if (loop === undefined) {
const reaction = (reaction) => reaction.emoji.name === '⏭️';
serverQueue.textChannel.send(`Playing: **${song.title}**`)
message.react('⏭️')
.then(console.log)
.catch(console.error);
message.awaitReactions((reaction) => (reaction.emoji.name == '⏭️'),
{ max: 1 }).then(collected => {
if (collected.first().emoji.name == '⏭️') {
if(!message.member.voice.channel) return message.channel.send("You need to be in a voice channel to skip the music")
if(!serverQueue) return message.channel.send("There is nothing to playing")
serverQueue.connection.dispatcher.end()
client.loop.delete(message.guild.id)
}
return undefined
})
}
}

You are right. Inside play(<args>){...} function you try to call .react() on undefined. Could you give more context to this problem? Like the calling context to see why play(<args>){} receives no value for its 4th parameter, message.

Related

Cant use any functions [Type error] Discord.js

The error:
TypeError: Cannot read properties of undefined (reading 'add') line 40
I looked everywhere like even in the discord API but nothing. If there is anything I can do better in my code tell me.
If it's necessary I use VSC and node.js.
The member is a variable and used in if() in the code but it doesn't work.
const { Client , GatewayIntentBits} = require('discord.js')
require('dotenv/config')
var not_stable = "⭕"
var working = "🔛"
var done = "✅"
var failed = "❌"
const client = new Client({
intents:[
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
})
client.on("ready", () => {
console.log("Bot is ready :D");
})
client.on("messageCreate", message => {
if(message.author == client.user) {
return;
}
var member = message.mentions.users.first();
var channel = message.channel;
var bug_channel = message.guild.channels.cache.find(r => r.id === "1030971519754588200");
var sup = message.guild.roles.cache.find(r => r.name == "Suporter")
var ping_sup = "<#&"+sup.id+"> "
if (message.content == "op <#"+member.id+">") {
if (member != undefined) {
let role = message.guild.roles.cache.find(r => r.id === "1030196677472178298");
try {
console.log(member)
member.roles.add(role); //my problem is at the add its not defined
}
catch(error) {
bug_channel.send(ping_sup+"Error while: \n"+error);
}
message.reply("BETA");
message.react(not_stable);
}
if (member === undefined) {
message.reply("There is no user in your command");
message.react(failed);
}
}
if (message.content === "ping") {
message.reply("PAMINHING pong");
message.react(done);
}
if (message.content === "timeout <#"+member.id+">") {
if (member === undefined) {
message.reply("Please do it manually");
message.react(failed)
}
else {
member.timeout(5 * 60 * 1000, 'Time to take a break');
message.reply("Timed out for 5min");
message.react(done);
}
}
if (message.content === "ids") {
message.reply("This is under construction and doesn't work");
}
})
client.login(process.env.TOKEN);
The error is always that noting after member. is recognised and I don't find the solution I'm new to js. ya thx for ya help :D
It's because your member variable is not a GuildMember, but a User. You try to get the roles of a User, but only GuildMembers have roles.
To fix this, you can use message.mentions.members.first() instead as message.mentions.members returns a GuildMember:
var member = message.mentions.members.first();

Discord.js on raw event breakage

Desired outcome: Assign role to a user who reacts to message in channel. On bot restart the message if not in cache, therefore user is not assigned role.
Issue: Code stops responding after guildID = client.guilds.get(packet.d.guild_id);
client has been defined at the start of the script.
Expected output: Returns guildID and adds the role to the user who reacted.
Followed this guide
client.on('raw', packet => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '<CHANNEL_ID>')) return;
//console.log(packet);
guildID = client.guilds.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
guildID.members.cache.get(packet.d.user_id).roles.add('<ROLE_ID>').catch()
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
}
});
Try to using these alternative way to use
And guildID = client.guilds.get(packet.d.guild_id); this wrong way to get guild since discord.js v12 updated it will be guildID = client.guilds.cache.get(packet.d.guild_id);
client.on('messageReactionAdd', (reaction, user) => {
console.log('a reaction has been added');
});
client.on('messageReactionRemove', (reaction, user) => {
console.log('a reaction has been removed');
});
Solved it with this
client.on('raw', async (packet) => {
if (!['MESSAGE_REACTION_ADD', 'MESSAGE_REACTION_REMOVE'].includes(packet.t)) return;
if (!(packet.d.channel_id === '800423226294796320')) return;
guild = client.guilds.cache.get(packet.d.guild_id);
if (packet.t === 'MESSAGE_REACTION_ADD') {
console.log("ADDED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.add(role);
} catch (error) {
console.log(error);
}
}
}
if (packet.t === 'MESSAGE_REACTION_REMOVE') {
console.log("REMOVED");
if (packet.d.emoji.name === '⭐') {
try {
member = await guild.members.fetch(packet.d.user_id);
role = await guild.roles.cache.find(role => role.name === 'star');
member.roles.remove(role);
} catch (error) {
console.log(error);
}
}
}
});

Discord.js Error: Cannot read property 'then' of undefined

I'm making a mute command for my discord bot and currently I'm get an error;
TypeError: Cannot read property 'then' of undefined
I do not know what exactly is causing this issue and would like to know if there are more errors with this code or not
const BaseCommand = require('../../utils/structures/BaseCommand');
const Discord = require('discord.js');
module.exports = class MuteCommand extends BaseCommand {
constructor() {
super('mute', 'moderation', []);
}
async run(client, message, args) {
if(!message.member.hasPermission("MUTE_MEMBERS")) return message.channel.send("You do not have Permission to use this command.");
if(!message.guild.me.hasPermission("MUTE_MEMBERS")) return message.channel.send("I do not have Permissions to mute members.");
const Embedhelp = new Discord.MessageEmbed()
.setTitle('Mute Command')
.setColor('#6DCE75')
.setDescription('Use this command to Mute a member so that they cannot chat in text channels nor speak in voice channels')
.addFields(
{ name: '**Usage:**', value: '=mute (user) (time) (reason)'},
{ name: '**Example:**', value: '=mute #Michael stfu'},
{ name: '**Info**', value: 'You cannot mute yourself.\nYou cannot mute me.\nYou cannot mute members with a role higher than yours\nYou cannot mute members that have already been muted'}
)
.setFooter(client.user.tag, client.user.displayAvatarURL());
let role = 'Muted'
let newrole = message.guild.roles.cache.find(x => x.name === role);
if (typeof newrole === undefined) {
message.guild.roles.create({
data: {
name: 'muted',
color: '#ff0000',
permissions: {
SEND_MESSAGES: false,
ADD_REACTIONS: false,
SPEAK: false
}
},
reason: 'to mute people',
})
.catch(console.log(err)); {
message.channel.send('Could not create muted role');
}
}
let muterole = message.guild.roles.cache.find(x => x.name === role);
const mentionedMember = message.mentions.members.first() || await message.guild.members.fetch(args[0]);
let reason = args.slice(1).join(" ");
const banEmbed = new Discord.MessageEmbed()
.setTitle('You have been Muted in '+message.guild.name)
.setDescription('Reason for Mute: '+reason)
.setColor('#6DCE75')
.setTimestamp()
.setFooter(client.user.tag, client.user.displayAvatarURL());
if (!reason) reason = 'No reason provided';
if (!args[0]) return message.channel.send(Embedhelp);
if (!mentionedMember) return message.channel.send(Embedhelp);
if (!mentionedMember.bannable) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == message.author.id) return message.channel.send(Embedhelp);
if (mentionedMember.user.id == client.user.id) return message.channel.send(Embedhelp);
if (mentionedMember.roles.cache.has(muterole)) return message.channel.send(Embedhelp);
if (message.member.roles.highest.position <= mentionedMember.roles.highest.position) return message.channel.send(Embedhelp);
await mentionedMember.send(banEmbed).catch(err => console.log(err));
await mentionedMember.roles.add(muterole).catch(err => console.log(err).then(message.channel.send('There was an error while muting the member')))
}
}
My guess is that the error has something to do with the last line of code, I'm not sure if this code has more errors is in it but I would very much like to know and am also open to any suggestions with improving the code itself.
You are putting then() in the wrong spot. You would execute then() against add(muterole) (which returns a promise) or you could apply it to catch() or within catch(), but you are applying it to console.log() which doesn't return anything nor is a Promise. Try the following:
await mentionedMember.roles
.add(muterole)
.then()
.catch((err) => {
console.log(err);
// You are trying to send an error message when an error occurs?
return message.channel.send("There was an error while muting the member")
});
or
await mentionedMember.roles
.add(muterole)
.catch((err) => console.log(err))
.then(() =>
message.channel.send("There was an error while muting the member")
);
Hopefully that helps!

Take user image as argument, then send message with same image with Discord.JS

Let's just get this started off with.
I've been looking around Google trying to find a guide on how to take images as arguments and then sending that same image with the message the user provided.
I'm making an announcement command.
Right now, my command only takes text as input, not files/images.
Here's my announce command:
module.exports = {
name: "afv!announce",
description: "announce something",
execute(msg, args, bot) {
if (msg.member.roles.cache.find((r) => r.name === "Bot Perms")) {
const prevmsg = msg;
const text = args.join().replace(/,/g, " ");
msg
.reply(
"Would you like to do `#here` :shushing_face: or `#everyone` :loudspeaker:?\nIf you would like to ping something else, react with :person_shrugging:. (you will have to ping it yourself, sorry)\n*react with :x: to cancel*"
)
.then((msg) => {
const areusure = msg;
msg
.react("🤫")
.then(() => msg.react("📢"))
.then(() => msg.react("🤷"))
.then(() => msg.react("❌"));
const filter = (reaction, user) => {
return (
["🤫", "📢", "🤷", "❌"].includes(reaction.emoji.name) &&
user.id === prevmsg.author.id
);
};
msg
.awaitReactions(filter, { max: 1, time: 60000, errors: ["time"] })
.then((collected) => {
const reaction = collected.first();
if (reaction.emoji.name === "🤫") {
areusure.delete();
prevmsg
.reply("<a:AFVloading:748218375909539923> Give me a sec...")
.then((msg) => {
bot.channels.cache
.get("696135322240548874")
.send("#here\n\n" + text);
msg.edit("<a:AFVdone:748218438551601233> Done!");
});
} else if (reaction.emoji.name === "📢") {
areusure.delete();
prevmsg
.reply("<a:AFVloading:748218375909539923> Give me a sec...")
.then((msg) => {
bot.channels.cache
.get("696135322240548874")
.send("#everyone\n\n" + text);
msg.edit("<a:AFVdone:748218438551601233> Done!");
});
} else if (reaction.emoji.name === "🤷") {
areusure.delete();
prevmsg
.reply("<a:AFVloading:748218375909539923> Give me a sec...")
.then((msg) => {
bot.channels.cache
.get("696135322240548874")
.send(
"Important: https://afv.page.link/announcement\n\n" +
text
);
msg.edit("<a:AFVdone:748218438551601233> Done!");
});
} else if (reaction.emoji.name === "❌") {
areusure.delete();
prevmsg.reply("Cancelled.");
}
})
.catch((collected) => {
msg.delete();
prevmsg.reply("you didn't react with any of the emojis above.");
});
});
}
},
};
Message has a property called attachments, which contains all of the attachments in the message. (A image uploaded by the user is counted as an attachment, however, a URL to an image, is not.)
Here's an example:
client.on('message', (message) => {
if (message.author.bot) return false;
if (message.attachments.size == 0)
return message.channel.send('No attachments in this message.');
const AnnouncementChannel = new Discord.TextChannel(); // This shall be announcement channel / the channel you want to send the embed to.
const Embed = new Discord.MessageEmbed();
Embed.setTitle('Hey!');
Embed.setDescription('This is an announcement.');
Embed.setImage(message.attachments.first().url);
AnnouncementChannel.send(Embed);
});
Avatar
To use images you can use this function :
message.author.displayAvatarURL(
{ dynamic: true } /* In case the user avatar is animated we make it dynamic*/
);
Then it will return a link you can use for an embed thumbnail or image. If you want to use it in an embed
let link = message.author.displayAvatarURL({ dynamic: true });
const embed = new Discord.MessageEmbed().setThumbnail(link);
Use Image Links
If you want to use an image link you'll have to transform it into a discord attachement.
const args = message.content.split(' ').slice(1);
const attach = new Discord.Attachement(args.join(' '), 'image_name.png');
message.channel.send(attach);
Hope I helped you. If not you can still search in the discord.js guide ^^
Not sure where the image link is
If you don't really know where the image link is in the message content you can separate it (you already did with arguments) and use a forEach function :
const args = message.content.split(' ').slice(1);
// a function to see if it's an url
function isvalidurl(string) {
try {
const a = new URL(string);
} catch (err) {
return false;
}
return true;
}
// check the function for each argument
args.forEach((a) => {
if (isvalidurl(a)) link = a;
});
if (link) {
// code
} else {
// code
}

Discord.js : How do i make my bot play an audio when someones enter any channel

I found someone's trying the same but mine appers this " TypeError: oldPresence.guild.channels.get is not a function"
bot.on('voiceStateUpdate', (oldPresence, newPresence) => {
let newUserChannel = newPresence.voiceChannel
let oldUserChannel = oldPresence.voiceChannel
let textChannel = oldPresence.guild.channels.get('TEXTCHANNEL ID')
connection.join()
.then()
if(oldUserChannel === undefined && newUserChannel !== undefined) {
if (newMember.id === 'MEMBER ID')
{
newUserChannel.join()
.then(connection => {
console.log("Joined voice channel!");
const dispatcher = connection.playFile("E:\UniConverter\Downloaded\Trio.mp3");
dispatcher.on("end", end => {newUserChannel.leave()});
})
.catch(console.error);
}
else
textChannel.send("Hello")
}
}
);
bot.login (token);
In the latest version of Discord.js (v12) the correct function is:
oldPresence.guild.channels.cache.get('ID');

Categories