如何运行命令的多个实例并能够取消discord.py中的某个实例

2024-06-02 04:49:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的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

这怎么可能呢


Tags: 用户命令sendmessagecount计数器usernameawait
1条回答
网友
1楼 · 发布于 2024-06-02 04:49:09

在while循环中,可以添加超时1秒的wait_for事件:

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


参考文献:

相关问题 更多 >