Trying to catch response but why wont it send? - node.js

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}`);
});

Related

CMD sending multiple embeds instead of one

I made a leaderboard command for my discord bot (v13) but it sends multiple embeds with each user's info individually instead of one whole message. I'm not sure how else to structure this so any help is appreciated.
const profileModel = require("../models/profileSchema");
module.exports = {
name: "leaderboard",
description: "Checks the leaderboard",
aliases: ['lb'],
async execute(client, message, args, cmd, Discord, profileData){
const lbData = await profileModel.find({}).sort({
reputation: -1,
}).limit(5);
for (let counter = 0; counter < lbData.length; ++counter) {
const { userID, health = 0 } = lbData[counter]
const Embed = new Discord.MessageEmbed()
.setColor('#fffffa')
.setTitle('Challenge Leaderboard')
.addFields(
{ name: '\u200b', value: `**${counter + 1}.** <#${userID}> - ${reputation} reputation\n` })
message.channel.send({ embeds: [Embed] });
}
}
}
The reason is the way you send the embed
Inside your for loop you create a new ebed every time and add the fields, where you need to create the embed outisde the for loop, add the field in the for loop and then send the embed
It would look something like:
const Embed = new Discord.MessageEmbed()
.setColor('#fffffa')
.setTitle('Challenge Leaderboard')
for (let counter = 0; counter < lbData.length; ++counter) {
const { userID, health = 0 } = lbData[counter]
Embed.addField({ name: '\u200b', value: `**${counter + 1}.** <#${userID}> - ${reputation} reputation\n` })
}
message.channel.send({ embeds: [Embed] });

Sending a message into all servers where bot is

How do I send one message per guild that my bot is in? It doesn't matter which channel it will be, but I don't know how to code it.
I finally came up with that idea:
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
but it doesn't work.
I'm working with commands handler so it has to be done with module.exports:
module.exports = {
name: "informacja",
aliases: [],
description: "informacja",
async execute(message) {
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
};
My code is not working at all
When I run it - nothing happens, no errors, no messages, just nothing.
tried to logged everything, but still nothing came up.
I also tried to log everything using console.log() but nothing is working
I remind: I need to send one message to all servers where my bot is, but only one channel
You could find a channel on each server where the client can send a message then send:
client.guilds.cache.forEach(guild => {
const channel = guild.channels.cache.find(c => c.type === 'text' && c.permissionFor(client.user.id).has('SEND_MESSAGES'))
if(channel) channel.send('MSG')
.then(() => console.log('Sent on ' + channel.name))
.catch(console.error)
else console.log('On guild ' + guild.name + ' I could not find a channel where I can type.')
})
This is a very simple boilerplate to start with, you can later check channel with id, or smth like that
client.channels.cache.forEach(channel => {
if(channel.type === 'text') channel.send('MSG').then('sent').catch(console.error)
})
v13 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "GUILD_TEXT" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}
v12 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "text" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}

Sending a newly created emoji after guild.emojis.create()

I have an addemoji command and I want it to send the new emoji created after the bot creates it. It sends like :emojiname: instead of the actual emoji added. How can I define the new emoji added? Somebody suggested that I use console.log but I have no idea how to use that information that it puts inside the log.
module.exports = {
name: 'addemoji',
description: 'ping pong',
execute(message, args) {
const Discord = require('discord.js');
const PREFIX = 'ly?';
const load = '<a:loading:824515478939762699>';
if (message.content.startsWith(PREFIX + 'addemoji')) {
if (message.guild.me.permissions.has('USE_EXTERNAL_EMOJIS')) {
if (message.guild.me.permissions.has('MANAGE_EMOJIS')) {
if (message.member.hasPermission('MANAGE_EMOJIS')) {
const match = /<(a?):(.+):(\d+)>/u.exec(message.content);
if (!match)
return message.reply(
'Please include a custom emoji in your message!',
);
// animated will be 'a' if it is animated or '' if it isn't
const [, animated, name, id] = match;
const url = `https://cdn.discordapp.com/emojis/${id}.${
animated ? 'gif' : 'png'
}`;
const user = message.mentions.users.first() || message.author;
const nameid = `<:${name}:${id}>`;
message.guild.emojis.create(url, name);
let newname = console.log(name);
let newid = console.log(id);
const embed = new Discord.MessageEmbed()
.setTitle(`Emoji added! <:${newname}:${newid}>`)
.setColor(0x7732a8);
message.channel.send(embed);
}
}
}
}
}
};
GuildEmojiManager#create() returns a Promise with the newly created emoji. You can access and display the new emoji by handling this promise, then using the <:name:id> wrapper for emoijs
message.guild.emojis.create(url, name).then(newEmoji => {
const embed = new Discord.MessageEmbed()
.setTitle(`Emoji added! <:${newEmoji.name}:${newEmoji.id}>`)
.setColor(0x7732a8)
message.channel.send(embed);
});

