client.on('messageUpdate' ....) not working properly? - discord.js

I'm trying to log when a user edits a message.
Its not really working....
Here is my code:
client.on('messageUpdate', (oldMessage, newMessage) => {
logMessageEdit(oldMessage, newMessage);
});
function logMessageEdit(oldMessage, newMessage) {
if (!newMessage.guild.channels.find('name', "logs")) return;
logChannel = newMessage.guild.channels.find('name', "logs");
let logEmbed = new Discord.RichEmbed()
.setAuthor(newMessage.author.tag, newMessage.author.avatarURL)
.setDescription(`💬 | Meddelande redigerat i ${oldMessage.channel}.`)
.addField("Innan", "test" + oldMessage.content)
.addField("Efter", "test" + newMessage.content)
.setTimestamp()
.setFooter(newMessage.id)
.setColor(greenColor);
logChannel.send(logEmbed)
}
And here is what it results in:

not too familiar with the client.on('messageUpdate') method but the bot is logging its own message sends, not just your messages. try updating your client.on('messageUpdate') method
client.on('messageUpdate', (oldMessage, newMessage) => {
if(newMessage.author.id === client.user.id) return;
logMessageEdit(oldMessage, newMessage);
});
if this doesn't work check for other calls of logMessageEdit such as in the client.on('message') event

Related

TypeError: Cannot read property 'activities' of null

My problem is that when the user starts a game and has the game status in discord, on the console I get the error "TypeError: Unable to read property 'activities' of null"
I hope the bot gives the member a role when starting the game. I'm using a game as an example, I need the function when starting the stream
Discord.js - v13 Code:
const client = require('../index')
client.on('presenceUpdate', function(oldMember, newMember) {
const guild = newMember.guild;
const streamingRole = guild.roles.cache.find(role => role.name === 'Fazendo Live');
// if (newMember.user.bot || newMember.presence.clientStatus === 'mobile' || oldMember.status !== newMember.status) return;
const oldGame = oldMember.activities ? oldMember.activities.find(activity => activity.type === 'PLAYING') : false;
const newGame = newMember.activities ? newMember.activities.find(activity => activity.type === 'PLAYING') : false;
if (!oldGame && newGame) { // Started playing.
newMember.member.roles.add(streamingRole)
.then(() => console.log(`${streamingRole.name} added to ${newMember.user.tag}.`))
.catch(console.error);
}
else if (oldGame && !newGame) { // Stopped playing.
newMember.member.roles.remove(streamingRole)
.then(() => console.log(`${streamingRole.name} removed from ${newMember.user.tag}.`))
.catch(console.error);
}
});
member.activities is not a thing. You need to go through presence first to go through activities.
const oldGame = oldMember.presence.activities ? oldMember.presence.activities.find(activity => activity.type === 'PLAYING') : false;
const newGame = newMember.presence.activities ? newMember.presence.activities.find(activity => activity.type === 'PLAYING') : false;
Did more digging...
...and found out that presenceUpdate actually outputs old and new presences and not the member. So in that way you are correct with
const oldGame = oldMember.activities
Now while doing my own testings I came across that when trying simply doing message.member.presence and console logging that, it comes out as null, and this is because I had no Intents set to my client for GUILD_PRESENCES now when I enabled this, it showed me the activity.
So my guess is that if you are getting null from it, or the error that Cannot read properties of null (reading 'activities') which I got aswell (before declaring intents), you might be setting your intents wrong.
Are you sure you have declared your intents correctly in index.js?
Mine for example:
const { Client, Intents } = require("discord.js");
client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.GUILD_PRESENCES]
});

How to ban user on pinging someone?

I'm trying to make a discord bot on, when pinging the owner, auto bans the author that pinged the player. The issue is, it bans the player for saying anything, how would I make it that it'd only ban if they pinged the owner?
Here's the code.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<#329005206526361610>'
client.once('ready', () => {
console.log("Wary's Defender Bot is up");
});
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
if (mention.startsWith('<#329005206526361610') && mention.endsWith('>')) return {
// mention = mention.slice(2, -1),
return: client.users.cache.get(mention)
}
}
client.on('message', _message => {
// if(!_message.content.users.has('#warycoolio')) return;
const user = getUserFromMention(_message.content);
if(user) return;
console.log('found target')
var member = _message.author
var rMember = _message.guild.member(_message.author)
// ban7, 'lol.'
rMember.ban({ days: 7, reason: 'They deserved it'}); {
// Successmessage
console.log('target dead.')
}
});
You can do this by checking _message.mentions.users with .has() and passing in the guild owner's id.
Use .has() instead of checking message content, this will automatically check the Message#mentions collection.
Dynamically get the guild owner's id using Guild#ownerID.
client.on('message', _message => {
if (_message.mentions.users.has(_message.guild.ownerID)) {
_message.author.ban({ days: 7, reason: 'They deserved it'});
}
});
You could just do a quick check to see if the mentions include a mention to the owner of the server, and then ban the user.
client.on("message", _message => {
if (_message.mentions.users.first().id === "owner id") {
message.author.ban()
}
})

Discord.JS bot not responding to several commmands

