【问题标题】:Calling await function in "after = lambda"在“after = lambda”中调用 await 函数
【发布时间】:2022-01-26 01:50:10
【问题描述】:

我目前正在开发一个在语音频道中播放音乐的不和谐机器人 (python 3.8.10)。 我有一个音乐队列和一个函数,它播放队列中的第一首歌曲,将其删除,然后在歌曲结束时调用自身。 问题是 lambda 函数必须是非等待的,我真的不知道如何避免这个问题。 感谢您的帮助

# plays next song in the queue
    # this function can be called from
        # the play command if the user adds a song to the music queue (and the bot is not playing anything)
        # the play_music() function when the previous song ends
        # the skip command (called by the user)
    async def play_music(self, ctx):
        try:
            if len(self.music_queue) > 0:
                # music queue is a list, each element composed by a playlist (dictionary) and a voice channel
                # so [0] means the first song, [0] means the playlist, ['source'] the value of source in the disctionary
                song_url = self.music_queue[0][0]['source']
                self.now_playing = self.music_queue[0]
                # removes the first element because it is about to be played
                self.music_queue.pop(0)
                if not self.voice_channel.is_playing():
                    # here's the error!!!
                    self.voice_channel.play(discord.FFmpegPCMAudio(song_url, **self.FFMPEG_OPTIONS), after = lambda e: self.play_music(ctx))
                # transforms the volume
                self.voice_channel.source = discord.PCMVolumeTransformer(self.voice_channel.source, volume=self.volume)
                # gets the time stamp of the playing song
                self.music_position = (datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
                self.is_playing = True
            else:
                self.is_playing = False
        except youtube_dl.DownloadError or HTTPError:
            # TODO: send message
            print('download error')
            return

我的例外是:

RuntimeWarning: coroutine 'music_cog.play_music' was never awaited

P.S.=奇怪的是,它仍然有效,虽然我得到了一个错误!

【问题讨论】:

  • 警告不是错误。仔细查看消息,并提供完整的堆栈跟踪
  • 确实如此,谢谢。从不等待函数是否会导致任何问题,或者我可以忽略警告吗?
  • @Liuk23,不,如果你不必依赖awaited协程的结果,例如下一行代码打印协程结果的情况.如果不是这种情况,您可以忽略警告。也许this 可以提供帮助。

标签: python python-3.x discord.py


【解决方案1】:

我实际上在这里找到了解决方案: how-to-use-await-in-a-python-lambda

就我而言,这就是我重写代码的方式:

self.voice_channel.play(discord.FFmpegPCMAudio(song_url, **self.FFMPEG_OPTIONS),
                                        after = lambda ctx: (await self.play_music(ctx) for _ in '_').__anext__())

【讨论】:

    猜你喜欢
    • 2022-01-27
    • 2020-01-31
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2019-08-28
    • 2019-09-19
    • 2014-08-11
    • 1970-01-01
    相关资源
    最近更新 更多