【问题标题】:python discord music bot youtube_dlpython discord 音乐机器人 youtube_dl
【发布时间】:2021-10-15 23:38:59
【问题描述】:
import discord

import youtube_dl

from discord.ext import commands
-----------------------------------------------
@cat.command(pass_context=True)
async def play(ctx):
    if not ctx.message.author.voice:
        await ctx.send('you are not connected to a voice channel')
        return

    else:
        channel = ctx.message.author.voice.channel

    await channel.connect()

    server = ctx.message.guild
    voice_channel = server.voice.client

    async with ctx.typing():
        player = await YTDLSource.from_url(url, loop = client.loop)
        voice_channel.play(player)
        
    await ctx.send(f'**Music:**{player.title}')

有没有办法解决这个错误?

AttributeError: 'Guild' object has no attribute 'voice'

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    检查这个工作示例。

    import discord
    
    import youtube_dl
    
    from discord.ext import commands
    
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }   
    
    def endSong(guild, path):
        os.remove(path)                                   
    
    @cat.command(pass_context=True)
    async def play(ctx, url):
        if not ctx.message.author.voice:
            await ctx.send('you are not connected to a voice channel')
            return
    
        else:
            channel = ctx.message.author.voice.channel
    
        voice_client = await channel.connect()
    
        guild = ctx.message.guild
    
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            file = ydl.extract_info(url, download=True)
            path = str(file['title']) + "-" + str(file['id'] + ".mp3")
    
        voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
        voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)
    
        await ctx.send(f'**Music: **{url}')
    

    可选的,有用的功能

    如果您愿意,您可以让您的机器人在歌曲停止播放后离开语音频道。在代码末尾添加:

    while voice_client.is_playing():
            await asyncio.sleep(1)
        else:
            await voice_client.disconnect()
            print("Disconnected")
    

    【讨论】:

      【解决方案2】:

      尝试用if 'voice' not in ctx.message.author:替换if not ctx.message.author.voice:

      【讨论】:

      • 错误:voice_channel = server.voice.client AttributeError:'Guild'对象没有属性'voice'
      • @return2749 对voice_channel = server.voice.client 执行类似的检查,看看它是否有voice 键:if 'voice' not in server:...
      猜你喜欢
      • 2018-07-24
      • 2021-05-27
      • 2019-04-30
      • 2021-05-24
      • 2022-12-20
      • 2020-05-15
      • 1970-01-01
      • 2021-04-25
      • 2018-05-18
      相关资源
      最近更新 更多