#javascript #node.js #json #discord #discord.js
Вопрос:
Как я могу исправить » Ошибку [ERR_PACKAGE_PATH_NOT_EXPORTED]: В файле package.json не определено основное значение «экспорт»? Как я могу исправить эту ошибку? Я уже некоторое время пытаюсь, и мне помогли, но мы не можем этого понять. Я вообще не понимаю этой проблемы, и чем больше я об этом думаю, тем больше она меня сбивает с толку.
Код JavaScript:
const { Client, Intents, Collection } = require('discord.js')
const { REST } = require('@discordjs/rest')
const { Routes } = require('discord-api-types/v9')
const Discord = require('discord.js')
const fs = require('fs')
const intents = new Discord.Intents(32767);
const client = new Discord.Client({ intents });
const config = require('./Data/config.json')
const versionNumber = "V1.0.0"
client.once("ready", () => {
console.log('-------------------------------------------');
console.log(`| Successfully logged in as Logic RP#7590 |`);
console.log('-------------------------------------------');
const commands = []
const commands_information = new Collection();
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"))
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
console.log(`Command loaded: ${command.data.name}`)
commands.push(command.data.toJSON())
commands_information.set(command.data.name, command);
}
const rest = new REST({ version: '9' }).setToken(config.token);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationGuildCommands(config.clientID, config.guildID),
{ body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (!commands_information.has(commandName)) return;
try {
await commands_information.get(commandName).execute(client, interaction, config);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
})
})
client.on("guildMemberAdd", async (member) => {
let members = client.guilds.cache.reduce((a, g) => a g.memberCount, 0);
console.log(`${member.user.tag} has joined Logic RP`);
console.log('-------------------------------------------');
const embed = new Discord.MessageEmbed()
.setTitle(`Welcome to the ${member.guild.name} Discord server!`)
.setThumbnail(member.user.displayAvatarURL({ dynamic: true }))
.setColor('GREEN')
.addFields(
{
name: "✅ Have fun!",
value: "The most important thing for us is that YOU have fun! You can chat with others in <#898349995315576883> and have all the fun that you want or talk to the community.",
inline: false
},
{
name: "📘 Check out our rules!",
value: "If you'd like to stay in this server, we ask that you read and follow all of our rules in <#898346754926338048>. This is important.",
inline: false
},
{
name: "🔔 Get your roles!",
value: "If you'd like to get notified for certain events or things related to this server, please check out <#898350339571462155> and get the roles that you want.",
inline: false
},
)
.setFooter(`Logic RP | ${versionNumber} - Member #${members}`)
.setTimestamp()
client.channels.cache.get('898346590245363772').send({embeds: });
})
client.login(config.token);
//npm run dev
Файл JSON:
{
"name": "logic-rp-discord-bot",
"version": "1.0.0",
"description": "Logic RP Discord Bot",
"main": "src/index.js",
"scripts": {
"test": "echo "Error: no test specified" amp;amp; exit 1",
"dev": "nodemon -e js"
},
"author": "killrebeest#1001",
"license": "ISC",
"dependencies": {
"@discordjs/builders": "^0.6.0",
"@discordjs/rest": "^0.1.0-canary.0",
"discord-api-types": "^0.23.1",
"discord.js": "^13.3.0-dev.1634342688.38cc89e",
"lodash": "^4.17.21",
"path": "^0.12.7",
"wokcommands": "^1.5.3"
},
"keywords": []
}
Whois.js Код:
const SlashCommandBuilder = require('@discordjs/builders')
const InteractionResponseType = require('discord-api-types')
const Discord = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName('whois')
.setDescription(`Information about a specified user.`),
async execute(client, interaction, config) {
const { guild, channel } = interaction
const user = interaction.mentions.users.first() || interaction.member.user
const member = guild.members.cache.get(user.id)
console.log(member)
const embed = new Discord.MessageEmbed()
.setTitle(`Who is ${interaction}?`)
.addFields(
{
name: "User Tag:",
value: user.tag
},
{
name: "Is Bot:",
value: user.bot
},
{
name: "Nickname:",
value: member.nickname || 'None'
},
{
name: "Joined Server:",
value: new Date(member.joinedTimeStamp).toLocaleDateString()
},
{
name: "Joined Discord:",
value: new Date(user.createdTimeStamp).toLocaleDateString()
},
{
name: "Roles",
value: member.roles.cache.size - 1
}
)
.setColor('AQUA')
.setThumbnail(interaction.user.displayAvatarURL({ dynamic: true }))
interaction.reply({ embeds: })
}}
Журналы ошибок:
node:internal/modules/cjs/loader:488
throw e;
^
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:Userssjim4DesktopLogic RP Discord Botnode_modulesdiscord-api-typespackage.json
at new NodeError (node:internal/errors:371:5)
at throwExportsNotFound (node:internal/modules/esm/resolve:440:9)
at packageExportsResolve (node:internal/modules/esm/resolve:692:3)
at resolveExports (node:internal/modules/cjs/loader:482:36)
at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:Userssjim4DesktopLogic RP Discord Botsrccommandswhois.js:2:33) {
code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
Любая помощь была бы очень признательна.
Комментарии:
1. Вам, вероятно, понадобится
const { InteractionResponseType } = require('discord-api-types')
Whois.js хотя я не знаком с этой посылкой. Прямо сейчас вам этого не хватает{}
.2. @DoubleJG Я все еще получаю ту же ошибку
Ответ №1:
Из discord-api-types
ридми:
Вы можете импортировать этот модуль, только указав версию API, на которую вы хотите настроить таргетинг. Добавьте /v* к пути импорта, где * представляет версию API.
Таким образом, ваше заявление require должно выглядеть примерно так:
const { InteractionResponseType } = require('discord-api-types/v9');
Ответ №2:
Используйте последнюю discord-api-types
версию , удалите старую версию package.json
и запустите npm i discord-api-types
ее снова. Это сработало для меня.