My issue here is when I execute the command the owner is only undefined instead of the actual owner of the server. How can I fix this issue?
module.exports.run = async (client, message, args) => {
const { MessageEmbed } = require('discord.js');
message.delete();
const guild = message.guild;
const Emojis = guild.emojis.cache.size || "No Emoji!";
const Roles = guild.roles.cache.size || "No Roles!";
const Members = guild.memberCount;
const Humans = guild.members.cache.filter(member => !member.user.bot).size;
const Bots = guild.members.cache.filter(member => member.user.bot).size;
const owner = guild.owner.user.tag
const embed = new MessageEmbed()
.setTitle(guild.name + " Information!")
.setColor("2F3136")
.setThumbnail(guild.iconURL())
.addField(`Name`, `${guild.name}`, true)
.addField(`Owner`, `${owner}`, true)
.addField(`ID`, `${guild.id}`, true)
.addField(`Roles Count`, `${Roles}`, true)
.addField(`Emojis Count`, `${Emojis}`, true)
.addField(`Members Count`, `${Members}`, true)
.addField(`Humans Count`, `${Humans}`, true)
.addField(`Bots Count`, `${Bots}`, true)
.addField(`Server Created At`, guild.createdAt.toDateString())
.setFooter(`Requested by ${message.author.username}`)
.setTimestamp();
message.channel.send({ embeds: [embed] });
}
module.exports.config = {
name: "serverinfo",
aliases: [""]
}
I'm pretty sure that there isn't an owner property in a Guild. To get the owner you have two methods:
Method 1 is using the .fetchOwner() method of a Guild
const owner = await message.guild.fetchOwner().user.tag
Method 2 is getting the owner id and then fetching the user from guild.members:
const owner = message.guild.members.cache.get(message.guild.ownerId)
You can choose which method is better for you
Related
I'm creating a message with buttons as reaction roles but do the reaction role handling in another file so it stays loaded after a reset but it either says "interaction.deferUpdate() is not a function, or in discord it says "this interaction failed" but it gave/removed the role
my code for creating the message:
const { ApplicationCommandType, ActionRowBuilder, ButtonBuilder, EmbedBuilder } = require('discord.js');
module.exports = {
name: 'role',
description: "reactionroles",
cooldown: 3000,
userPerms: ['Administrator'],
botPerms: ['Administrator'],
run: async (client, message, args) => {
const getButtons = (toggle = false, choice) => {
const row = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setLabel('member')
.setCustomId('member')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
new ButtonBuilder()
.setLabel('member2')
.setCustomId('member2')
.setStyle(toggle == true && choice == 'blue' ? 'Secondary' : 'Primary')
.setDisabled(toggle),
);
return row;
}
const embed = new EmbedBuilder()
.setTitle('Wähle eine rolle')
.setDescription('Wähle die rolle, die du gern haben möchtest')
.setColor('Aqua')
message.channel.send({ embeds: [embed], components: [getButtons()] })
.then((m) => {
const collector = m.createMessageComponentCollector();
collector.on('collect', async (i) => {
if (!i.isButton()) return;
await i.deferUpdate();
});
});
}
};
code for the reaction role:
const fs = require('fs');
const chalk = require('chalk')
var AsciiTable = require('ascii-table')
var table = new AsciiTable()
const discord = require("discord.js");
table.setHeading('Events', 'Stats').setBorder('|', '=', "0", "0")
module.exports = (client) => {
client.ws.on("INTERACTION_CREATE", async (i) => {
let guild = client.guilds.cache.get('934096845762879508');
let member = await guild.members.fetch(i.member.user.id)
let role = guild.roles.cache.find(role => role.name === i.data.custom_id);
if (!member.roles.cache.has(role.id)) {
member.roles.add(role);
} else {
member.roles.remove(role);
}
return i.deferUpdate()
})
};
The client.ws events give raw data (not discord.js objects), so the .deferUpdate() method doesn't exist there. You should be using client.on("interactionCreate")
client.on("interactionCreate", async (i) => {
// ...
return i.deferUpdate()
})
I am coding a bot with the below command and it throws an error, but i don't know where is the error
i tried my best
const Discord = require("discord.js");
const client = new Discord.Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if(!reason) reason = "No reason given."
if(!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if(!member) return message.channel.send("❌ You didn't mention a member!")
if(member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then (() => {
const embed = new Discord.MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
embed.setFooter(`Requested by ${message.author.username}`)
message.channel.send(embed)
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(error => {
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
If I have made a mistake, please help me out
Sorry I don't speak English well
Try the below code out, I made notes along the way to explain as well as improved a small bit of code. I assume this is a collection of 2 separate files which is why they are separated. If they aren't 2 separate files, you do not need the top section, just the bottom.
const {
Client,
Intents,
MessageEmbed
} = require("discord.js");
const client = new Client({
allowedMentions: {
parse: ["roles", "users", "everyone"],
},
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.DIRECT_MESSAGES
]
});
const config = require("../config.json");
const {
MessageEmbed,
Permissions
} = require("discord.js");
module.exports = {
name: "quar",
run: async (client, message, args) => {
if (!message.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) return;
let role = message.guild.roles.cache.find(role => role.name === "Quarantined" || role.name === "Quarantine")
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0])
let reason = message.content.split(" ").slice(2).join(" ")
if (!reason) reason = "No reason given."
if (!role) return message.channel.send("❌ This server doesn't have a quarantine role!")
if (!member) return message.channel.send("❌ You didn't mention a member!")
if (member.roles.cache.has(role.id)) return message.channel.send(`❌ That user already quarantined!`)
member.roles.add(role)
.then(() => {
const embed = new MessageEmbed()
.setTitle(`✅ ${member.user.tag} was quarantined!`)
.setColor("RANDOM")
.setTimestamp()
.setFooter({
text: `Requested by ${message.author.username}`
})
// author and footer are now structured like this
// .setAuthor({
// name: 'Some name',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// url: 'https://discord.js.org',
// })
// .setFooter({
// text: 'Some footer text here',
// icon_url: 'https://i.imgur.com/AfFp7pu.png',
// })
message.channel.send({
embeds: [embed]
}) //embeds must be sent as an object and this was the actual line that was causing the error.
member.send(`You were quarantined in \`${message.guild.name}\`. Reason: ${reason} `).catch(() => { // if error is not used, it is not required to be stated
message.channel.send(`❌ Can't send DM to ${member.user.tag}!`);
});
})
}
}
https://pastebin.com/FWYFSdfD
const Discord = require('discord.js')
module.exports = {
name: 'warn',
description: 'warn a member',
async execute(message, args){
edited = message.content.slice(5);
const guildID = message.guild.Discord
const UserId = message.member.Discord
const Reason = args.splice(1).join('')
let User = message.mentions.users.first()
if(message.member.permissions.has('KICK_MEMBERS')){
try{
member = await message.guild.members.find(message.mentions.users.first())
}catch(err){
const warnEmbed = new Discord.MessageEmbed()
.setTitle("**Warn**")
.setColor("#FF0000")
.addField('text', 'value')
.addField("User:", User, true)
.addField("Reason:", Reason, true)
.setThumbnail("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRGagFW_bh2AfgI1BqAis81CXVg37j8_MKtwg&usqp=CAU")
.setTimestamp()
}
try{
User.send(warnEmbed)
message.channel.send(warnEmbed)
}
catch(err){
return(message.reply('You must format the command <#mention> <reason>'))
}
}
else{
message.channel.send('only staff can use this command')
}
}
}
This is the warn code. But when I try to use it, I get an error saying MessageEmbed field values must be non-empty strings. And how many words do I need to write to send this.
I am trying to make a code that searches a custom status for the phrase ".gg/RoundTable" and will then give the person a certain role I have in my server.
Here is my code so far , the code runs with no errors but it will not assign the role.
const Discord = require("discord.js")
const client = new Discord.Client()
const mySecret = process.env['TOKEN']
client.login(mySecret)
const roleID = 865801753462702090
client.on('presenceUpdate', async (oldPresence, newPresence) => {
const role = newPresence.guild.roles.cache.find(role => role.name === 'Pic Perms (.gg/RoundTable)');
const status = ".gg/RoundTable"
const member = newPresence.member
console.log(member.user.presence.activities[0].state)
if(member.presence.activities[0].state.includes(status)){
return newPresence.member.roles.add(roleID)
} else {
if(member.roles.cache.has(roleID)) {
newPresence.member.roles.remove(roleID)
}
}
})
Try this:
const Discord = require("discord.js");
const client = new Discord.Client();
const roleID = "851563088314105867";
client.on("presenceUpdate", async (_, newPresence) => {
const role = newPresence.guild.roles.cache.get(roleID);
const status = ".gg/RoundTable";
const member = newPresence.member;
if (member.presence.activities[0].state?.includes(status)) {
return newPresence.member.roles.add(role);
} else {
if (member.roles.cache.has(role)) {
newPresence.member.roles.remove(role);
}
}
});
client.login("your-token");
I'd recommend finding your role in the RoleManager.cache using get() as you already have the roleID and then actually assign that role instead of the roleID. Note I added an optional chaining operator since if a user does not have a custom status .state will be null.
const { MessageEmbed } = require('discord.js')
module.exports = {
name: "addrole",
aliases: ["role", "P!role"],
category: "moderation",
description: "Add role to any user",
run: async (client, message, args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) {
return message.channel.send("sorry you need permission to mute someone");
}
if (!message.guild.me.hasPermission("MANAGE_ROLES")) {
return message.channel.send("I do not have the permissions");
}
const targets = message.mentions.members;
if(!targets.first()) return message.reply(`<:no:677902165859237894>please mention user!`)
let arole = message.mentions.roles.first();
if(!arole) return message.reply(`<:no:677902165859237894>please mention role for add!`)
const embed = new MessageEmbed()
.setColor("RANDOM")
.setDescription(`<a:ok_:731369076315652167>role added ${arole}`)
await message.channel.send(embed)
targets.forEach(target => target.roles.add(arole));
}
}
This adds role to the mentioned users.
Instead is there a way to alter
const targets = message.mentions.members
Such that the targets are all server members? And then by foreach, I can give the role to all the targets.
You could access all guild members from message.guild.members.cache and use .forEach().