Fetch bots own message - discord.js

Trying to make a ping command, want to edit the "Pinging..." command with a embed, but do not know how i can get the info for the "Pinging..." command
Here's my code:
}else if(command === "ping"){
const msg = message.channel.send('Pinging...');//.then(fetch);
const msginfo = Discord.TextChannel.message.fetch(msg);
console.log(msginfo);
const embedPing = new Discord.MessageEmbed()
.setColor(0xC1CCDE)
.setTitle('Pong!')
.setDescription(`Bot Latency is **${Math.floor(msg.createdTimestamp - message.createdTimestamp)} ms** \nAPI Latency is **${Math.round(client.ws.ping)} ms**`);
setTimeout(() => message.channel.send(embedPing), 100);

You can just add await to the message.channel.send and then edit the message with the latency information
const msg = await message.channel.send('Pinging...');
msg.edit(`Bot Latency is **${Math.floor(msg.createdTimestamp - message.createdTimestamp)} ms** \nAPI Latency is **${Math.round(client.ws.ping)} ms**`);

Related

Discord bot join/leave channel change separately per guild

I am trying to find out how to make a command that detects a channel from separate guilds (etc. $setwelcome #channel). I have made the command but, instead of setting it for one guild its setting it for all guilds. this is my code
client.on('guildMemberAdd', member => {
console.log("New member joined.");
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel){
console.log("The joinChannel does not exist.");
}else{
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
member.roles.add(member.guild.roles.cache.find(i => i.name === 'member'));
}
});
/*const channel = member.guild.channels.cach.find((ch) => {
console.log(ch.name);
return ch.name === joinChannel;*/
client.on('guildMemberRemove', member =>{
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Goodbye ${member}, we will miss you :cry:`);
})
client.on("message", message => {
if (!message.author.bot){
const content = message.content;
if (content.toLowerCase().startsWith(`${prefix}setwelcome`)){
joinChannel = content.substring((`${prefix}setwelcome`).length).trim();
console.log(`Join channel changed to ${joinChannel}`);
}
}
});
I guess you could use JSON, best in a database, or different file:
//how the JSON should look like
{
"G123456789012345678": "123456789012345678"
}
//first part is the guild ID, second, is the id the channel you choose
Now you have to somehow modify this data, for this I will use fs, which assumes that this is in the file system. I’ll reference it as if it was in the same folder, and is named: welcomeChannels.json
const fs = require('fs');
//maybe other "requires"
client.on('message', msg => {
//checking message content etc
let ChansString = fs.readFileSync('./welcomeChannels.json');
let chans = JSON.parse(ChansString);
//you can get the channel for the guild with chans['G'+guild.id]
chans['G'+msg.guild.id] = msg.mentions.channels.first().id || msg.channel.id;
fs.writeFileSync('./welcomeChannels.json', JSON.stringify(chans));
})
//use chans[`G${guild.id}`] to get the welcome channel id
Warning: this could fill up your storage. You should use a database instead.

Send Server Message after Track Users Status (discord.js)

I try to send a Message in a Server. This Server ID is logged in MongoDB and the Channel ID too. But everytime i'll try it, it does not working. Here's my Code:
The Error is the return console.log Text
//This is the guildMemberUpdate file
const client = require("../index.js")
const {MessageEmbed} = require("discord.js")
const {RED, GREEN, BLUE} = require("../commands/jsons/colors.json")
const Schema = require("../models/StatusTracker.js")
client.on("guildMemberUpdate", async(member) => {
const data = await Schema.findOne({Guild: member.guild.id})
let channel = member.guild.channels.cache.get(data.Channel)
if(!channel) return console.log("Es wurde kein Channels gefunden");
if(member.user.presence.status === "offline") {
let offlineEmbed = new MessageEmbed()
.setColor(RED)
.setDescription(member.user.toString() + " ist jetzt offline!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(offlineEmbed)
} else if(member.user.presence.status === "dnd" || member.user.presence.status === "online" || member.user.presence.status === "idle"){
let onlineEmbed = new MessageEmbed()
.setColor(GREEN)
.setDescription(member.user.toString() + " ist jetzt online!")
.setAuthor(member.user.tag, member.user.avatarURL({ dynamic: true }))
channel.send(onlineEmbed)
}
})```
//This is the MongoDB File
"Guild": "851487615358337065",
"Channel": "859444321975009290"
The problem is that you're using the guildMemberUpdate event, but that only tracks nickname and role changes. The one that you're looking for is presenceUpdate. That'll trigger when any user goes offline etc.
Check the docs for more details: here
Note: You'll probably need to enable 'Presence intent' in 'Privileged Gateway Intents' in your bot's settings page for this to work. (https://discord.com/developers/applications)

discord.js can not read property'id' of undefined when bulk delete messages

I have been working on a bulk delete message logs, but for whatever reason it can not get the ID of the channel from the guild in a seperate file. so it returns that ID is undefined.
THE CODE
module.exports = async (bot, messages) => {
const length = messages.array().length
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
let mEmbed = new MessageEmbed()
.setAuthor(messages.guild.name, messages.guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
In the index file I specified the
messageDeleteBulk
When trying to send the message to the messageChannel it does not send because 'id' is undefined. Is there something I am missing?
So, the command works fine all I forgot was that earlier when I defined length I used
messages.first()so where I just put messages I have to add .first()
THE NEW CODE
module.exports = async (bot, messages) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[messages.first().guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
const length = messages.array().length;
let mEmbed = new MessageEmbed()
.setAuthor(messages.first().guild.name, messages.first().guild.iconURL({dynamic: true}))
.setColor(red_light)
.setDescription(`**Bulk Delete in <#${messages.first().channel.id}>, ${length} messages deleted.**`)
.setTimestamp()
msgChannel.send(mEmbed)
}
Now it logs the bulk deleted messages and does not return any errors.

How do i delete a message in discord.js v12

I have made a bot, and when I updated to discord.js v12 I change the code to v12 but I get this error
here is my code
I have tried to uninstall and then install the discord.js
const Discord = require("discord.js");
const bot = new Discord.Client();
module.exports.run = async (bot, message, args) => {
message.delete();
let totalSeconds = (bot.uptime / 1000);
totalSeconds %= 86400;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let uptimeEmbed = new Discord.MessageEmbed()
.setDescription(`${bot.user.username} Bot Uptime`)
.setColor("#e56b00")
.addField("Hours", hours)
.addField("Minutes", minutes)
.setTimestamp()
.setFooter(`Lavet`)
message.channel.send(uptimeEmbed).then(message.delete({ timeout: 5000 })).catch(console.error)
}
module.exports.help = {
name: "uptime" //NAVNET ER LIG MED KOMMANDOEN
}
This is the error I get when I try
C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\rest\RequestHandler.js:154
throw new DiscordAPIError(request.path, data, request.method, res.status);
^
DiscordAPIError: Unknown Message
at RequestHandler.execute (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async MessageManager.delete (C:\Users\lauri\Desktop\QuebecCity\node_modules\discord.js\src\managers\MessageManager.js:126:5) {
method: 'delete',
path: '/channels/791725159362330635/messages/798219060780466196',
code: 10008,
httpStatus: 404
}
In your code, you try to delete the same message twice.
First, in message.delete();, and next in
message.channel.send(uptimeEmbed).then(message.delete({ timeout: 5000 })).catch(console.error)
For context, error code 10008 in the Discord API means that the message could not be found, which makes sense in the current situation.
In order to fix this, assuming that the second message.delete is trying to delete the uptimeEmbed message sent by the bot, you can do this:
module.exports.run = async (bot, message, args) => {
let channel = message.channel;
message.delete();
let totalSeconds = (bot.uptime / 1000);
totalSeconds %= 86400;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let uptimeEmbed = new Discord.MessageEmbed()
.setDescription(`${bot.user.username} Bot Uptime`)
.setColor("#e56b00")
.addField("Hours", hours)
.addField("Minutes", minutes)
.setTimestamp()
.setFooter(`Lavet`)
channel.send(uptimeEmbed).then(msg => msg.delete({ timeout: 5000 })).catch(console.error);
}
Instead of attempting to delete the same message twice, this stores the channel in a variable, send the message to the channel, and then deletes its own message.

How to make this bot listen to argument after prefix and answer?

so i'm trying this 8ball bot, and everything is working fine, but i can't get how can i leave in the condition that only when the bot get "!verda arg1 arg2" it answers one of the replies in the array.
meanwhile my condition is if the user type the prefix "!verda" only, it replies , i want to include the argument too in the condition
const Discord = require("discord.js");
const client = new Discord.Client();
const cfg = require("./config.json");
const prefix = cfg.prefix;
client.on("message", msg => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase;
if (msg.content === prefix){
let replies = [
"Yes.",
"No.",
"I don't know.",
"Maybe."
];
let result = Math.floor((Math.random() * replies.length));
msg.channel.send(replies[result]);
}
else if (msg.content === "!help"){
msg.channel.send("I have only 1 command [!verda]");
}
})
client.login(cfg.token);
const command = args.shift().toLowerCase;
toLowerCase is a function and therefore should be
const command = args.shift().toLowerCase();
By doing msg.content === prefix, you are checking if the whole content of the message is equal to that of cfg.prefix
if(msg.content.startsWith(`${prefix}8ball`) {
}
The answer was simple as i figured it out, i simply had to join the spaces
if (msg.content === `${prefix} ${args.join(" ")}`)

Resources