Discord JS Commands Not Sending/Responding to Commands - node.js

I am coding a discord bot in discord.js. I am trying to implement some basic commands.
My problem: every time I try to run a command the bot does not respond. Can anybody help me?
This is my code:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (commandName === 'ping') {
await interaction.reply('Pong!');
} else if (commandName === 'beep') {
await interaction.reply('Boop!');
} else if (commandName === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members:
${interaction.guild.memberCount}`);
} else if (commandName === 'user-info') {
await interaction.reply(`Your username: ${interaction.user.username}\nYour ID:
${interaction.user.id}`);
}
});
client.login('MY TOKEN');

Related

Error connecting Chatgpt API to Discord Server

I'm trying to use the ChatGPT Api and connect to a discord bot but I am getting this error. Can anyone show me how to fix this?
Error
ReferenceError: require is not defined in ES module scope, you can use
import instead This file is being treated as an ES module because it
has a '.js' file extension and
'C:\Users\jkru0\OneDrive\Desktop\gpt\package.json' contains "type":
"module". To treat it as a CommonJS script, rename it to use the
'.cjs' file extension.
Full Code
import Discord from 'discord.js';
import { ChatGPTAPI } from 'chatgpt';
import readline from 'readline';
const apiKey = 'hidden';
const api = new ChatGPTAPI({ apiKey });
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
let conversationId;
let parentMessageId;
async function sendMessage(message, channel) {
let res = await api.sendMessage(message, {
conversationId: conversationId,
parentMessageId: parentMessageId
});
conversationId = res.conversationId;
parentMessageId = res.id;
console.log('\nBot:', res.text, '\n');
if (channel) {
await channel.send(res.text);
}
}
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async (message) => {
if (message.author.bot) return;
if (message.content === 'quit') {
process.exit();
}
await sendMessage(message.content, message.channel);
});
async function main() {
await sendMessage('Hello World!');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askQuestion() {
rl.question('\nYou: ', async (question) => {
if (question === 'quit') {
rl.close();
process.exit();
}
await sendMessage(question);
askQuestion();
});
}
askQuestion();
}
client.login('hidden');
main();
The error message is telling you that you cannot use require in an ES module, and you should use import instead. However, in your code, you are using both require and import statements.
It is a simple fix by replacing require with import
Example:
import Discord, { Client, Intents } from 'discord.js';
Full Code:
import Discord, { Client, Intents } from 'discord.js';
import { ChatGPTAPI } from 'chatgpt';
import readline from 'readline';
const apiKey = 'hidden';
const api = new ChatGPTAPI({ apiKey });
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
let conversationId;
let parentMessageId;
async function sendMessage(message, channel) {
let res = await api.sendMessage(message, {
conversationId: conversationId,
parentMessageId: parentMessageId
});
conversationId = res.conversationId;
parentMessageId = res.id;
console.log('\nBot:', res.text, '\n');
if (channel) {
await channel.send(res.text);
}
}
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async (message) => {
if (message.author.bot) return;
if (message.content === 'quit') {
process.exit();
}
await sendMessage(message.content, message.channel);
});
async function main() {
await sendMessage('Hello World!');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askQuestion() {
rl.question('\nYou: ', async (question) => {
if (question === 'quit') {
rl.close();
process.exit();
}
await sendMessage(question);
askQuestion();
});
}
askQuestion();
}
client.login('hidden');
main();

TypeError: Cannot read property 'user' of undefined discord.js

So I was trying to fix this thing for a few hours now, and I have no idea what I'm doing wrong.
This thing should execute itself when member joins the guild
const { Discord, MessageEmbed } = require("discord.js")
module.exports = {
name: "guildMemberAdd",
run: async ({bot, member}) => {
const welcome = new MessageEmbed()
.setDescription(`
<:nezuko_peek:974066160108732517> — New friend just showed up: <#${member.user.id}>
Welcome fellow adventurer in **Jasmine Dragon**! What brings you in these sides? <:girl_love:973968823449436190> Here, go to <#972618593294512128> to introduce yourself and talk with us in <#971800237507248158>!
`)
.setImage("https://64.media.tumblr.com/01a9f72f062feaafa60cdbf80f9ba729/tumblr_inline_orgoyznIM51sd5e91_500.gif")
.setColor("#F7DF79")
.setFooter({ text: "Thank you for joining and enjoy your stay!" })
member.guild.channels.cache.get("971800237507248158").send({ content: `<#&974343947105206382>`, embeds: [welcome] })
}
}
Here's my event handler
const { getFiles } = require("../util/functions")
module.exports = (bot, reload) => {
const {client} = bot
let events = getFiles("./events/", ".js")
if (events.length === 0){
console.log("No events to load")
}
events.forEach((f, i) => {
if (reload)
delete require.cache[require.resolve(`../events/${f}`)]
const event = require(`../events/${f}`)
client.events.set(event.name, event)
if (!reload)
console.log (`${i + 1}. ${f} loaded`)
})
if (!reload)
initEvents(bot)
}
function triggerEventHandler(bot, event, ...args){
const {client} = bot
try {
if (client.events.has(event))
client.events.get(event).run(bot, ...args)
else
throw new Error(`Event ${event} does not exist`)
}
catch(err){
console.error(err)
}
}
function initEvents(bot) {
const {client} = bot
client.on("ready", () => {
triggerEventHandler(bot, "ready")
})
client.on("messageCreate", (message) => {
triggerEventHandler(bot, "messageCreate", message)
})
client.on("guildMemberAdd", () => {
triggerEventHandler(bot, "guildMemberAdd")
})
}
And here's my index.js
const Discord = require("discord.js")
require("dotenv").config()
const { MessageEmbed, MessageActionRow, MessageSelectMenu } = require("discord.js")
const slashcommands = require("./handlers/slashcommands")
const client = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS"
]
})
// Bot config
let bot = {
client,
prefix: "i?",
owners: ["511889215672287242"]
}
// Handlers
client.commands = new Discord.Collection()
client.events = new Discord.Collection()
client.slashcommands = new Discord.Collection()
client.loadEvents = (bot, reload) => require("./handlers/events")(bot, reload)
client.loadCommands = (bot, reload) => require("./handlers/commands")(bot, reload)
client.loadSlashCommands = (bot, reload) => require("./handlers/slashcommands")(bot, reload)
client.loadEvents(bot, false)
client.loadCommands(bot, false)
client.loadSlashCommands(bot, false)
// Slash commands handler
client.on("interactionCreate", (interaction) => {
if (!interaction.isCommand()) return
if (!interaction.inGuild()) return interaction.reply("This command can only be used in a server")
const slashcmd = client.slashcommands.get(interaction.commandName)
if (!slashcmd) return interaction.reply("Invalid slash command")
if (slashcmd.perm && !interaction.member.permissions.has(slashcmd.perm))
return interaction.reply("You don not have permission for this command")
slashcmd.run(client, interaction)
})
module.exports = bot
client.login(process.env.TOKEN)
Other events like "ready" and "messageCreate" are working just fine so I'm not sure why it's not working.

