大家下午好,

我正在try 使用Discord创建Discord机器人.py的最终目标是从Discord中的一个命令启动,它开始计算自发出start命令以来的天数,并在每天早上向Discord发送一条包含计数的消息.我还将有一个命令重置计数,另一个命令取消计数器.

我的问题是,我试图使用discord.ext task for the loop,但我显然不知道如何正确使用它,我在网上的研究也没有让我更清楚.我希望这里的一些人能把我引向正确的方向.我在下面提供了我的代码.

当我执行代码时,我期望发生什么:

  • 我发出$start arg命令,机器人会发送一条消息"已经过了X分钟"
  • 每隔10秒,机器人会发送相同的消息,直到1分钟过go ,然后消息会显示"已经过了X+1分钟"
  • 继续循环直到取消

实际发生的情况:

  • 我发出$start arg命令,机器人会发送一条消息"已经过了X分钟"
  • 没别的了.没有其他消息或任何discord的事情发生,控制台中没有显示错误.

该代码目前托管在replit上.com,因此有了keep_alive函数,使用UpTimeRobot使机器人保持活动状态.

import discord
import os
import keep_alive
from datetime import date, datetime, time, timedelta
from discord.ext import commands, tasks

bot = commands.Bot(command_prefix="$")
init_count = 0
count = 0
channel_id = My_Channel_ID_Here

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@tasks.loop(seconds=10, count=None, reconnect=True)
async def min_counter():
    global count
    global init_count
    count = init_count
    today = datetime.today()
    now = datetime.today()
    channel = bot.get_channel(channel_id)

    if today.minute != now.minute:
            # increment count by 1
      count = count + 1
      today = now
      print('Count: ' + str(count))
      await channel.send('It Has Been ' + str(count) + ' Minutes.') # Send message of minutes count

@bot.command() # Command to start the counter
async def start (ctx, arg: int): # arg is initial number of minutes to start with
    global init_count
    init_count = arg
    await ctx.send('It Has Been ' + str(init_count) + ' Minutes.') # Send message of minutes count
    min_counter.start()

@bot.command() # Command to reset counter
async def reset (ctx):
    global count
    count = 0
    await ctx.send('It Has Been 0 Minutes.') # Send message that count is not zero

@bot.command() # Command to stop the counter
async def stop (ctx):
    min_counter.cancel()
    await ctx.send('Counter Stopped.')

keep_alive.keep_alive() # keep alive function call
bot.run(os.getenv('TOKEN')) # Discord bot private token call

推荐答案

快速判断时,您正在循环方法min_counter(),但每次调用时,您都将nowtoday的值更改为datetime.today().

所以当你比较这里的值时:

if today.minute != now.minute:
  # increment count by 1
  count = count + 1
  today = now
  print('Count: ' + str(count))
  await channel.send('It Has Been ' + str(count) + ' Minutes.') # Send message of minutes count

这将始终判断为False.

Easy Fix

虽然我不太喜欢使用globals,但下面是我们如何解决这个问题,保持您现在的风格.

启动计数器并在全局范围内初始化名为start_time的变量:

@bot.command() # Command to start the counter
async def start (ctx, arg: int): # arg is initial number of minutes to start with
    global init_count, start_time
    start_time = datetime.today()
    await ctx.send('It Has Been ' + str(init_count) + ' Minutes.') # Send message of minutes count
    min_counter.start()

然后判断循环中的start_time是否等于now:

@tasks.loop(seconds=10, count=None, reconnect=True)
async def min_counter():
    global count, start_time, init_count
    now = datetime.today()
    channel = bot.get_channel(channel_id)

    if start_time != now:
      # increment count by 1
      count = count + 1
      print('Count: ' + str(count))
      await channel.send('It Has Been ' + str(count) + ' Minutes.') # Send message of minutes count

如果一切顺利,请告诉我,如果需要,我很乐意进一步帮助.

Python相关问答推荐

过载功能是否包含Support Int而不是Support Int?

阅读Polars Python中管道的函数定义

拆分pandas列并创建包含这些拆分值计数的新列

根据给定日期的状态过滤查询集

Python中使用时区感知日期时间对象进行时间算术的Incredit

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

根据条件将新值添加到下面的行或下面新创建的行中

如何比较numPy数组中的两个图像以获取它们不同的像素

如何使用html从excel中提取条件格式规则列表?

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

如何在python polars中停止otherate(),当使用when()表达式时?

为什么抓取的HTML与浏览器判断的元素不同?

如何使用Numpy. stracards重新编写滚动和?

在pandas数据框中计算相对体积比指标,并添加指标值作为新列

在单次扫描中创建列表

Matplotlib中的字体权重

Cython无法识别Numpy类型

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

从一个df列提取单词,分配给另一个列

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上