提问者:小点点

我的不和谐音乐机器人无法按预期工作


你好,我试着用ChatGPT做一个不和谐的机器人,但我不知道Python。有人能告诉我我的代码有什么问题吗?

所以机器人运行正常,vs Code没有给我任何错误,但是如果我输入*play url…在我的不和中什么都不会发生。

这是我的代码:

从discord. ext导入不和谐命令导入youtube_dl

意图=不一致。意图。默认()意图。成员=真

Bot=commands.Bot(command_prefix='*', intents=intents)

@bot. order()async def play(ctx,*,query):voice_channel=ctx.author.voice.channel如果没有voice_channel:await ctx.send("您没有连接到语音通道")返回

permissions = voice_channel.permissions_for(ctx.me)
if not permissions.connect or not permissions.speak:
    await ctx.send("I don't have permission to join or speak in that voice channel.")
    return

voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)

if not voice_client:
    await voice_channel.connect()
    voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)

with youtube_dl.YoutubeDL() as ydl:
    info = ydl.extract_info(query, download=False)
    url = info['url']
    title = info['title']

ffmpeg_options = {
    'options': '-vn'
}

voice_client.play(discord.FFmpegPCMAudio(url, **ffmpeg_options), after=lambda e: print(f'Finished playing: {e}'))

await ctx.send(f'**Now playing:** {title}')

bot.run(我的信物)


共1个答案

匿名用户

所以正如Peterrrrrrr所说,你需要正确格式化你的代码,不要使用chat gpt,因为它的数据有限,它提供了太多的错误。我对你的代码做了一些修改,这样当用户已经在语音频道时,它就可以加入语音频道。如果没有,用户会收到一条消息。对于播放部分,我也做了一些修改,但是你很可能会收到一个错误,因为youtube_dl由于youtube更新而不再工作,所以卸载youtube_dl使用pip uninstallyoutube_dl,然后使用pip install githttps://github.com/ytdl-org/从github安装master分支youtube-dl.git@master#ege=youtube_dl(你需要git,在这里下载)。为了让机器人播放音乐,你需要安装PyNaCldiscord.py[语音]。还要确保安装asyncio,我们需要这个用于音乐部分。

pip install PyNaCl
pip install discord.py[voice]
pip install asyncio

最后但同样重要的是,您的计算机上需要一个ffmpeg可执行文件。在此处下载ffmpeg。解压zip并在bin文件夹中搜索ffmpeg. exe,然后将其移动到您的bot文件所在的同一目录。这是带有注释的更新代码:

import discord
from discord.ext import commands
import youtube_dl
import asyncio

intents = discord.Intents.default()
intents.members = True
intents.message_content = True #needed for your bot

bot = commands.Bot(command_prefix='*', intents=intents)
#These are options for the youtube dl, not needed actually but are recommended
ytdlopts = { 
    'format': 'bestaudio/best',
    'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0',  
    'force-ipv4': True,
    'preferredcodec': 'mp3',
    'cachedir': False
    
    }

ffmpeg_options = {
        'options': '-vn'
    }

ytdl = youtube_dl.YoutubeDL(ytdlopts)


@bot.command()
async def play(ctx, *, query):
    
    try:
        voice_channel = ctx.author.voice.channel #checking if user is in a voice channel
    except AttributeError:
        return await ctx.send("No channel to join. Make sure you are in a voice channel.") #member is not in a voice channel

    permissions = voice_channel.permissions_for(ctx.me)
    if not permissions.connect or not permissions.speak:
        await ctx.send("I don't have permission to join or speak in that voice channel.")
        return
    
    voice_client = ctx.guild.voice_client
    if not voice_client:
        await voice_channel.connect()
        voice_client = discord.utils.get(bot.voice_clients, guild=ctx.guild)

    loop = asyncio.get_event_loop()
    data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url=query, download=False)) #extracting the info and not downloading the source

    
    title = data['title'] #getting the title
    song = data['url'] #getting the url

    if 'entries' in data: #checking if the url is a playlist or not
            data = data['entries'][0] #if its a playlist, we get the first item of it

    try:
        voice_client.play(discord.FFmpegPCMAudio(source=song,**ffmpeg_options, executable="ffmpeg")) #playing the audio
    except Exception as e:
        print(e)

    await ctx.send(f'**Now playing:** {title}') #sending the title of the video


bot.run('my token')

我已经测试了这段代码,它应该适合您。如果有任何错误等,请告诉我。