Unexpected token 'if' - javascript

if (interaction.commandName === 'embed') {
const embed = new EmbedBuilder()
.setTitle('Embed title')
.setDescription('This is an embed description')
.setColor('Random')
.addFields(
{
name: 'Field title',
value: 'Some random value',
inline: true,
},
{
name: '2nd Field title',
value: 'Some random value',
inline: true,
}
);
interaction.reply({ embeds: [embed] });
}
That is my new Discord bot, with slash commands. That's the only issue for now. Anyone know why it says "SyntaxError: unexpected token 'if'"?
I wanted it to send an embed based on a slash command.

Related

Discord.js sending embed in dm using a / command

My code is simple, it should send a dm embed at the person choose by the user using the command (it is a test for a ban command but it is easier to no ban my alt to after dean him and rejoin with him).
There is my code :
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('test')
.setDescription('Send a private message to a selected user')
.addUserOption(option =>
option
.setName('target')
.setDescription('The member to send the message to')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for sending the message'))
.setDMPermission(false),
async execute(interaction) {
const target = interaction.options.getUser('target');
if (!target) return interaction.reply({ content: "You must provide a target user with the 'target' option.", ephemeral: true });
const reason = interaction.options.getString('reason') || 'No reason provided';
const owner = await interaction.guild.fetchOwner();
if (!owner) return interaction.reply({ content: "I couldn't fetch the guild owner.", ephemeral: true });
if (target.user === interaction.client.user) return interaction.reply({ content: "I can't send a message to myself.", ephemeral: true });
const banEmbed = new EmbedBuilder()
.setColor(0x0099FF)
.setTitle('Hello! 😃')
.setAuthor({ name: `request by ${interaction.user.username}`, iconURL: interaction.guild.iconURL({ format: 'png', dynamic: true }) })
.setDescription(`You have been banned from ${interaction.guild}.`)
.addFields(
{ name: '\u200B', value: `If you think there's an error, please contact ${owner.user.username}#${owner.user.discriminator}.` },
{ name: '\u200B', value: `Reason: ${reason}` },
)
.setTimestamp()
.setFooter({ text: 'Have a good day !' });
try {
await target.send({ content: "hello", embed: banEmbed });
interaction.reply({ content: "The message has been sent successfully.", ephemeral: true });
} catch (error) {
console.error(error);
interaction.reply({ content: "I couldn't send the message to the target user.", ephemeral: true });
}
},
};
The code is working only if I add content not embedded, in that case it won't send the embed and if I don't put the content, it will just send the error :
DiscordAPIError[50006]: Cannot send an empty message
at SequentialHandler.runRequest (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:667:15)
at processTicksAndRejections (/Users/theophile/Desktop/test bot copie/lib/internal/process/task_queues.js:96:5)
at async SequentialHandler.queueRequest (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:464:14)
at async REST.request (/Users/theophile/Desktop/test bot copie/node_modules/#discordjs/rest/dist/index.js:910:22)
at async DMChannel.send (/Users/theophile/Desktop/test bot copie/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:176:15)
at async Object.execute (/Users/theophile/Desktop/test bot copie/commands/test.js:41:7)
at async Client.<anonymous> (/Users/theophile/Desktop/test bot copie/index.js:71:3) {requestBody: {…}, rawError: {…}, code: 50006, status: 400, method: 'POST', …}

UNHANDLED_REJECTION: DiscordAPIError: Unknown interaction

My code :
module.exports = {
name: "plusbg",
description: "Qui est le plus beau de ce serveur ?",
run: (client, message, args) => {
const embed = new MessageEmbed()
.setTitle('Le plus beau est Ratile')
.setThumbnail(client.user.displayAvatarURL())
.addField (
{ name: 'Latence', value: `\`${client.ws.ping}ms\``, inline: true },
{ name: 'Uptime', value: `<t:${parseInt(client.readyTimestamp / 1000)}:R>`, inline: true},
)
.setTimestamp()
.setFooter({ text: message.author.username, iconURL: message.author.displayAvatarURL() });
message.channel.send({ embeds: [embed]});
},
runSlash: (client, interaction) => {
const embed = new MessageEmbed()
.setColor('DARK_VIVID_PINK')
.setTitle('Le plus beau est Ratile')
.setThumbnail(client.user.displayAvatarURL())
.addFields(
{ name: 'Latence', value: `\`${client.ws.ping}ms\``, inline: true },
{ name: 'Uptime', value: `<t:${parseInt(client.readyTimestamp / 1000)}:R>`, inline: true},
)
.setTimestamp()
.setFooter({ text: interaction.user.username, iconURL: interaction.user.displayAvatarURL() });
interaction.reply({ embeds: [embed]})
},
};
(the message is in french)
I can use the commands on discord, it's working, but in the terminal there is an error called
Unknown interaction on the discord api.
-----
Promise {
<rejected> DiscordAPIError: Unknown interaction
at RequestHandler.execute (C:\Users\ratil\Desktop\Bot - Skypiea\node_modules\discord.js\src\rest\RequestHandler.js:350:13) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (C:\Users\ratil\Desktop\Bot - Skypiea\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async CommandInteraction.reply (C:\Users\ratil\Desktop\Bot - Skypiea\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:99:5) {
method: 'post',
path: '/interactions/992792318635683912/aW50ZXJhY3Rpb246OTkyNzkyMzE4NjM1NjgzOTEyOkhUUnI5ZXF1bUw3WmxuR1RoN3gyU2N4eGFNYjYxWGgzb2JhWjhyOXVNTnlHSnQ4azhqRkxQaUF4QTVwZTFUZkxZNjVHdEhEOXh4WklTV2g0Yk9xM28yQURPUFBlS2Qwd050R3BSbHVGcFVFdDNXWWlHUW5xUXZZbFdpTzAyc3Ry/callback',
code: 10062,
httpStatus: 404,
requestData: { json: [Object], files: [] }
}
}
Can you help me please
The interactionCreate file (that's french too) :
module.exports = {
name: "interactionCreate",
once: false,
async execute(client, interaction) {
if (interaction.isCommand()) {
const cmd = client.commands.get(interaction.commandName);
if (!cmd) return interaction.reply(`Cette commande n\'existe pas`);
cmd.runSlash(client, interaction);
}
}
};

Discord.js v13 ReferenceError: member is not defined | in a kick command

So basically I was updating this bot to Discord.js v13 a few months ago and now that I got back to this (I got busy with other things), I can't seem to figure out what went wrong with this Kick command.
The Error
ReferenceError: member is not defined
at Object.run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Commands\Moderation\Kick.js:49:30)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async run (C:\Users\Admin\OneDrive\Desktop\mybots\testbot\src\Events\InteractionCreate.js:32:11)
kick.js | The kick command src
const { confirm } = require('../../Structures/Utils');
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'kick',
description: 'Kick a member.',
category: 'Moderation',
options: [
{
name: 'user',
description: 'Mention a user',
required: true,
type: 'USER'
},
{
name: 'reason',
description: 'Specify reason for kick',
required: true,
type: 'STRING'
}
],
permissions: 'KICK_MEMBERS',
async run({ interaction, bot }) {
const user = interaction.options.getMember('user');
const reason = interaction.options.getString('reason');
if (!user.kickable)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`I don't have permissions to kick ${user}.`)]
});
if (user.id === interaction.user.id)
return interaction.reply({
embeds: [new MessageEmbed().setColor('RED').setDescription(`You cannot kick yourself.`)]
});
const confirmation = await confirm(
interaction,
new MessageEmbed()
.setTitle('Pending Conformation')
.setColor('ORANGE')
.setDescription(`Are you sure you want to kick ${user} for reason: \`${reason}\`?`)
.setFooter({ text: 'You have 60 seconds.' })
);
if (confirmation.proceed) {
const embed = new MessageEmbed()
.setColor('ORANGE')
.setDescription(`**${member.user.tag}** was kicked for \`${reason}\`.`);
try {
await user.send({
embeds: [
new MessageEmbed()
.setTitle('You were kicked')
.setColor('ORANGE')
.addField('Reason', reason, false)
.addField('Guild', interaction.guild.name, false)
.addField('Date', time(new Date(), 'F'), false)
]
});
} catch (err) {
embed.setFooter({
text: `I was not able to DM inform them`
});
}
await confirmation.i.update({
embeds: [embed],
components: []
});
await user.kick({ reason });
}
const embed = new MessageEmbed()
.setTitle('Process Cancelled')
.setColor('ORANGE')
.setDescription(`${user} was not kicked.`);
if (confirmation.reason) embed.setFooter({ text: confirmation.reason });
await confirmation.i.update({
embeds: [embed],
components: []
});
}
};
InteractionCreate.js | Another file that showed up in the error
const { MessageEmbed } = require('discord.js');
module.exports = {
event: 'interactionCreate',
async run(bot, interaction) {
if (!interaction.isCommand()) return;
const command = bot.commands.get(interaction.commandName);
if (!command) return;
if (command.permission && !interaction.member.permissions.has(command.permission)) {
return await interaction.reply({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription(`You require the \`${command.permission}\` to run this command.`)
]
});
} else {
// If command's category is `NSFW` and if interaction.channel.nsfw is false, inform them to use the command in nsfw enabled channel.
if (command.category === 'NSFW' && !interaction.channel.nsfw) {
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [
new MessageEmbed()
.setColor('RED')
.setDescription('You can use this command in Age-Restricted/NSFW enabled channels only.')
.setImage('https://i.imgur.com/oe4iK5i.gif')
],
ephemeral: true
});
} else {
try {
await command.run({ interaction, bot, options: interaction.options, guild: interaction.guild });
} catch (err) {
console.log(err);
await interaction[interaction.deferred ? 'editReply' : interaction.replied ? 'followUp' : 'reply']({
embeds: [new MessageEmbed().setColor('RED').setDescription(err.message || 'Unexpected error')]
});
}
}
}
}
};
Thanks a lot in advance!
In line 49 of your Kick.js file you're using member.user.tag but you did not define member. Add this:
const user = interaction.options.getMember('user');
const member = interaction.guild.members.cache.get(user.id);
And in line 72, you're trying to ban the user instead of the guild member.
Change this:
await user.kick({ reason });
To this:
await member.kick({ reason });

