Node.js and Discord.js error Message by Coding a DC Bot - node.js

I'm trying to program a Discord Bot but I get an error message every time
error Message:
Cannot read properties of undefined (reading 'FLAGS')
My Code:
const Discord = require("discord.js");
const config = require("./config.json");
const client = new Discord.Client({
restTimeOffset: 0,
allowedMentions: {
prase: [/* "rolea", "users" */],
repliedUser: true ,
},
pratials: [ "MESSAGE", "CHANNEL", "REACTION" ],
intents: [
Discord.Intents.FLAGS.GUILDS,
//Discord.Intents.FLAGS.GUILD_MEMBERS,
//Discord.Intents.FLAGS.GUILD_BANS,
//Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
//Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
//Discord.Intents.FLAGS.GUILD_WEBHOKKS,
//Discord.Intents.FLAGS.GUILD_INVITES,
//Discord.Intents.FLAGS.GUILD_VOUCE_STATES,
//Discord.Intents.FLAGS.GUILD_PRESENCES,
Discord.Intents.FLAGS.GUILD_MESSAGES,
//Discord.Intents.FLAGS.GUILD_MESSAG_REACTIONS,
//Discord.Intents.FLAGS.GUILD_TYPING,
],
presence: {
activity: {
name: "Cool Tut",
type: "WATCHING",
url: "https://www.twitch.tv/LeCharismo"
},
status: "dnd"
}
});
const bot = client;
client.login(config.token)
/*---------------------------------------------------------------------------*/
bot.once("ready", () =>{
console.log("The Bot is online");
});
bot.on("message", message => {
console.log("a new message was send");
console.log(message);
console.log(message.content);
})
Can anyone help me I've searched a lot on the internet but couldn't find anything
I don't know what else I can do and because I'm just starting out I don't really know the programming language and that makes it even more jarring for me

Related

Discord.js | interaction.reply is not a function [SlashCommand][Typescript]

