Discord.js Ping Latency Inside Embed from Slash Command - discord.js

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

Related

.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()

How do I make my discord bot send an attachment when certain word is sent

I'm new to working with discord bot and decided to try it out, to start I just wanted to make the bot send an attachment (image, video, etc) when for example, "sendpicture" is written in chat.
I've changed the code several times yet I get the same error everytime, "Attachment is not a constructor" or "Discord.Attachment is not a constructor".
My current code looks like this:
const client = new Discord.Client();
client.once(`ready`, () => {
console.log("online");
});
const PREFIX = "!"
//replying with a text message
client.on('message', msg => {
if (msg.content === 'test1') {
msg.channel.send('working');
}
});
//replying with attachment
client.on("message", function(message){
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]) {
case "test2":
message.channel.send(new Discord.Attachment(`.a/this/bestpic.png`, `bestpic.png`) )
.then(msg => {
//aaaaaaaa
})
.catch(console.error);
break;
}
})
tyia
Had you tried looking at the official documentation ?
I don't think you should use new Discord.Attachment(), try this instead :
switch(args[0]) {
case "test2":
message.channel.send({
files: [{
attachment: '.a/this/bestpic.png',
name: 'bestpic.png'
}]
}).then(msg => {
//aaaaaaaa
}).catch(console.error);
break;
}
Discord.Attachment() is not a thing, i believe the answer you are looking for is this :)
new Discord.MessageAttachment()
Try this code, short and simple to use.
if (message.content.toLowerCase() === 'word') { //only word, without prefix
message.channel.send({ files: ['./path_to_your_file'] })
}
You should try using MessageAttachment because Discord.Attachment is not a thing, then add the attachment into the files property
I would consider making the attachment a variable instead of putting it directly into the function, it is optional tho
const { MessageAttachment } = require("discord.js");
const attachment = new MessageAttachment("url", "fileName(optional)", data(optional));
message.channel.send({ files: [attachment] }).then(//code...)
Let me know if it works

How to send a message based on event Google PubSub?

I need some help with PubSub...
I need to send a message to a topic every time someone accept cookies in my website. This message should contain the encodedURL that contains the services accepted.
I have this script:
const topicName = "myTopic";
const data = JSON.stringify({
encodeConsentURL:""
});
// Imports the Google Cloud client library
const { PubSub } = require("#google-cloud/pubsub");
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function publishMessageWithCustomAttributes() {
// Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
const dataBuffer = Buffer.from(data);
// Add two custom attributes, origin and username, to the message
const customAttributes = {};
const messageId = await pubSubClient
.topic(topicName)
.publish(dataBuffer, customAttributes);
console.log(`Message ${messageId} published.`);
console.log(customAttributes);
}
publishMessageWithCustomAttributes().catch(console.error);
This code works, it sends the message, what I'm finding very hard to do is how to set everything right for running this code in my cookie script. In my cookie script I have a function that writes the cookie, in the same function I would like to send the message, is this possible? Thanks in advance!
It is a bit late, but I don't get it, if you already have a working cookie script and a working publish script, isn't it just about putting them together?
If you still need help I'll be happy to help you
Something like
const runEverything = async () => {
try {
await checkCookiesThing()
await publishMessage()
} catch (e) {
console.error(e)
}
}

Discord.js Sharding, How do you send an embed message with broadcastEval?

I'm trying to send an embed message to an specific channel with a sharded bot.
I've achieved sending a simple message successfully with this code:
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send("Hello")
})()
`)
The problem starts when I want to send an embed message. I've tried passing the variable like this:
//exampleEmbed is created
client.shard.broadcastEval(`
(async () => {
let channel = await this.channels.get("683353482748756047");
channel.send('${exampleEmbed}')
})()
`)
but the message is sent like "[object Object]".
I thought about returning the channel object back outside of broadcastEval and then sending my variable, but I've read this is not possible because you can't return full discord objects.
How should I send the embed message? Thank you for your time.
Okay, I solved it by creating the embed message inside the broadcastEval, and using the '${}' syntax to poblate it.
Example:
client.shard.broadcastEval(`
(async () => {
const Discord = require('discord.js');
let channel = await this.channels.get("683353482748756047");
if(channel){
//if shard has this server, then continue.
let message = new Discord.RichEmbed()
.setThumbnail(this.user.displayAvatarURL)
.setTitle('Title')
.addField("Something useful:", '${useful}')
.addField("Another useful thing:", '${useful2}')
.setTimestamp()
channel.send(message)
}
})()

SyntaxError: Unexpected Token ':'

So it's my first ever time coding and i'm creating a discord bot. It's all been going fine until I try to run the bot.js file on commmand line (using "node bot.js")
But It just comes up with a bunch of errors.
My Code:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
});
client.login(auth.token);
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
});
Question: Will you re-post you error picture? When you click on it it says the page doesn't exist.
PLEASE READ ALL BEFORE MAKING CHANGES!
First (Bad) Guess: But without the picture, I would guess (and this is not a good guess) that it's because "client.login(auth.token)" isn't at the bottom. Another guess is that ".content ===" does nothing. You should try and remove ".content" to see if it then works.
Here is your code with just that change:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong')
}
});
client.login(auth.token);
Logging bot is ready: The is also some other things I think you should change, this changing "client.user.tag" to "client.user.username" to instead show the bot's username. Another thing is "msg.content" I'm pretty sure this does nothing, and should be changed to just "===", there are some other ones, but that's my favorite one because it's the least amount of characters and easiest to type.
Here is your code with all of these changes:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg === "ping") {
msg.reply('pong')
}
});
client.login(auth.token);
Token (& patrik's answer): (No hate to patrik) What patrik says that putting your token in the actual script will help (It won't, and makes it easier to hack), now while I do this, I really don't care if my bot gets hacked, it's in one server. He/She also says that the token error means that discord.js can't get the token, this is a node.js error, not a discord.js error. You probably messed up on writing a piece of code, that is likely in "auth.json". You should probably re-run through your files before doing any of these changes.
A auth/config/token (token file) .json file should look like this:
{
"token":"TOKEN-HERE"
}
And then it should be used by doing
const auth|config|token = require(./auth|config|token.json);
client.login(auth.token);
I hope this helps with coding your bot!
It's because the node.js version is not updated to be compatible with the new discord.js version
First, install old version of discord.js in console type
npm i discord.js.old#11.6.4
In your script change
this:
const Discord = require('discord.js')
To:
const Discord = require('discord.js.old')
Glad to see you are into making bots too!
I would firstly suggest replacing all those "client" words with "bot"
The unexpected token might be because of that above mentioned thing or that your token is not just simply there.
Remove line:
client.login(auth.token);
and replace it with:
bot.login('YOUR-TOKEN-HERE');
You can check what if your token at the Discord Developer page

Resources