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")
Related
I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})
I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
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 have this code:
msg.author.send(Finished);
And it isn't working. Finished is a const variable which is a Discord.MessageEmbed. This issue is very annoying and I can't figure out how to fix it. Any help is appreciated.
If you want to see most of the code here it is:
client.on('message', msg => {
if (msg.content === '-na') {
if (msg.channel === Discord.DMChannel) {
return
} else
if (msg.member.roles.cache.has('756713479003701338')) {
msg.author.send(Ping);
msg.author.dmChannel.awaitMessages(m => m.author.id === msg.author.id,
{max: 1, time: 300000}).then(collected => {
msg.author.send(Title);
EmbedPing = collected.first().content;
msg.author.dmChannel.awaitMessages(m => m.author.id === msg.author.id,
{max: 1, time: 300000}).then(collected => {
msg.author.send(Message);
EmbedTitle = collected.first().content;
msg.author.dmChannel.awaitMessages(m => m.author.id === msg.author.id,
{max: 1, time: 300000}).then(collected => {
msg.author.send(Image);
EmbedMessage = collected.first().content;
msg.author.dmChannel.awaitMessages(m => m.author.id === msg.author.id,
{max: 1, time: 300000}).then(collected => {
if (collected.first().content.toLowerCase() === 'yes') {
msg.author.send(ImageURL);
EmbedImage = collected.first().content;
var FinishedEmbedImage = new Discord.MessageEmbed()
.setColor('#FFD700')
.setTitle(EmbedTitle)
.setDescription(EmbedMessage)
.setImage(EmbedImage)
.setTimestamp()
.setFooter('Sent By: ' + msg.author)
allyAnnouncementChannel.send(EmbedPing, FinishedEmbed);
} else
msg.author.send(Finished);
var FinishedEmbed = new Discord.MessageEmbed()
.setColor('#FFD700')
.setTitle(EmbedTitle)
.setDescription(EmbedMessage)
.setTimestamp()
.setFooter('Sent By: ' + msg.author)
allyAnnouncementChannel.send(EmbedPing, FinishedEmbed);
}).catch(Cancelled)
}).catch(Cancelled)
}).catch(Cancelled)
}).catch(Cancelled)
};
};
});
Ping, Title, Message, Image, ImageURL and Finished are all embed variables.
EmbedPing, EmbedTitle, EmbedMessage, and EmbedImage are all empty string variables.
const allyAnnouncementChannel = client.channels.cache.get('756701256122236941')
Discord is obviously the require function.
client is Discord.Client();.
I made a userinfo command which works fine but the only problem is that it doesn't display the game of the user if they are playing a game. I don't have any error when I use the command. I'm using version 12.1.1 of discord.js
const {
MessageEmbed
} = require("discord.js");
const moment = require("moment");
module.exports.run = async(bot, message, args) => {
message.delete()
const user = message.mentions.users.first() || bot.users.cache.get(args[0]) || message.author;
if (!user) return;
const userStatus = {
online: "En ligne",
idle: "Inactif",
dnd: "Ne pas déranger",
offline: "Hors ligne"
}
const emojiStatus = {
online: "<:Online:697378421319270401>",
idle: "<:Idle:697378421130395749>",
dnd: "<:DND:697378421386248282>",
offline: "<:Off:697378421264875594>"
}
if (user.bot) {
isBot = "Yes";
} else {
isBot = "No";
}
const uiEmbed = new MessageEmbed()
.setAuthor(user.username)
.setColor(message.member.displayHexColor)
.setThumbnail(user.displayAvatarURL({
dynamic: true
}))
.addField("<:Discord:697378425178030171> Username and Tag", user.tag, true)
.addField("<:ID:697380447876808716> ID", user.id, true)
.addField(`${emojiStatus[user.presence.status]} Status`, userStatus[user.presence.status], true)
.addField("<:Game:697380448447234148> Game", `${user.presence.activity ? user.presence.activity.name : "User isn't playing"}`, true)
.addField("<:Bot:697378421163950152> Bot ?", isBot, true)
.addField("<:Dis:697380487785873499> Account created at :", moment(user.createdAt).format("LL"), true)
message.channel.send(uiEmbed);
}
module.exports.help = {
name: "ui"
}
presence.activity is not a thing. You need to use presence.activities which returns an array of Activity.
You could either just get the first Activity:
.addField("<:Game:697380448447234148> Game", `${user.presence.activities[0] ? user.presence.activities[0].name : "User isn't playing"}`, true)
Or you could find the activity that has the type PLAYING inside the activities array:
const activity = user.presence.activities.find(activity => activity.type === 'PLAYING') || null
.addField("<:Game:697380448447234148> Game", `${activity !== null ? activity : "User isn't playing"}`, true)