I am making a /ping command in my bot, following the discordjs guide, but when I use the command, I get an error:
TypeError: interaction.reply is not a function
at Object.<anonymous> (C:\Users\timda\code\discord bot\bot-data\commands\ping.ts:8:15)
at Generator.next (<anonymous>)
at C:\Users\timda\code\discord bot\bot-data\commands\ping.ts:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\timda\code\discord bot\bot-data\commands\ping.ts:4:12)
at Object.execute (C:\Users\timda\code\discord bot\bot-data\commands\ping.ts:18:16)
at C:\Users\timda\code\discord bot\main.ts:43:18
at Generator.next (<anonymous>)
at C:\Users\timda\code\discord bot\main.ts:8:71
at new Promise (<anonymous>)
This is the /ping commands code:
import { SlashCommandBuilder } from 'discord.js';
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction: { reply: (arg0: string) => any }) {
console.log(interaction);
interaction.reply('Pong!');
},
};
And here is the code in my main file that loads in the SlashCommand files:
import fs from 'node:fs';
import path from 'node:path';
import { Client, Collection, GatewayIntentBits, Partials, REST, Routes } from 'discord.js';
import { clientId, token } from './config.json';
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent],
partials: [Partials.Message, Partials.Channel],
presence: { status: 'online', activities: [{ name: 'you 👀', type: 3 }] }
});
(client as any).commands = new Collection();
const commands: any[] = [];
for (const file of (fs.readdirSync(path.join('./bot-data/commands')).filter(file => file.endsWith('.ts')))) {
const command = require(`./bot-data/commands/${file}`);
(client as any).commands.set(command.data.name, command);
commands.push(command.data.toJSON());
};
client.on('ready', async (client: { user: { tag: any; }; }) => {
const rest = new REST({ version: '10' }).setToken(token);
try {
await rest.put(Routes.applicationCommands(clientId), { body: commands});
} catch (error) {
console.error(error);
}
console.log(`Succesfully logged in as ${client.user.tag}!`);
});
client.on('interactionCreate', async interaction => {
if(interaction.isCommand()) {
const command = (client as any).commands.get(interaction.commandName);
if (!command) {
await interaction.reply({content: `Something went wrong while executing ${interaction.commandName}.`, ephemeral: true});
return;
}
try {
await command.execute(client, interaction);
} catch (error) {
await interaction.reply({content: `Something went wrong while executing ${interaction.commandName}., ephemeral: true});
console.error(error);
}
}
});
The command does get loaded when /ping is used, because it does log the interaction in the console.
I am writing the bot in Typescript, that's why I did interaction: { reply: (arg0: string) => any }
and I'm using node to compile and run it.
NVM: version 1.1.10
NPM: version 8.19.2
I've tried writing interaction: { reply: (arg0: string) => any } in different ways and I've also already done a lot of googling, but I can't find the problem I'm facing here.
If someone could help me I would appreciate it.
Inside of main.ts, you're calling the execute function with these arguments:
await command.execute(client, interaction);
But inside of ping.ts, you're only accepting these arguments:
async execute(interaction: { reply: (arg0: string) => any }) { // etc
You need to include both client and interaction as arguments in ping.ts to prevent the values being passed into the wrong variables.
// I'm fairly certain that these are the right imports
import { BaseInteraction, SlashCommandBuilder, Client} from 'discord.js';
...
async execute(client: Client, interaction: BaseInteraction) { // etc

How to send a message to all members who have a role from person with role, that have permission to use this cmd (discord.js)

I'm coding a bot using discord.js. I would like to send a <message> to all members who have <role> when person with role, that have permission to use command:
/send <role> <message>
in a channel.
How can I do this?
I copied and slightly remade this topic, because in the original one the answer was irrelevant at the moment
I tried a similar theme, but it is not relevant at the moment
related question
Try this
const {
SlashCommandBuilder
} = require('#discordjs/builders')
module.exports = {
data: new SlashCommandBuilder()
.setName('newsletter')
.setDescription('Send a message to members by role')
.addRoleOption(option =>
option
.setName('role')
.setDescription('What role')
.setRequired(true))
.addStringOption(option =>
option
.setName('message')
.setDescription('What is the message.')
.setRequired(true)),
async execute(client, interaction) {
const guild = client.guilds.cache.get('959899135258026055')
const role2have = [
'54654546545645656',
'65465456465456465456'
]
if (interaction.member.roles.cache.some(role => role2have.includes(role.id))) {
const role = guild.roles.cache.get(interaction.options.getRole('role').id)
console.log(role)
role.members.forEach(member => {
member.send({
content: `${interaction.options.getString('message')}`
}).catch((err) => {
console.log(`Unable to DM ${member.user.username} - received error:\n${err}`)
})
})
return interaction.reply({
content: 'Message sent',
ephemeral: true
})
} else {
return interaction.reply({
content: 'You do not have permission to use this command',
ephemeral: true
})
}
}
}
This command is then executed:
/newsletter role: #role message: message content

Discord.js maximum number of webhooks error

Have this slash command code and turned it into webhook. It worked when I used it once but it stopped working after that. I got this error DiscordAPIError: Maximum number of webhooks reached (10). Does anyone have any idea on how to fix this?
Code:
run: async (client, interaction, args) => {
if(!interaction.member.permissions.has('MANAGE_CHANNELS')) {
return interaction.followUp({content: 'You don\'t have the required permission!', ephemeral: true})
}
const [subcommand] = args;
const embedevent = new MessageEmbed()
if(subcommand === 'create'){
const eventname = args[1]
const prize = args[2]
const sponsor = args[3]
embedevent.setDescription(`__**Event**__ <a:w_right_arrow:945334672987127869> ${eventname}\n__**Prize**__ <a:w_right_arrow:945334672987127869> ${prize}\n__**Donor**__ <a:w_right_arrow:945334672987127869> ${sponsor}`)
embedevent.setFooter(`${interaction.guild.name}`, `${interaction.guild.iconURL({ format: 'png', dynamic: true })}`)
embedevent.setTimestamp()
}
await interaction.followUp({content: `Event started!`}).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
}
}
You cannot fix that error, discord limits webhooks per channel (10 webhooks per channel).
However, if you don't want your code to return an error you can just chock that code into a try catch or add a .catch
Here is an example of how to handle the error:
try {
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
} catch(e) {
return // do here something if there is an error
}

Can you mass kick people from a server using discord.js

So I want to have a moderation bot that kicks all members with a certain role e.g. "unverified" from the server.
1, is this possible?
2, is this allowed, or would it possibly be a Discord API Breach?
I have a normal kick/ ban command and despite searching the web for ages I can't find any answers. Any help would be hugely appreciated. Thanks in advance.
Yes it is possible, you would just have to be able to group them somehow, (say the role you mentioned for instance) and then run a forEach() on it and kick.
Is it allowed, yes.
Is it a breach: unclear depends on how many you are kicking but these commands will only kick in small groups (5 per 5 seconds).
Example below:
regular command:
(prefix)purge RoleName Reason
const { Discord, Permissions } = require('discord.js')
module.exports.run = async (client, message, args) => {
if (!message.member.Permissions.has("ADMINISTRATOR")) {
//handle however if they are not admin
} else {
let kicked = []
const role = message.guild.roles.cache.find(r => r.name === args[0])
args.shift()
const kickReason = args.join(' ') || 'No Reason'
message.guild.members.forEach(member => {
if (member.roles.has(role)) {
kicked.push(member)
member.kick({
reason: kickReason
})
}
})
const completeEmbed = new Discord.MessageEmbed()
.setTitle('Purge')
.setDescription(`Members with the following role have been purged "${role.name}".`)
.addField({
name: `The members kicked were:`,
value: `${kicked.join('\n')}`
})
message.channel.send({
embeds: [completeEmbed],
ephemeral: true
})
}
}
module.exports.help = {
name: "purge",
description: "Kick members with a certain role",
usage: "(prefix)purge [RoleName] [Reason]"
}
And as a slash command (interaction): and can be built differently if needed.
/purge role: Rolename reason: reason
const { Discord, Permissions, SlashCommandBuilder } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('purge')
.setDescription('Purge server of role')
.addRoleOption(option =>
option
.setName('role')
.setDescription('Which role to purge')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('Reason for purge.')
.setRequired(true)),
async execute(client, interaction) {
const reason4Kick = interaction.options.getString('reason')
const role2Kick = interaction.options.getRole('role')
if (!interaction.member.Permission.has('ADMINISTRATOR')) {
// handle if user doesn't have permission to run
return
} else {
let kicked = []
interaction.guild.members.forEach(member => {
if (member.roles.has(role2Kick)) {
kicked.push(member)
member.kick({
reason: reason4Kick
})
}
})
const completeEmbed = new Discord.MessageEmbed()
.setTitle('Purge')
.setDescription(`Members with the following role have been purged "${role.name}".`)
.addField({
name: `The members kicked were:`,
value: `${kicked.join('\n')}`
})
interaction.channel.reply({
embeds: [completeEmbed],
ephemeral: true
})
}
}
}

How to export and import functions for telegrams bot?

I'm create a bot telegram with two buttons. On each button I want to hang the action. I want to transfer these actions to another file. How can I do that?
const Telegraf = require("telegraf");
const session = require("telegraf/session");
const Composer = require('telegraf/composer');
const bot = new Telegraf('Token')
const first = require('./command/first');
bot.command('start', (ctx) => {
const markdown = `
Hi! Click on the button 1 or 2!`;
ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
parse_mode: 'Markdown',
reply_markup: {
keyboard: [
['1', '2'],
],
resize_keyboard: true
},
disable_notification: false
});
});
bot.use(session());
bot.use(Telegraf.log())
bot.on('1', first.hears()) ///myfunction command
bot.startPolling();
console.log(Telegraf.log());
and file ./command/first
module.exports = {
hears: function () {
console.log("debug 1");
bot.action('1', (ctx) => {
const markdown = ` Type some text...`;
ctx.telegram.sendMessage(ctx.message.chat.id, markdown, {
parse_mode: 'Markdown',
reply_markup: {
keyboard: [
['🔙 Back'],
],
resize_keyboard: true
},
disable_notification: false
});
})
}
};
but nothing works. When starting the bot writes immediately debug 1
And nothing.. Help me please!
Firstly Change:
bot.on('1', first.hears()) // on is for events
to
bot.hears('1', first.hears()) // hears listens for the specified string from bot
Then rewrite the module in /command/first to:
module.exports = {
hears: function (ctx) {
console.log("debug 1");
// Added markdown formatting
const message = `*Bold text* and _italic text_`;
ctx.telegram.sendMessage(ctx.message.chat.id, message, {
parse_mode: 'Markdown',
reply_markup: JSON.stringify({ // You also missed JSON.stringify()
keyboard: [
['🔙 Back'],
],
resize_keyboard: true
}),
disable_notification: false
});
}
}
This should work. I hope this helps.

Resources