I'm setting up Slash Commands with my Discord.JS bot.
I have a /rank command in the XP/leveling portion of my bot, but when I check interaction.member.presence for displaying it in the rank card, it returns null.
I've tried to look up this problem and look through the documentation of Discord.JS, but nobody else seems to have had this problem yet and I don't see anything in the documentation or Discord.JS guide to help solve this problem.
Here is the /rank command:
const Discord = require("discord.js");
const SQLite = require("better-sqlite3");
const sql = new SQLite('./mainDB.sqlite')
const client = new Discord.Client({ intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES] });
const canvacord = require("canvacord");
module.exports = {
name: 'rank',
aliases: ['rank'],
description: "Get your rank or another member's rank",
cooldown: 3,
category: "Leveling",
async execute(interaction) {
if(!interaction.isCommand()) return console.log("yes");
await interaction.deferReply()
.then(console.log("a"))
.catch(console.error);
let user = interaction.user;
client.getScore = sql.prepare("SELECT * FROM levels WHERE user = ? AND guild = ?");
client.setScore = sql.prepare("INSERT OR REPLACE INTO levels (id, user, guild, xp, level, totalXP) VALUES (#id, #user, #guild, #xp, #level, #totalXP);");
const top10 = sql.prepare("SELECT * FROM levels WHERE guild = ? ORDER BY totalXP").all(interaction.guild.id);
let score = client.getScore.get(user.id, interaction.guild.id);
if (!score) {
return interaction.editReply(`This user does not have any XP yet!`)
}
const levelInfo = score.level
const nextXP = levelInfo * 2 * 250 + 250
const xpInfo = score.xp;
const totalXP = score.totalXP
let rank = top10.sort((a, b) => {
return b.totalXP - a.totalXP
});
let ranking = rank.map(x => x.totalXP).indexOf(totalXP) + 1
//if (!interaction.guild.me.hasPermission("ATTACH_FILES")) return interaction.editReply(`**Missing Permission**: ATTACH_FILES or MESSAGE ATTACHMENTS`);
try {
var cardBg = sql.prepare("SELECT bg FROM background WHERE user = ? AND guild = ?").get(user.id, message.guild.id).bg;
var bgType = "IMAGE";
} catch (e) {
var cardBg = "#000000";
var bgType = "COLOR";
}
console.log(interaction.member.presence);
const rankCard = new canvacord.Rank()
.setAvatar(user.displayAvatarURL({
format: "jpg"
}))
.setStatus(interaction.member.presence.status, true, 1)
.setCurrentXP(xpInfo)
.setRequiredXP(nextXP)
.setProgressBar("#5AC0DE", "COLOR")
.setUsername(user.username)
.setDiscriminator(user.discriminator)
.setRank(ranking)
.setLevel(levelInfo)
.setLevelColor("#5AC0DE")
.renderEmojis(true)
.setBackground(bgType, cardBg);
rankCard.build()
.then(data => {
const attachment = new Discord.MessageAttachment(data, "RankCard.png");
return interaction.editReply({attachments: [attachment]});
});
}
}
Notes:
I do have the Presence Intent enabled.
Sorry if this seems like too little information. It's just what I
know so far, and I can't think of anything that I can do about it.
I know this command is very messy. I'm not asking how to fix that. I will fix that later.
Even though you have the PRESENCE INTENT enabled, you need to specify that you will be using the aforementioned intent in ClientOptions.
const client = new Discord.Client({
intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES, Discord.Intents.FLAGS.GUILD_PRESENCES],
});
First You need to enable intent
const client = new Discord.Client({
intents: [
Discord.Intents.FLAGS.GUILD_PRESENCES
],
});
Now we need Create a var of member
let member = message.mentions.members.first()
For get the presence of members use #presence
console.log(member.presence)
Will get results as
Presence {
userId: 'USER_ID',
guild: [Guild],
status: 'online',
activities: [Array],
clientStatus: [Object]
}
Related
this is my ../Events/Guild/guildMemberAdd.js https://sourceb.in/iEEfLj7uM7
im trying to set placeholders that will in turn give out an output like
Welcome to OnlyScoped.gg #azz#5271! We're glad to have you as the 500th member.
but output is
Welcome to OnlyScoped.gg <#undefined>! We're glad to have you join us as the undefinedth member.`
../Commands/Moderation/setup-welcome.js
const {Message, Client, SlashCommandBuilder, PermissionFlagsBits} = require("discord.js");
const welcomeSchema = require("../../Models/Welcome");
const {model, Schema} = require("mongoose");
module.exports = {
data: new SlashCommandBuilder()
.setName("setup-welcome")
.setDescription("Set up your welcome message for the discord bot.")
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.addChannelOption(option =>
option.setName("channel")
.setDescription("Channel for welcome messages.")
.setRequired(true)
)
.addStringOption(option =>
option.setName("welcome-message")
.setDescription("Enter your welcome message.")
.setRequired(true)
)
.addRoleOption(option =>
option.setName("welcome-role")
.setDescription("Enter your welcome role.")
.setRequired(true)
),
async execute(interaction) {
const {channel, options} = interaction;
const welcomeChannel = options.getChannel("channel");
const welcomeMessage = options.getString("welcome-message");
const roleId = options.getRole("welcome-role");
if(!interaction.guild.members.me.permissions.has(PermissionFlagsBits.SendMessages)) {
interaction.reply({content: "I don't have permissions for this.", ephemeral: true});
}
welcomeSchema.findOne({Guild: interaction.guild.id}, async (err, data) => {
if(!data) {
const newWelcome = await welcomeSchema.create({
Guild: interaction.guild.id,
Channel: welcomeChannel.id,
Msg: welcomeMessage,
Role: roleId.id
});
}
interaction.reply({content: 'Succesfully created a welcome message', ephemeral: true});
})
}
}
../Models/Welcome.js
const { model, Schema } = require("mongoose");
let welcomeSchema = new Schema({
Guild: String,
Channel: String,
Msg: String,
Role: String,
});
module.exports = model("Welcome", welcomeSchema);
im attempting to use string.replace()but its not working as expected
i decided to put it in guildMemberAdd.js since when a member joins this gets runs so it would be unwise to place it in setup-welcome.js or Welcome.js since those are not listening for anything.
for reference here's my package.json:
https://sourceb.in/FMBgygjyoh
for the record i cant find any of the id's like member.id or member.count so those are wild guesses as to what they are. it could very well just be that as im still learning v14 this is my first project in it.
one other way i thought could work is if i just pass it off as an interpolated string in mongodb but it seems that the only string is with "" so i cant use default ones like ${member.count} so i decided to add placeholders
The basics of formatting a template are this:
const string = "Welcome to OnlyScoped.gg {tagUser}! We're glad to have you as the {memberCount} member.";
string = string.replace(/{tagUser}/g, member.toString());
string = string.replace(/{memberCount}/g, '500th');
return string; // "Welcome to OnlyScoped.gg <#123456789012345678>! We're glad to have you as the 500th member.";
To make something extensible, put template strings like this somewhere in your configuration:
{
"welcome_message": "Welcome to OnlyScoped.gg {tagUser}! We're glad to have you as the {ordinal:memberCount} member."
}
and make a function
function formatMessage(template, lookup) {
let output = template;
output = output.replace(/{ordinal:([^}]*)}/g, (_, target) => withOrdinalSuffix(lookup(target)));
output = output.replace(/{([^}]*)}/g, (_, target) => lookup(target));
return output;
}
// https://stackoverflow.com/a/31615643/3310334
// turn 1 into '1st', 500 into '500th', 502 into '502nd'
function withOrdinalSuffix(n) {
var s = ["th", "st", "nd", "rd"],
v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
and then use the function with a template and the lookup function:
client.on('guildMemberAdd', member => {
const welcomeMessageTemplate = config.welcome_message;
const memberCount = member.guild.members.filter(member => !member.user.bot).size;
const lookup = (item) => {
const items = {
memberCount,
tagUser: member.toString()
};
return items[item];
};
const welcomeMessage = formatMessage(welcomeMessageTemplate, lookup);
const welcomeChannel = member.guild.channels.cache.find(channel => channel.name === 'welcome');
welcomeChannel.send(welcomeMessage);
});
The main issue I can see is incorrect property names as you mention in the question.
DiscordJS Docs: GuildMember
member.id => The Members ID
member.user.username => The Members username
member.guild.name => The Server's Name
member.guild.memberCount => Number of users within the Server
I'd advise the user to input data in a specific format like Hello {userName}!. Then you could run a program like
while (string.includes('{userName}')) {
string = string.replace('{userName}', member.user.username);
}
Hey i made a xp system with discord-xp i wanted to make a slashcommand that can give a user xp. But everytime i give this user xp in the database there is a # behind the user id and i want it without because otherwise the bot will not work.
Here is my Code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const Levels = require('discord-xp');
const { MessageEmbed } = require('discord.js');
const client = require("../index")
module.exports = {
data: new SlashCommandBuilder()
.setName("addxp")
.setDescription("add xp")
.addUserOption((option) => option.setName('user').setDescription('add user xp').setRequired(true))
.addNumberOption(option => option.setName('num').setDescription('Enter a number').setRequired(true)),
async execute(client, interaction) {
const user = interaction.options.user.id('target')
const number = interaction.options.getNumber('num');
var userID = interaction.user.id;
const levels = await Levels.fetch(userID, interaction.guildId);
Levels.appendXp(user, interaction.guild.id, number);
interaction.reply(`**${user.tag}** got added ${number} XP.`);
}
}
You can use this:
const user = interaction.options.getUser('user')
const id = user?.id
first issue: all the embeds in my code stopped working - no matter what command I try to run if it has an embed in it I get the error: DiscordAPIError: Cannot send an empty message
second issue: I'm currently programming a mute command with a mongoDB database, it puts everything I need it in the database however if I try to mute someone it ends up only muting them for 1s by default, basically completely ignoring the second argument. heres what I want the command to do: when you mute someone you need to provide the user id and a time (works in ms) + reason then it puts it in the data base.
here's the code: [P.S. Im not getting an error message, it just doesnt work properly like I want it to]
const mongo = require('../mongo.js')
const muteSchema = require('../schemas/mute-schema.js')
const Discord = require('discord.js')
const ms = require ("ms")
module.exports = {
commands: 'mute',
minArgs: 2,
expectedArgs: "<Target user's #> <time> <reason>",
requiredRoles: ['Staff'],
callback: async (message, arguments) => {
const target = message.mentions.users.first() || message.guild.members.cache.get(arguments[0])
if (!target) {
message.channel.send('Please specify someone to mute.')
return
}
const { guild, channel } = message
arguments.shift()
const mutedRole = message.guild.roles.cache.find(role => role.name === 'muted');
const guildId = message.guild.id
const userId = target.id
const reason = arguments.join(' ')
const user = target
const arg2=arguments[2]
const mute = {
author: message.member.user.tag,
timestamp: new Date().getTime(),
reason,
}
await mongo().then(async (mongoose) => {
try {
await muteSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$push: {
mutes: mute,
},
},
{
upsert: true,
}
)
} finally {
mongoose.connection.close()
}
})
message.delete()
user.roles.add(mutedRole)
setTimeout(function() {
user.roles.remove(mutedRole)
}, ms(`${arg2}`));
try{
message.channel.send(`works`)
}
catch(error){
const embed3 = new Discord.MessageEmbed()
.setDescription(`✅ I Couldn't DM them but **${target} has been muted || ${reason}**`)
.setColor('#004d00')
message.channel.send({ embeds: [embed3] });
}
},
}
djs v13 has a new update where you need to send embeds like this:
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('example')
.setDescription('example')
.setColor('RANDOM')
message.channel.send({embed: [exampleEmbed]});
I am trying to send an embed whenever a invite is created.
Channel set file
let config = require("../config.json");
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js");
const client = new Discord.Client();
module.exports = {
name: "setinvite",
description: "set invite channel log.",
async execute(message, args) {
if (!message.member.hasPermission(`ADMINISTRATOR`)) {
return message.channel.send(
`:x: You do not have permission to use this command!`
);
} else {
let channelx =
message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx)
return message.channel.send(
`:x: Please specify a channel to make it as the modlogs!`
);
message.channel.send(`${channelx} has been set!`);
}
},
};
Index.js Modules (PS: I took the most relevant ones.)
const Discord = require("discord.js");
const client = new Discord.Client();
const fs = require("fs");
const { MessageEmbed } = require("discord.js");
const guildInvites = new Map();
const { channelx } = require("./commands/setinvite");
Index.js file
client.on("inviteCreate, message", async (invite) => {
const setc = client.channels.cache.get(`${channelx}`);
message.guild.fetchInvites().then((invites) => {
let allInvites = invites.map((i) => ({
name: "Invite",
value: `**Inviter:** ${i.inviter}
**Code:** https://discord.gg/${i.code}
**Usages:** ${i.uses} of ${i.maxUses === 0 ? "∞" : i.maxUses}
**Expires on:** ${
i.maxAge
? new Date(i.createdTimestamp + i.maxAge * 1000).toLocaleString()
: "never"
}`,
inline: true,
}));
setc.send(new Discord.MessageEmbed().addFields(allInvites));
});
});
I don't think the two events (inviteCreate, message) belong I did it because I received a error:
ReferenceError: message is not defined
Now, the channel set features works as intended but whenever the invite is created the embed doesn't send.
You can't merge all events inside one function.
You only need to keep the inviteCreate event. Then, you have to find a way to get the guild without using the "message" variable. Instead you can use the "invite" parameter that is present inside the inviteCreate event.
client.on("inviteCreate", async (invite) => {
const setc = client.channels.cache.get(`${channelx}`);
invite.guild.fetchInvites().then((invites) => {
let allInvites = invites.map((i) => ({
name: "Invite",
value: `**Inviter:** ${i.inviter}
**Code:** https://discord.gg/${i.code}
**Usages:** ${i.uses} of ${i.maxUses === 0 ? "∞" : i.maxUses}
**Expires on:** ${
i.maxAge
? new Date(i.createdTimestamp + i.maxAge * 1000).toLocaleString()
: "never"
}`,
inline: true,
}));
setc.send(new Discord.MessageEmbed().addFields(allInvites));
});
});
Im trying to develop a little warn system for my Discord Bot. If someone types !warn #mention Reason, it should store the data in a JSON File. It works, but only with one User in one Guild. What I want is, that
the JSON File looks like this:
{
"superniceguildid":
{
"member": "636302212787601408",
"warns": 3
},
{
"meber": "7837439745387549"
"warns": 1
}
}
Now only this exists:
{
"627818561947041816": {
"guild": "636302212787601408",
"warns": 3
},
}
How can I do it, that the File is generating like above?
My current code is this:
module.exports = {
name: 'warn',
description: "test",
execute(message, args){
const { Client, MessageEmbed } = require("discord.js")
const client = new Client()
const fs = require("fs")
const ms = require("ms")
warns = JSON.parse(fs.readFileSync("./warns.json", "utf8"))
client.servers = require ("./servers.json")
let guild = client.servers[message.guild.id].message
/*Embeds*/
const oops = new MessageEmbed()
.setTitle("Error")
.setColor("RED")
.setDescription("You cant warn a member. Please ask a Moderator")
.setAuthor("MemeBot", "this is a link")
const Mod = new MessageEmbed()
.setTitle("Error")
.setColor("RED")
.setDescription("You cant warn a Moderator.")
.setAuthor("MemeBot", "linkhere xD")
/**Commands */
let wUser = message.mentions.users.first() || message.guild.members.cache.fetch(`${args[0]}`)
if (!wUser) return message.channel.send("Are you sure, that this was a User? I think it wasn't one...")
let wReason = args.join(" ").slice(27)
if (!wReason) return message.channel.send("Please tell me, why you want to warn this person. Because, you know, it's a warn :D");
if(!message.member.hasPermission("KICK_MEMBERS")) return message.channel.send(oops)
if(wUser.hasPermission("KICK_MEMBERS")) return message.channel.send(Mod)
if(!warns[message.guild.id]) warns[message.guild.id] = {
user: wUser.id,
warns: 0
}
warns[wUser.id].warns++
fs.writeFile("./warns.json", JSON.stringify(warns, null, 4), err => {
if(err) console.log(err)
});
let warnEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned User", `${wUser}`)
.addField("Moderator", `${message.author.id}`)
.addField("Reason", `${wReason}`)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Warned at", `${message.createdAt}`)
let warnonEmbed = new MessageEmbed()
.setTitle("Warned")
.setColor("YELLOW")
.addField("Warned on", `${message.guild.name}`)
.addField("Moderator", `${message.author}`)
.addField("Reason", `${wReason}`)
.addField("Warned at", `${message.createdAt}`)
let logchannel = message.guild.channels.cache.find(c => c.id === 'id');
if(!logchannel) return
wUser.send(warnonEmbed)
logchannel.send(warnEmbed)
}
}
That particular layout doesn't make a lot of hierarchical sense. You might want to nest the user inside the guild and any parameters belonging to the user inside that. Something like this...
"superniceguildid":
{
"636302212787601408":
{
"warns": 3
},
"7837439745387549":
{
"warns": 1
}
},
Accessing it then would be as easy as using something like the following:
let guildWarns = warns["superniceguildid"];
let userWarns = guildWarns["636302212787601408"];
let numberOfWarns = userWarns.warns;
you can combine that as well.
let numberOfWarns = warns["superniceguildid"]["636302212787601408"].warns;
Of course, remember that if it doesn't exist it will be undefined.