【发布时间】:2021-03-31 16:38:31
【问题描述】:
所以基本上我是在 python 中编写一个不和谐的机器人。它是一个机器人,您可以在其中从商店购买/出售东西,并外出耕种或采矿以获取资源。我需要帮助的主要一点是让函数休息大约 5 分钟。这个机器人可能会在 5 分钟内被多次使用,所以我不能暂停整个代码。显然 time.sleep 将不起作用,因为它会暂停整个脚本。我尝试了一些不同的方法,但效果不佳,我在互联网上找不到太多其他东西。我的代码是:
@client.command()
async def farm(ctx, item):
fakelocation = 11
await get_bank_data()
users = await get_bank_data()
if users[str(ctx.author.id)]["location"] == "Farm":
item = item.lower()
returnholder = 6
product = "none"
user = ctx.author
users = await get_bank_data()
if item == "potato":
product = "potato"
amount = random.randrange(2, 10)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if item == "carrot":
product = "carrot"
amount = random.randrange(4, 12)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if item == "wheat":
product = "wheat"
amount = random.randrange(7, 15)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if item == "apple":
product = "apple"
amount = random.randrange(2, 13)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if item == "banana":
product = "banana"
amount = random.randrange(4, 10)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if item == "orange":
product = "orange"
amount = random.randrange(3, 8)
await ctx.send("Your crops will be given to you at the end of the session!")
returnholder = 5
if returnholder == 6:
await ctx.send("That crop does not exist here!")
return
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index += 1
if t == None:
obj = {"item": product, "amount": amount}
users[str(user.id)]["bag"].append(obj)
except:
obj = {"item": product, "amount": amount}
users[str(user.id)]["bag"] = [obj]
with open("mainbank.json", "w") as f:
json.dump(users, f)
fakelocation = 4
if fakelocation == 11:
await ctx.send("Please move to the Farm to farm!")
return
这是代码,和Mine函数比较相似。它会检查项目是什么,然后如果它存在,它会给你随机数量的项目。我想让它在try: 中停止第一件事,否则它会在时间到之前给你项目。感谢您的帮助!
【问题讨论】:
-
之前的评论很有帮助。但概念是您线程化进程并在该进程的定义中放入睡眠时间
-
@Matiiss 我如何才能线程化这个过程并使其工作?抱歉,我对 Python 很陌生,我不了解我正在研究的一些复杂的东西。
-
欢迎来到stackoverflow。您必须在程序中包含多个线程。请注意,线程是一个高级主题。
-
他已经在使用异步了。 @ACKtbt do
import asyncio; await asyncio.sleep(SECONDS)它是异步的,不会停止你的整个程序。