Why discord.js ?.command.set(command) don't works? - discord.js

I was developing a discord bot and I was wrong to register a slash commands and I wanted to overwrite it with the .set function but it gave me an error in a file that I had not edited.
index.js code:
client.on('messageCreate', async (message) =>{
if(message.content.toLowerCase() === "lava.register"){
const data = {
name: "ban",
description: "Banna un utente dal server",
option: [
{
name: "UTENTE",
description: "Specifica l\'utente da bannare dal server",
type: "USER",
require: true,
},
{
name: "MOTIVO",
description: "Specifica il motivo del ban",
type: "STRING",
require: true,
}
]
};
const comando = await client.guilds.cache.get('957317299289858108')?.commands.set(data);
console.log(comando)
}
})
error:
data: commands.map(c => this.constructor.transformCommand(c)),
^
TypeError: commands.map is not a function
at GuildApplicationCommandManager.set (/Users/Me/Desktop/VolcanoBot/node_modules/discord.js/src/managers/ApplicationCommandManager.js:157:22)
at Client.<anonymous> (/Users/yihanzhou/Desktop/VolcanoBot/index.js:35:87)
at Client.emit (node:events:537:28)
at MessageCreateAction.handle (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/discord.js/src/client/actions/MessageCreate.js:26:14)
at module.exports [as MESSAGE_CREATE] (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:346:31)
at WebSocketShard.onPacket (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:478:22)
at WebSocketShard.onMessage (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:317:10)
at WebSocket.onMessage (/Users/yihanzhou/Desktop/VolcanoBot/node_modules/ws/lib/event-target.js:199:18)
at WebSocket.emit (node:events:537:28)
the file
(VolcanoBot/node_modules/discord.js/src/managers/ApplicationCommandManager.js:157:22)
async set(commands, guildId) {
const data = await this.commandPath({ guildId }).put({
data: commands.map(c => this.constructor.transformCommand(c)),
});
return data.reduce((coll, command) => coll.set(command.id, this._add(command, true, guildId)), new Collection());
}
What should I do?

Try out using client.application.commands.set() for setting global commands.

Related

Problem: TypeError: Cannot read properties of null (reading 'roles')

