Discord JS (Bot Presence) - javascript

So, in Discord, users can have a custom status, however, when I try to set my bot up with one nothing happens...Even though CUSTOM_STATUS is available
I have bot.user.setPresence({ activity: { name: "Testing", type: "CUSTOM_STATUS" }, status: "online" });
inside of the ready event. I was just wondering why this doesn't work and if there is a work around

According to the docs.
Bots cannot set a CUSTOM_STATUS, it is only for custom statuses received from users
The valid types you could choose from are:
PLAYING
STREAMING
LISTENING
WATCHING

Try client.user.setActivity(Your Status)
I am using this and its working fine
If you are using v12 then i cant help you

You should make sure that your setPresence command is in your ready event. For example, this is my ready command:
const {PREFIX} = require('../config.json');
const { Message } = require('discord.js');
const message = require('./message.js');
//must update when new module.exports event happens
const leaveEvent = require('../util/guildMemberRemove');
const invitecounterEvent = require('../util/guildMemberAddinvitecounter');
const modmailEvent = require('../util/modmail');
module.exports = (client, message) => {
//must update when new module.exports event happens
leaveEvent(client);
invitecounterEvent(client);
modmailEvent(client);
console.log(' ');
console.log(`Hi, ${client.user.username} is now online! My Prefix is ${PREFIX}`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
//client.user.setActivity(`Serving ${client.guilds.size} servers`); (big servers only)
client.user.setActivity('U', { type: 'WATCHING' }) //PLAYING, STREAMING, LISTENING, WATCHING, CUSTOM_STATUS
.then(presence => console.log(`Activity set to: WATCHING ${presence.activities[0].name}`))
.catch(console.error);
console.log(`Ready as ${client.user.tag} to serve in ${client.channels.cache.size} channels on ${client.guilds.cache.size} servers, for a total of ${client.users.cache.size} users.`);
client.generateInvite(['SEND_MESSAGES', 'MANAGE_GUILD', 'MENTION_EVERYONE', 'ADMINISTRATOR',])
.then(link => {
console.log(`Generated bot invite link: ${link}`);
// eslint-disable-next-line no-undef
inviteLink = link;
});
};
The part that should help you is client.user.setActivity('U', { type: 'WATCHING' })
The different types you can do are PLAYING, STREAMING, LISTENING, and WATCHING.

Related

problem trying to send a client.reply as an embed Message with discord.js

actually i´m working and learning about discord.js and node.js to make a bot, but i have a simple issue, and i don´t know why the embed messages doesn´t work, i tried with the documentarion examples and code of other devs, but in all cases when i try to send the message to a channel, using client.reply(embed) throws me an error saying me that can send an empty message.
i´m using the last version of discord.js (v13.3.1) and i´m using the basic documentation event and the command handlers (works perfectly if i don´t try to send embeds).
This is my index.js and my help.js files:
//This is my index.js i don´t have problem with this but i include it if there are an issue related with this topic.
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { token } = require('./config.json');
client.commands = new Collection();
const commandFiles = fs.readdirSync('./Commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./Commands/${file}`);
client.commands.set(command.data.name, command);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
return interaction.reply({ content: 'Parece que ha ocurrido algun problema con el comando.', ephemeral: true });
}
});
const eventFiles = fs.readdirSync('./Events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./Events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
client.login(token);
Now the help.js , this is going to be a Command, but i don´t wanna only to code the commands using the SlashCommands, because of it i´m triying to create this as an event:
//This is the help command using an event
const { clientId } = require("../config.json");
const { MessageEmbed } = require("discord.js");
//testx is going to store the embed message
const testx = new MessageEmbed().setTitle('Test').setDescription('Test');
module.exports = {
name: 'messageCreate',
execute(client) {
//This condition determines if isn´t a message of the bot, and if the written command is !!help
if (client.author.id !== clientId && client.content === '!!help') {
//if the condition is true, send the embed message
//client.reply(testx); //the problem is here.
console.log(testx);
}
},
};
And this is the error i got from the terminal:
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\ //...and more info of my dirs
if i print the testx const in my console, i can see the two values i setted in the const filled with the text "Test", i don´t know why isn´t work or what i need to take this to work.
Thanks and i appreciate any help.
In V13, embeds must be sent differently.
client.reply({embeds: [testx]});
I also recommend editing client to interaction in your command files as it may be misleading, or to actually pass the client and interaction, as you'll most likely need to access the client at some point.
Also, you seem to be confusing interactions with messages.
Interactions do not have an author property, you must use user or member.
They also do not have a content property, to get an argument you must use interaction.options
You also, as far as I can see, are not actually deploying your commands. It looks like you've merged the V12 and V13 command handler tutorial together. I reccomend reading this tutorial again, and making sure you're doing it properly for V13.

Importing variables from other files

I am trying to import a variable from one of my files (File 1) and use it in File 2. I have imported File 2 into File 1 but I am receiving error. My channel ID is correct, in this case you would have to choose the channel so the channel ID is not the issue here.
TypeError: setr.send is not a function
File 1
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const channelx =
message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx)
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
message.reply(`All server restart logs will now go to ${channelx}.`)
},
};
File 2
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
let setr = require("./setrestart"); // This is importing file 1
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setDescription(`F8 connect to ${config.SERVER_URL} `)
.setColor("RANDOM")
.setTimestamp()
.setFooter(`${config.SERVER_LOGO}`);
setr.channelx.send(restart) // This does not work.
},
};
Help is much appreciated.
Edit: I left out the most crucial thing about what I am trying to import.
I am trying to import channelx which is in File 1 and I am trying to use the variable in File 2.
Output
User: /setrestart #channel
Bot: All server restart logs will now go to ${channelx}.
User: /restart
Bot: Embed sent in channelx
The variable channelx is accessible only in the function scope of execute(), you can't import it. Basically after the function goes out of scope the variable is lost. Use a global object, note that the object is destroyed when the program exits. So if you are trying to make some kind of bot's configuration, you want to save the object to a file.
Here is an example of how to properly implement what you are trying to do.
File 1 (file1.js):
// ... Load storage from a JSON file ...
const storage = {};
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... Permission checking ...
const channelx = message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx) {
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
}
// Store restart channel id per guild
storage[message.guild.id] = channelx.id;
message.reply(`All server restart logs will now go to ${channelx}.`);
// ... Write to the storage JSON file and update it with new data ...
},
};
module.exports.storage = storage;
File 2 (file2.js):
const Discord = require("discord.js");
const file1 = require("./file1.js");
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... Permission checking ...
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setColor("RANDOM")
.setTimestamp();
const channelId = file1.storage[message.guild.id];
// If there is no restart channel set, default to the system channel
if (!channelId) channelId = message.guild.systemChannelID;
const channel = await message.client.channels.fetch(channelId);
channel.send(restart);
},
};
Note that I have remove some parts of your code, to make it work on my machine.
Using discord.js ^12.5.3.
I am pretty sure you can't use the module.exports in that way. You should just add the channelx to the exports instead.
using this.channelx = channelx.
This is not how importing and exporting works. Your channelx variable is defined within the execution of a function, and you are not returning it.
I am not sure how the whole Discord API works and what are the shapes that get returned, but you should be able to do something like this:
File 1
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... everything as per your file
message.reply(`All server restart logs will now go to ${channelx}.`);
return channelx;
},
};
File 2
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... everything the same as per your file
const channelx = await setr.execute(message, args);
channelx.send(restart);
},
};
Basically, what is happening here is that the first module exposes a function that figures out your target channel and then returns it.
Once you return it, you can do whatever you want with that.
Please be aware that your first function might not need to be async as you don't have any await instruction.
Read more about scope: https://developer.mozilla.org/en-US/docs/Glossary/Scope

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

