discrod.js REST is not a constructor - discord.js

const config = require("./config.json");
const Discord = require('discord.js');
const { Intents } = Discord;
const client = new Discord.Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
})
const { REST, Routes } = require('discord.js');
const commands = [
{
name: 'test',
description: 'test',
},
];
const rest = new REST({ version: '10' }).setToken(config.BOT_TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationCommands(config.CLIENT_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'test') {
await interaction.reply('Hello boi!');
}
});
client.login(config.BOT_TOKEN)
const rest = new REST({ version: '10' }).setToken(config.BOT_TOKEN);
^
TypeError: REST is not a constructor
I followed the instructions to create a bot. I run it and then this error occurs. I 've been looking everywhere for a solution

You should probably change the following:
const { REST, Routes } = require('discord.js');
with the following lines:
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v10');
This can been verified by checking this.

Related

firebase react cloud messaging push notification [duplicate]

I was working on a project using Firebase cloud messaging react. I was sending this to my server, but it doesn't work. Surely I have tried, but I don't know what's wrong again.
Below is the code.
Here it sends a POST request to Firebase, and it should send a notification to the user.
async function sendNotification(id, userMessage) {
const headers = {
'Authorization': `key=${code}`,
'Content-Type': 'application/json'
}
const message = {
'to': `${id}`,
'content_available': true,
'apns_priority': 5,
'notification': {
body: `${userMessage}`
},
const url = 'https://fcm.googleapis.com/fcm/send'
//console.log(code)
await axios.post(url, message, {
headers: headers
})
}
const sendMessageToServer = async (e) => {
//e.preventDefault();
toggle()
const docRe = doc(database, "help", mailer);
const data = {
email: user.email,
user: newMessage,
}
//console.log(data, 'not clear')
setNewMessage('')
//console.log(data, newMessage, 'cleared')
setShow(false)
if(newMessage === '') {
}
else {
const docRef = doc(database, "users", mailer);
await updateDoc(docRe, {
msg: arrayUnion(data)
})
.then(() => {
async function p() {
const id = await getDoc(docRef)
//console.log(id.data())
sendNotification(id.data().notice, `Admin : ${data.user}`)
}
p()
})
}
Sometimes it sends to my localhost because I tested there, but it doesn't work on my Netlify app. Secondly, I noticed that it keeps generating the same token for each user, but that's not the issue, but if you can help in both I would be grateful.
export default function Dashboard() {
async function callToken() {
await getToken(messaging, {vapidKey: process.env.NOTIFICATION})
.then((code) => {
//console.log(code)
async function docRef() {
const dc = doc(database, "users", auth.currentUser.email);
await updateDoc(dc, {
notice: code
});
}
docRef()
})
}
async function requestPermission() {
await Notification.requestPermission()
.then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.')
callToken()
}
})
}
const goTo = useNavigate();
useEffect(() => {
onAuthStateChanged(auth, (data) => {
if(!data) {
goTo('/login')
}
else {
currentBalance();
requestPermission()
}
})
})
}
Please know I imported all required modules.

State Not Finished Setting before being used in useEffect