Discord JS - DiscordAPIError: Missing Access

So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
method: 'post',
path: '/applications/901999677011005472/guilds/905266476573950023/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: {
name: 'ping',
description: 'Bot uptime/latency checker.',
type: undefined,
options: undefined,
default_permission: undefined
},
files: []
}
}
I also try looking at my code but I didn't see something wrong.
This is my code, I really think something is wrong in the code.
const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
client.on('ready', () => {
console.log("The bot is online")
// Carlos: 883425101389914152
const guildId = '905266476573950023'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Bot uptime/latency checker.',
})
commands.create({
name: 'add',
description: 'Adds two numbers given by user.',
options: [
{
name: 'number1',
description: 'The first number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
{
name: 'number2',
description: 'The second number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
]
})
})
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, Options } = interaction
if (commandName === 'ping') {
interaction.reply({
content: 'Pong! **60ms**',
// If anyone can see = True, Only command user can see = False
ephemeral: true,
})
} else if (commandName === 'add') {
interaction.reply({
content: 'The sum is ${number1 + number2}'
})
}
})
client.login(process.env.KEY)
For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.
You did not select the right permissions when creating bot login link for your discord server.
Goto developers / oauth again, click bot and select all the required permissions that you're using in this bot.
Then copy the link generated and use it to login with your bot into your server.
don't forget to change this:
content: 'The sum is ${number1 + number2}'
to this:
content: `The sum is ${number1 + number2}`

Making an embed on Discord.js

so im making a discord bot and i want it to send an embed when i type hy!help
so i used the format on discord.js documantion and so far my code looks like this
const client = new Discord.Client({
token: "pls-no-hack-ty"
});
client.on("ready", () => {
//do stuff lol
});
client.on("message", message => {
if(message.content === "hy!help") {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org')
.setDescription('Some description here')
.setThumbnail('https://i.imgur.com/wSTFkRM.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/wSTFkRM.png')
.setTimestamp()
.setFooter('Some footer text here', 'https://i.imgur.com/wSTFkRM.png');
channel.send(exampleEmbed);
} } )
But i get an channel dot defined error.
What am i doing wrong?
Thanks -rly907
In your last line instead of channel.send(exampleEmbed); do
message.channel.send(exampleEmbed);
You should to user message.channel.send it can't use channel.send
message.channel.send(Embed);

Categories

Resources