When I try to run the command on the powershell termianl (node .\index.js\) I get the same error every time. I changed the token multiple times but still got the same error. I run the command on the right root directory, so I don't know what to do.
Code:
import { config } from 'dotenv';
import { Client, GatewayIntentBits, Routes } from 'discord.js';
import { REST } from '#discordjs/rest';
config();
const TOKEN = process.env.BOT_TOKEN_CLOUD;
const CLIENT_ID = process.env.CLIENT_ID;
const GUILD_ID = process.env.GUILD_ID;
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
]
});
const rest = new REST({ version: '10' }).setToken('TOKEN');
client.on('ready', () => {console.log(`${client.user.tag} has logged in!`);});
async function main() {
const commands = [
{
name: 'testcommand',
description: 'test command'
},
];
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), {
body: commands,
});
client.login(TOKEN);
} catch (err) {
console.log(err);
}
}
main();
Error:
DiscordAPIError[0]: 401: Unauthorized
at SequentialHandler.runRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:283:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.mjs:95:14)
at async REST.request (file:///C:/Users/Name/Documents/djs-v14/node_modules/#discordjs/rest/dist/lib/REST.mjs:48:22)
at async main (file:///C:/Users/Name/Documents/djs-v14/index.js:32:9) {
rawError: { message: '401: Unauthorized', code: 0 },
code: 0,
status: 401,
method: 'PUT',
url: 'https://discord.com/api/v10/applications/CLIENT_ID/guilds/948742790421053482/commands',
requestBody: { files: undefined, json: [ [Object] ] }
}
You need to use the specific token for your bot instead of 'TOKEN' string
const rest = new REST({ version: '10' }).setToken('TOKEN');
here, .setToken() should be like .setToken(TOKEN)
Almost certain you forgot the ApplicationCommands scope(remember bot as well) when adding a bot to the server. Ensure you add that scope in the developer portal. Another possible reason is your client ID not matching the token.
Related
I am trying to use the Get method from the code below. I can use the Post method to post new instances to the database but my Get method is not working. When I tried to use the Get method I encountered the "AxiosError: Request failed with status code 404" error.
This is my code that contains the Get and Post methods:
const express = require('express');
const mongoose = require('mongoose');
const { ObjectId } = require('mongodb');
const { connectToDb, getDb, URI } = require('./db');
const Root = require('../models/Root');
const port = process.env.PORT || 7000;
const URL = 'http://localhost:7000'
const axios = require('axios');
// init & middleware
const app = express();
const router = express.Router();
app.use(express.json());
mongoose.set('strictQuery', false);
mongoose.set('bufferCommands', false);
let db
connectToDb((err) => {
if (!err) {
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
}
});
mongoose.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// POST
app.post('/roots', async (req, res) => {
const { root_id, node_id, name } = req.body;
if (!root_id || !node_id || !name) {
return res
.status(400).send({ error: 'Please provide all required fields' });
}
const root = new Root({ root_id, node_id, name });
try {
const savedRoot = await root.save();
res.send(root);
} catch (err) {
//console.error('Error saving root:', err);
res.status(400).send(err);
}
});
// GET
app.get('/roots/:root_id', async (req, res) => {
try {
const response = await axios.get(
`${URL}/roots?filter={"where":{"root_id":${req.params.root_id}}}`
);
res.status(200).json(response.data);
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not fetch the root' });
}
});
// DELETE
app.delete('/roots/:root_id', async (req, res) => {
try {
await axios.delete(`${URL}/roots/${req.params.root_id}`);
res.status(200).json({ message: 'Root deleted successfully' });
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not delete the root' });
}
// Call to a method to delete all children nodes of the tree in the Node tables
});
// PATCH
app.patch('/roots/:root_id', async (req, res) => {
try {
const response = await axios.patch(
`${URL}/roots/${req.params.root_id}`,
req.body
);
res.status(200).json(response.data);
} catch (err) {
res.status(500).json({ error: 'Could not update the root' });
}
});
I use this code to connect to the database:
// Use this file to connect to database - easy to switch between local and cloud for testing
const{MongoClient} = require('mongodb')
let dbConnection
// Connect to local database
let URI = 'mongodb://127.0.0.1:27017/PM_AI'
module.exports = {
connectToDb: (cb) => {
MongoClient.connect(URI)
// MongoClient.connect(cloudURI)
.then((client) => {
dbConnection = client.db()
return cb()
})
.catch(err => {
console.log(err)
return cb(err)
})
},
getDb: () => dbConnection,
URI
}
ERROR LOG for the error that I encounter:
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 404\n at settle (D:\\CSDS_395_Project\\AI-PM\\node_modules\\axios\\dist\\node\\axios.cjs:1900:12)\n at IncomingMessage.handleStreamEnd (D:\\CSDS_395_Project\\AI-PM\\node_modules\\axios\\dist\\node\\axios.cjs:2944:11)\n at IncomingMessage.emit (node:events:525:35)\n at endReadableNT (node:internal/streams/readable:1359:12)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"User-Agent": "axios/1.3.3",
"Accept-Encoding": "gzip, compress, deflate, br"
},
"method": "get",
"url": "http://localhost:7000/roots?filter={\"where\":{\"root_id\":1}}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
The URL that I use to test my method in Postman is http://localhost:7000/roots/1.
Please let me know what am I doing wrong with my code here.
Thank you very much!
In your expressjs server file, the url you are using in mongoose.connect() refers to the expressjs server itself instead of localhost mongodb instance
So in your server.js/app.js or whatever is your main expressjs server file,
const MONGO_URL = 'mongodb://127.0.0.1:27017/PM_AI'
I can also see that you are using both mongo client and mongoose which I don't understand why... You only need one of these libaries to connect to mongodb from your backend
Also your code is pretty messed up so I've made the following changes
No need to use mongoose strict query and other configurations, simply using mongoose.connect() in latest mongoose version is enough. As mongodb connection establishes, you can launch your server
In terminal, write npm install dotenv. It is a package that is used to access variables in .env file, without it your server won't work properly
I've removed mongo client as it is not needed, simply using mongoose is enough
I don't know why you are making axios requests to your own server. This axios thing is what is causing 404 error. You should use axios only when you need to make api calls from frontend, or make api calls from your backend to some other backend server. For your own server, you should always prefer using a controller function for every route otherwise you will get 404 error. By controller function, I mean instead of axios.get, you need to execute mongoModel.delete() instead of axios.delete() or return mongoModel.findById() instead of axios.get()
For mongodb connection, use MONGO_URL and for connecting your own server, use URL
So the final version of your code should look like:
const express = require('express');
const mongoose = require('mongoose');
const { ObjectId } = require('mongodb');
const Root = require('../models/Root');
const MONGO_URL = 'mongodb://127.0.0.1:27017/PM_AI'
const axios = require('axios');
// For environmental variables in .env file
const dotenv = require("dotenv")
dotenv.config()
// init & middleware
const app = express();
const router = express.Router();
app.use(express.json());
const port = process.env.PORT || 7000
const URL = `http://localhost:${port}`
mongoose.connect(MONGO_URL).then(() => {
console.log("Mongodb connected")
app.listen(port,() =>
{console.log("Server started") }
});
// POST
app.post('/roots', async (req, res) => {
const { root_id, node_id, name } = req.body;
if (!root_id || !node_id || !name) {
return res
.status(400).send({ error: 'Please provide all required fields' });
}
const root = new Root({ root_id, node_id, name });
try {
const savedRoot = await root.save();
res.send(root);
} catch (err) {
//console.error('Error saving root:', err);
res.status(400).send(err);
}
});
// GET
app.get('/roots/:root_id', async (req, res) => {
try {
const response = await axios.get(
`${URL}/roots?filter={"where":{"root_id":${req.params.root_id}}}`
);
res.status(200).json(response.data);
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not fetch the root' });
}
});
// DELETE
app.delete('/roots/:root_id', async (req, res) => {
try {
await axios.delete(`${URL}/roots/${req.params.root_id}`);
res.status(200).json({ message: 'Root deleted successfully' });
} catch (err) {
console.error('Error getting root:', err);
res.status(400).send(err);
// res.status(500).json({ error: 'Could not delete the root' });
}
// Call to a method to delete all children nodes of the tree in the Node tables
});
// PATCH
app.patch('/roots/:root_id', async (req, res) => {
try {
const response = await axios.patch(
`${URL}/roots/${req.params.root_id}`,
req.body
);
res.status(200).json(response.data);
} catch (err) {
res.status(500).json({ error: 'Could not update the root' });
}
});
I have tried to setup a data migration service using postgrator version 7.1.0. I have the following code
import Postgrator from "postgrator";
import pg from "pg";
import { dirname } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
async function doMigration() {
// Create a client of your choice
const client = new pg.Client({
host: "0.0.0.1",
port: 9075,
database: "test",
user: "test",
password: "!testPwd",
});
try {
// Establish a database connection
await client.connect();
// Create postgrator instance
const postgrator = new Postgrator({
migrationDirectory: __dirname + '/migration-scripts',
driver: "pg",
database: "test",
schemaTable: "migration_version",
execQuery: (query) => client.query(query),
});
await postgrator.migrate();
console.log("schema migration completed successfully")
} catch (error) {
console.error(error);
}
// Once done migrating, close your connection.
await client.end();
}
doMigration();
But I got an error when running the above code
TypeError: invalid pattern
I've been following this tutorial with this library, but the code snippets provided are producing errors. I have registered the app with Azure and followed the instructions, but when I run the code, it says SyntaxError: await is only valid in async functions and the top level bodies of modules at /script.js:74:20
Here's a relevant snippet of code, but if you have Replit, I would really appreciate it if you could collaborate with me on my Repl instead.
Replit link: https://replit.com/join/rgqcqfcohh-5pengoo
Code:
const msal = require('#azure/msal-node');
// Create msal application object
const cca = new msal.ConfidentialClientApplication(config);
const REDIRECT_URI = "http://localhost:3000/redirect";
const config = {
auth: {
clientId: "ebcb2e8c-4675-411f-a76e-25aafe0c026d",
authority: "https://login.microsoftonline.com/98ca2106-858a-413a-b7d5-31301dcf9869/",
// I wasn't sure if this meant the key value or the secret ID
clientSecret: "ee10b5ce-f9c4-460a-a402-064030841f86"
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
};
// 1st leg of auth code flow: acquire a code
app.get('/', (req, res) => {
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// get url to sign user in and consent to scopes needed for application
pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
res.redirect(response);
}).catch((error) => console.log(JSON.stringify(error)));
});
// 2nd leg of auth code flow: exchange code for token
app.get('/redirect', (req, res) => {
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
pca.acquireTokenByCode(tokenRequest).then((response) => {
console.log("\nResponse: \n:", response);
res.sendStatus(200);
}).catch((error) => {
console.log(error);
res.status(500).send(error);
});
});
try {
let userDetails = await client.api("/me").get();
console.log(userDetails);
} catch (error) {
throw error;
}
MohammedMehtabSiddiqueMINDTREELIMI-9821 on the Microsoft Docs informed me that...
"You can use "await" only inside a function which is "async".
Here you can try remove 'await' from the code and try to run it"
and it worked!
I am using discord.js v13. I have successfully created a bot with scopes bot and application.commands and successfully add it to a channel on my server. Now I am following the tutorial for registering slash commands. I created a file deploy-commands.js with the following content:
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('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user 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);
Then I run command node deploy-commands.js and I get error:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:198:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:99:20) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/901217590259617813/guilds/901235476399280138/commands'
}
I have reviewed a lot of info on the internet but could not find the solution. I have triple checked the clientId, guildId and application token.
Adding on to Pedro's comment,
From Trying to register commands: DiscordAPIError[50001]: Missing Access:
"Have you made sure that the 'applications.commands' scope is checked in the scopes section of the OAuth2 settings for your bot in the discord developer portal?"
You mention you remade the application and bot but did not verify you correctly set the application.commands scope permission. This is likely your issue.
I am trying to get a response from '/razorpay' route in my index.js file, and use it in displayRazorpay()
. For this, I'm using fetch, but it shows forbidden 403 error. Can someone help out? I have attached my '/razorpay' route, and displayRazorpay() function below. I'm new to node.js, so any help is appreciated!
router.post('/razorpay', async function(req,res,next){
if(!req.session.cart){
return res.redirect('/shopping-cart');
}
var cart = new Cart(req.session.cart);
const payment_capture = 1;
const amount = cart.totalPrice;
const currency = 'INR';
const options = {
amount: amount * 100,
currency,
receipt: shortid.generate(),
payment_capture,
}
try {
const response = await razorpay.orders.create(options);
console.log(response);
res.json({
id: response.id,
currency: response.currency,
amount: response.amount
});
} catch (error) {
console.log(error);
}
});
async function displayRazorpay() {
const data = await fetch('/razorpay', {method:'POST'}).then((t) =>
t.json()
);
console.log(data);
const options = {
key: 'rzp_test_2eJE3rP3gEWqze',
amount: 400,
order_id: data.id,
name: 'Donation',
description: 'Thank you for nothing. Please give us some money',
image: '/images/modiLogo3.png',
handler: function (response) {
alert(response.razorpay_payment_id);
alert(response.razorpay_order_id);
alert(response.razorpay_signature);
},
prefill: {
email: 'sdfdsjfh2#ndsfdf.com',
phone_number: '9899999999'
}
}
const paymentObject = new window.Razorpay(options);
paymentObject.open();
}
This is a problem of CORS. Make sure you enable cors on your server side.
Since you are using express, here's sample code
First install cors: npm install cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})