I am hosting a react app in aws amplify using the aws-serverless version of express as the REST API, which sits inside of a lambda function. A big problem that I am facing is that asynchronous jobs in aws-serverless express cause the lambda function to complete before the promises resolve. Leaving me with no data and no error handling. This caused me to bring a lot of the asynchronous work to the front end of the application.
The problem here is that I need to bring a large amount of data into state. Right now, I am using a delay workaround (shown below) but instead need a programatic way to make sure state is finished updating before being used in the second useEffect hook (dependent on odds & failedTries props) instead of using the delay functionality.
Any help would be greatly appreciated.
const App = ({ signOut }) => {
const [odds, setOdds] = useState([]);
const [updateTime,setUpdateTime] = useState(0);
const [failedTries,setFailedTries] = useState(0);
useEffect(() => {
const setNflOdds = async () => {
let response = await updateNflOdds();
let data = response;
setOdds(data);
};
setNflOdds();
setUpdateTime(1);
const interval = setInterval(() => {
setNflOdds();
setUpdateTime(updateTime => updateTime +1);
}, 100000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
const s3Push = (() => {
if(!odds.length) {
setFailedTries(failedTries => failedTries + 1);
} else {
const delay = ms => new Promise(res => setTimeout(res, ms));
const nflOddsRefDelay = async() => {
*//This is the current workaround, wait ten seconds before pushing odds state up to the s3 bucket*
await delay(10000);
oddsS3Helper(odds);
};
nflOddsRefDelay()
}
});
s3Push();
}, [odds, failedTries]);
With the above indicated delay workaround this works for my use case (13k records inside of the array) but the data size is highly variable and I want to figure out a way that no matter the data size it brings the entire call up to the s3 bucket.
below is the content of the functions being called in the useEffect hook
const pushToS3 = async ( file, key ) => {
const creds = await Auth.currentCredentials()
const REGION = {region};
const s3Client = new S3Client({
credentials: Auth.essentialCredentials(creds),
region: REGION
});
const params = {
Bucket: {s3 bucket name}
Key: key,
Body: file,
};
s3Client.send(new PutObjectCommand(params));
console.log("file is sent");
};
const oddsS3Helper = (async (odds) => {
console.log("inside s3 helper: ",odds);
let csv = '';
let headers = Object.keys(odds[0]).join(',');
let values = odds.map(odd => Object.values(odd).join(',')).join('\n');
csv += headers + '\n' + values;
const buffedFile = csv;
const key = 'nflprops.csv'
const delay = ms => new Promise(res => setTimeout(res, ms));
const propRefDelay = async() => {
await delay(5000);
await postNflOdds();
};
pushToS3( buffedFile, key );
await propRefDelay();
});
async function getNflGames() {
const apiName = {name of serverless API inside of lambda};
const path = {path name};
const init = {
headers: {} // OPTIONAL
};
const data = await API.get(apiName, path, init);
return data;
};
async function getNflOdds(gameId) {
const apiName = {name of serverless API inside of lambda};
const path = {path name};
const init = {
headers: {}, // OPTIONAL
body: { gameId }
};
const data = await API.post(apiName, path, init);
return data;
};
async function updateNflOdds() {
const ojNflGames = await getNflGames();
const nflGameProps = [];
const nflOddsPush = ( async () => {
try {
await ojNflGames.data.map( async (game) => {
const ojNflOdds = await getNflOdds(game.id)
await ojNflOdds.data[0].odds.map((line) => {
nflGameProps.push(
{
gameId: game.id,
oddsId: line.id,
sports_book_name: line.sports_book_name,
name: line.name,
price: line.price,
checked_date: line.checked_date,
bet_points: line.bet_points,
is_main: line.is_main,
is_live: line.is_live,
market_name: line.market_name,
home_rotation_number: line.home_rotation_number,
away_rotation_number: line.away_rotation_number,
deep_link_url: line.deep_link_url,
player_id: line.player_id,
}
);
});
});
} catch (err) {
console.log("there was an error", err);
}
});
try {
await nflOddsPush();
} catch(err) {
console.log("odds push errored: ", err);
}
console.log("inside of updateNflOdds function: ",nflGameProps);
return nflGameProps;
};

Discord js v14 i am trying to get the value of the option input to export and use in the index file, the value is always undefined and an error occurs

When I put the command through, the "ign" option seems to not be read after specifying to get the string value of the option. It returns error:
{ message: 'Unknown interaction', code: 10062 },
code: 10062,
status: 404,
method: 'POST',
Command file:
const { SlashCommandBuilder, GatewayIntentBits } = require("discord.js");
const { Client } = require("discord.js");
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
module.exports = {
data: new SlashCommandBuilder()
.setName('stats')
.setDescription('Flex your tournament stats')
.addStringOption(option =>
option.setName('ign')
.setDescription("Your minecraft name")
.setRequired(true)),
};
client.on("interactionCreate", async (interaction)=> {
if (!interaction.isCommand()) {
return
}
const{ commandName, options } = interaction
if (commandName === 'stats') {
const ign = options.getString('ign');
module.exports = { ign };
}
});

How to configure NextJS Server API GraphQL Subscription

currently i'm learning how to develop an application using graphql.
I'm facing the error of implementing the subscription inside my application
resolver.js
const pubsub = new PubSub()
export const resolvers = {
Mutation: {
createCategory:async(parent,arg,{pubsub}) => {
console.log(pubsub)
const prisma = new PrismaClient();
const {name} = arg
await prisma.category.create({
data:{
name:name,
author:{
connect:{
id: "vjuwU0KvWhVDehB1gPgJ7TFRwcy1"
}
}
}
});
pubsub.publish('NEW_CATEGORY',{
newCategory:{
id:"1"
}
})
return true;
}
},
Subscription:{
category:{
subscribe: (_,__,)=>pubsub.asyncIterator(['NEW_CATEGORY']),
}
}
};
api/graphql.js
const pubsub = new PubSub()
const apolloServer = new ApolloServer({ typeDefs, resolvers,context:({req,res})=>({req,res,pubsub})});
const startServer = apolloServer.start();
export default cors(async function handler(req, res) {
if (req.method === "OPTIONS") {
res.end();
return false;
}
await startServer;
await apolloServer.createHandler({
path: "/api/graphql",
})(req, res);
});
export const config = {
api: {
bodyParser: false,
},
};
Error were occurred, i was unable to solve it due to this error message
error - image

Slash commands, Echo and Hello randomly added to my bot

For some reason, when using/checking the available slash commands of my bot. I have an echo and hello command, that I have not coded in AT ALL, that just appears. I was wondering if there is anything I can do to remove these?
Here are my packages I am using for this project
"#discordjs/builders": "^0.9.0",
"#discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.25.2",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0",
"fs": "^0.0.1-security",
"yarn": "^1.22.17"
Here is the interaction Creator
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
}
},
};
Here is the command handler
const {
REST
} = require('#discordjs/rest');
const {
Routes
} = require('discord-api-types/v9');
const fs = require('fs');
// Place your client and guild ids here
const clientId = '904224432338399243';
const guildId = '922603289898528768';
module.exports = (client) => {
client.handleCommands = async(commandFolders, path) => {
client.commandArray = [];
for (folder of commandFolders) {
const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
// Set a new item in the Collection
// With the key as the command name and the value as the exported module
client.commands.set(command.data.name, command);
client.commandArray.push(command.data.toJSON());
}
}
const rest = new REST({
version: '9'
}).setToken(process.env.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: client.commandArray },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
};
};
Mintels!
Try those solutions:
Registering your bot in a single guild (not globally)
Kicking the bot out of the guild and re-inviting it
Leave your code running for some time
Hope this helped and have a great day!

Resources