使用discord.py运行多个命令

时间:2020-06-20 03:45:34

标签: python discord.py

使用discord.py和python:

好吧,基本上我有这个机器人,可以每分钟更新某个游戏的最佳价格。但是,当我这样做时,其他人将无法访问该机器人。例如,假设我有一个名为“ hello”的命令,该命令在聊天时会打出问候。由于代码始终运行,因此用户无法调用命令hello,因为代码太忙于运行每分钟更新的代码。有什么办法喜欢它,以便updateminute代码可以在其他人也可以输入命令的同时运行吗?

import discord
import asyncio
import bazaar
from discord.ext import commands, tasks

client = commands.Bot(command_prefix = '.')


@client.command()
async def calculate(ctx):
    while True:
        await ctx.send(file2.calculate())
        await asyncio.sleep(210)

@client.command()
async def hello(ctx):
    await ctx.send("Hello")

client.run(token)

在file2.py中:

def updateminute():
    for product in product_list:
       #Grab Api and stuff
       #check to see whether it is profitable
       time.sleep(0.3) #cause if i don't i will get a key error

    #calculate the stuff
    #return the result

总而言之,由于机器人太忙于计算更新分钟并等待,其他人无法访问该机器人。我有什么办法可以解决此问题,以便机器人计算出自己的东西,从而使人们可以使用机器人命令?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以查看threading!基本上,运行两个单独的线程:一个用于接收请求,一个用于更新价格。

答案 1 :(得分:1)

您还可以考虑将其转换为异步功能,从本质上讲,它可以更轻松地并行运行事物。 因此,您的标准def将变为async def,然后要调用该函数,您只需在其之前添加一个等待,所以await file2.calculate()

希望它会有所帮助,并且也易于理解