EDIT: I JUST NEEDED TO PASS THE CLIENT
this is the code that i made in its own file
const Discord = require("discord.js");
const bot= new Discord.Client();
module.exports = {
name: 'set' ,
execute(message, args){
if(message.member.hasPermission("MANAGE_GUILD"))
{
if (args[2]==='picture')
{const image=message.attachments.first().url;
bot.user.setAvatar(image);}
else if (args[2]==='activity')
{
let initial = message.content ;
initial= initial.replace('asb set activity','').replace(args[3],'');
bot.user.setActivity(initial, { type: args[3] });
}
else
message.reply('invalid command');
}
else
return message.reply('You can use this command only if u have permisions to manage the server');
}
}
and this is the error
bot.user.setActivity(initial, { type: args[3] });
^
TypeError: Cannot read property 'setActivity' of null
if i remove the bot client and use client.message it gives me the same error
The problem here is that bot is a new Discord.Client();
What you should do instead is pass the client object from your index.js file to the command file and use that to set its activity.
Or you can get the client also with: message.client , so your code would be something like:
message.client.user.setActivity(...);
Related
I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.
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.
Hi I'm making a Javascript based Discord bot, and I really wanted to implement the new Discord Buttons feature, the problem is, even using the documentation examples, I get the same error, again and again :
(node:6184) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message
Here is the code (I am using module.exports with separated files for each commands) :
const { MessageButton } = require('discord-buttons')
module.exports = {
name: 'invite',
descritipion: 'test command',
async execute(client, message, args) {
let button = new MessageButton()
.setStyle('url')
.setURL('https://npmjs.com/discord-buttons')
.setLabel('Click me !')
await message.channel.send('Hey, I am powered by npm discord-buttons : https://npmjs.com/discord-buttons');
await message.channel.send(button);
}
}
You cannot just send a button on its own. Instead, try adding the button to the previous message so they both get sent in one message as shown below
The official documentation for this is here
// Replace these
const { MessageButton } = require('discord-buttons')
await message.channel.send('Hey, I am powered by npm discord-buttons : https://npmjs.com/discord-buttons');
await message.channel.send(button);
// With these
const { MessageButton, MessageActionRow } = require('discord-buttons')
await message.channel.send('Hey, I am powered by npm discord-buttons : https://npmjs.com/discord-buttons', {
component: new MessageActionRow().addComponent(button)
});
Also, did you forget to initialize DiscordButtons? Do it when you initialize your discord bot
// Where you initialized your discord bot
const bot = new Discord.Client()
// Add this line
require("discord-button")(bot)
I'm having some trouble coding prefix changing in my Discord bot. I've got all the basic functionality working:
The prefix is saved in a config file
The bot can write to the file and save it for later use
However, I can't seem to get the bot to use the new prefix after it's changed until I restart the bot. The config file shows that the prefix has been changed, but the bot doesn't respond to it.
So, my question is either, how can I refresh the memory so that the config is reloaded, or how can I get the bot to read my config again and use the new prefix?
Thanks!
prefix.js:
const fs = require('fs'); // node.js file system module
config = require('../config.json');
const Discord = require("discord.js");
module.exports = {
name: 'prefix', // command keyword
description: 'Changes the bot prefix', // info about command
group: 'settings', // command group (not displayed in !help [command name])
aliases: ['botprefix', 'newprefix'], // using these keywords also triggers command
usage: '[new prefix]', // how command is supposed to be used
cooldown: '1', // time command cannot be reused after it has been called
args: true, // are arguments required
execute(message, args) {
fs.exists("../config.json", function (error) {
if (error) {
console.log(error);
}
})
? fs
.readFile("../config.json", function (error) {
if (error) {
console.log(error);
}
})
.toString()
: config.prefix;
const newPrefix = args.shift().toString();
newConfig = {
token: config.token,
prefix: newPrefix,
};
fs.writeFile("config.json", JSON.stringify(newConfig, null, 2), function (
error
) {
if (error) {
console.log(error);
}
});
}
config.json:
{
"token": "token",
"prefix": "!"
}
If you want to access data via require, it won't be updated later as the function is run once at the beginnign of the project, even if you re-require it. This article can give you a bit more background on it. Basically: Always use fs.readFile and you're fine
Every line of code i try to use to send a message to a specific channel doesn't seem to work in discord.js v12 even when i got that code from the official documentation. Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const announcementChannel = client.channels.cache.get(process.env.CHANNELANN);
let announcement = "MESSAGE HERE";
client.on("presenceUpdate", (oldPresence, newPresence) => {
if (!newPresence.activities) return false;
newPresence.activities.forEach(activity => {
if (activity.type == "STREAMING") {
if(newPresence.user.id == "THE ID IS HERE") {
announcementChannel.send(announcement);
}
} else {
client.user.setActivity("over the server", {
type: "WATCHING"
});
};
});
});
client.login(process.env.TOKEN);
Here is the error i receive:
announcementChannel.send(announcement);
^
TypeError: Cannot read property 'send' of undefined
I was able to fix this by replacing that line with:
client.channels.cache.get(process.env.CHANNELANN).send(announcement);
However, now it just keeps spamming the message and doesn't only send it once then stops. You know any fix for that?
Once initiated, make it wait until the stop streaming
None of the answers I found worked with the latest version (12.5.1) so here's what worked for me.
const channel = client.channels.cache.get(textChannelId) as TextChannel;
if (channel) {
const m = new Message(client, {id: clientId}, channel);
const content: MessageOptions = {content: message};
//if (image) {
// content.embed = {image: {url: image}};
//}
await m.channel.send(content);
}