My discord bot isn't working after 13.0.0 - discord

I am trying out discord.js version 13.1.0 and I am following discord's guide on how to setup a bot. I have followed all the steps. When I have the bot running, and I send a message or a command into the server, nothing gets printed to the console. Any ideas?
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", (interaction) => {
console.log(interaction);
});
client.login(process.env.TOKEN);

From the Discord Developer Portal:
An Interaction is the message that your application receives when a user uses an application command or a message component.
By an application command is meant a special type of command, that you have to register against the Discord API. To learn more about application commands, read this.
From the discord.js docs main page, how to register an application (slash) command:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [{
name: 'ping',
description: 'Replies with Pong!'
}];
const rest = new REST({ version: '9' }).setToken('token');
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
However if you are looking for a way to reply to (or just capture) a normal message sent in a TextChannel, you are probably looking for the messageCreate event.
client.on("messageCreate", (message) => {
console.log(message);
});
Also note that to receive messageCreate event, you need GUILD_MESSAGES intent.
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });

Related

Why isn't my slash command working? discord.js

I was trying to create a bot that with a slash command can create a azure ad account and message it to the user. However when I run the code it doesn't create a slash command. How would I fix this.
Code:
// import dependencies
const Discord = require('discord.js');
const axios = require('axios');
// create a new Discord client
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
],
});
// listen for the ready event
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// listen for the interactionCreate event
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'create-account') {
// retrieve user input from slash command
const displayName = interaction.options.getString('displayname');
const password = interaction.options.getString('password');
// retrieve sensitive information from Replit secrets
const tenantId = process.env.AZURE_TENANT_ID;
const clientId = process.env.AZURE_CLIENT_ID;
const clientSecret = process.env.AZURE_CLIENT_SECRET;
try {
// create Azure AD account using Microsoft Graph API
const response = await axios.post(`https://graph.microsoft.com/v1.0/${tenantId}/users`, {
displayName: displayName,
passwordProfile: {
password: password
},
accountEnabled: true
}, {
headers: {
'Authorization': `Bearer ${await getAccessToken(clientId, clientSecret, tenantId)}`
}
});
// send success message to Discord
await interaction.reply(`Account with display name "${displayName}" created on Azure AD.`);
// log created account to Discord webhook
const webhook = new Discord.WebhookClient({
id: process.env.DISCORD_WEBHOOK_ID,
token: process.env.DISCORD_WEBHOOK_TOKEN
});
await webhook.send(`Account created on Azure AD:\nDisplay name: ${displayName}\nObject ID: ${response.data.id}`);
} catch (error) {
console.error(error);
// send error message to Discord
await interaction.reply('An error occurred while creating the account. Please try again later.');
}
}
});
// start the Discord client
client.login(process.env.DISCORD_TOKEN);
// helper function to get access token for Microsoft Graph API
async function getAccessToken(clientId, clientSecret, tenantId) {
const response = await axios.post(`https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`, {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
scope: 'https://graph.microsoft.com/.default'
});
return response.data.access_token;
}
I want it to create a slash command which I can run that'll let me create an azure ad account but the slash command does not show up when I try using it.

TypeError when trying to create a discord bot

I'm trying to build a discord bot that sends data to an airtable. This one sends user info when they join my server. I have the following code, but every time I try to run it, I get the following error:
TypeError: Cannot read properties of undefined (reading 'GUILDS')at Object.
This is the code:
const { Intents } = require('discord.js');
const Discord = require('discord.js');
const Airtable = require('airtable');
const client = new Discord.Client({
token: 'TOKEN_ID',
intents: [Intents.GUILDS, Intents.GUILD_MEMBERS]
});
Airtable.configure({ apiKey: 'API_KEY' });
const base = Airtable.base('BASE_ID');
client.on('guildMemberAdd', member => {
base('New Members').create({
'Username': member.user.username,
'Time Joined': new Date().toISOString()
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(`Added new record with ID ${record.getId()}`);
});
});
client.login();
Using Discord.js v14, the way to declare intents is as follows:
import { Client, GatewayIntentBits } from "discord.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers
]
});
and your token should be put in client.login
client.login("your-bot-token");

Receiving empty content / embed from other bot by slash command in Discord.js