My bot is not responding to any commands except for the .purge command.
Here is my code.
const { Client, MessageEmbed } = require('discord.js');
const client = new Client();
const { prefix, token } = require('./config.json');
client.on('ready', () => {
client.user.setStatus('invisible');
console.log('Bot ready!');
client.user.setActivity('Bot is in WIP Do not expect stuff to work', {
type: 'STREAMING',
url: "https://www.twitch.tv/jonkps4"
});
console.log('Changed status!');
});
client.on('message', message => {
if (message.content.startsWith(".") || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (message === 'apply') {
message.reply("The Small Developers Application form link is:")
message.reply("https://forms.gle/nb6QwNySjC63wSMUA")
}
if (message === 'kick') {
const user = message.mentions.users.first();
// If we have a user mentioned
if (user) {
// Now we get the member from the user
const member = message.guild.member(user);
// If the member is in the guild
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
// We let the message author know we were able to kick the person
message.reply(`Successfully kicked ${user.tag}`);
})
.catch(err => {
message.reply('I was unable to kick the member \n Maybe due to I having missing permissions or My role is not the higher than the role the person to kick has');
// Log the error
console.error(err);
});
} else {
// The mentioned user isn't in this guild
message.reply("That user isn't in this guild!");
}
// Otherwise, if no user was mentioned
} else {
message.reply("You didn't mention the user to kick!");
}
}
if (command === 'purge') {
const amount = parseInt(args[0]) + 1;
if (isNaN(amount)) {
return message.reply('Not a valid number');
} else if (amount > 100) {
return message.reply('Too many messages to clear. \n In order to clear the whole channel or clear more please either ```1. Right click on the channel and click Clone Channel``` or ```2. Execute this command again but more times and a number less than 100.```');
} else if (amount <= 1) {
return message.reply('Amount of messages to clear **MUST** not be less than 1 or more than 100.')
}
message.channel.bulkDelete(amount, true).catch(err => {
console.error(err);
message.channel.send('**There was an error trying to prune messages in this channel!**');
});
}
});
client.login(token);
I need a specific command to work which is the .apply command
and i would like to know why my embeds do not work.
I tried this embed example It didn't work.
const embed = new MessageEmbed()
// Set the title of the field
.setTitle('A slick little embed')
// Set the color of the embed
.setColor(0xff0000)
// Set the main content of the embed
.setDescription('Hello, this is a slick embed!');
.setThumbnail('https://tr.rbxcdn.com/23e104f6348dd71d597c3246990b9d84/420/420/Decal/Png')
// Send the embed to the same channel as the message
message.channel.send(embed);
What did I do wrong? I am quite new to Discord.JS Any help would be needed.
You used the message parameter instead of command. Instead of message === 'xxx' put command === 'xxx'. Simple mistake, I think that was what you meant anyways. Of course the purge command worked because you put command === 'purge' there

How to check a users permissions in a certain server

So I am making a DM command and I want to make it so when the user uses the command it will check the users permissions in a certain server. This is my current code:
bot.on("message", async msg => {
if(msg.channel.type === "dm") {
if(msg.content.startsWith(";announce")) {
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await msg.channel.send(Question1)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error = new Discord.MessageEmbed()
.setDescription("You must have a certain permission to do this. If your roles have just been changed, please type `retry` now so I can check again.")
ERRMSG = await msg.channel.send(error)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if(msg2.content === "retry") {
if(msg.member.hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await ERRMSG.edit(Question1)
msg2.delete()
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error2 = new Discord.MessageEmbed()
.setDescription("I still could not find your permissions. Please retry when you have the correct permissions.")
ERRMSG.edit(error2)
msg2.delete()
}
}
})
}
}
}
})
This gives me the error:
(node:347) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
(node:347) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:347) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This just throws this error but I am not sure how I can check the actual permissions in this discord server. How can I manipulate this feature into my Discord Bot?
Well, first of all, you would want to get the guild object of the guild you're referring to, and obviously check if that guild even exists. something that could be done using:
const guildObject = client.guilds.cache.get('place guild id here'); // gets the guild object of the id provided
if (!guildObject) return console.log('Guild could not be found!'); // Would console log in the case that the guild you've provided does not exist.
From there on, we could use the guild object we've found to check if the message author actually exists in this guild, which can be done using
const memberObject = guildObject.member(message.author.id)
if (!memberObject) return console.log('User could not be found in the provided guild!');
Finally, we could determine whether or not the user has the wanted permissions using:
if (!memberObject.hasPermission('Permission here')) return console.log('User does not have the corresponding permissions needed!')
The error you get comes from this line:
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS"))
What are you checking with this line of code? If the author has permission?
You can check if the author has permission by doing:
if(msg.guild.member(msg.author).hasPermission("BAN_MEMBERS"))

Edit message in a specific channel in a specific guild | Discord.js

Hello
(I'm French so sorry for my bad English)
I want my bot to edit a message in a specific channel, I tried lots of codes but none of them worked.
let channels = Bot.guilds.find(g => g.id == "guild id").channels.filter(c => c.id == "another guild id").array();
channels.forEach(channel => {
channel.fetchMessage("message id").edit("Message Edited");
);
I also tried with for etc... channel is defined, but it can't fetch any message...
I don't even know if I can do that...
Thanks for helping me !
You can use the get() and find() methods to do so as shown below.
// Note: This code must be inside of an async function.
const guild = bot.guilds.get('guildIDhere');
if (!guild) return console.log('Unable to find guild.');
const channel = guild.channels.find(c => c.id === 'channelIDhere' && c.type === 'text');
if (!channel) return console.log('Unable to find channel.');
try {
const message = await channel.fetchMessage('messageIDhere');
if (!message) return console.log('Unable to find message.');
await message.edit('Test.');
console.log('Done.');
} catch(err) {
console.error(err);
}

Resources