How do I check if the bot has permmsion to manage webhooks? - discord.js

My problem is that I'm getting an error whenever I use the following code:
else if (cmd === "sayw") {
const embed2 = new Discord.RichEmbed()
.setDescription("❌ You can't make me say nothing! \nWait, you just did-")
.setFooter(`Requsted by ${message.author.tag}.`, message.author.avatarURL)
if(!args[0]) return message.channel.send(embed2)
const guild = message.guild
const embed = new Discord.RichEmbed()
.setAuthor("Say Webhook", bot.user.avatarURL)
.setDescription("❌ I need the `MANAGE_WEBHOOKS` permision first!" )
.setImage(`https://i.gyazo.com/d1d5dc57aa1dd20d38a22b2f0d4bd2f6.png`)
const member = guild.members.get(bot.id)
if (member.hasPermission("MANAGE_WEBHOOKS")) {
message.channel.createWebhook(message.author.username, message.author.avatarURL)
.then(webhook => webhook.edit(message.author.username, message.author.avatarURL))
.then(wb => {wb.send(args.join(" "))
setTimeout(() => {
bot.fetchWebhook(wb.id, wb.token)
.then(webhook => {
console.log("deleted!")
webhook.delete("Deleted!")
}, 5000)})})
} else {
message.channel.send(embed)
}}
I want the bot to tell the user if it can't create the webhook, but instead, I get this error when trying to use this command:
(node:10044) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'hasPermission' of undefined
How do I make this code work?

If you're using Discord.js v12 (the latest verison), guild.members.get(bot.id) won't work as guild.memebrs is now a GuildMemberManager.
Use
const member = guild.members.cache.get(bot.id)
or you could even use this as a shortcut:
const member = guild.me

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

Discord JS - forEach looped embed

I'm quite new to Javascript, normally a Python person. I've looked at some other answers but my embed does not add the fields as expected. The embed itself is sent.
My Discord bot follows the guide provided by the devs (primary file, slash commands, command files). I am trying to loop through the entries in an SQLite query and add them as fields.
My command file is below.
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
const sqlite = require('sqlite3').verbose();
module.exports = {
data: new SlashCommandBuilder()
.setName('rank')
.setDescription('Rank all points.'),
async execute(interaction) {
const rankEmbed = new MessageEmbed()
.setColor('#0099ff')
.setTitle('Rank Board')
let db = new sqlite.Database('./databases/ranktest.db', sqlite.OPEN_READWRITE);
let queryall = 'SELECT name, points FROM pointstable ORDER BY points DESC'
db.all(queryall, [], (err, rows) => {
if (err) {
console.log('There was an error');
} else {
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, true);
});
}
})
return interaction.reply({embeds: [ rankEmbed ] });
}
}
I would also like to convert row.name - held as Discord IDs - to usernames i.e. MYNAME#0001. How do I do this by interaction? I was able to obtain the User ID in another command by using interaction.member.id, but in this case I need to grab them from the guild. In Python I did this with await client.fetch_user but in this case the error await is only valid in async functions and the top level bodies of modules is thrown.
Thanks.
OK I've solved the first aspect, I had the return interaction.reply in the wrong place.
Relevant snippet:
rows.forEach((row) => {
console.log(row.name, row.points)
rankEmbed.addField('\u200b', `${row.name}: ${row.points}`, false);
})
return interaction.reply({embeds: [rankEmbed ]} );
Would still appreciate an answer to the converting row.name (user ID) to user name via fetch.
I've solved the second aspect also. Add the below into the loop.
rows.forEach((row) => {
let client = interaction.client
const uname = client.users.cache.get(row.name);
rankEmbed.addField('\u200b', `${uname}: ${row.points}`, false);

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

discord.js v12 | TypeError: Cannot read property 'send' of undefined

Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.

Block Kick or set Limit to Kick Discord.js

hello I don't want the mods to do kick action in my server i see discord.js doesnt add guildKickAdd like guildMemberAdd
so how can i block kick or set limit kick ?
this is ban block when someone do ban action bot taking roles and gives him punished.
client.on("guildBanAdd", async function(guild, user) {
const entry = await guild
.fetchAuditLogs({ type: "MEMBER_BAN_ADD" })
.then(audit => audit.entries.first());
const yetkili = await guild.members.get(entry.executor.id);
setTimeout(async () => {
let logs = await guild.fetchAuditLogs({ type: "MEMBER_BAN_ADD" });
if (logs.entries.first().executor.bot) return;
guild.members
.get(logs.entries.first().executor.id)
.removeRoles(guild.members.get(logs.entries.first().executor.id).roles); ///TÜM ROLLERİNİ ALIR
setTimeout(() => {
guild.members
.get(logs.entries.first().executor.id)
.addRole("633026228537917460"); /// VERİLECEK CEZALI ROL İD
}, 3000);
const sChannel = guild.channels.find(c => c.id === "641032067840344064");
const cıks = new Discord.RichEmbed()
.setColor("RANDOM")
.setDescription(
`<#${yetkili.id}> ${user} adlı Kişiye Sağ tık ban Atıldığı için Banlayan Kişinin Yetkileri Alındı`
)
.setFooter("Created by Tokuchi");
sChannel.send(cıks);
guild.owner.send(
`Tokuchi Affetmez † Guard | ** <#${yetkili.id}> İsimili Yetkili <#${user.id}>** Adlı Kişiyi Banladı Ve Yetkilerini Aldım.`
);
}, 2000);
});```
You need to use guildMemberRemove event:
// When a member left. Maybe he left himself, but maybe he was kicked.
client.on("guildMemberRemove", (member) => {
// Get the last kick case of the server
const entry = await guild
.fetchAuditLogs({ type: "MEMBER_KICK" })
.then(audit => audit.entries.first());
// if there's not any kick case in this server
if(!entry) return;
// if the target was not the member who left
if(entry.target.id !== member.id) return;
// Else, you know the member was kicked, and you have the entry so you can do what you want
});
This is the best way to know if someone was kicked.

Resources