discord.js Problem with reaction roles. Bot didn't give the role

I'm trying to code bot that has reaction role function. My bot adds reactions to the message, but when I'll react to the message nothing happens. Bot should give me a "user" role. All permissions are set up in my discord server.
I'm using 13.6.0 discord.js like my package.json file said. I'm still beginner in this stuff so please be understanding.
Here's my main.js code:
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] , partials: ["MESSAGE" , "CHANNEL" , "REACTION"] });
const prefix = '-';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('BOT is online!');
});
client.on('messageCreate' , message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'command') {
client.commands.get('command').execute(message, args, Discord);
}
else if (command === "rr") {
client.commands.get('rr').execute(message, args, Discord, client);
}
else if (command === 'weryfikacja') {
client.commands.get('weryfikacja').execute(message, args, Discord);
}
});
client.login('EMPTY')
Here's my rr.js code:
module.exports = {
name: "rr",
description: "Create reaction roles!",
execute(message, args, Discord, client) {
if(!args[0] || !args[1] || !args[2] === null) {
message.channel.send("You did not provide all the arguments!");
return;
}
message.delete();
let reactionroleserver = message.guild.roles.cache.get(args[2]);
message.channel.messages.fetch(args[0]).then(message => message.react(args[1]));
let emojiToReact = args[1];
client.on('messageReactionAdd', async (reaction, user) =>{
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if(reaction.emoji.name === emojiToReact) {
await reaction.message.guild.members.cache.get(user.id).roles.add(reactionroleserver);
} else {
return;
}
})
client.on('messageReactionRemove', async (reaction, user) =>{
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if(reaction.emoji.name === emojiToReact) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(reactionroleserver);
} else{
return;
}
})
}
}
Enable GUILD_MESSAGE_REACTIONS intent
const client = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES",
"GUILD_MESSAGE_REACTIONS"
],
partials: [
"MESSAGE",
"CHANNEL",
"REACTION"
]
})

Discord Reaction Roles not working after the bot restarts

