I want to get message id from interaction message, but i can't get it :|
discord.js verson : ^13.1.0
client.on('interactionCreate',async interaction => {
if(interaction.commandName==='test') {
let message = await interaction.reply({content:'testing...',ephemeral:true});
console.log(message); //undefined
}
});
You can use the CommandInteraction#fetchReply() method to fetch the Message instance of an initial response.
Example:
client.on('interactionCreate', async (interaction) => {
if (interaction.commandName === 'test') {
interaction.reply({
content: 'testing...',
ephemeral: true,
})
const message = await interaction.fetchReply()
console.log(message)
}
})
For latest version of Discord.js:
You can use the fetchReply property of InteractionReplyOptions to fetch the Message object after send it.
let message = await interaction.reply({content:'testing...',ephemeral:true, fetchReply: true});
console.log(message); //Message Object
Related
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'denick') {
await interaction.deferReply();
const data = fetch('http://api.antisniper.net/account/api_disabled/counts')
.then(response => response.json());
interaction.editReply({ content: data });
}
});
ERROR:
if (typeof data !== 'string') throw new error(errorMessage);
RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string.
Great question, this is less of a discord.js question, rather a how to format a .then.
You can either carry on in the function after .then or use an async/await.
First method:
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'denick') {
await interaction.deferReply();
const data = fetch('http://api.antisniper.net/account/api_disabled/counts')
.then(async response => {
var jsonResponse = await response.json();
var jsonToString = JSON.stringify(jsonResponse)
interaction.editReply({ content: data });
});
}
});
As you can see above, I've shifted everything after the .then function. I've also done an await response.json() and a stringify. Missing either of those will send an error(either the error you got or [Object object]).
The second method:
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'denick') {
await interaction.deferReply();
const data = await fetch('http://api.antisniper.net/account/api_disabled/counts');
var jsonResponse = await data.json();
var jsonToString = JSON.stringify(jsonResponse)
interaction.editReply({ content: data });
}
});
I've removed the .then function and replaced it with an await. The rest is the same.
Either methods should be able to work, if it helped, please remember to mark the question as correct, if there's any problems, please comment!
Edit:
To only show the winstreak_data_hidden data, simply use the returned jsonResponse as a object.
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'denick') {
await interaction.deferReply();
const data = await fetch('http://api.antisniper.net/account/api_disabled/counts');
var jsonResponse = await data.json();
var hiddenWinStreakData = jsonResponse.winstreak_data_hidden;
if(hiddenWinStreakData){
interaction.editReply({ content: hiddenWinStreakData });
}
}
});
I've done a simple if statement to avoid discord throwing errors, you can also do an else statement after to say that the user doesn't have hidden win streak data. Hope this helped!
const { SlashCommandBuilder } = require("#discordjs/builders");
const {
MessageEmbed,
MessageActionRow,
MessageSelectMenu,
} = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup")
.setDescription("Setup the bot to your server!"),
async execute(interaction) {
let array = [];
await interaction.guild.members.cache.forEach(async (user) => {
if (user.user.bot === false || user.user.id === "925077132865052702")
return;
array.push({
label: user.user.username,
description: user.id,
value: user.id,
emoji: "<a:right:926857658500251668>",
});
});
let row;
if (array < 5) {
row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId("select")
.setMinValues(1)
.setMaxValues(parseInt(array.length))
.setPlaceholder("Nothing selected.")
.addOptions(array)
);
} else {
row = new MessageActionRow().addComponents(
new MessageSelectMenu()
.setCustomId("select")
.setMinValues(1)
.setMaxValues(5)
.setPlaceholder("Nothing selected.")
.addOptions(array)
);
}
let welcome = new MessageEmbed()
.setTitle("UChecker | Setup")
.setDescription(
"Please select from the dropdown below all the bots you would like to be notified for."
)
.setColor("FUCHSIA");
let message = await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
});
const filter = i => {
return i.user.id === interaction.user.id;
};
await message.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 })
.then(async interaction => await interaction.editReply(`You selected ${interaction.values.join(', ')}!`))
.catch(err => console.log(`No interactions were collected.`));
},
};
Here is my code. As you can see at the bottom I am using awaitMessageComponent and it says an error:
TypeError: Cannot read properties of undefined (reading 'createMessageComponentCollector')
at Object.execute (C:\Users\Owner\Desktop\UChecker\src\setup.js:55:31)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (C:\Users\Owner\Desktop\UChecker\index.js:38:3)
C:\Users\Owner\Desktop\UChecker\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90
if (this.deferred || this.replied) throw new Error('INTERACTION_ALREADY_REPLIED');
^
Error [INTERACTION_ALREADY_REPLIED]: The reply to this interaction has already been sent or deferred.
at CommandInteraction.reply (C:\Users\Owner\Desktop\UChecker\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:90:46)
at Client.<anonymous> (C:\Users\Owner\Desktop\UChecker\index.js:41:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'INTERACTION_ALREADY_REPLIED'
}
I am confused as I thought you could edit a reply? Could someone please help me out because I am really confused. I have created a reply so then it can be edited by the interaction collector and it says it has already replied.
You have to use CommandInteraction#fetchReply() to retrieve the reply message.
await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
});
const message = await interaction.fetchReply();
Interaction replies are not returned unless you specify fetchReply: true in the options
let message = await interaction.reply({
embeds: [welcome],
components: [row],
ephemeral: true,
fetchReply: true
})
So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs
So how do we detect the userID with the kick command below?
So below is my kick command and whenever I kick a person I need to mention them (?kick #test) I want to kick a user by their user id (?kick 354353) and their mentions.
const client = new Discord.Client();
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// Ignore messages that aren't from a guild
if (!message.guild) return;
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
});
client.login('TOKEN');
I recommend setting up Arguments if you plan to make more commands that take user input.
However if you're not interested in fully setting up arguments, you can just slice the message and grab the id. You will then need to fetch the member object, make sure to make your function is async for this, or use Promise#then if you prefer.
if (message.content.startsWith('?kick')) {
if (member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS']))
return;
const memberId = message.content.slice(' ')[1];
if (memberId) {
const memberToKick = await message.guild.members.cache.fetch(userId);
memberToKick.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member');
// Log the error
console.error(err);
});
}
}
I'm trying to get my bot join a vc that a user is in, when saying "+sing". After the audio is finished the bot should disconnect from the vc. This is as far as i've gotten, I don't know what I have done wrong.
client.on("message", msg => {
if (message.content === '+sing') {
const connection = msg.member.voice.channel.join()
channel.join().then(connection => {
console.log("Successfully connected.");
connection.play(ytdl('https://www.youtube.com/watch?v=jRxSRyrTANY', { quality: 'highestaudio' }));
}).catch(e => {
console.error(e);
connection.disconnect();
})
});
Btw I'm using discord.js.
You can get their GuildMember#VoiceState#channel and use that as the channel object to join
client.on("message", msg => {
if (message.content === '+sing') {
// you should add a check to make sure they are in a voice channel
// join their channel
const connection = msg.member.voice.channel.join()
}
})