I'm using Discord.js 14.6.0
When user use slash command (/) with other bot, I can receive message, but the embeds and content are empty.
(I can get embeds and content when bot send normal message)
I've already checked "Privileged Gateway Intents > MESSAGE CONTENT INTENT" in Discord Bot setting
And here's my code:
const { Client, GatewayIntentBits , Partials , EmbedBuilder } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMembers,
],
partials: [Partials.Channel],
});
client.login(TOKEN);
client.on("ready", () => {
console.log("Server is on!")
});
client.on("messageCreate", (message) => {
console.log(message)
// When using slash commamd by other Bot, `message.content` result: []
});

DiscordJS 403 Error Missing Access Error when trying to add Slash Commands

I am following the docs at DiscrodJS step by step and have been able to invite my bot just fine to my test server. My problem comes in when I try to add the slash commands.
Here is my index.js file.
const { Client, GatewayIntentBits } = require('discord.js')
require('dotenv').config()
const client = new Client({
intents: [
GatewayIntentBits.GuildMessages,
],
})
client.once('ready', () => {
console.log('Ready!')
})
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return
const { commandName } = interaction
const command = interaction.client.commands.get(commandName)
if (!command) {
console.error(`No command matching ${commandName} was found.`)
return
}
try {
await command.execute(interaction)
}
catch (error) {
console.error(error)
await interaction.reply({ ontent: 'There was an error while executing this command', ephemeral: true })
}
})
client.login(process.env.DISCORD_PRIVATE_TOKEN)
Here is my deploy-commands.js file.
const fs = require('node:fs')
const { Routes } = require('discord.js')
const { REST } = require('#discordjs/rest')
require('dotenv').config()
const {
DISCORD_PRIVATE_TOKEN,
DISCORD_CLIENT_ID,
DISCORD_GUILD_ID,
} = process.env
const commands = []
// Grab all the command files from the commands directory you created earlier
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
commands.push(command.data.toJSON())
}
// Construct and prepare an instance of the REST module
const rest = new REST({ version: '10' }).setToken(DISCORD_PRIVATE_TOKEN)
// and deploy your commands!
const deployCommand = async () => {
try {
console.log(`Started refreshing ${commands.length} application (/) commands.`)
// The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put(
Routes.applicationGuildCommands(DISCORD_CLIENT_ID, DISCORD_GUILD_ID),
{ body: commands },
)
console.log(`Successfully reloaded ${data.length} application (/) commands.`)
}
catch (error) {
// And of course, make sure you catch and log any errors!
console.error(error)
}
}
deployCommand()
There error that I get back from this is the following:
requestBody: { files: undefined, json: [ [Object] ] },
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/[client_id]/guilds/[guild_id]/commands'
}
In the bot settings
I've set auth method to In-app Authorization.
I've set the scope to bot and applications.commands then included Use Slash Commands (also tried this with ALL including Administrator bot permissions.
I've also done this through the URL Generator path.
In my discord server
I've put my Discord server into Developer mode to test my bot.
I've invited my bot to my test server.
In my code
I've ran the one time script for deploy-commands.js.

How to Pin a Message in Discord

I am trying to make a discord bot for a small server that I am in, and I want it to pin a certain message to the channel that it was sent in. I have done a few bots before, but it seems that the syntax has changed since I last used it, and code that I was going to reuse no longer works. I have managed to get around some of those changes (like the intents,) but when I try to check for a sent message, it just does nothing. My current code
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin()
}
});
client.login(token);
I have tried supplementing messageCreate for message like I have seen a few people recommend, but it still seems to do nothing. Even changing the msg.pin() to console.log(msg) still shows nothing in the console
client.on("messageCreate", (msg) => {
if (msg.content == "something goes here") {
console.log(msg)
}
});
I do have the privileged intent toggle enabled, so I don't think that that is the problem
[privileged toggles]
Does anybody know what the problem here is, and how I could fix it? Any help is appreciated, thanks!
First of all, you have not enabled the GUILD_MESSAGES intent in your client so you need to add that by doing this:
const client = new Client({
intents: [
Intents.FLAGS.GUILDS
Intents.FLAGS.GUILD_MESSAGES
]
});
Other than that, the .pin() function is still there and there is no change in it. You can provide a reason as well. The .pin() function also returns a promise, so you will have to use .then() or await, so your final code might look like this:
const { Client, Intents } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (msg.content == "something goes here") {
msg.pin().then(() => console.log)
}
});
client.login(token);
You can learn more about the .pin() function here => pin | discord.js
For Discord.js v13 use the following:
const { Client } = require("discord.js");
const { token } = require("./config.json");
const client = new Client({
intents: new Intents(32767)
});
client.login(token)
client.on("message", (ctx) => {
if (ctx.content == "something goes here") {
ctx.pin(ctx.id, "Pinned")
}
});

Resources