voice_channel.play() 不播放音频

时间:2021-07-30 20:11:45

标签: python discord discord.py

我最近决定学习 discord.py 库,并试图制作一个音乐机器人。当我使用“播放”命令时,它不会引发任何错误,但也不会播放任何音频。同样在使用“播放”后,如果使用“暂停”、“停止”和“继续”命令,我会收到一个错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression

代码:

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.vc = None

    @commands.command(name="join",help="Müzük açmadan önce kanala katılırım.")
    async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send(f"{ctx.message.author.mention}Şu anda bir ses kanalında değilsin.")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.send(f"{ctx.message.author.mention}Şu anda başka bir ses kanalındayım.")
        print(ctx.voice_client.is_playing())

    @commands.command(name="disconnect",help="Kanaldan çıkıp giderim.")
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command(name="play",aliases =['p'],help="YouTube linkini alıp oynatırım.")
    async def play(self, ctx, url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options':'vnd'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client
        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url,download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)
        await ctx.send("Şu anda şarkını çalıyorum.")
    @commands.command(name = "pause",help="Müzüğü durdururum.")
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.send("Müzik durduruldu")

    @commands.command(name="stop",help="Müzük kapanır")
    async def stop(self, ctx):
        await ctx.voice_client.stop()
        await ctx.send("Müzüğü kapattım.")

    @commands.command(name = "resume",help="Müzüğü devam ettiririm.")
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.send("Müzik devam ediyor")

def setup(client):
    client.add_cog(music(client))

2 个答案:

答案 0 :(得分:0)

欢迎使用堆栈溢出!主要问题是您的代码没有以正确的方式缩进。您的命令需要缩进,以便它成为 cog 文件的一部分。更新后的代码应该是..

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    // This is of Any type as it will be casted later to the proper DataBinding generated class when the ViewStub layout inflated
    private lateinit var stubBinding: Any

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        val model = ViewModelProvider(this).get(ActivityViewModel::class.java)

        binding.model = model

        // Listener to ViewStub inflation so that we can change its layout
        binding.layoutStub.setOnInflateListener { _, inflated ->
            stubBinding =
                (if (model.isOk) DataBindingUtil.bind<LayoutContainer1Binding>(
                    inflated
                )
                else DataBindingUtil.bind<LayoutContainer2Binding>(
                    inflated
                ))!!
            
            // Changing the text of the inflated layout in the ViewStub using the ViewStubBinding
            if (model.isOk)
                (stubBinding as (LayoutContainer1Binding)).textview.text = "This is Layout container 1"
            else
                (stubBinding as (LayoutContainer2Binding)).textview.text = "This is Layout container 2"
        }


        // Inflating the ViewStub
        if (!binding.layoutStub.isInflated) {
            binding.layoutStub.viewStub?.layoutResource = if (model.isOk)
                R.layout.layout_container_1 else R.layout.layout_container_2

            binding.layoutStub.viewStub?.inflate()
        }

    }

}

其他一切对我来说都很好,但我不使用 youtube-dl 库,所以如果还有更多错误,请告诉我 :D 另外,这也应该修复 TypeError 错误。

答案 1 :(得分:0)

好的,显然 'options':''vnd' 使得它不会出于某种原因播放音频。将 'vnd' 更改为 '-vn' 刚刚解决了音频问题。

至于错误,我只是删除了“停止”、“暂停”和“继续”中的等待命令。所以工作代码看起来像这样:

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.vc = None

    @commands.command(name="join",help="Müzük açmadan önce kanala katılırım.")
    async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send(f"{ctx.message.author.mention}Şu anda bir ses kanalında değilsin.")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.send(f"{ctx.message.author.mention}Şu anda başka bir ses kanalındayım.")

    @commands.command(name="disconnect",help="Kanaldan çıkıp giderim.")
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command(name="play",aliases =['p'],help="YouTube linkini alıp oynatırım.")
    async def play(self, ctx, url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client
        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url,download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)
        await ctx.send("Şu anda şarkını çalıyorum.")
    @commands.command(name = "pause",help="Müzüğü durdururum.")
    async def pause(self,ctx):
        ctx.voice_client.pause()
        await ctx.send("Müzik durduruldu")

    @commands.command(name="stop",help="Müzük kapanır")
    async def stop(self, ctx):
        ctx.voice_client.stop()
        await ctx.send("Müzüğü kapattım.")

    @commands.command(name = "resume",help="Müzüğü devam ettiririm.")
    async def resume(self,ctx):
        ctx.voice_client.resume()
        await ctx.send("Müzik devam ediyor")

def setup(client):
    client.add_cog(music(client))