No error message, it just keep saying interaction failed
please help me which part is wrong
I want to make a rock,paper, scissor command.
So basically how this works, I click a button, and the bot will randomly pick another/same button.
and the winner will get 1 point. after some time, the winner is the one with most points
I have to put some stuff because "ur post is mostly code"
like I just want this thing to work man..
const { MessageActionRow, MessageButton, Discord } = require('discord.js');
const { MessageEmbed } = require('discord.js')
module.exports = new Command({
name: 'rps',
description: "play rock paper scissors",
permission: "ADMINISTRATOR",
async run(message, args, client) {
let botPick;
let botEmoji;
let botChoose;
let playerScore = 0;
let botScore = 0;
let rock = ":fist: Rock";
let paper = ":hand_splayed: Paper";
let scissor = ":v: Scissor";
const rockButton = new MessageButton().setCustomId("rock").setStyle('SECONDARY').setLabel("Rock");
const paperButton = new MessageButton().setCustomId("paper").setStyle('SECONDARY').setLabel("Paper");
const scissorButton = new MessageButton().setCustomId("scissor").setStyle('SECONDARY').setLabel("Scissor");
const row = new MessageActionRow().addComponents([rockButton, paperButton, scissorButton]);
let embed = new MessageEmbed()
.setColor("RANDOM")
.setDescription("Winner: **-**")
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
message.channel.send({ embeds: [embed], components: [row] }).then((message) => {
const ifilter = i => i.user.id === message.author.id;
const collector = message.channel.createMessageComponentCollector({ filter: ifilter, time: 30000 })
collector.on("collect", async i => {
button.deferUpdate();
botPick = Math.floor(Math.random() * 3) + 1;
if (botPick === 1) {
botChoose = "rock";
}
if (botPick === 2) {
botChoose = "paper";
}
if (botPick === 3) {
botChoose = "scissor";
}
let embed1 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
if (button.id === "rock") {
botPick = Math.floor(Math.random() * 3) + 1;
if (botChoose === "paper") {
botScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${paper}**\nYou picked: **${rock}**\n**Result**: You lost`, embeds: [embed2], components: [row] })
}
if (botChoose === "rock") {
return message.edit({ content: `I picked: **${rock}**\nYou picked: **${rock}**\n**Result**: We tied`, embeds: [embed1], components: [row] })
}
if (botChoose === "scissor") {
playerScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${scissor}**\nYou picked: **${rock}**\n**Result**: You Won`, embeds: [embed2], components: [row] })
}
}
if (button.id === "paper") {
botPick = Math.floor(Math.random() * 3) + 1;
if (botChoose === "scissor") {
botScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${scissor}**\nYou picked: **${paper}**\n**Result**: You lost`, embeds: [embed2], components: [row] })
}
if (botChoose === "paper") {
return message.edit({ content: `I picked: **${paper}**\nYou picked: **${paper}**\n**Result**: We tied`, embeds: [embed1], components: [row] })
}
if (botChoose === "rock") {
playerScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${rock}**\nYou picked: **${paper}**\n**Result**: You Won`, embeds: [embed2], components: [row] })
}
}
if (button.id === "scissor") {
botPick = Math.floor(Math.random() * 3) + 1;
if (botChoose === "rock") {
botScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${rock}**\nYou picked: **${scissor}**\n**Result**: You lost`, embeds: [embed2], components: [row] })
}
if (botChoose === "scissor") {
return message.edit({ content: `I picked: **${scissor}**\nYou picked: **${scissor}**\n**Result**: We tied`, embeds: [embed1], components: [row] })
}
if (botChoose === "paper") {
playerScore++;
let embed2 = new MessageEmbed()
.setColor("RANDOM")
.setDescription('Winner: **-**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
return message.edit({ content: `I picked: **${paper}**\nYou picked: **${scissor}**\n**Result**: You Won`, embeds: [embed2], components: [row] })
}
}
collector.on("end", async(x) => {
if (x.size === 0) {
message.edit(`No one even played againts me lol!`, null);
} else if (x.size > 0) {
if (playerScore === botScore) {
let embed2 = new MessageEmbed()
.setColor("BLACK")
.setDescription('Winner: **TIED**')
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
message.edit({ content: [null], embeds: [embed2], components: [null] })
} else if (playerScore > botScore) {
let embed2 = new MessageEmbed()
.setColor("GREEN")
.setDescription(`Winner: **${message.author}**`)
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
message.edit({ content: [null], embeds: [embed2], components: [null] })
} else if (playerScore < botScore) {
let embed2 = new MessageEmbed()
.setColor("RED")
.setDescription(`Winner: **${client.user}**`)
.addField(`Score RPS`, `\`->\` ${message.author}: **${playerScore} Point**\n\`->\` ${client.user}: **${botScore} Point**`)
message.edit({ content: [null], embeds: [embed2], components: [null] })
}
}
})
})
})
}
});```
In your collector.on("collect", ...)'s callback, you take a parameter i, but use button.deferUpdate() in the body of the function. button is not defined, result in an error, and the interaction times out.
In addition, your message.channel.send(...).then(message) overwrites the original message variable, so your filter is actually looking for interactions from the bot itself.
To fix this, remove the unnecessary variable message from the .then():
message.channel.send({ embeds: [embed], components: [row] }).then(() => {
// ...
Also, change the parameter's name from i to button:
collector.on("collect", async button => {
button.deferUpdate();
// ...
}
Another issue is that collector.on("end") is called within collector.on("collect"). This may be unintended, and you may want to move that outside of the collector.on("collect") callback function.
Note that you cecked the wrong value of the button id
use button.customId instead of button.id this is not a correct to check the id.
Also on your collector there is so many resource embed create , practicaly this is a bad idea considering using one function to handle that win and lose :)
for making collector recognized what the component you been using you need to declare the type of components.
Like this.
const collector = message.createMessageComponentCollector({
filter: ifilter,
componenType: "BUTTON",
time: 30000
})
Its seem your collector did not recognized your component.
Related
I want to create a command to define a channel where the logs will be sent, I tried many things but I couldn't
client.on("messageUpdate", (message, oldMessage, newMessage) => {
const channel = client.channels.cache.get("1073738678758817863");
const embed = new Discord.EmbedBuilder()
.setTitle(`Log | Mensagem Editada.`)
.setColor('#ff00ff')
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setFooter({ text: `© ${client.user.username} 2023`})
.setTimestamp(new Date())
.setDescription(`Autor da mensagemn:\n> **Usuário:** ${message.author} \n> **ID:** \`${message.author.id}\`\nCanal ‣ ${message.channel} \n\n**Mensagem antiga:** \n \`\`\`${message.content}\`\`\` \n**Mensagem nova:** \n \`\`\`${oldMessage.content}\`\`\``)
let botao = new ActionRowBuilder().addComponents(
new Discord.ButtonBuilder()
.setLabel("Ir para mensagem")
.setStyle(Discord.ButtonStyle.Link)
.setURL(`${message.url}`)
.setEmoji("📩")
)
channel.send({ embeds: [embed], components: [botao] })
})
client.on(Events.MessageDelete, async message => {
if (!message.guild) return;
const fetchedLogs = await message.guild.fetchAuditLogs({
limit: 1,
type: AuditLogEvent.MessageDelete,
});
const deletionLog = fetchedLogs.entries.first();
const { executor, target } = deletionLog;
if (target.id === message.author.id) {
const channel2 = client.channels.cache.get("1073738678758817863");
const embed2 = new Discord.EmbedBuilder()
.setTitle(`Log | Mensagem Deletada.`)
.setColor('#ff00ff')
.setFooter({ text: `© ${client.user.username} 2023`})
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTimestamp(new Date())
.setDescription(`Autor da mensagemn:\n> **Usuário:** ${message.author} \n> **ID:** \`${message.author.id}\`\nCanal ‣ ${message.channel} \n\n**Mensagem deletada:** \n \`\`\`${message.content}\`\`\`\nMensagem deletada por:\n> **Usuário:** ${executor.tag}\n> **ID:**\`${executor.id}\``)
channel2.send({ embeds: [embed2] });
} else {
const channel3 = client.channels.cache.get("1073738678758817863");
const embed3 = new Discord.EmbedBuilder()
.setTitle(`Log | Mensagem Deletada.`)
.setColor('#ff00ff')
.setFooter({ text: `© ${client.user.username} 2023`})
.setThumbnail(`${client.user.displayAvatarURL({ size: 2048 })}`)
.setTimestamp(new Date())
.setDescription(`Autor da mensagemn:\n> **Usuário:** ${message.author} \n> **ID:** \`${message.author.id}\`\nCanal ‣ ${message.channel} \n\n**Mensagem deletada:** \n \`\`\`${message.content}\`\`\`\nMensagem foi deletada por: **Ele mesmo**`)
channel3.send({ embeds: [embed3] });
}
});```
TICKET PROBLEM
When I reopen the ticket and want to close it again, the "interaction.channel.edit" function is not working, why?
There are no errors, version v13
When I close my ticket before reopening, everything is fine
//Now I am writing a sample message because they are stating that I wrote the code alone
const client = require("../index");
const { createTranscript } = require('discord-html-transcripts');
const { MessageEmbed, MessageActionRow, MessageButton, Message } = require("discord.js");
client.on("interactionCreate", async (interaction) => {
// Slashe
if (interaction.isCommand()) {
await interaction.deferReply({ ephemeral: false }).catch((error) => { console.log(error)});
const cmd = client.slashCommands.get(interaction.commandName);
if (!cmd)
return interaction.followUp({ content: "Wystapil jakis blad!" });
const args = [];
for (let option of interaction.options.data) {
if (option.type === "SUB_COMMAND") {
if (option.name) args.push(option.name);
option.options?.forEach((x) => {
if (x.value) args.push(x.value);
});
} else if (option.value) args.push(option.value);
}
interaction.member = interaction.guild.members.cache.get(interaction.user.id);
cmd.run(client, interaction, args);
}
// Context menu
if (interaction.isContextMenu()) {
await interaction.deferReply({ ephemeral: false });
const command = client.slashCommands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
// Buttony
if(interaction.isButton()) {
await interaction.deferUpdate()
if(interaction.customId === 'verify') {
let error = 0
const roleAdd = interaction.guild.roles.cache.get('949702807517265930')
const roleRemove = interaction.guild.roles.cache.get('949702776508792864')
if(!interaction.guild.me.permissions.has('ADMINISTRATOR')) {
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Nie posiadam permissji potrzebnych do weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleAdd.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą dodaje podczas weryfikacji!")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(interaction.guild.me.roles.highest.position <= roleRemove.position){
const channel = interaction.guild.channels.cache.get("949716268146131066")
const embed = new MessageEmbed()
.setColor('RED')
.setTitle("ERROR")
.setDescription("Moja rola jest niżej niż rola, którą zabieram podczas weryfikacji")
.setTimestamp();
error = 1
channel.send({ embeds:[embed]});
}
if(error > 0){
interaction.guild.members.cache.get("613438379174133770").send("Błąd podczas weryfikacji!")
return interaction.member.send("Wystąpił błąd podczas weryfikacji!");
}
await interaction.member.roles.add(roleAdd)
await interaction.member.roles.remove(roleRemove)
interaction.member.send("Pomyślnie zweryfikowano!")
}if(interaction.customId === 'ticket-open'){
if(interaction.guild.channels.cache.find(ch => ch.topic == interaction.user.id)) {
return interaction.followUp({
content: `Posiadasz już ticket!`,
ephemeral: true
})}
interaction.guild.channels.create(`Ticket-${interaction.user.username}`, {
parent: '949978511324635136',
permissionOverwrites: [{
id: interaction.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: '949701839560011797',
deny: ['VIEW_CHANNEL', 'SEND_MESSAGES']
},
{
id: client.user.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES']
}],
topic: interaction.user.id
})
.then(async(tick) => {
interaction.followUp({
content: `Ticket otworzony <#${tick.id}>`,
ephemeral: true
})
const tickEmbed = new MessageEmbed()
.setColor('GREEN')
.setFooter({
text: `${interaction.user.username} ${new Date().getFullYear()}`,
iconURL: interaction.user.displayAvatarURL({ dynamic: true })
})
.setTitle("Ticket")
.setDescription(`**Otworzyłeś/aś ticket, poczekaj cierpliwie, aż ktoś z administracji Cie obsłuży, nie pinguj oraz zachowaj kulturę na tickecie**`);
const closeButton = new MessageButton()
.setCustomId("close-button")
.setLabel("Zamknij")
.setEmoji("🔒")
.setStyle("SECONDARY");
const row = new MessageActionRow()
.setComponents(closeButton);
tick.send({
content: `Cześć <#${interaction.user.id}>, administracja za chwilę Cie obsłuży <#&949982338031423541>`,
embeds: [tickEmbed],
components: [row]
})
})
} if(interaction.customId === 'close-button'){
if(interaction.channel.name.includes(`zamkniety`)) return interaction.followUp({ content: 'Ticket jest już zamknięty!', ephemeral: true });
const buttonTak = new MessageButton()
.setCustomId('close-tak')
.setLabel('Zamknij')
.setStyle('SECONDARY')
const buttonNie = new MessageButton()
.setCustomId('close-nie')
.setLabel('Anuluj')
.setStyle('DANGER')
const raw = new MessageActionRow()
.setComponents([buttonTak, buttonNie])
interaction.channel.send({
content:'Czy napewno chcesz zamknąć ticket?',
components: [raw]
})
} if(interaction.customId === 'close-tak'){
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
name: "zamkniety",
permissionOverwrites: [{
id: interaction.channel.topic,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id: '949701839560011797',
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
const embed = new MessageEmbed()
.setDescription(`Ticket zamknięty przez <#${interaction.user.id}>`)
interaction.channel.send({embeds:[embed]})
setTimeout(() => {
const embed2 = new MessageEmbed()
.setDescription(`\`\`\`System kontroli ticketów po zamknięciu\`\`\``)
.setColor('YELLOW');
const buttonReopen = new MessageButton()
.setCustomId("reopenButton")
.setLabel("Otworz")
.setEmoji('🔓')
.setStyle('SECONDARY')
const buttonTranscript = new MessageButton()
.setCustomId("transcriptButton")
.setLabel("Transcript")
.setEmoji('📝')
.setStyle('SECONDARY')
const buttonDelete = new MessageButton()
.setCustomId("deleteButton")
.setLabel("Usun")
.setEmoji('⛔')
.setStyle('SECONDARY')
const row = new MessageActionRow()
.setComponents([ buttonTranscript, buttonReopen, buttonDelete])
interaction.channel.send({
embeds:[embed2],
components: [row]
})
}, 500)
} if(interaction.customId === 'close-nie'){
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
} if(interaction.customId === 'reopenButton') {
const usd = interaction.guild.members.cache.get(interaction.channel.topic)
const name = usd.user.username
interaction.channel.edit({
permissionOverwrites: [{
id: interaction.channel.topic,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL']
}, {
id:'949701839560011797' ,
deny: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}, {
id: client.user.id,
allow: ['SEND_MESSAGES', 'VIEW_CHANNEL'],
}],
name: `ticket`
})
const embed = new MessageEmbed()
.setDescription(`Ticket został ponownie otworzony przez <#${interaction.user.id}> (${interaction.user.username})`)
.setColor('GREEN')
interaction.channel.send({embeds:[embed]})
const message = await interaction.channel.messages.fetch(interaction.message.id).catch(() => null);
if (message) {
interaction.message.delete()
}
}
// } if(interaction.customId === 'transcriptButton'){
// interaction.channel.send({ content: "Tworzenie zapisu..." })
// const user = await client.users.fetch(interaction.channel.topic)
// const transcript = await createTranscript(interaction.channel, {
// limit: -1,
// fileName: `ticket-${interaction.channel.topic}.html`,
// returnBuffer: false,
// })
// client.channels.cache.get("950383700904931368").send({
// files: [transcript]
// }).then(() => {
// interaction.channel.delete()
// })
// }
}
});
I'm going to make a discord.js. When I enter !otherhelp, I try to get an embed, but it doesn't get an embed doesn't come out.
this is my code...
const { Client, Intents, DiscordAPIError } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {prefix, token} = require('./config.json')
const fs = require('fs')
const { MessageEmbed } = require('discord.js');
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
});
const convertEmoji = (who) => {
if(who === "!가위바위보 가위"){
return "✌";
}
else if(who === "!가위바위보 바위"){
return "👊";
}
else if(who === "!가위바위보 보"){
return "✋";
}
}
client.on('message', msg => {
if(msg.content === "!서버주소"){
msg.reply("1.8.9 beargames.mcv.kr");
}
if(msg.content === "!가위바위보 가위" || msg.content === "!가위바위보 바위" || msg.content === "!가위바위보 보") {
const human = msg.content;
const list = ["!가위바위보 가위", "!가위바위보 바위", "!가위바위보 보"];
const random = Math.floor(Math.random() * 3);
const bot = list[random];
let winner = "";
if(human === bot) {
winner = "비김";
}
else {
human === "!가위바위보 가위" ? (winner = bot === "!가위바위보 바위" ? "봇" : "사람") : "";
human === "!가위바위보 바위" ? (winner = bot === "!가위바위보 보" ? "봇" : "사람") : "";
human === "!가위바위보 보" ? (winner = bot === "!가위바위보 가위" ? "봇" : "사람") : "";
}
const result =
`
봇 : ${convertEmoji(bot)}
${winner === "비김" ? "우리는 비겼다 인간." : winner + "의 승리다"}
`
msg.reply(result);
}
if(msg.convertEmoji === !otherhelp){
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor({ name: 'Some name', iconURL: 'https://i.imgur.com/AfFp7pu.png', url: 'https://discord.js.org' })
.setDescription('Some description here')
.setThumbnail('https://i.imgur.com/AfFp7pu.png')
.addFields(
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{ name: 'Inline field title', value: 'Some value here', inline: true },
{ name: 'Inline field title', value: 'Some value here', inline: true },
)
.addField('Inline field title', 'Some value here', true)
.setImage('https://i.imgur.com/AfFp7pu.png')
.setTimestamp()
.setFooter({ text: 'Some footer text here', iconURL: 'https://i.imgur.com/AfFp7pu.png' });
channel.send({ embeds: [exampleEmbed] });
}
});
client.login('(token)');
this is my error
C:\Users\User\Desktop\dev\discordbot\index.js:51
if(msg.convertEmoji === !otherhelp){
^
ReferenceError: otherhelp is not defined
at Client. (C:\Users\User\Desktop\dev\discordbot\index.js:51:26)
at Client.emit (node:events:390:28)
at MessageCreateAction.handle (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\actions\MessageCreate.js:33:18)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)
at WebSocketShard.onPacket (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
at WebSocketShard.onMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
at WebSocket.onMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\ws\lib\event-target.js:199:18)
at WebSocket.emit (node:events:390:28)
at Receiver.receiverOnMessage (C:\Users\User\Desktop\dev\discordbot\node_modules\ws\lib\websocket.js:1093:20)
convertEmoji is not part of the Discord message object.
Use message.content instead.
if(msg.content === "!otherhelp")
I posted about this a few days ago, but after following their suggestion it still does not seem to be working. Any idea why? I am using replit and uptime to host the bot.
I am new to coding and I just can't figure out whats wrong
Figured I would ask you guys and see if you have any idea why. Please lemme know if you have any ideas
const prefix = '?';
const Discord = require('discord.js');
const { MessageEmbed } = require('discord.js');
const bot = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES"
]
});
const config = process.env;
bot.on('ready', () => {
console.log(bot.user.username + ' is online.')
});
//CONSTANT COMMANDS
//Text Commands
bot.on('messageCreate', (msg) => {
if(msg.author.bot || msg.channel.type === "dm")
return;
const messageArray = msg.content.split(' ');
const cmd = messageArray[0];
const args = msg.content.substring(msg.content.indexOf(' ') + 1);
const prefix = config.prefix;
if(cmd.toLowerCase() === prefix + 'discord' ) {
msg.channel.send({
content: 'https://discord.gg/RehTqdDpEm'
})
}
if(cmd.toLowerCase() === prefix + 'realm' ) {
msg.channel.send({
content: 'https://realms.gg/5T7DrRwbS7o'
})
}
if(cmd.toLowerCase() === prefix + 'yada' ) {
msg.channel.send({
content: 'yada'
})
}
//Embed Commands
if(message.content.toLowerCase() === prefix + "help") {
let embed = new MessageEmbed()
.setTitle("Command List")
.setDescription("**?Player Description**- Shows a description of all the players. \n **realm**- Sends a realm invite \n **?factions**- Shows the factions of this season and their members \n **?info {faction}**- Shows the lore and banner of a faction \n **?help**- Shows this help menu \n **?quote**- Sends a random quote from the server \n **?world**- sends the world lore.")
.setColor("RANDOM")
message.channel.send({ embeds: [embed]})
}
if(message.content.toLowerCase() === prefix + "world") {
let embed2 = new MessageEmbed()
.setTitle("World Lore")
.setDescription("lore")
.setColor("RANDOM")
message.channel.send({ embeds: [embed2]})
}
if(message.content.toLowerCase() === prefix + "info giraduan") {
let embed2 = new MessageEmbed()
.setTitle("The Giraduan Dominion")
.setDescription("lore")
.setColor("RANDOM")
message.channel.send({ embeds: [embed2]})
}
if(message.content.toLowerCase() === prefix + "info rpa") {
let embed2 = new MessageEmbed()
.setTitle("Rerualin Preservation Association")
.setDescription("faction lore")
.setColor("RANDOM"
)
message.channel.send({ embeds: [embed2]})
}
if(message.content.toLowerCase() === prefix + "player description") {
let embed2 = new MessageEmbed()
.setTitle("Player Descriptions")
.setDescription("oops no info for you")
.setColor("RANDOM")
message.channel.send({ embeds: [embed2]})
}
if(message.content.toLowerCase() === prefix + "character example") {
let embed2 = new MessageEmbed()
.setTitle("Example Character")
.setDescription("description")
.setColor("RANDOM")
.setThumbnail('https://cdn.discordapp.com/attachments/877727121341026304/904443409614401546/YIN_YANG-removebg-preview.png')
message.channel.send({ embeds: [embed2]})
}
});
//Game Commands
bot.login(config.token);
As you can see I'm trying to do a list in form of an embed, where users can sign themselves in, via discord buttons. I already created the buttons and I thought with this code I could do what I wanted, but there are some problems. For example the first press on the buttons always results in a failed interaction. Or when someone else presses a button after I pressed one, he changes my name in the Array. And after some clicks the bot also crashes with the error "DiscordAPIError: Unknown interaction" at this function: "await i.update({ embeds: [newEmbed], components: [row] });". As I'm new to Programming and stuck for several days now, someone really needs to help me. This is the part of the code, that doesn't work how it should:
client.on('interactionCreate', async interaction => {
var users = [];
var buttonclicker = interaction.member.nickname
var greenbtnclicker = '🟢 ${buttonclicker}'
var yellowbtnclicker = '🟡 ${buttonclicker}'
const collector = interaction.channel.createMessageComponentCollector({ time: 2147483647 });
if(!interaction.isButton()) return;
collector.on('collect', async (i) => {
if (i.customId === 'green') {
if(users.indexOf(greenbtnclicker) == -1) {
if(users.indexOf(yellowbtnclicker) > -1) {
var int = users.indexOf(yellowbtnclicker)
users.splice(int, 1)
}
users.push(greenbtnclicker)
users.sort();
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already green')
}
} else if (i.customId === 'red') {
if(users.indexOf(yellowbtnclicker) != -1) {
var int = users.indexOf(yellowbtnclicker)
users.splice(int, 1)
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else if(users.indexOf(greenbtnclicker) != -1) {
var int = users.indexOf(greenbtnclicker)
users.splice(int, 1)
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already out')
}
} else if (i.customId === 'yellow') {
console.log(users)
if(users.indexOf(yellowbtnclicker) == -1) {
if(users.indexOf(greenbtnclicker) != -1) {
var int = users.indexOf(greenbtnclicker)
users.splice(int, 1)
}
users.push(yellowbtnclicker)
users.sort();
const newEmbed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription('Active Players: ${users.length}')
.setFooter('Footer')
for(var j=0;j < users.length; j++) {
newEmbed.addField('--------------------------------', users[j])
}
await i.update({ embeds: [newEmbed], components: [row] });
} else {
console.log('Already yellow')
}
}
});
});
I also have this before the essential code:
const { MessageActionRow, MessageButton, MessageEmbed} = require("discord.js");
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("green")
.setStyle("SUCCESS")
.setLabel("green")
.setEmoji("🟢"),
new MessageButton()
.setCustomId("red")
.setStyle("DANGER")
.setLabel("red")
.setEmoji("🔴"),
new MessageButton()
.setCustomId("yellow")
.setStyle("SECONDARY")
.setLabel("yellow")
.setEmoji("🟡"),
);
client.once("messageCreate", async (msg) => {
if(msg.content.toLowerCase() == "!createrecord" && msg.guild && !msg.member.user.bot){
msg.delete()
var embed = new MessageEmbed()
.setColor('#208c3d')
.setTitle('Active list')
.setDescription("No active players")
.setFooter("Footer")
msg.channel.send({ embeds: [embed], components: [row] })
}
})
It looks like you didn’t define row, try to define row
Try adding the following code
const {
MessageActionRow,
MessageButton
} = require('discord.js');
const row = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId("buttonsid")
.setLabel('test!')
.setStyle('PRIMARY'),
);