【问题标题】:Running multiple commands with discord.py使用 discord.py 运行多个命令
【发布时间】:2020-10-10 08:43:05
【问题描述】:

使用 discord.py 和 python:

好吧,基本上我有这个机器人,它每分钟都会更新某个游戏的最优惠价格。但是,当我这样做时,其他人无法访问该机器人。例如,假设我有一个名为“hello”的命令,当被调用时,它会在聊天中打印出 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

综上所述,由于 bot 忙于计算 updateminute 和等待,其他人无法访问该 bot。有什么办法可以尝试解决这个问题,以便机器人计算它的东西,以便人们可以使用机器人命令?谢谢!

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你也可以考虑把它变成一个异步函数,本质上让并发运行更容易。 因此,您的标准 def 将变为 async def 然后调用该函数,您只需在其前面添加一个 await 即可 await file2.calculate()

      希望它有所帮助,也更容易理解

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-20
        • 1970-01-01
        • 1970-01-01
        • 2021-04-16
        相关资源
        最近更新 更多