I'm new to js and i tried making a discord bot, i got the bot on the server but i cant register the commands. This is the error I'm getting:DiscordAPIError[50035]: Invalid Form Body application_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. guild_id[NUMBER_TYPE_COERCE]: Value "undefined" is not snowflake. at SequentialHandler.runRequest (c:\Users\Waku\Desktop\Discord bot\node_modules\#discordjs\rest\dist\index.js:708:15) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async SequentialHandler.queueRequest (c:\Users\Waku\Desktop\Discord bot\node_modules\#discordjs\rest\dist\index.js:511:14) { rawError: { code: 50035, errors: { application_id: [Object], guild_id: [Object] }, message: 'Invalid Form Body' }, code: 50035, status: 400, method: 'put', url: 'https://discord.com/api/v9/applications/undefined/guilds/undefined/commands', requestBody: { files: undefined, json: [ [Object], [Object] ] } }
This is the code:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('marco').setDescription('Replies with polo!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
Blockquote
Related
I'm trying to make my bot type a message upon joining a guild, but it doesn't seem to work.
What I've tried: (among some other variations)
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
const { PermissionsBitField } = require('discord.js');
module.exports = async (client, guild) =>{
const channel = guild.channels.cache.find(channel => channel.type === 0 && guild.members.me.permissionsIn(channel).has(PermissionsBitField.Flags.SendMessages))
channel.send("Thank you for inviting me!")
}
For some reason it still tries to send in a channel where the bot doesn't have permission to send messages in.
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:659:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:458:14)
at async REST.request (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\#discordjs\rest\dist\index.js:902:22)
at async TextChannel.send (C:\Users\Gleyv\3D Objects\Botveon [Pre-Alpha]\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:175:15) {
requestBody: {
files: [],
json: {
content: 'Thank you for inviting me!',
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined,
thread_name: undefined
}
},
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'POST',
url: 'https://discord.com/api/v10/channels/1007005313968390306/messages'
}
Turns out adding
&&channel.permissionsFor(guild.members.me).has(PermissionsBitField.Flags.ViewChannel) has solved my problem.
I am coding a Discord bot and found an issue I cannot fix.
checking if the bot was online to send a message in the console and a rich presence
client.on("ready", () => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: 'online',
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
});
});
All the code
const { MessageHandler } = require("discord-message-handler"); // npm install discord-message-handler //
const handler = new MessageHandler();
const discord = require("discord.js"); // npm i discord.js //
const { Options } = require("discord.js");
const { GatewayIntentBits } = require("discord.js");
var logger = require("winston"); // npm install winston //
const { client, Collection } = require("discord.js");
const { config } = require("dotenv");
const Client = {
disableEveryone: true,
};
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console(), {
colorize: true,
});
logger.level = "debug";
// Initialize Discord Bot
var bot = new discord.Client({
autorun: true,
});
client.on("ready", () => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: "online",
game: {
name: "Cool kid the movie 2",
type: "WATCHING",
},
});
});
client.login(process.env.TOKEN);
you have to mention client in the function you created
and also you defined your Discord Bot as bot
so code will be
bot.on("ready", (client) => {
console.log(`${client.user.username} is in the house!`);
client.user.setPresence({
status: 'online',
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
});
});
here is an example code
const {
Client,
Partials,
Collection,
PermissionFlagsBits,
EmbedBuilder,
} = require("discord.js");
const { config } = require("");// enter your path
const { user, Message, GuildMember} =
Partials;
const client = new Client({
intents: 131071,
Partials: [
user,
Message,
GuildMember,
PermissionFlagsBits
],
allowedMentions: { parse: ["everyone", "roles", "users"] }
});
client.login(//token path).catch((err) => console.log(err));
client.on("ready", (client) => {
client.user.setPresence({
status: "online",
game: {
name: 'Cool kid the movie 2',
type: 'WATCHING'
}
})
});
[Shopify Sales Tracker/16:28:9]: [ERROR] ➜ uncaughtException => DiscordAPIError: Invalid Form Body
parent_id: Value "" is not snowflake.
at RequestHandler.execute (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async TextChannel.edit (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\node_modules\discord.js\src\structures\GuildChannel.js:336:21)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\commands\shopify\addshop.js:16:4)
at async Object.module.exports.run (C:\Users\Hp\Downloads\Shopify-Live-Sales-Tracker-doener\Shopify-Live-Sales-Tracker-doener\src\client\events\messageCreate.js:29:3)
module.exports.run = async (app, client, message, args) => {
const shop_url = args[0];
if (!app.shopify.config.shops.includes(shop_url)) {
const server = message.guild;
var webhook;
if (!app.shopify.config.webhooks[shop_url]) {
const channel_name = app.config.discord.shop_channel_name(shop_url);
const channel = await server.channels.create(channel_name, {
type: 'text',
});
await channel.setParent(app.config.discord.products_category);
webhook = await channel.createWebhook(shop_url);
}
await app.utils.shopify.addNewShopToConfig(
shop_url,
webhook ? webhook.url : undefined
);
const embed = app.utils.discord.createEmbed('info', {
title: `Shop hinzugefügt [${shop_url}]`,
description: `\`\`${shop_url}\`\` wurde erfolgreich zur Datenbank hinzugefügt.`,
});
await app.utils.shopify.loadProducts();
return await message.channel.send({ embeds: [embed] });
} else {
const embed = app.utils.discord.createEmbed('error', {
description: 'Du hast diesen Shop bereits hinzugefügt',
});
return await message.channel.send({ embeds: [embed] });
}
};
module.exports.conf = {
name: 'addshop',
description: 'Füge einen Shop in die db hinzu',
category: 'Shopify',
owner: false,
premium: false,
admin: false,
guild: true,
dm: false,
disabled: false,
usage: ['addshop <url>'],
example: ['addshop hoopsport.de'],
aliases: ["add"],
minArgs: 0,
maxArgs: 0,
};
The problem is here
await channel.setParent(app.config.discord.products_category);
I see you use this github repo. So look what's on the src folder, config subfolder and discord.js file :
products_category: '', // create a category in your server and put its id inside here
Just create a category channel and copy it's id and paste it here and restart your bot.
I'm struggling to debug a NextJS API that is working in development (via localhost) but is silently failing in production.
Below, the two console.log statements are not returning, so I suspect that the textToSpeech call is not executing correctly, potentially in time?
I'm not sure how to rectify, happy to debug as directed to resolve this!
const faunadb = require('faunadb')
const secret = process.env.FAUNADB_SECRET_KEY
const q = faunadb.query
const client = new faunadb.Client({ secret })
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1')
const { IamAuthenticator } = require('ibm-watson/auth')
const AWS = require('aws-sdk')
const { randomUUID } = require('crypto')
import { requireAuth } from '#clerk/nextjs/api'
module.exports = requireAuth(async (req, res) => {
try {
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
})
const textToSpeech = new TextToSpeechV1({
authenticator: new IamAuthenticator({
apikey: process.env.IBM_API_KEY
}),
serviceUrl: process.env.IBM_SERVICE_URL
})
const uuid = randomUUID()
const { echoTitle, chapterTitle, chapterText } = req.body
const synthesizeParams = {
text: chapterText,
accept: 'audio/mp3',
voice: 'en-US_KevinV3Voice'
}
textToSpeech
.synthesize(synthesizeParams)
.then(buffer => {
const s3Params = {
Bucket: 'waveforms/audioform',
Key: `${uuid}.mp3`,
Body: buffer.result,
ContentType: 'audio/mp3',
ACL: 'public-read'
}
console.log(buffer.result)
console.log(s3Params)
s3.upload(s3Params, function (s3Err, data) {
if (s3Err) throw s3Err
console.log(`File uploaded successfully at ${data.Location}`)
})
})
.catch(err => {
console.log('error:', err)
})
const dbs = await client.query(
q.Create(q.Collection('audioform'), {
data: {
title: echoTitle,
published: 2022,
leadAuthor: 'winter',
user: req.session.userId,
authors: 1,
playTime: 83,
chapters: 1,
gpt3Description: '',
likes: 20,
image:
'https://waveforms.s3.us-east-2.amazonaws.com/images/Mars.jpeg',
trackURL: `https://waveforms.s3.us-east-2.amazonaws.com/audioform/${uuid}.mp3`,
albumTracks: [
{
title: chapterTitle,
text: chapterText,
trackURL: `https://waveforms.s3.us-east-2.amazonaws.com/audioform/${uuid}.mp3`
}
]
}
})
)
res.status(200).json(dbs.data)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
Replace the async fragments something like this, assuming they are meant to be executed sequentially.
try {
// code removed here for clarity
const buffer = await textToSpeech.synthesize(synthesizeParams);
const s3Params = {
Bucket: 'waveforms/audioform',
Key: `${uuid}.mp3`,
Body: buffer.result,
ContentType: 'audio/mp3',
ACL: 'public-read'
}
await s3.upload(s3Params).promise();
const dbs = await client.query(...);
res.status(200).json(dbs.data);
} catch (e) {
res.status(500).json({ error: e.message });
}
So i follow worn off keys tutorial to discord bot and i don't know what the problem is, here is the error
/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Missing Access
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:349:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:50:14)
at async GuildApplicationCommandManager.create (/home/container/node_modules/discord.js/src/managers/ApplicationCommandManager.js:117:18) {
method: 'post',
path: '/applications/901999677011005472/guilds/905266476573950023/commands',
code: 50001,
httpStatus: 403,
requestData: {
json: {
name: 'ping',
description: 'Bot uptime/latency checker.',
type: undefined,
options: undefined,
default_permission: undefined
},
files: []
}
}
I also try looking at my code but I didn't see something wrong.
This is my code, I really think something is wrong in the code.
const DiscordJS = require('discord.js')
const { Intents } = require('discord.js')
const dotenv = require('dotenv')
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
client.on('ready', () => {
console.log("The bot is online")
// Carlos: 883425101389914152
const guildId = '905266476573950023'
const guild = client.guilds.cache.get(guildId)
let commands
if (guild) {
commands = guild.commands
} else {
commands = client.application.commands
}
commands.create({
name: 'ping',
description: 'Bot uptime/latency checker.',
})
commands.create({
name: 'add',
description: 'Adds two numbers given by user.',
options: [
{
name: 'number1',
description: 'The first number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
{
name: 'number2',
description: 'The second number',
required: true,
type: DiscordJS.Constants.ApplicationCommandOptionTypes.NUMBER,
},
]
})
})
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, Options } = interaction
if (commandName === 'ping') {
interaction.reply({
content: 'Pong! **60ms**',
// If anyone can see = True, Only command user can see = False
ephemeral: true,
})
} else if (commandName === 'add') {
interaction.reply({
content: 'The sum is ${number1 + number2}'
})
}
})
client.login(process.env.KEY)
For anyone that having the same problem. I fix this by simply going to bot developer portal then go to OAuth2 > URL generator. And for the scope select both "bot" and "applications.commands". Then scroll down choose whatever permission your bot need copy the URL.
You did not select the right permissions when creating bot login link for your discord server.
Goto developers / oauth again, click bot and select all the required permissions that you're using in this bot.
Then copy the link generated and use it to login with your bot into your server.
don't forget to change this:
content: 'The sum is ${number1 + number2}'
to this:
content: `The sum is ${number1 + number2}`