How do I fetch the creator of a channel in discord?

bot.on('channelCreate', async channel => {
if (!channel.guild) return;
const fetchedLogs = await channel.guild.fetchAuditLogs({
limit: 1,
type: 'CHANNEL_CREATE',
});
const logbook = channel.guild.channels.cache.get("ChannelID")
const deletionLog = fetchedLogs.entries.first();
if (!deletionLog) return logbook.send(`A channel was updated but no relevant autid logs were found`);
const { executor, user } = deletionLog;
if (user.id) {
logbook.send(`${executor.tag} created a channel`);
} else {
logbook.send(`A channel was created but idk who did.`);
}
});
I am a newbie when it comes to fetching actions through Discord Audit Logs; so I am experimenting and somehow came up with this code. However, when I create a channel, it does not send any messages saying that a channel has been created by #user. I have no idea what my next step will be. All I wanted to do was to know who created the channel.
Discord.JS: v12.2.0
client.on("channelCreate", async channel => {
if (!channel.guild) return false; // This is a DM channel.
const AuditLogFetch = await channel.guild.fetchAuditLogs({limit: 1, type: "CHANNEL_CREATE"}); // Fetching the audot logs.
const LogChannel = client.channels.cache.get("722052103060848664"); // Getting the loggin channel. (Make sure its a TextChannel)
if (!LogChannel) return console.error(`Invalid channel.`); // Checking if the channel exists.
if (!AuditLogFetch.entries.first()) return console.error(`No entries found.`);
const Entry = AuditLogFetch.entries.first(); // Getting the first entry of AuditLogs that was found.
LogChannel.send(`${Entry.executor.tag || "Someone"} created a new channel. | ${channel}`) // Sending the message to the logging channel.
});
If the code I provided is not working, please make sure the bot has access to view AuditLogs.

discord.js client.user.setPresence() breaks bot

My bot currently runs fine. I decided to add a 'playing ' status to it. This is the relevant code:
// Import the discord.js modules required
const Discord = require('discord.js');
// Create an instance of a Discord client
const client = new Discord.Client();
// Load config properties from 'config.json'
const config = require("./config.json");
const contest = config.contest;
// Set bots status to playing 'contest' defined in 'config.json'
client.user.setPresence({
game:{
name:contest
},
status:'online'
});
In 'config.json':
{
"contest": "Example Game"
}
When I add this, the bot no longer works, and appears offline. Any ideas?
EDIT:
Source of the information:
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setPresence
In the example section:
// Set the client user's presence
client.user.setPresence({ game: { name: 'with discord.js' }, status: 'idle' })
.then(console.log)
.catch(console.error);
You need to read the config, instead of
const config = require(...)
You need
const fs = require("fs");
const config = JSON.parse(fs.readFileSync("config.json"));
const contest = config.contest;
Then
game:{
name:contest
}
Figured it out - this needs to be placed inside an event, otherwise it's just floating code. For example, I placed this inside a
client.on('ready) event.

Categories

Resources