我正在做一个 Discord 机器人,在将机器人连接到语音频道时遇到问题,有啥建议吗?

Posted

技术标签:

【中文标题】我正在做一个 Discord 机器人,在将机器人连接到语音频道时遇到问题,有啥建议吗?【英文标题】:I'm doing a Discord bot, and having trouble connecting bot to voice channel, any suggestions?我正在做一个 Discord 机器人,在将机器人连接到语音频道时遇到问题,有什么建议吗? 【发布时间】:2021-12-26 04:54:56 【问题描述】:

我想从 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);

play.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');
        
    

package.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"

这些是我在 *** 上找到的命令

import  joinVoiceChannel  from "@discordjs/voice";

const connection = joinVoiceChannel(
    
        channelId: message.member.voice.channel,
        guildId: message.guild.id,
        adapterCreator: message.guild.voiceAdapterCreator
    );

【问题讨论】:

为什么同时使用es6模块和普通js模块? 这是我自己 ping 通的唯一方法。 【参考方案1】:

.cjs 文件是 CommonJS。这些需要require 而不是import 关键字

const  joinVoiceChannel  = require("@discordjs/voice")
const ytdl = require('ytdl-core')
const ytSearch = require('yt-search')

由于你在 package.json 中有 "type": "module".js 文件将需要 import 关键字

【讨论】:

我现在这样做了,但现在它说找不到模块。 好像没有安装,做npm install @discordjs/voice【参考方案2】:
const  joinVoiceChannel  = require('@discordjs/voice');

在你的 module.exports 上方使用它,它应该开始工作,但在那之后我遇到了音频问题,它将加入通话但不播放任何音频

我的错误代码是 connection.play(stream, seek: 0, volume: 1, type: "opus") ReferenceError: 未定义连接

【讨论】:

以上是关于我正在做一个 Discord 机器人,在将机器人连接到语音频道时遇到问题,有啥建议吗?的主要内容,如果未能解决你的问题,请参考以下文章

Discord.js 在嵌入链接中将 api 连接到不和谐机器人

为啥我的 Heroku Discord 机器人无法连接到端口后崩溃? [复制]

有没有办法在将消息从节点服务器发布到频道时获取 Discord 消息 ID?

Discord bot 正在运行,但无法连接到服务器

检查 Discord 机器人是不是在线

discord.py bot 使用 Pillow - ValueError:图像不匹配