Discord.js Get Status from Message - node.js

Hi I'm trying to make my Bot change its status from a message, and also set it with quick.db so if it restarts it changes back to the sotd. For example the message would be something like : Song of the day: "Wild Reputation" from the Album(s) PWR UP and I only want the song name as the status.
client.on('message', message => {
if (message.channel.id === '792250171320434688') {
if (message.author.id === '403657714812715008') {
const ms = message.content
db.set('sotd_', ms)
let so = db.get('sotd_')
client.user.setActivity(so, { type: "PLAYING"})
}
}
});

I guess the problem is somewhere with quick.db because as far as I can tell the discord.js part is correct. My suggestion is to try the following:
client.on('message', message => {
if (message.channel.id === '792250171320434688' && message.author.id === '403657714812715008') {
const ms = message.content
client.user.setActivity(ms, { type: "PLAYING"})
db.set('sotd_', ms)
}
});
This way you eliminate possible errors when trying to get the data from the database. And then if you want to get the last status from quick.db do something like
client.on('ready', () => {
const lastStatus = db.get('sotd_');
client.user.setActivity(lastStatus, { type: "PLAYING"});
});

Related

Trying to catch response but why wont it send?

I am currently working on a command right now that I would like the server owner to use. When done it sends the embed and will wait for the server owner to paste we will say the channel id. I want to label this to call in another command but at the moment it sends the embed but when I send a channel ID nothing happens. No message is sent but it also does not break the bot. I am still able to send the command again and again.
Please do not mind the slop, I am new to all this and trying to learn as I go any tips would be appreciated!
EDIT: I am using version 12 (12.5.3)
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'setchannel',
description: 'command to assign bot to channel',
execute(message, args) {
if(message.channel.type == "dm") {
const keepinservercommandembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('**Im Sorry!**')
.addFields(
{ name: `**Can` + `'t accept: ${prefix}setchannel**`, value: 'Please keep this command to the server!' },
)
message.channel.send(keepinservercommandembed);
}
else {
const messagesender = message.member.id;
const serverowner = message.guild.owner.id;
const setchannelembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Let's get searching!**`, value: `Hello ${message.guild.owner}, what channel would you like me to post group finding results?` },
)
const notownerembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Whoops!**`, value: `Sorry only ${message.guild.owner} can use this command.` },
)
if(messagesender == serverowner) {
message.delete ();
const filter = m => m.content.message;
const collector = message.channel.createMessageCollector(filter, { time: 15000 });
message.channel.send(setchannelembed).then(() => {
collector.on('collect', m => {
message.channel.send(`${m.content}`)
});
});
}
else {
message.delete ();
message.channel.send(notownerembed);
}
}
}
}
After comparing your code to my similiar discord.js v13 code and checking out the v12 docs, I think I found the problem.
I don't think m.content.message is a function. If your aim is for someone to paste the channel ID, the filter code would be:
const filter = m => m.author.id === message.guild.owner.id;
To filter out other people who may be entering an ID (assuming the input is valid).
Use the filter as follows:
message.channel.createMessageCollector({filter: filter, time: 15000 });
To filter out invalid inputs:
collector.on('collect', m => {
if (isNaN(m)) return; //all channel id's in discord are integers (numbers)
else message.channel.send(`${m.content}`);
});

Banning user who is replied to (Discord JS)

As title says, I'm trying to write some code that will ban a user if their message is replied to with the word ban. I think the way im getting the id of the original message is wrong but I'm not sure how to implement it otherwise. The error im getting is "TypeError: Cannot read properties of undefined (reading 'id')"
client.on("messageCreate", (message) => {
if (message.content == "ban" && message.type == 'REPLY') {
const member = message.reference.author.id;
message.guild.members.ban(member).then(console.log)
.catch(console.error);
}
})
Change your current code to:
const client = new Discord.Client({ intents: [ "GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS" ] });
client.on("messageCreate", (message) => {
if (message.content == "ban" && message.type == 'REPLY') {
const member = message.author.id;
message.guild.members.ban(member).then(console.log)
.catch(console.error);
}
})
To access the Server Members Intent:
Go to discord/developers
In Applications, click your project/bot
Click the BOT section
Scroll down until you see the Privileged Gateway Intents
Find for the Server Members Intent
Enable it
Now try the script again
I'm suggest you do like this:
const client = new Discord.Client({ intents: [ "GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS" ] });
client.on("messageCreate", async (message) => {
if (message.content == "ban" && message.reference) {
const msg = await message.channel.messages.fetch(message.reference.messageId);//cache the message that replied to
const member = msg.member//cache the author of replied to
member.ban(member).then(console.log)//ban the user
.catch(console.error);
}
})

How to get the ID of the user who sent the slash command in Discord.js V13

Just had a simple question, I have some moderation slash commands on discord bot running on Discord.js V13, and I need to get the user ID of the person who runs the slash command. So I can then check for the permissions of the user on the guild to make sure he has the Ban_Members permission per example. And also how do I get the guild ID of where the slash command was executed
Thanks! If I wasn't clear feel free to ask me to clarify something
The code I tried
client.ws.on("INTERACTION_CREATE", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I just receive undefined in the console log
Something else I tried
client.on("interactionCreate", async (interaction) => {
if (interaction.data.component_type) return;
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command == "mute") {
const guildId = interaction.guildId;
console.log(guildId);
// client.api.interactions(interaction.id, interaction.token).callback.post({
// data: {
// type: 4,
// data: {
// embeds: [muteembed],
// ephemeral: "false",
// },
// },
// });
}
});
And I get this error:
if (interaction.data.component_type) return;
^
TypeError: Cannot read properties of undefined (reading 'component_type')
its usually
interaction.user.id
interaction.member.id
The two things you need is a user and a guild. Make sure you check there is a guild, otherwise things will go wrong.
if(!interaction.guild) return; // Returns as there is no guild
var guild = interaction.guild.id;
var userID = interaction.user.id;

discord.js Counting command with webhooks

i'm new in StackOverflow.
I need counting command for my discord bot (discord.js)...
I need that when the user starts counting for example 1, then the bot will delete his message and change the webhook to his name and avatar and send his message and the variable will increase by 1...
This is what I got, but there is an error :(
client.on('message', ({message, channel, content, member}) => {
if (channel.id === 'channel_id') {
let webhookClient = new Discord.WebhookClient('webhook_id', 'webhook_token');
let count = 0;
if (member.user.bot) return
if (Number(content) === count + 1) {
webhookClient.send(count, {
username: content.author.username,
avatarURL: content.author.displayAvatarURL()
});
count++
}
}
})
Error: TypeError: Cannot read property 'username' of undefined
And I would also like the bot to delete all messages that are not associated with the counter, such as words or emoji ... ("hello", "😀")
In order to get the author's username and avatarURL you need to:
username: message.author.username
avatarURL: message.author.displayAvatarURL()
Something like this should work:
client.on('message', async message =>{
if (message.channel.id === 'channel_id') {
let webhookClient = new Discord.WebhookClient('webhook_id', 'webhook_token');
let count = 0;
if (message.author.bot) return;
if (Number(message.content) === count + 1) {
webhookClient.send(count, {
username: message.author.username,
avatarURL: message.author.displayAvatarURL()
});
count++
}
}
});

Discord.js TypeError: Cannot read property 'client' of undefined

I encounter error "TypeError: Cannot read property 'client' of undefined" while writing my command in i think its from this line did i write it correctly? (i'm not quite sure since i'm new to coding and was getting help from a friend) I'm using discord v12 btw
if(client.guilds.cache.get(order.guildID).client.me.hasPermission("CREATE_INSTANT_INVITE")) {
// Send message to cook.
message.reply(`Order has been sent to ${client.guilds.cache.get(order.guildID).name}`);
// Get invite.
}else {
// Bot delivers it's self.
client.channels.cache.get(order.channelID).send(`${client.users.cache.get(order.userID)}, Here is your taco that you ordered. Remember you can do \`.tip [Amount]\` to give us virtual tips, and \`.feedback [Feedback]\` to give us feedback on how we did. ${order.imageURL}`);
// Logs in console.
console.log(colors.green(`The bot did not have the Create Instant Invite Permissions for ${client.guilds.get(order.guildID).name}, so it delivered the taco itself.`));
}
if it was not the problem the full code for the command is here:
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const fsn = require("fs-nextra");
const client = new Discord.Client();
const colors = require("colors");
module.exports = {
name: 'deliver',
description: 'Deliverying an order',
args: 'true',
usage: '<order ID>',
aliases: ['d'],
execute(message) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
if (message.member.roles.cache.find(r => r.id === '745410836901789749')) {
if(message.guild.channels.cache.find(r => r.id === '746423099871985755')) {
fsn.readJSON("./orders.json").then((orderDB) => {
let ticketID = args[1];
let order = orderDB[ticketID];
// If the order doesn't exist.
if(order === undefined) {
message.reply(`Couldn't find order \`${args[1]}\` Try again.`);
return;
}
// Checks status.
if (order.status === "Ready") {
// Delete ticket from database.
delete orderDB[ticketID];
// Writes data to JSON.
fsn.writeJSON("./orders.json", orderDB, {
replacer: null,
spaces: 4
}).then(() => {
// If bot has create instant invite permission.
if(client.guilds.cache.get(order.guildID).client.me.hasPermission("CREATE_INSTANT_INVITE")) {
// Send message to cook.
message.reply(`Order has been sent to ${client.guilds.cache.get(order.guildID).name}`);
// Get invite.
}else {
// Bot delivers it's self.
client.channels.cache.get(order.channelID).send(`${client.users.cache.get(order.userID)}, Here is your taco that you ordered. Remember you can do \`.tip [Amount]\` to give us virtual tips, and \`.feedback [Feedback]\` to give us feedback on how we did. ${order.imageURL}`);
// Logs in console.
console.log(colors.green(`The bot did not have the Create Instant Invite Permissions for ${client.guilds.get(order.guildID).name}, so it delivered the popsicle itself.`));
}
}).catch((err) => {
if (err) {
message.reply(`There was an error while writing to the database! Show the following message to a developer: \`\`\`${err}\`\`\``);
}
});
}else if(order.status === "Unclaimed") {
message.reply("This order hasn't been claimed yet. Run `.claim [Ticket ID]` to claim it.");
}else if(order.status === "Claimed") {
if(message.author.id === order.chef) {
message.reply("You haven't set an image for this order! yet Use `.setorder [Order ID]` to do it.");
}else {
message.reply(`This order hasn't been set an image yet, and only the chef of the order, ${client.users.get(order.chef).username} may set this order.`);
}
}else if(order.status === "Waiting") {
message.reply("This order is in the waiting process right now. Wait a little bit, then run `.deliver [Order ID] to deliver.");
}
});
}else {
message.reply("Please use this command in the correct channel.");
console.log(colors.red(`${message.author.username} used the claim command in the wrong channel.`));
}
}else {
message.reply("You do not have access to this command.");
console.log(colors.red(`${message.author.username} did not have access to the deliver command.`));
}
}
}
You're not required to add client while checking for the client's permissions.
You can simply use the following to check your client's permissions:
if(client.guilds.cache.get(order.guildID).me.hasPermission("CREATE_INSTANT_INVITE")) {
// code here
}

Resources