How can I make my Discord bot ignore the set prefix for certain commands only? (Discord.js)

I'm very new to Java and trying to code a simple bot. When I first coded this, it did not have a command handler with multiple files, and everything worked. However, while some commands like sending random images still work, I can't figure out a way to make my bot ignore prefixes for certain commands: For example, before my bot could respond to "Where are you?" with "I am here" without having the prefix "!" in front. When I include this command in the index.js file with an if statement it still works, but trying to put it in another file doesn't. I'd really appreciate if anyone could help me with this.
Here is my code:
index.js
const discord = require('discord.js');
const client = new discord.Client({ disableMentions: 'everyone' });
client.config = require('./config/bot');
client.commands = new discord.Collection();
fs.readdirSync('./commands').forEach(dirs => {
const commands = fs.readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));
for (const file of commands) {
const command = require(`./commands/${dirs}/${file}`);
console.log(`Loading command ${file}`);
client.commands.set(command.name.toLowerCase(), command);
};
});
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
};
client.login(client.config.discord.token);
Some of my commands files:
sendrand.js (This one works)
module.exports = {
name: 'sendrand',
category: 'sendpic',
execute(client, message, args) {
var num = 33;
var imgNum = Math.floor(Math.random() * (num - 1 + 1) + 1);
message.channel.send({files: ["./randpics/" + imgNum + ".png"]});
}
};
where.js(This one doesn't)
module.exports = {
name: 'where',
category: 'core',
execute(client, message, args) {
if(message.startsWith('where are you){
message.channel.reply('I am here!)
}
};
I know I could make it so that the bot would respond to "!where are you", but I'd like to have it without the prefix if possible
You could do:
module.exports = {
name: "respond",
category: "general",
execute(client, message) {
if (message.content.toLowerCase().startsWith("where are you")) {
message.reply("I am here!");
}
},
};

Discord.js - Message edit/delete logger error

I'm trying to add a code to my bot that logs whenever a user edits/deletes a message. The bot sends an embed to a specified channel with the information of the event. However, there's this error that I've been stuck on for a long while now, with no identified solution.
Here's the error that follows:
RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
Here's the code:
client.on("messageUpdate", message => {
var messages = []
if(messages.includes(message.id)){return;}
channel = message.guild.channels.cache.get('channelID')
const channel9 = client.channels.cache.find(channel => channel.id === 'id');
const ediembed = new Discord.MessageEmbed()
.setColor(1752220)
.setTitle(":pencil: Message Edited")
.addFields (
{name: "__Channel:__", value: `<\#${message.channel.id}>`},
{name: "__Message Author:__", value: `${message.author.tag} - <\#${message.author.id}>`},
{name: "__Original Message:__", value: message.content}
)
.setTimestamp()
.setThumbnail(message.author.avatarURL())
.setFooter("super cool api")
channel9.send(ediembed)
}
)
2 fixes,
1: you dont need to get channel
2: try sending to channel a different way
client.on("messageUpdate", (message) => {
var messages = [];
if (messages.includes(message.id)) {
return;
}
const ediembed = new Discord.MessageEmbed()
.setColor(1752220)
.setTitle(":pencil: Message Edited")
.addFields(
{ name: "__Channel:__", value: `<\#${message.channel.id}>` },
{
name: "__Message Author:__",
value: `${message.author.tag} - <\#${message.author.id}>`,
},
{ name: "__Original Message:__", value: message.content }
)
.setTimestamp()
.setThumbnail(message.author.avatarURL())
.setFooter("super cool api");
client.channels.cache.get("CHANNEL ID").send(ediembed);
});

Resources