簡體   English   中英

Discord.py VoiceChannel.connect() 導致線程掛起

[英]Discord.py VoiceChannel.connect() causes a thread to hang

我正在嘗試在 python 中編寫一個簡單的 discord 機器人。我希望機器人能夠加入語音頻道,並不斷重復播放 mp3 文件。 我首先嘗試在 on_ready() function 中使用 while 循環,結果很糟糕,這是可以理解的。 我現在已經嘗試使用一個線程來獨立於主線程運行循環,但是 discord.py 的函數使用異步/等待,所以我不得不即興創作(很糟糕)。

import asyncio
import threading

import discord
from discord import app_commands

intents = discord.Intents.all()
client = discord.Client(intents=intents)
discord.Permissions.manage_nicknames = True
tree = app_commands.CommandTree(client)


def targeter():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(play_sounds())
    loop.close()

async def play_sounds():
    for channel in client.guilds[1].channels:
        if str(channel.type) == "voice":
            print("started")
            player_channel = await channel.connect()
            print("done")

@client.event
async def on_ready():
    await tree.sync()
    threading.Thread(target=targeter).start()

client.run("token")

當我運行所述線程時,它到達我引入等待的 discord.VoiceChannel.connect() function 的行並掛起。 命令的 rest 工作正常,只是那個線程。 connect() 命令在正常運行時通常會在幾毫秒內返回一個 VoiceClient。 這與我嘗試跨線程運行函數有關嗎? 如果是這樣,是否有我沒有看到的更好的解決方案?

>>> started

為什么要使用線程? 看看tasks 創建一個每分鍾左右運行一次的任務; 如果它不在其中(又名第一次運行),讓它加入 VC,然后讓它檢查歌曲是否仍在運行/播放。

在此處查看創建player 將播放器 object 保存在任務中,然后當任務循環運行時,您可以執行player.is_done()檢查它是否仍在播放 - 然后再次開始播放歌曲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM