Discord.JS getting "Expected a string primitive Received: | undefined" when registering command - discord

i was trying to create a new slash command, i use a folder called commands and i require every file in that folder to register it
this is the command file:
const { SlashCommandBuilder, EmbedBuilder, Client, CommandInteraction, CommandInteractionOptionResolver } = require("discord.js");
module.exports = {
name: "ping",
data: new SlashCommandBuilder()
.setName("ping")
async do(client, interaction, options) {
const check = await interaction.reply({content: "Pinging...", fetchReply: true});
const latency = check.createdTimestamp - interaction.createdTimestamp;
const pingEmbed = new EmbedBuilder()
.setTitle(":ping_pong: Pong!")
.setColor([40,40,38,255])
.setTimestamp()
.addFields(
{name: "Bot Latency", value: `${latency}ms`, inline: true},
{name: "API Latency", value: `${client.ws.ping}ms`, inline: true});
await interaction.editReply({content: "", embeds: [pingEmbed]});
}
};
when i try to load it i keep getting an Expected a string primitive error
i was expecting it to register the command successfully, but instead it keeps giving me an error, i tried everything on the guide what it said

The issue is very simple and straightforward and if you would have reviewed the discord.js documentation, you would have known that slash commands need to have a description to register.
Therefore, add a .setDescription() below your .setName method and give it a description before trying again.

Related

Discord.js Ping Latency Inside Embed from Slash Command

Newbie here. I am trying to get a slash command to send an embed with the amount of time it took between the initial message and the message response time. I am getting TypeError: Cannot read properties of undefined (reading 'createdTimestamp') and Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred. I've jumped around looking at others code trying to find a way to make this work but slash command handling still doesn't make a lot of sense to me. My code block is below. I followed along with https://discordjs.guide so if you have any other suggestions with structure feel free to comment them below. Thank you!
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
await interaction.reply("Pinging bot...").then (async (msg) =>{
const exampleEmbed = new MessageEmbed()
.setColor('0x0000ff')
.setTitle('Pong! :ping_pong:')
.addField("Time taken: ", `${msg.createdTimestamp - message.createdTimestamp}`)
.setThumbnail("https://78.media.tumblr.com/be43242341a7be9d50bb2ff8965abf61/tumblr_o1ximcnp1I1qf84u9o1_500.gif")
interaction.editReply({ embeds: [exampleEmbed] });
})
},
};
first you need to fetch the reply you send, u can use fetchReply to get the interaction reply. instead of replying with "Pinging bot..." you can defer the reply and then use the createdTimestamp. A basic example of a ping command would be
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction) {
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true });
await interaction.editReply(`:ping_pong: Pong!\n:stopwatch: Uptime: ${Math.round(interaction.client.uptime / 60000)} minutes\n:sparkling_heart: Websocket heartbeat: ${interaction.client.ws.ping}ms.\n:round_pushpin: Rountrip Latency: ${sent.createdTimestamp - interaction.createdTimestamp}ms`);
},
};
You can customize the response into an embed or however you like. The djs guide has a section on ping command here

.setname is not a function in discord.js

I have finished completing the code for my bot from a tutorial on YouTube: https://www.youtube.com/watch?v=fN29HIaoHLU
Here is the entire code on replt.it: https://replit.com/#TylerLanier/Comusity-Bot#slash/info.js:6:4
And I am getting this error: TypeError: (intermediate value).setname is not a function at "..."
Here is the code at slash/info.js:
module.exports = {
data: new SlashCommandBuilder()
.setname("info")
.setDescription("Displays info about the currently playing song"),
run: async ({client, interaction}) => {
const queue = client.player.getQueue(interaction.guildId)
if(!queue)
return await interaction.editReply("There are no songs in the queue")
let bar = queue.createProgressBar({
queue: false,
length: 19
})
const song = queue.current
await interaction.editReply({
embeds: [
new MessageEmbed()
.setThumbnail(song.thumbnail)
.setDescription(`Currently Playing [${song.title}](${song.url})\n\n` + bar)
],
})
},
}
The reason behind the error is a capitalisation mistake when you use .setname(). It needs to be .setName() with a capital N. This is why you need to go through your code just to check the spelling of each function and variable you call. You will also have to change this incorrect spelling in every command except the play command as in each file, you are using .setname()

My bot sends an embed that is invisible to all users and shows no message sent

I've been working on using JS to create a simple Discord Bot for my server. I have been trying to have it send a message with the rules of the server embedded into it. When the /rules command is run, I receive a notification to state a message was sent, but there is no message to be seen on any device. I am able to view message history so I do not understand why there is no visible embed or message.
My code was made using Autocode's Discord Embed Builder, and has worked for other embeds within the same Bot. A link to view the full embed code in the Builder and see how it is supposed to look is here.
It would be much easier to learn to make these yourself than using a generator and trying to reverse engineer how their coding works:
a simple example would be this:
const {
MessageEmbed
} = require('discord.js')
module.exports = {
name: "rules",
description: "Post rules",
run: async (client, interaction) => {
// build the message
const embed = new MessageEmbed()
.setColor('#00ff00') //change the color if you want
.setTitle('Some Title')
.setDescription(`Some description`)
.addFields({
name: 'Rule Name/Number',
value: 'Rule text',
inline: true
}, {
name: 'Rule Name/Number',
value: `Rule text`,
inline: true
}, {
name: 'Rule Name/Number',
value: 'Rule text',
inline: true
})
// add more if needed
// send the message
interaction.channel.send({
embeds: [embed]
})
// confirm they are sent and complete the interaction only visible to you
return interaction.reply({
content: 'Done',
ephemeral: true
})
}
}

Copying and moving message in another channel

My suggestion Script worked totally fine for the last couple of months, but it stopped working a few days ago. I noticed that my .send function was underlined, and it said this:
Property 'send' does not exist on type 'GuildChannel | ThreadChannel'.
Property 'send' does not exist on type 'GuildChannel'
I'm btw. not sure if that's the problem with the script or if they changed anything I didn't notice, and I'm getting no errors. The Script basically just don't work.
My suggestion script:
case "suggestion":
var str = message.content.slice(" .suggestion".length);
const suggestionembed = new Discord.MessageEmbed()
.setThumbnail('png')
.setTitle("Suggestion")
.setColor('#151515')
.addFields(
{ name: "Person, that suggested somenthing:", value: `<#!${message.author.id}>` },
{ name: 'Suggestion:', value: `${str}` },
{ name: 'Channel:', value: `${message.channel}` },
)
.setTimestamp()
await message.guild.channels.cache.find(c => c.name === 'suggestion')
.send({ embeds: [suggestionembed] })
.then(embedMessage => {
embedMessage.react("✅")
embedMessage.react("❌")
});
message.delete();
break;
Just ignore that if you are sure that it's a text channel. That is only there because it can be a VoiceChannel. You won't have autocomplete in Visual Studio Code but it will still work as intended. If you are using TypeScript, you could use as to tell TypeScript it's a TextChannel

Embed message discord.js

Ive seen many discord embed codes like this:
(This is an old question and im new to coding so...)
const { MessageEmbed } = require('discord.js');
const exampleEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Some title')
.setURL('https://discord.js.org/')
.setAuthor('Some name', 'https://i.imgur.com/AfFp7pu.png', '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('Some footer text here', 'https://i.imgur.com/AfFp7pu.png');
channel.send({ embeds: [exampleEmbed] });
So, what i dont understand is what is the trigger? Like you're supposed to type .ping for pong right? so what do i type to get my bot type this embed?
The way you're sending your embed is(afaik) specific to version 13 of discord.js and you most likely haven't updated discord.js yet:
channel.send({ embeds: [exampleEmbed] });
the version I am currently using is 12.5.3 .
Check your version of discord.js in package.json and if the version is not 13 or above, update or if you want to stick with version 12.5.3 try some of the methods below:
channel.send( exampleEmbed );
Or like this:
channel.send({ embed: exampleEmbed });
Sending the embed like this: "{ embeds: [exampleEmbed] }" makes discord think you are sending an empty message and therefore it doesn't send anything.
This code is meant to be inside an event handler (such as on.message). If that code is already inside an event handler (except for this const { MessageEmbed } = require('discord.js');, it should go at the top), and if it is still not sending, then you should change this line:
channel.send({ embeds: [exampleEmbed] });
to
message.channel.send(exampleEmbed)
There is no trigger in the code sample you provided. You need to have a listener for the message event or interactionCreate event to listen to traditional message-based commands and slash commands. You can pass in handlers into these listeners and respond to command usages.
Since it looks like you're reading the discord.js guide, I would suggest reading from the start, where you would be introduced to how to handle messages first.
To send it, just use a message event. Like this:
const { MessageEmbed, Client } = require('discord.js');
const client = new Client();
client.on('message', msg => {
const { channel, content } = msg;
if(msg.content === 'someCommand') {
const exampleEmbed = new MessageEmbed()
//setProperties...
channel.send({ embeds: [exampleEmbed] });
}
})
client.login('[TOKEN_HERE'])
What's happening here is that the client is receiving a Message object when someone messages (msg). We then use the channel and content properties to evaluate the command, and send the embed if the command is correct. I took out the property settings to save space. You can add them back.

Resources