javascript - 我正在做一个 Discord 机器人,在将机器人连接到语音频道时遇到问题,有什么建议吗?
问题描述
我想从 discordjs/voice 导入 joinVoiceChannel,但它说
SyntaxError: 不能在模块外使用 import 语句
那是因为我使用的是 .cjs 文件,如果我使用的是 .js 文件,那么什么都不会起作用。
谁能帮我如何将 DiscordBot 连接到语音通道,我可以 ping 他但无法连接他。
main.js
import DiscordJS, { Intents } from 'discord.js'
import dotenv from 'dotenv'
import { createRequire } from "module";
dotenv.config()
const client = new DiscordJS.Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
})
const prefix = '!';
const require = createRequire(import.meta.url);
const fs = require('fs');
client.commands = new DiscordJS.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.cjs'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Mariachi is online!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command === 'play') {
client.commands.get('play').execute(message, args);
} else if (command === 'leave') {
client.commands.get('leave').execute(message, args);
}
});
client.login(process.env.TOKEN);
播放.cjs
import { joinVoiceChannel } from "@discordjs/voice";
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
module.exports = {
name: 'play',
description: 'Joins and plays a video from youtube',
async execute(message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissions');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissions');
if (!args.length) return message.channel.send('You need to send the second argument!');
const validURL = (str) =>{
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if(!regex.test(str)){
return false;
} else {
return true;
}
}
if(validURL(args[0])){
const connection = await joinVoiceChannel.join();
const stream = ytdl(args[0], {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
message.channel.send('leaving channel');
});
await message.reply(`:thumbsup: Now Playing ***Your Link!***`)
return
}
const connection = await joinVoiceChannel.join();
const videoFinder = async (query) => {
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if(video){
const stream = ytdl(video.url, {filter: 'audioonly'});
connection.play(stream, {seek: 0, volume: 1})
.on('finish', () =>{
voiceChannel.leave();
});
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}
包.json
{
"name": "discordbot",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@discordjs/opus": "^0.7.0",
"@discordjs/voice": "github:discordjs/voice",
"discord.js": "^13.3.1",
"dotenv": "^10.0.0",
"ffmpeg-static": "^4.4.0",
"yt-search": "^2.10.2",
"ytdl-core": "^4.9.1"
},
"type": "module"
}
这些是我在 StackOverflow 上找到的命令
import { joinVoiceChannel } from "@discordjs/voice";
const connection = joinVoiceChannel(
{
channelId: message.member.voice.channel,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
解决方案
.cjs
文件是 CommonJS。这些需要require
而不是import
关键字
const { joinVoiceChannel } = require("@discordjs/voice")
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')
而且由于您"type": "module"
在 package.json 中,因此.js
文件将需要import
关键字
推荐阅读
- arrays - 如何排除数组列表中不存在的项目?
- amazon-web-services - 如何在 AWS elasticsearch 中通过模板显式放置分片大小?
- amazon-web-services - 告诉 Terraform 忽略不同工作区中的 Route53 资源
- python - 这是否可以从 Django(Python) Web 应用程序调用 QGroundControl 的方法?
- discord.js - MessageEmbed 中的“客户端”存在问题
- cuda - CUDA 统一内存和设备代码中 std::vector 的使用
- swift - 在 UITable 中加载数据时出现问题 - 仅在第二次单击后刷新数据
- ruby-on-rails - facebook auth 自我召回后的sign_in_and_redirect
- python - 如何使用 Python 3 正确操作内存中的 tar 文件?
- c - C++ Libcurl + Cloudflare