大家下午好,
我正在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