同时在discord.py中运行两个命令

时间:2020-10-28 23:53:18

标签: python discord.py

我有一个小型机器人,可以从youtube视频下载音频并将其上传到Anonfiles。这是此时的代码:

@commands.command(name='audio')
async def audio_download(self, ctx, name, *, link: str):
    cwd = os.getcwd()
    path = f'{cwd}/media/audio'
    
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
        'outtmpl': f'{path}/{name}.mp3',
        'quiet': True
    }

    abspath = f'{path}/{name}.mp3'

    with ytb.YoutubeDL(ydl_opts) as ydl:
        ydl.download([link])

    r = requests.post('https://api.anonymousfiles.io',
                    files={'file': open(f'{abspath}', 'rb')})

    json_all = json.loads(r.text)
    url_file = json_all["url"]

    await ctx.send(f'File: {url_file}')

    os.remove(abspath)

问题是两个不同的人想同时下载。当这段代码运行时,机器人将停止响应任何命令,直到任务结束为止,直到将文件上传到Anonfiles。有没有办法使此代码异步,并使两个人可以同时使用它?人们 A 要从视频 X 下载音频,人们 B 要从视频 Y 下载音频。 / p>

1 个答案:

答案 0 :(得分:0)

我认为您可以使用如下所示的线程库来做到这一点:

import threading
from threading import Thread

bot1_thread = Thread(target = bot1)
bot2_thread = Thread(target = bot1)