I'm currently working on a kick command (following reconlx's Kick, Ban, and Unban command tutorial). All commands stop working (including the kick command).
If anyone can take a look, it'd be helpful.
Code for kick.js and the error is down below.
const { MessageEmbed, Message } = require("discord.js");
module.exports = {
name: 'kick',
description: 'Kicks a member',
userPermissions: ["KICK_MEMBERS"],
options: [
{
name: "member",
description: "The member you wish to kick",
type: "USER",
required: true
},
{
name: "reason",
description: "Reason for kicking",
type: "STRING",
required: false
},
],
/**
* #param {Client} client
* #param {CommandInteraction} interaction
* #param {String[]} args
*/
run: async (client, interaction, args) => {
const target = interaction.options.getMember("target");
const reason =
interaction.options.getString("reason") || "No reason(s) provided";
const rolePositionCheck = new MessageEmbed()
.setTitle("You can't kick a person with a higher role than yours!")
.setFooter({ text: "Error: Lower Role Position"})
if (
target.roles.highest.position >=
interaction.member.roles.highest.position
)
return interaction.followUp({
embeds:
[rolePositionCheck],
});
// Message which is sent to the person kicked
const kickMessage = new MessageEmbed()
.setTitle(`You've been kicked from ${interaction.guild.name}`)
.setFooter({ text: `Reason: ${reason}` })
await target.send({ embeds: [kickMessage] });
// The action of kicking, along with the reason
target.kick(reason)
// Message which is sent to the mod who kicked.
const kickAftermath = new MessageEmbed()
.setTitle(`${target.user.tag} has been kicked!`)
.setFooter({ text: `${reason}` })
interaction.followUp({
embeds:
[kickAftermath],
});
},
};
Error
TypeError: Cannot read properties of null (reading 'roles')
at Object.run (C:\Users\admin\Desktop\Tonkotsu\SlashCommands\moderation\kick.js:38:20)
at Client.<anonymous> (C:\Users\admin\Desktop\Tonkotsu\events\interactionCreate.js:27:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Mongoose: TypeError: Invalid value for schema path `guildId.type`, got value "undefined"

I got this error but I don't know what I have done wrong.
My code:
const mongoose = require('mongoose');
const GuildConfigSchema = new mongoose.Schema({
guildId: {
type: mongoose.SchemaType.String,
required: true,
unique: true,
},
prefix: {
type: mongoose.SchemaType.String,
required: true,
default: 'b!',
},
defaultRole: {
type: mongoose.SchemaType.String,
required: false,
},
memberLogChannel: {
type: mongoose.SchemaType.String,
required: false,
},
});
module.exports = mongoose.model('GuildConfig', GuildConfigSchema);
And my guild create event where I am setting the values of the database:
// https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-guildCreate
const BaseEvent = require('../utils/structures/BaseEvent');
const GuildConfig = require('../database/schemas/GuildConfig');
module.exports = class GuildCreateEvent extends BaseEvent {
constructor() {
super('guildCreate');
}
async run(client, guild) {
try {
const guildConfig = await GuildConfig.create({
guildId: guild.id,
});
console.log('Successfully joined server!');
} catch(err) {
console.log(err);
}
}
}
My error:
TypeError: Invalid value for schema path `guildId.type`, got value "undefined"
Does anyone see what I've done wrong?
explicitly export GuildConfigSchema
module.exports.GuildConfigSchema = GuildConfigSchema;
and use destructuring where the schema is required.
const { GuildConfigSchema } = require("path to schema file");

DiscordJS v13 AudioPlayer is stuck on buffering when trying to stream audio from a youtube video

Here is the code so far for my discord music bot. I believe the bot has the appropriate permissions, and is able to join the voice channel of the person who called the "!play" command. The issue I am having is that I can't seem to figure out why the audio stream is stuck on the "buffering" state. The docs states that the "buffering" state should either go through or fail, but it appears to be stuck.
client.on("messageCreate", async message => {
if (message.content.slice(0, 6) == "!play ") {
// check input to see if it is a youtube URL
let input = message.content.slice(6);
if (isYoutubeUrl(input)) {
url = input;
} else {
formatInput(input);
url = await searchVideo(searchTerm);
}
if (message.member.voice.channelId !== null) {
const permissions = message.member.voice.channel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
const connection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
})
const stream = await ytdl(url, { filter:'audioonly' });
const player = createAudioPlayer();
var resource = createAudioResource(stream, { seek: 0, volume: 1 });
player.play(resource);
connection.subscribe(player);
} else {
message.reply("You need to be in a voice channel to play music!");
}
}
})
Here is what comes up when I console.log the player itself
<ref *1> AudioPlayer {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
subscribers: [
PlayerSubscription {
connection: [VoiceConnection],
player: [Circular *1]
}
],
_state: {
status: 'buffering',
resource: AudioResource {
playbackDuration: 0,
started: false,
silenceRemaining: -1,
edges: [Array],
playStream: [OggDemuxer],
metadata: null,
silencePaddingFrames: 5,
audioPlayer: [Circular *1]
},
onReadableCallback: [Function: onReadableCallback],
onFailureCallback: [Function: onFailureCallback],
onStreamError: [Function: onStreamError]
},
behaviors: { noSubscriber: 'pause', maxMissedFrames: 5 },
debug: [Function (anonymous)],
[Symbol(kCapture)]: false
}
Turns out that the stream was not the issue. I just needed to use the "getVoiceConnection" component from the "#discordjs/voice" package and broadcast the stream to that connection instead.

TypeError: Cannot read property 'startsWith' of undefined

I will only publish the part of the code that gives me errors.
When I run the bot it takes about 3 seconds and the bot crashes with the error that I have placed below.
In case it helps something to fix the error, the bot is a ticket bot to support users, it consists of reacting to an emoji and the bot creates a room with permissions and a message, you can close the ticket and the room is removed.
const discord = require('discord.js');
const client = new discord.Client();
const config = require('./config.json');
var userTickets = new Map();
client.login(config.token);
client.on('ready', () => {
console.log(client.user.username + " has logged in.");
client.user.setPresence( {
status: "online",
game: {
name: "Tickets",
type: "WATCHING"
}
})
});
// code
client.on('message', message => {
if(message.author.bot) {
if(message.embeds.length === 1 && message.embeds[0].description.startsWith('Reacc')) {
message.react(idemoji1).then( () => message.react(idemoji2)).then( () => message.react(idemoji3))
.then(msgReaction => console.log('reacted'))
.catch(err => console.log(err));
}
if(message.embeds.length === 1 && message.embeds[0].description == '¡Gracias por crear el ticket!\nEl soporte se pondrá en contacto contigo lo antes posible.\n\nPor favor, responde las preguntas que se te hacen a continuación para poder date el mejor soporte.\n\n Si no escribes nada, el ticket se cerrará en 2 horas.\n\nPara cerrar este ticket reacciona a 🔒') {
message.react(emoji5)
.then(reaction => console.log("A reaccionado con " + reaction.emoji.name))
.catch(err => console.log(err));
}
};
Console error:
C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\ticketbot-reaction.js:43
if(message.embeds.length === 1 && message.embeds[0].description.startsWith('Reacc')) {
^
TypeError: Cannot read property 'startsWith' of undefined
at Client.<anonymous> (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\ticketbot-reaction.js:43:73)
at Client.emit (events.js:315:20)
at MessageCreateHandler.handle (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
at WebSocketConnection.onPacket (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\nilma\Documents\Discord Bots\Discord-Ticket-Psyco\node_modules\ws\lib\websocket.js:789:20)
at Receiver.emit (events.js:315:20)

React - Testing a wrapper for server request with Jest and mock throws: "Error: read ECONNRESE"

TL;DR: How can I test a function that wraps fetch with React?
I'm building a React app with TypeScript. To use the fetch api I added these libs to my tsconfig:
"lib": ["es2017", "dom"],
Now I wrote the following function:
import { Schema } from "normalizr";
import { camelizeAndNormalize } from "../../core";
export const getRequest = (fullUrlRoute: string, schema: Schema) =>
fetch(fullUrlRoute).then(response =>
response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return Promise.resolve(camelizeAndNormalize(json, schema));
})
);
The function camelizeAndNormalize literally does what it says. (I'm normalizing my state for Redux using normalizr).
Now I wanted to test this wrapper function with the following Jest test:
import fetch from "jest-fetch-mock";
import { schema } from "normalizr";
import { getRequest } from "./getRequests";
const response = {
author: {
id: "1",
name: "Paul"
},
comments: [
{
commenter: {
id: "2",
name: "Nicole"
},
id: "324"
}
],
id: "123",
title: "My awesome blog post"
};
const expected = {
entities: {
articles: {
"123": {
author: "1",
comments: ["324"],
id: "123",
title: "My awesome blog post"
}
},
comments: {
"324": { id: "324", commenter: "2" }
},
users: {
"1": { id: "1", name: "Paul" },
"2": { id: "2", name: "Nicole" }
}
},
result: "123"
};
const fullTestUrl = "https://google.com";
const user = new schema.Entity("users");
const comment = new schema.Entity("comments", {
commenter: user
});
const testSchema = new schema.Entity("articles", {
author: user,
comments: [comment]
});
describe("get request", () => {
beforeEach(() => {
fetch.resetMocks();
});
it("calls the given fullUrlRoute and returns data", () => {
fetch.mockResponseOnce(JSON.stringify(response));
expect.assertions(3);
return getRequest(fullTestUrl, testSchema).then(res => {
expect(res).toEqual(expected);
expect(fetch.mock.calls.length).toEqual(1);
expect(fetch.mock.calls[0][0]).toEqual(fullTestUrl);
});
});
it("recognizes when a response's status is not okay", () => {
fetch.mockResponseOnce(JSON.stringify({ ok: false }), { status: 403 });
expect.assertions(1);
return getRequest(fullTestUrl, testSchema).catch(err => {
expect(err.ok).toEqual(false);
});
});
it("recognizes a failed fetch request", () => {
fetch.mockReject(new Error("fake error message"));
expect.assertions(1);
return getRequest(fullTestUrl, testSchema).catch(err => {
expect(err).toEqual(Error("fake error message"));
});
});
});
In this test I mocked fetch using jest-fetch-mock. This test throws the error though:
FAIL src/services/utils/serverRequests/GET/getRequests.test.ts
● Console
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 68.178.213.61:443
at Object.dispatchError (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:65:19)
at Request.client.on.err (/Users/jan/Startup/pontemio/pontem/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:676:20)
at Request.emit (events.js:165:20)
at Request.onRequestError (/Users/jan/Startup/pontemio/pontem/node_modules/request/request.js:881:8)
at ClientRequest.emit (events.js:160:13)
at TLSSocket.socketErrorListener (_http_client.js:389:9)
at TLSSocket.emit (events.js:160:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:152:19) undefined
Why is the mock not working? How can I test a function that uses fetch in React with Jest?
Found out what I was missing out on. I needed to add the following to my src/setupTests.ts:
// react-testing-library renders your components to document.body,
// this will ensure they're removed after each test.
// this adds jest-dom's custom assertions
import "jest-dom/extend-expect";
import "react-testing-library/cleanup-after-each";
// setupJest.js or similar file
const globalAny: any = global;
// tslint:disable-next-line
globalAny.fetch = require("jest-fetch-mock");

Resources