first time posting here. I hope I've posted this correctly, but basically getting the error message "interaction.options.getMember is not a function" I've tried using getUser as well (someone suggested this) and it doesnt seem to fix the problem. I'm pretty new to all this so please go easy on me. as far as I can see everything has been defined correctly and I'm pretty sure the issue is from here somewhere as the rest of the commands work absolutely fine. Any help greatly appreciated!!
const { Client, CommandInteraction, MessageEmbed } = require("discord.js");
module.exports = {
name: "ban",
description: "Bans the target member",
permission: "ADMINISTRATOR",
options: [
{
name: 'target',
description: "Select a target to ban",
type: "USER",
required: true,
},
{
name: 'reason',
description: "Provide a reason for the ban",
type: "STRING",
required: true,
},
{
name: 'messages',
description: "Choose one of the choices",
type: "STRING",
required: true,
choices: [
{
name: "Don't delete any",
value: "0"
},
{
name: "Previous 7 days",
value: "7"
}
]
},
],
/**
*
* #param {Client} client
* #param {CommandInteraction} interaction
*/
execute(client, interaction) {
//ERROR IS LINE BELOW//
const Target = interaction.options.getMember('target');
if (Target.id === interaction.member.id)
return interaction.followUp({embeds: [new MessageEmbed().setColor("RED").setDescription(`⛔ You can't ban yourself.`)]})
if (Target.permissions.has("ADMINISTRATOR"))
return interaction.followUp({embeds: [new MessageEmbed().setColor("RED").setDescription(`⛔ You can't ban an administrator.`)]})
const Reason = interaction.options.getString('reason');
if (Reason.length > 512)
return interaction.followUp({embeds: [new MessageEmbed().setColor("RED").setDescription(`⛔ The reason cannot exceed 512 characters`)]})
const Amount = interaction.options.getString('messages')
Target.ban({days: Amount, reason: Reason})
interaction.followUp({embeds: [new MessageEmbed().setColor("GREEN").setDescription(`✅ **${Target.user.username}** has been banned!`)]})
}
}
According to your code, and per Discord API, you have your member (actually user) here:
name: 'target',
description: "Select a target to ban",
type: "USER",
required: true,
so that line should read
const Target = interaction.options.getUser('target');
You need to get the member by using the below code
const targetMember = interaction.guild.members.cache.find(member => member.id === Target)
The rest needs to change Target to targetMember or simplify with example below:
if (targetMember.permissions.has(Permissions.FLAGS.BAN_MEMBERS) || targetMember.user.bot || targetMember.user.id === interaction.user.id) {
return interaction.reply({
content: 'You are not authorized to ban this member or yourself.',
ephemeral: true
})
I actually managed to fix the issue before I went sleep at 4am. Essentially the problem was actually caused by the execute (client, interaction). In my other file, these parameters are (interaction, client). I also changed all instances of "followUp" with "reply" and it started working as intended.
Thanks for helping out though!
Related
const {Client, CommandInteraction, MessageEmbed} = require("discord.js");
const db = require("../../Structures/Schemas/InfractionDB");
module.exports = {
name: "warnings",
description: "Give a warning",
permission: "ADMINISTRATOR",
options: [
{
name: "target",
description: "Select a target.",
type: "USER",
required: true
},
{
name: "reason",
description: "Provide a reason.",
type: "STRING",
required: true
},
{
name: "evidence",
description: "Provide evidence.",
type: "STRING",
required: false
},
],
/**
*
* #param {CommandInteraction} interaction
* #param {Client} client
*/
execute(interaction, client) {
const{guild, member, options} = interaction
const Target = options.getMember("target");
const Reason = options.getString("reason");
const Evidence = options.getString("evidence") || "None provided";
const Response = new MessageEmbed()
.setColor("RED")
.setAuthor({name: "MOD BOT", iconURL: guild.iconURL()});
db.findOne({GuildID: guild.id, UserID: Target.id}, async (err,data)=> {
if(err) throw err;
if(!data || !data.WarnData) {
data = new db({
GuildID: guild.id,
UserID: Target.id,
WarnData: [
{
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
],
})
} else {
const WarnDataObject ={
ExecuterID: member.id,
ExecuterTag: member.user.tag,
TargetID: Target.id,
TargetTag: Target.user.tag,
Reason: Reason,
Evidence: Evidence,
Date: parseInt(interaction.createdTimestamp / 1000)
}
data.WarnData.push(WarnDataObject)
}
data.save()
});
Response.setDescription(`Warning Added: ${Target.user.tag} | ||${Target.id}||\n**Reason**: ${Reason}\n**Evidence**:${Evidence}`);
guild.channels.cache.get("946217387336818699").send({embeds:[Response]});
}}
originally this was routed to a different collection in my db. I've tried to convert it so I can see everything in one place. but it's taken me hours and don't seem to be getting anywhere. Like I said, the data is being stored on the db, but the Response is failing. Any ideas how to fix this? There are no errors in terminal
The error i think is that your application is taking too long to respond.
you have only 3 seconds to respose.
for this i would suggest that you execute you interaction as a async function
and you should use await before trying to find it in the database. because it can take some time to find the data in the database.
The data is store in database because it has no concern with the response time but the discord api wants a reply in 3 seconds or it will fail.
I have read your code. it seems okay.
i would suggest you to use the easier way instead of using the object or json form to create the commands.
SlashCommandBuilder from #discordjs/builders
its easy to use and simple.
here is an example of how easy it is if you use SlashCommandBuilder
const { SlashCommandBuilder } = require('#discordjs/builders');
const data = new SlashCommandBuilder()
.setName('gif')
.setDescription('Sends a random gif!')
.addStringOption(option =>
option.setName('category')
.setDescription('The gif category')
.setRequired(true)
.addChoice('Funny', 'gif_funny')
.addChoice('Meme', 'gif_meme')
.addChoice('Movie', 'gif_movie'));
you can install all the dependencies using
npm install discord.js #discordjs/rest discord-api-types
When someone adds an emoji to the server, the bot will log it. I'm trying to make it where it will but the emoji in the thumbnail of the log embed. Whenever it trys to log, I get the error..
[15:55:28] [UTC June:10:2021] [ERROR] (node:11176) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.thumbnail.url: Scheme "undefined" is not supported. Scheme must be one of ('http', 'https'). embeds[0].thumbnail.url: Scheme "undefined" is not supported. Scheme must be one of ('http', 'https').
I'm guessing that the code for the thumbnail is returned undefined and you can't put that into a thumbnail. My code is
const Discord = require("discord.js")
exports.run = async(client) => {
client.on("emojiCreate", function(emoji){
console.log(emoji)
const Embedf = new Discord.MessageEmbed()
.setColor("#1CDEA3")
.setTitle('New Emoji Created')
.addFields(
{ name: 'Emoji Name:', value: emoji.name, inline: false },
{ name: 'Emoji ID:', value: emoji.id, inline: false },
{ name: 'Nitro Emote?', value: emoji.animated, inline: false })
.setThumbnail(`${emoji.icon}`)
.setFooter(`${emoji.guild.name}`)
.setTimestamp()
client.channels.cache.find(channel => channel.id == "851987273837969408").send(Embedf)
})
}
How can I fix this? Thanks
A GuildEmoji does not have an icon property.
You may have meant to use the url property.
const Embedf = new Discord.MessageEmbed()
.setColor("#1CDEA3")
.setTitle('New Emoji Created')
.addFields(
{ name: 'Emoji Name:', value: emoji.name, inline: false },
{ name: 'Emoji ID:', value: emoji.id, inline: false },
{ name: 'Nitro Emote?', value: emoji.animated, inline: false })
.setThumbnail(emoji.url) // use URL instead of icon
.setFooter(emoji.guild.name)
.setTimestamp()
I have a bot which is supposed to create a channel under a specific category and then add two users to this channel.
The following bit of code is "supposed" to work and add user two, but fails with DiscordAPIError: Missing Permissions.
What I can't figure out is the actual permission required for this?
function addUserToChannel(ch, user, altCh) {
console.log(user.username,"sendmsg",ch.permissionsFor(client.user).has("MANAGE_CHANNELS", false)); //returns true
if (!ch.permissionsFor(user).has("SEND_MESSAGES", false)) {
console.log("User", user.username, "lacks view-channel permission");
ch.updateOverwrite(user, { //fails here obviously
SEND_MESSAGES: true,
VIEW_CHANNEL: true
});
} else {
console.log("WARN:", user.username, " already in channel ", ch.name);
altCh.send(user.toString() + " join conversation here: " + ch.toString());
}
}
The channel is created using the following code:
function createPrivateChannel(guild, convo, user) {
let everyoneRole = guild.roles.cache.find(r => r.name === "#everyone");
let parent = guild.channels.cache.find(ch => {
//console.log(ch.id,secret.convoCat.id);
return ch.id == secret.convoCat.id;
});
return guild.channels.create(convo.chName, {
type: "text",
parent: parent,
permissionOverwrites: [
{
id: everyoneRole.id, //private channel
deny: ["VIEW_CHANNEL", "SEND_MESSAGES"]
},
{
id: client.user.id, //bot permissions
allow: [ "VIEW_CHANNEL", "SEND_MESSAGES", "READ_MESSAGE_HISTORY", "MANAGE_CHANNELS" ]
},
{
id: user.user.id, //a different user
allow: ["VIEW_CHANNEL", "SEND_MESSAGES", "READ_MESSAGE_HISTORY"]
}
]
});
}
According to the Discord documentation for the 'Edit Channel Permissions' route (which is what updateOverwrite ultimately uses):
Requires the MANAGE_ROLES permission. Only permissions your bot has in the guild or channel can be allowed/denied (unless your bot has a MANAGE_ROLES overwrite in the channel).
I'm trying to make logs for my server, so when someone sends, deletes or edits a message, the bot will send an embed message in a specific channel with all the information. For some reason, the messageUpdate and messagedDelete events are triggered multiple times, and I can't understand why. I have tried everything, but nothing works. Why does this happen and how can I fix it?
I have the logs for each thing (sent, edited, deleted) in individual files, by the way. In my main file, this is the code I have for the messageUpdate:
bot.on('messageUpdate', (oldMessage, newMessage) => {
if (oldMessage.author.id === bot.user.id) return;
if(oldMessage.content === newMessage.content) return;
bot.events.get('editlogs').execute(oldMessage, newMessage);
})
This is my code for the edit logs:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.login(process.env.TOKEN);
module.exports = {
name: 'editlogs',
description: 'logs messages that were edited.',
category: 'logs',
execute(oldMessage, newMessage){
const logsChannel = bot.channels.cache.get("743142195594526822")
const logEmbed = new Discord.MessageEmbed()
.setColor('#ffa600')
.setTitle('Message Edited')
.setAuthor(oldMessage.author.tag, oldMessage.author.avatarURL())
.setThumbnail(oldMessage.author.avatarURL())
.addFields(
{ name: 'Old Message', value: oldMessage.content},
{ name: 'New Message', value: newMessage.content},
{ name: 'Channel', value: oldMessage.channel.toString(), inline: true },
{ name: 'Author', value: oldMessage.author, inline: true },
{ name: 'Author ID', value: oldMessage.author.id},
{ name: 'Message ID', value: oldMessage.id},
{ name: 'Message', value: '[Jump To Message](' + oldMessage.url + ')'},
)
.setTimestamp()
.setFooter('Edited in ' + oldMessage.guild.toString(), oldMessage.guild.iconURL());
logsChannel.send(logEmbed);
}}
So I was trying to put code into my Discord bot to give it a custom status for users to see, then when I found the code I had no idea where to put it.
Here's the code: where should I put it?
* Sets the full presence of the client user.
* #param {PresenceData} data Data for the presence
* #returns {Promise<ClientUser>}
* #example
* // Set the client user's presence
* client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
* .then(console.log)
* .catch(console.error);
*/
setPresence(data) {
return new Promise(resolve => {
let status = this.localPresence.status || this.presence.status;
let game = this.localPresence.game;
let afk = this.localPresence.afk || this.presence.afk;
if (!game && this.presence.game) {
game = {
name: this.presence.game.name,
type: this.presence.game.type,
url: this.presence.game.url,
};
}
This code above belongs to the ClientUser.js file. It might belong to other files like Presence.js
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
client.user.setPresence({
status: 'online',
activity: {
name: ".help",
type: "PLAYING"
}
});
});
The status can be online, idle, dnd, or invisible. (dnd is Do not disturb)
The other variable here is activity. It is a group of two variables: name and type.
The name is what the bot is doing. This is a string of your choice. The type is the other thing that will help it display as. It can be "PLAYING", "STREAMING", "WATCHING", "LISTENING", and "CUSTOM_STATUS".
You can put it anywhere but most likely you want to put it into your ready event like
client.on('ready', () => {
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
console.log(`${client.user.username} is up and running!`);
})