I was making a simple coinflip command in my discord bot. It is working but makes an "Interaction Failed" event without reason. It edits the embed and changes things it should change. and it deletes the message without any problem.
My Code:
const randomResult = Math.floor(Math.random() * 2) == 0 ? "Heads" : "Tails";
const embed = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("again")
.setLabel("Throw Again")
.setEmoji("🔁")
.setStyle("PRIMARY"),
new MessageButton()
.setCustomId("delete")
.setLabel("Delete")
.setEmoji("♻")
.setStyle("DANGER")
);
message.channel.send({ embeds: [embed], components: [row] }).then(msg => {
global.msg = msg;
})
const iFilter = (i) => i.user.id === message.author.id;
const collector = message.channel.createMessageComponentCollector({
filter: iFilter,
time: 30000,
});
collector.on("collect", async (i) => {
if (i.customId === "again") {
const randomResult =
Math.floor(Math.random() * 2) == 0 ? "Heads" : "Tails";
const newEmbed = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("again")
.setLabel("Throw Again")
.setEmoji("🔁")
.setStyle("PRIMARY"),
new MessageButton()
.setCustomId("delete")
.setLabel("Delete")
.setEmoji("♻")
.setStyle("DANGER")
);
msg.edit({ embeds: [newEmbed], components: [row] });
}
if (i.customId === "delete") {
msg.delete();
}
})
collector.on("end", async (i) => {
const newEmbed2 = new MessageEmbed()
.setTitle("Coin Flip")
.setColor("YELLOW")
.setDescription(` > ${randomResult}`)
.setFooter({
text: `Requested by ${message.author.username}`,
iconURL: message.author.displayAvatarURL(),
});
const row = new MessageActionRow().addComponents(
new MessageButton()
.setCustomId("ended")
.setLabel("Coin Flip Ended")
.setEmoji("❎")
.setStyle("DANGER")
.setDisabled(true),
);
msg.edit({embed: [newEmbed2], components: [row]})
})
Note: I am not getting any errors. I am using discord.js v13 and node.js v16
You still have to reply to the interaction using Interaction#reply() method. This is to acknowledge to discord that you handled the interaction. Something like interaction.reply("success") will probably do the job
Related
I'm creating a discord bot with queue system. A queue is created in play.js file. The queue is then fetched in skip.js using player.getQueue() method to be able to skip songs. However, it returns undefined meaning no queue was found.
I know for a fact a queue exist because I logged it in the console but somehow this methode can't find it.
play.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('plays music')
.addStringOption(option => option
.setName("song")
.setDescription("what to play")
.setRequired(true)),
async execute(interaction, Discord) {
const voice_channel = interaction.member.voice.channel;
const bot_channel = interaction.guild.me.voice.channel;
if (!voice_channel) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription('You need to be in a voice channel to play music!')],
ephemeral: true
});
}
if (bot_channel && bot_channel.id != voice_channel.id) {
await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setDescription(`I'm already connected on ${bot_channel.toString()}`)],
ephemeral: true
});
}
const song = interaction.options.getString("song");
const player = new Player(interaction.client);
const searchResult = await player.search(song, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
}).catch(() => { });
if (!searchResult || !searchResult.tracks.length) {
return interaction.reply({ content: 'No music found!', ephemeral: true });
}
const queue = player.createQueue(interaction.guild);
queue.options.initialVolume = 50;
queue.options.leaveOnEmptyCooldown = 5000;
try {
if (!queue.connection) await queue.connect(voice_channel);
} catch {
void player.deleteQueue(interaction.guildId);
return void interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
}
searchResult.playlist ? queue.addTracks(searchResult.tracks) : queue.addTrack(searchResult.tracks[0]);
if (!queue.playing) {
await queue.play().then(queue.playing = true);
// console.log(queue);
}
const row = new Discord.MessageActionRow()
.addComponents(
new Discord.MessageButton()
.setCustomId('pause')
.setLabel('⏸')
.setStyle('PRIMARY'),
)
.addComponents(
new Discord.MessageButton()
.setCustomId('resume')
.setLabel('▶')
.setStyle('PRIMARY'),
);
const play_embed = await interaction.reply({
embeds: [new Discord.MessageEmbed()
.setColor('#FFDAB9')
.setTitle(`${queue.nowPlaying().title}`)
.setURL(`${queue.nowPlaying().url}`)
.setThumbnail(`${queue.nowPlaying().thumbnail}`)
.setAuthor({ name: ` | Now Playing`, iconURL: `https://imgur.com/krzRxsN.png` })
.addField('Duration :', `\`${queue.nowPlaying().duration}\``, true)
.addField('Author :', `\`${queue.nowPlaying().author}\``, true)
.setTimestamp()
.setFooter({ text: `Requested By ${interaction.user.username}`, iconURL: `${interaction.user.displayAvatarURL()}` })
],
// components: [row]
});
}
}
skip.js Code :
const { SlashCommandBuilder } = require('#discordjs/builders');
const { Player, QueryType } = require('discord-player');
module.exports = {
data: new SlashCommandBuilder()
.setName('skip')
.setDescription('skips to the next music in queue'),
async execute(interaction, Discord) {
await interaction.deferReply();
const player = new Player(interaction.client);
console.log(player.queues);
const queue = player.getQueue(interaction.guildId);
// console.log(queue);
if (!queue || !queue.playing) return void interaction.followUp({ content: "❌ | No music is being played!" });
const currentTrack = queue.current;
const success = queue.skip();
return void interaction.followUp({
content: success ? `✅ | Skipped **${currentTrack}**!` : "❌ | Something went wrong!"
});
}
}
In index.js ,
client.player = new Player(client);
In execute function, pass client as an argument.
execute({interaction, client})
In skip.js, While getting the queue, Try this--
const queue = await client.player.getQueue(interaction.guildId)
I would like to send a message every X seconds and that the user who reacts first gives him 10 coins.
The problem does not come from the system of coins, it is correctly executed.
This code does not work and tells me
Cannot read properties of undefined (reading 'send')
I know this is because I'm not using Client.on('message', message => { }) but I really wish it would go through ready is there any way to do it differently? Can you help me to correct this code?
Client.on('ready', () => {
const fs = require('fs');
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
const channel2up22 = Client.channels.cache.get('935549530210983976');
//Random Drop
const doSomething = () => {
let Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'🚀'`` to this message to win **10 🪙!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter(text="🤖 GuinbearBot | 🌐 Guinbeargang.io")
.setTimestamp()
channel2up22.send(Embed)
.then(message => {
message.react('🚀');
Client.on('messageReactionAdd', (reaction, user) => {
if (reaction.emoji.name === '🚀' && user.id == "338621907161317387") {
message.delete();
var Magic09 = 1;
while (Magic09 <= 10)
{
userCoin[user.id].CoinsAmount++;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {if (err) console.error(err);})
let Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("<#"+ user.id + "> has won the **Wild Gift 🎁 !**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter(text="🤖 GuinbearBot | 🌐 Guinbeargang.io")
.setTimestamp()
channel2up22.send(Embed)
}
})
}).catch(console.error);
}
setInterval(doSomething(), 5000)
})
//Random Drop
});
Not able to fully test this code but this should work assuming all this code goes into a single file, if you get errors or anything comment below and I'll see what I can do to help out.
// Near top of file but after you have defined your client with const Client = new Discord.Client()
const fs = require('fs')
const Discord = require('discord.js')
const Client = new Discord.Client ({
intents: /*your intents here*/,
})
const guild = Client.guilds.cache.get('935549530210983976')
const channel2up22 = guild.channels.cache.get('935549530210983976');
// channels are an element of the guild not the client
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
// placing the function outside of a listener and can be called at anytime
function doSomething() {
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'🚀'`` to this message to win **10 🪙!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "🤖 GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
}).then(message => {
message.react('🚀');
}).catch(console.error);
}
Client.on('ready', () => {
setInterval(doSomething(), 5000)
// every 5 seconds
})
// you want to avoid nesting listeners if at all possible
Client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.channel.id === channel2up22) {
if (reaction.emoji.name === '🚀' && user.id === "338621907161317387") {
// only lets one user react
reaction.message.delete();
var Magic09 = 1;
while (Magic09 <= 10) {
userCoin[user.id].CoinsAmount;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
if (err) console.error(err);
})
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription(`${user} has won the **Wild Gift 🎁 !**`)
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "🤖 GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
})
}
}
})
Here is my code after your first modifications,
I got now an error back : Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'channels') on the line : const channel2up22 = guild.channels.cache.get('935549530210983976');
const Discord = require("discord.js");
const Client = new Discord.Client;
const fs = require('fs')
const guild = Client.guilds.cache.get('925830522138148976');
const channel2up22 =
guild.channels.cache.get('935549530210983976');
const userCoin = JSON.parse(fs.readFileSync('Storage/userCoin.json', 'utf-8'));
function doSomething() {
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription("Be the **first** to react ``'🚀'`` to this message to win **10 🪙!**")
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "🤖 GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
}).then(message => {
message.react('🚀');
}).catch(console.error);
}
Client.on('ready', () => {
setInterval(doSomething(), 5000)
});
Client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.channel.id === channel2up22) {
if (reaction.emoji.name === '🚀' && user.id === "338621907161317387") {
reaction.message.delete();
var Magic09 = 1;
while (Magic09 <= 10) {
userCoin[user.id].CoinsAmount;
Magic09++;
}
fs.writeFile('Storage/userCoin.json', JSON.stringify(userCoin), (err) => {
if (err) console.error(err);
})
const Embed = new Discord.MessageEmbed()
.setTitle("Wild Gift 🎁 ! | GuinGame - v2.0 🎰")
.setColor('#caabd0')
.setDescription(`${user} has won the **Wild Gift 🎁 !**`)
.setThumbnail("https://media.giphy.com/media/Jv1Xu8EBCOynpoGBwd/giphy.gif")
.setFooter({
text: "🤖 GuinbearBot | 🌐 Guinbeargang.io"
})
.setTimestamp()
channel2up22.send({
embeds: [Embed]
})
}
}
});
The code doesn't work when it subtract the variable (enemy's health)
This is my code
if (message.content === ".battle") {
//hidden code....
let damage = Math.floor(Math.random() * 10)
let user = message.author
let embed = new Discord.MessageEmbed()
.setTitle(`${user.username}'s battle`)
.setColor("GREEN")
.setDescription(`
**${user.username}'s Stats**
Health: ${player_health}
Mana: ${player_mana}
Power: ${power}
Frist Skill: ${a1}
Second Skill: ${a2}
Third Skill: ${a3}
`)
//enemy embed
let ene_health = 100
let ene_xp = 10
let embed1 = new Discord.MessageEmbed()
.setTitle(`${user.username}'s battle`)
.setDescription(`
**Enemy's Stats**
Health: ${ene_health}
Mana: ${ene_mana}
`)
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('primary')
.setLabel(`Use: ${power}`)
.setStyle('PRIMARY'),
);
//hidden code......
await message.reply({ content: "You have 1 minute to choose the skills", embeds: [embed, embed1], components: [row] });
const filter = i => i.customId === 'primary' && i.user.id === `${message.author.id}`;
const collector = message.channel.createMessageComponentCollector({ filter, time: 60000 });
collector.on('collect', async i => {
if (i.customId === 'primary') {
await i.deferUpdate();
await wait(4000);
await i.editReply({ content: `You've use ${power} power and you deal the ${damage} Dmg.`, components: [] })
//there the problem
damage - ene_health
}
});
collector.on('end', collected => console.log(`Collected ${collected.size} button`));
}
I wonder at the damage - ene_health why it doesn't subtract the enemy's health
I am using discord.js v13 and quickdb
damage - ene_health
isn't doing anything. In your case you have to CHANGE the damage variable.
damage = damage - ene_health
or even better, use the Substract assignment :
damage -= ene_health
So I wanted to make a help embed in a channel, but when I started running it, it didn't work as I thought... I've looked at it, but I can't find any problems with it..
If there is someone that can help me, please do so.
I know this code is a little weird.
Packages I'm using:
#discordjs/rest 0.1.0-canary.0,
discord-api-types 0.22.0,
discord-buttons 4.0.0,
discord.js 13.1.0
i 0.3.6
npm 7.21.1
Here is the error I get when I use, node .
C:\Users\emilb\OneDrive\Desktop\Carly Support Center\node_modules\discord-buttons\src\v12\Classes\APIMessage.js:9
class sendAPICallback extends dAPIMessage {
^
TypeError: Class extends value undefined is not a constructor or null
at Object.<anonymous> (C:\Users\emilb\OneDrive\Desktop\Carly Support Center\node_modules\discord-buttons\src\v12\Classes\APIMessage.js:9:31)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:94:18)
at Object.<anonymous> (C:\Users\emilb\OneDrive\Desktop\Carly Support Center\node_modules\discord-buttons\src\v12\Classes\WebhookClient.js:2:20)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
Here is the index.js
const { Client, Intents, MessageActionRow, MessageButton } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
//Importing Rest & api-types
const { REST } = require('#discordjs/rest')
const { Routes } = require('discord-api-types/v9')
//Loading Config
const config = require('./config.json');
const { default: discordButtons } = require('discord-buttons');
console.log('Config Loaded')
var owners = config.owners
//Ready Event
client.on('ready', async () => {
console.log(`${client.user.tag} is Ready!`)
client.user.setPresence({
status: "online",
activities: [{
name: config.status,
type: "LISTENING",
}]
})
//Registering Slash
if (config.enable_slash) {
const rest = new REST({ version: '9' }).setToken(config.token)
const commands = [{
name: 'create',
description: 'Replies with Help Embed!'
}]
try {
console.log('Started refreshing application (/) commands.')
await rest.put(
Routes.applicationCommands(client.user.id),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.')
}
catch (error) {
console.error(error)
}
}
})
/**
* #author Emiluvik#8447 <https://github.com/Emiluvik>
*/
client.on("interactionCreate", async (interaction) => {
var SupportEmbed =
{
author: { name: config.embed_content.title, icon_url: client.user.displayAvatarURL({ size: 2048, dynamic: false, format:"png"}) },
timestamp: new Date(),
color: `0x${config.embed_content.color}`,
thumbnail: { url: config.thumbnail ? config.thumbnail_url : client.user.displayAvatarURL({ size: 2048, format: "png", dynamic: false}) },
description: `\u200b\n1️⃣ ${config.embed_content.question_1}\n\u200b\n2️⃣ ${config.embed_content.question_2}\n\u200b\n3️⃣ ${config.embed_content.question_3}\n\u200b\n4️⃣ ${config.embed_content.question_4}\n\u200b\n5️⃣ ${config.embed_content.question_5}\n\u200b\n> **None Of The Above**\nIf Your Question is not in the Above List.(Further Assistance)\n\u200b\n`,
footer:{
text: interaction.guild.name
}
}
let button1 = new MessageButton()
.setStyle("SECONDARY")
.setEmoji("1️⃣")
.setCustomId("button_one")
let button2 = new MessageButton()
.setEmoji("2️⃣")
.setStyle("SECONDARY")
.setCustomId("button_two")
let button3 = new MessageButton()
.setEmoji("3️⃣")
.setStyle("SECONDARY")
.setCustomId("button_three")
let button4 = new MessageButton()
.setEmoji("4️⃣")
.setStyle("SECONDARY")
.setCustomId("button_four")
let button5 = new MessageButton()
.setEmoji("5️⃣")
.setStyle("SECONDARY")
.setCustomId("button_five")
let button6 = new MessageButton()
.setLabel("None Of The Above")
.setStyle("SUCCESS")
//.setEmoji("🤷🏻♂️")
.setCustomId("none_of_the_above")
let buttonRow1 = new MessageActionRow()
.addComponents([button1, button2, button3, button4, button5])
let buttonRow2 = new MessageActionRow()
.addComponents([button6])
if (interaction.isCommand()) {
if (!owners.includes(interaction.user.id)) {
await interaction.reply({ content: "You aren\'t Authorized To use This Command!", ephemeral: true })
}
await interaction.reply({ embeds: [SupportEmbed], components: [buttonRow1, buttonRow2] })
}
else if (interaction.isButton()) {
let responseembed =
{
author:{ name: config.title, icon_url: config.thumbnail ? config.thumbnail_url : client.user.displayAvatarURL({ size: 2048, format: "png", dynamic: false}) },
color: `0x${config.embed_content.color}`,
description: null,
timestamp: new Date(),
footer:{
text: interaction.guild.name
}
}
const logchannel = interaction.guild.channels.cache.get(config.log_channel_id)
if (interaction.customId === "button_one") {
responseembed.description = `\u200b\n**${config.responses.response_1}**\n\u200b\n`
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
// let invitecutie = new MessageButton()
// .setLabel("Invite Link")
// .setStyle("url")
// .setURL("Link")
// let buttonRow = new MessageActionRow()
// .addComponent(invitecutie)
//!If You Want Button in the Response remove // from the the Above 6 lines
return interaction.reply({ embeds: [responseembed], ephemeral: true })//If you want to send link button add ,component: buttonRow after the ephermeral: true declaration
}
if (interaction.customId === "button_two") {
responseembed.description = `**${config.responses.response_2}**\n\u200b\n`
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
return interaction.reply({ embeds: [responseembed], ephemeral: true })
}
if (interaction.customId === "button_three") {
responseembed.description = `**${config.responses.response_3}**`
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
return interaction.reply({ embeds: [responseembed], ephemeral: true })
}
if (interaction.customId === "button_four") {
responseembed.description = `**${config.responses.response_4}**`
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
return interaction.reply({ embeds: [responseembed], ephemeral: true })
}
if (interaction.customId === "button_five") {
responseembed.description = `**${config.responses.response_5}**`
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
return interaction.reply({ embeds: [responseembed], ephemeral: true })
}
if (interaction.customId === "none_of_the_above") {
responseembed.description = `**Go to <#${config.assistance_channel_id}> Channel and ask Your Questions.**`
interaction.guild.members.cache.get(interaction.user.id).roles.add('856799419402813440')
interaction.guild.channels.cache.get(config.assistance_channel_id).send(`<#${interaction.user.id}> Here you can Ask your Further Questions.`)
logchannel.send(`> **${interaction.user.username + "#" + interaction.user.discriminator}**(${interaction.user.id}) Used ${interaction.customId}\nTimeStamp: ${new Date()}`)
return interaction.reply({ embeds: [responseembed], ephemeral: true })
}
}
})
client.on("messageCreate", async (msg) => {
if (msg.author.bot) return
if (msg.channel.type === "dm") return
if (!owners.includes(msg.author.id)) return
if (msg.content !== `${config.prefix}create`) return
if (msg.content = `${config.prefix}create`) {
await msg.delete().catch(() => {})
let button1 = new MessageButton()
.setStyle("SECONDARY")
.setEmoji("1️⃣")
.setCustomId("button_one")
let button2 = new MessageButton()
.setEmoji("2️⃣")
.setStyle("SECONDARY")
.setCustomId("button_two")
let button3 = new MessageButton()
.setEmoji("3️⃣")
.setStyle("SECONDARY")
.setCustomId("button_three")
let button4 = new MessageButton()
.setEmoji("4️⃣")
.setStyle("SECONDARY")
.setCustomId("button_four")
let button5 = new MessageButton()
.setEmoji("5️⃣")
.setStyle("SECONDARY")
.setCustomId("button_five")
let button6 = new MessageButton()
.setLabel("None Of The Above")
.setStyle("SUCCESS")
//.setEmoji("🤷🏻♂️")
.setCustomId("none_of_the_above")
let buttonRow1 = new MessageActionRow()
.addComponents([button1, button2, button3, button4, button5])
let buttonRow2 = new MessageActionRow()
.addComponents([button6])
const supportembed = {
author: { name: config.embed_content.title, icon_url: client.user.displayAvatarURL({ size: 2048, dynamic: false, format:"png"}) },
timestamp: new Date(),
color: `0x${config.embed_content.color}`,
thumbnail: { url: config.thumbnail ? config.thumbnail_url : client.user.displayAvatarURL({ size: 2048, format: "png", dynamic: false}) },
description: `\u200b\n1️⃣ ${config.embed_content.question_1}\n\u200b\n2️⃣ ${config.embed_content.question_2}\n\u200b\n3️⃣ ${config.embed_content.question_3}\n\u200b\n4️⃣ ${config.embed_content.question_4}\n\u200b\n5️⃣ ${config.embed_content.question_5}\n\u200b\n> **None Of The Above**\nIf Your Question is not in the Above List.(Further Assistance)\n\u200b\n`,
footer:{
text: msg.guild.name
}
}
return msg.channel.send({ embeds: [supportembed], components: [buttonRow, buttonRow2] })
} else return
})
client.login(config.token).catch(() => console.log('Invalid Token.Make Sure To Fill config.json'))
And here is the config.json..
{
"token": "Token",
"status": "cs!help",
"prefix": "cs!",
"enable-slash": true,
"owners": ["468053162729799700"],
"embed_content": {
"title": "Carly Support",
"color": "FFA500",
"thumbnail": true,
"thumbnail_url": "profile.png",
"question_1": "How do I invite Carly?",
"question_2": "How do I setup Carly?",
"question_3": "Carly isn't responding",
"question_4": "How do I make a bug report?",
"question_5": "How do I suggest a command to Carly?"
},
"responses": {
"response_1": "If you type: [prefix]invite, Carly will you give an invite link!",
"response_2": "Carly is already set and done! If you wish to change the prefix\nto Carly, type ?prefix [prefix].",
"response_3": "If Carly isn't responding, it is because, the MongoDb pass failed\nto connect, or it's because the bot is shutting down.",
"response_4": "If you join the (support center)[https://discord.gg/nB84Fn6VGd]\nyou can make a report a bug!",
"response_5": "If you join the (support center)[https://discord.gg/nB84Fn6VGd]\nyou can make a suggestion!"
},
"log_channel_id": "880869600298954802",
"assistance_channel_id": "880869600298954802",
"assistance_role_id": "880870840030351520"
}
I've tried to install diferent npm packages, but it still wouldn't work.
So here I am asking for help.
The discord-buttons library currently only supports v12 of Discord.js and relies on a class from that lib that doesn't exist anymore in the latest version 13. There's also an issue to update the package to support v13 but it doesn't look like that's going to happen anytime soon. If you'd like to use the package, either downgrade your djs version to v12 or use something like patch-package to fix the problem yourself.
Hope this helps ;3
I am trying to send a message to a specific channel, and it works only in the server, where the channel is in. Do you have any idea how to fix it?
What I tried:
message.guild.channels.cache.get("816714319172599828")
The error I get:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'channels' of undefined
Edit: My full code:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: "feedback",
description: "Send your feedback for the bot!",
async execute(message, args) {
const feedback = args.slice(0).join(" ");
const no_feedback = new Discord.MessageEmbed()
.setColor("#993333")
.setTitle("Feedback")
.setDescription("An error has occured.")
.addField("Error" , "You didn't type your feedback after the command!")
.addField("What to do?" , "Type `=feedback` and add your feedback right after.")
.setFooter(message.author.username)
.setTimestamp();
const confirm = new Discord.MessageEmbed()
.setColor("#993333")
.setTitle("Confirm")
.setDescription("Trolling results in not being able to do this command anymore.")
.addField("Limit" , `Reactions will not be accepted after 10 minutes.`)
.addField("Feedback" , `Your feedback will be shown as \n **${feedback}**`)
.setFooter(message.author.username)
.setTimestamp();
if(!feedback) return message.reply(no_feedback);
const confirmation = await message.channel.send(confirm);
const emojis = ['✅', '❌'];
emojis.forEach((emoji) => confirmation.react(emoji));
const filter = (reaction, user) =>
user.id === message.author.id && emojis.includes(reaction.emoji.name);
const collector = confirmation.createReactionCollector(filter, { max: 1, time: 600000 });
collector.on('collect', (reaction, user) => {
const [confirm, cancel] = emojis;
confirmation.delete();
if (reaction.emoji.name === cancel) {
const cancelEmbed = new Discord.MessageEmbed()
.setColor('#993333')
.setTitle('Cancelled')
.setDescription(
`Cancelled! The feedback has not been sent.`,
)
.setFooter(message.author.username)
.setTimestamp();
return message.channel.send(cancelEmbed);
}
if (reaction.emoji.name === confirm) {
const doneEmbed = new Discord.MessageEmbed()
.setColor('#993333')
.setTitle('Sent')
.setDescription(
`Your feedback has been sent!`,
)
.setFooter(message.author.username)
.setTimestamp();
message.channel.send(doneEmbed);
const feedback_admins = new Discord.MessageEmbed()
.setColor('#993333')
.setTitle('Feedback')
.setDescription(
`Unread`,
)
.addFields(
{name:"From" , value: message.author.username} ,
{name:"In" , value: message.guild.name} ,
{name:"Feedback" , value: feedback} ,
{name:"❌" , value: "React to this message if the \n feedback isn't helpful"} ,
)
.setFooter(message.author.username)
.setTimestamp();
const feedback_channel = message.guild.channels.cache.get("816714319172599828");
const fbmsg = feedback_channel.send(feedback_admins)
.then((embedMsg) => {
const emojis2 = ['✅', '❌'];
emojis2.forEach((emoji) => embedMsg.react(emoji))
const filter2 = (reaction, user) =>
!user.bot && emojis2.includes(reaction.emoji.name);
const collector_2 = embedMsg.createReactionCollector(filter2, {max: 1});
collector_2.on('collect', (reaction, user) => {
const [accept, deny] = emojis2;
embedMsg.delete();
if (reaction.emoji.name === accept) {
const accepted = new Discord.MessageEmbed()
.setColor('#009933')
.setTitle('Feedback')
.setDescription(
`Accepted`,
)
.addFields(
{name:"From" , value: message.author.username} ,
{name:"In" , value: message.guild.name} ,
{name:"Feedback" , value: feedback} ,
)
.setFooter(message.author.username)
.setTimestamp();
feedback_channel.send(accepted);
}
}
)
}
)
}})}}
You have to use message.client.channels.fetch(channelID) and since the method fetch() returns a Promise, you have to put an await in front of it and make your execute async.
So change this
execute: (message, args) => {
// your code
}
To this:
execute: async (message, args) => {
// example:
const channelID = '<Your target channel id>'
const channel = await message.client.channels.fetch(channelID)
}