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 - discord

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 };
}
});

Related

Why im getting this error tho the cmd is fine? Cannot read properties of undefined (reading 'get')

DiscordJS context menu problem, like it says the cmd is running fine but when it does it shows the error of Cannot read properties of undefined (reading 'get') don't know why
Im getting this error on my events folder in discordjs v14 my content.js event
the error kept showing up though the context is still executed/working
I know i should be ignoring this error as long as the command is running good but it just annoying to my console and it doesn't look clean haha...
my context events:
module.exports = {
name: 'interactionCreate',
execute: async (interaction, client) => {
if (interaction.isContextMenuCommand()) {
const { command } = client;
const { commandName } = interaction;
const contextCommand = command.get(commandName);
if (!contextCommand) return;
try {
await contextCommand.execute(client, interaction)
} catch (e) {
console.log(e)
}
}
}
}
simple wave context
const { ApplicationCommandType, EmbedBuilder } = require("discord.js"); // packages
const superagent = require('superagent');
const ee = require('../../Config/embed.json');
module.exports = {
name: 'wave', // name of the command
// description: '', description of the command
developer: false, // false if the command is for public
type: ApplicationCommandType.User, // chatinput
cooldown: 3000, // cooldown of the commands
default_member_permissions: 'SendMessages', // discord perms
// options: [], options string
execute: async (client, interaction) => {
try {
let { body } = await superagent.get(`https://api.waifu.pics/sfw/wave`);
const embed = new EmbedBuilder()
.setColor(ee.color)
.setDescription(`Hey <#${interaction.targetUser.id}>!, <#${interaction.user.id}> just wave at you!`)
.setImage(body.url)
.setTimestamp()
.setFooter({ text: `${client.user.username} | waifumusic.ml` })
interaction.reply({ embeds: [embed] })
} catch (e) {
console.log(e)
}
}
}

discrod.js REST is not a constructor

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.

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

Getting "#ReferenceError: connection is not defined"

I've been using the code from discord.js guide and keep getting this error when I try to make it join
Here's my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const PREFIX = '%';
const request = require('request');
const cheerio = require('cheerio');
var servers = {};
client.on('ready', () => {
console.log('This client is online!');
})
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'image':
var imreq = (args[1])
image(message, imreq);
break;
case 'bruh':
client.on('message', async message => {
// Join the same voice channel of the author of the message
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
}
});
const dispatcher = connection.play('C:\Users\jayja\Downloads\Bruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
break;
}
});
function image(message, imreq) {
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + imreq,
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
};
request(options, function(error, response, responseBody) {
if (error) {
return;
}
$ = cheerio.load(responseBody);
var links = $(".image a.link");
var urls = new Array(links.length).fill(0).map((v, i) =>
links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
return;
}
// Send result
message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
});
}
client.login(token)
Heres a screenshot of the terminal:
Screenshot
So like I guessed, you don't need to listen to the message event of the client. You already have the message object via the initial command trigger.
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('C:\Users\jayja\Downloads\Bruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
}
This should be all you need. You also might find this guide interesting to read.

Apollo Subscriptions not listening to new data on client

Previously my apollo setup was listening to subscriptions until I added in socket.io and now my client setup is no longer listening to new data. my server codes seem to be ok based on my testing using graphql playground.
in my browser console, i get the following error message
client.js:652 WebSocket connection to 'ws://localhost:4000/' failed: Error during WebSocket handshake: Unexpected response code: 400
There seems to be some issue with my client side setup to use apollo subscriptions.
Appreciate any pointers? Thanks in advance
import { ApolloClient } from "apollo-client";
import { onError } from "apollo-link-error";
import { ApolloLink, split } from "apollo-link";
import { createUploadLink } from "apollo-upload-client";
import gql from "graphql-tag";
import { withClientState } from "apollo-link-state";
import { InMemoryCache } from "apollo-cache-inmemory";
import { WebSocketLink } from "apollo-link-ws";
import { getMainDefinition } from "apollo-utilities";
import { setContext } from "apollo-link-context";
const cache = new InMemoryCache();
const defaultState = {
currentGame: {
__typename: "currentGame",
teamAScore: 0,
teamBScore: 0,
teamAName: "EAGLES",
teamBName: "LOL"
}
};
const stateLink = withClientState({
cache,
defaults: defaultState,
resolvers: {
Mutation: {
updateGame: (_, { index, value }, { cache }) => {
const query = gql`
query GetCurrentGame {
currentGame #client {
teamAScore
teamBScore
teamAName
teamBName
}
}
`;
const previous = cache.readQuery({ query });
const data = {
currentGame: {
...previous.currentGame,
[index]: value
}
};
cache.writeQuery({ query, data });
return null;
},
resetCurrentGame: (_, d, { cache }) => {
cache.writeData({ data: defaultState });
}
}
}
});
const host = "http://localhost:4000";
// httpLink
const httpLink = createUploadLink({
uri: `${host}/graphql`,
credentials: "same-origin"
});
// wsLink
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/`,
options: {
reconnect: true
}
});
// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
const webLink = split(
// split based on operation type
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
wsLink,
httpLink
);
// authMiddleware
const authLink = setContext(async (req, { headers }) => {
// const token = await AsyncStorage.getItem("#token");
const token = "";
return {
headers: {
...headers,
authorization: token ? `${token}` : ""
}
};
});
const errorLink = onError(({ networkError, graphQLErrors }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) console.log(`[Network error]: ${networkError}`);
});
export const client = new ApolloClient({
link: ApolloLink.from([authLink, stateLink, errorLink, webLink]),
cache
});
My server side code if required
//! Using Apollo Server Express
const app = express();
const path = "/graphql";
const schema = genSchema();
export const startServer = async () => {
const server = new ApolloServer({
schema,
context: ({ req }: any) => ({
req,
pubsub,
userLoader: userLoader()
})
});
app.use(cors());
app.use(authMiddleware);
app.use("/images", express.static("images"));
app.use(
"graphql",
graphqlUploadExpress({
uploadDir: "/",
maxFileSize: 100000000,
maxFiles: 10
}),
graphqlHTTP({ schema }) as any
);
server.applyMiddleware({ app, path });
//! Added Subscription Handler
const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);
const port = process.env.PORT || 4000;
await createConnection();
await httpServer.listen({
port
});
console.log(`Server is running on localhost:${port}${server.graphqlPath}`);
};
Rectified. My client side apollo setup should point to ws://localhost:4000/graphql and not just ws://localhost:4000/
// wsLink
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/graphql`,
options: {
reconnect: true
}
});

Resources