我有一个简单的discord.py机器人,它几乎只是计数到用户想要的任何数字。到目前为止,这个命令是这样的。
@bot.command()
async def count(ctx, startNum, endNum):
startNum = int(startNum)
endNum = int(endNum)
currentNum = startNum
if startNum > endNum:
await ctx.send("nice try, i'm not counting backwards")
while currentNum < (endNum + 1) or startNum < endNum:
await ctx.send(ctx.message.author.name + ": " + str(currentNum))
currentNum += 1
await ctx.send(ctx.message.author.mention + " I've finished counting to " + str(endNum))
假设你运行 count 10
,它将显示
username: 1
username: 2
username: 3
...
username: 10
我想创建一个命令,几乎允许用户取消 一个特定的计数器 而不是任何其他的。
最好是每个计数器都显示一个单独的计数器ID,然后你可以用类似于 cancel ID
. 它看起来有点像。
> count 1 50
CounterID: 1
CounterID: 2
CounterID: 3
> cancel CounterID
CounterID has been cancelled
如何做到这一点?
在while循环中,你可以添加一个 wait_for
事件,超时1秒。
import asyncio # for the exception
@bot.command()
async def count(...):
# code
# make sure the person cancelling the timer is the original requester
# and they are cancelling it from the same channel
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower().startswith("cancel")
while currentNum < endNum:
try:
msg = await bot.wait_for(message, check=check, timeout=1)
await ctx.send("Your counter has been cancelled!")
break # break the loop if they send a message starting with "cancel"
except asyncio.TimeoutError:
await ctx.send(ctx.author.name + ": " + str(currentNum))
currentNum += 1
虽然这个例子不允许取消特定的计数器(除了用户自己的计数器),但如果你有一些数据库(如json, sqlite, mongodb等),你也许可以存储每个用户的当前计数器ID。如果你有一些数据库(如json、sqlite、mongodb等),你或许可以为每个用户存储当前的计数器ID。
参考文献。