Recently I decided to update my Discord Bot from V12 to V13 and I encountered a problem with my Reaction Roles.
It only works if the bot doesn't restart. It worked perfectly on discord.js 12.5.3 and now I'm using discord.js 13.5.0. Could you guys help me with the problem?
Here is my code:
const { MessageEmbed } = require("discord.js");
const Discord = require('discord.js');
const { Client } = require('discord.js');
const client = new Client({
intents: 32767,
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
});
const config2 = require("../config2");
module.exports = async (client, message, args) => {
client.on('messageCreate', async message => {
if (message.content.startsWith("22ar")) {
const embed = new MessageEmbed()
.setColor('#FFA500')
.setTitle(`Pick the roles`)
.setDescription(`🔓 **- You unlock yourself.**
✅ **- You get access to the server.**
💜 **- You get notified for X things.**
[🔓, ✅] - obligatory.
[💜] - optional.
\`Wait at least 30 seconds and try again if you don't get the roles.\``)
const msg = await message.channel.send({ embeds: [ embed ] })
msg.react('🔓')
msg.react('✅')
msg.react('💜')
}
})
const CHANNEL = config2.ROLECHANNEL;
const UROLE = config2.UNLOCKROLE;
const MROLE = config2.MEMBERROLE;
const NROLE = config2.NOTIFYROLE;
const unlockEmoji = '🔓';
const checkEmoji = '✅';
const notifyEmoji = '💜';
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if(reaction.message.channel.id === CHANNEL) {
if (reaction.emoji.name == checkEmoji) {
const memberRole = reaction.message.guild.roles.cache.find(r => r.id === MROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.add(MROLE);
}
if (reaction.emoji.name == unlockEmoji) {
const unlockRole = reaction.message.guild.roles.cache.find(r => r.id === UROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(UROLE)
}
if (reaction.emoji.name == notifyEmoji) {
const notifyRole = reaction.message.guild.roles.cache.find(r => r.id === NROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.add(NROLE)
}
}
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Fetching message failed: ', error);
return;
}
}
if (!user.bot) {
if(reaction.message.channel.id === CHANNEL) {
if (reaction.emoji.name == checkEmoji) {
const memberRole = reaction.message.guild.roles.cache.find(r => r.id === MROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(memberRole);
}
if (reaction.emoji.name == unlockEmoji) {
const unlockRole = reaction.message.guild.roles.cache.find(r => r.id === UROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(unlockRole)
}
if (reaction.emoji.name == notifyEmoji) {
const notifyRole = reaction.message.guild.roles.cache.find(r => r.id === NROLE);
const { guild } = reaction.message
const member = guild.members.cache.find(member => member.id === user.id);
member.roles.remove(notifyRole)
}
}
}
})
}
})
}
I am not getting any error in the console and the bot continues to work as usual.
Thank you for your attention.
Messages sent before your bot started are uncached unless you fetch them first. By default, the library does not emit client events if the data received and cached is not sufficient to build fully functional objects. Since version 12, you can change this behavior by activating partials.
Official guide about this here (Listening for reactions on old messages).

Node packages work locally but not when deployed to Heroku

I've implemented a very simple discord.js music bot which uses the node.js packages ytdl-core and opus-script. The bot is never able to join the voice channels and stream the music using the new packages implemented when deployed to Herkou, however the messages associated with each command such as the embeds still send.
const ytdl = require('ytdl-core');
const streamOptions = { seek: 0, volume: 1}
const Discord = require('discord.js')
require('dotenv-flow').config()
const config = {
token: process.env.TOKEN,
owner: process.env.OWNER,
prefix: process.env.PREFIX
}
const ytdl = require('ytdl-core')
const streamOptions = {
seek: 0,
volume: 1
}
const prefix = config.prefix
const client = new Discord.Client()
client.on('ready', () => {
console.log('ready!')
console.log(prefix)
client.user.setActivity("foo", {
type: "WATCHING"
})
});
client.on("message", async message => {
const args = message.content.slice(prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
if (message.author.bot) return
if (message.content.indexOf(prefix) !== 0) return
if (command === "play") {
const link = args[0]
if (message.channel.id === musicChannel) {
if (message.member.voiceChannel) {
if (!link) return message.reply("please enter a YouTube url to play!")
if (!ytdl.validateURL(`${link}`)) return message.reply("pleae enter a valid YouTube url!")
message.member.voiceChannel.join().then(connection => {
console.log("Successfully connected.");
const stream = ytdl(`${link}`, {
filter: 'audioonly'
})
const dispatcher = connection.playStream(stream, streamOptions);
})
.catch(e => {
console.error(e);
})
const embed = new Discord.RichEmbed()
.setTitle("__A New Youtube URL Is Playing:__")
.setThumbnail(client.user.avatarURL)
.addField("Current URL:", `${link}`)
.addField("Changed by:", `${message.member.user}`)
.setColor("#32a852")
message.guild.channels.get(musicChannel).send(embed).catch(e => {
console.error(e);
})
} else {
message.reply("you must be in a voice channel!")
}
} else {
message.reply(`please use music commands in: <#${musicChannel.toString()}>`)
}
}
if (command === "stop") {
if (message.channel.id === musicChannel) {
if (message.guild.voiceConnection) {
message.guild.voiceConnection.disconnect()
message.channel.send("successfully disconnected from voice channel!")
} else {
message.reply("There is currently no music playing!")
}
} else {
message.reply(`please use music commands in: <#${musicChannel.toString()}>`)
}
}
}
});
client.login(process.env.TOKEN);
Tried uploading it through github desktop? (no gitignore , upload it with the node-modules folder)

Resources