You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py机器人的每日定时消息中实现递增天数计数功能

Got it, let's fix that counting issue for your Discord bot! The "counter is not defined" errors you're hitting happen because the counter variable isn't properly set up to persist between your daily task runs. Here's a straightforward implementation that adds the automatic day increment:

Step-by-Step Fix & Full Code

First, we'll initialize a counter outside the task loop, then update it every time the message sends. We'll also generate the message dynamically instead of using a fixed string:

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

client = discord.Client()

# Initialize your starting day count here
day_counter = 13
# Replace these with your actual target user ID and their name
TARGET_USER_ID = 123456789012345678
TARGET_USER_NAME = "Your Friend's Name"
# Replace with your target channel ID
TARGET_CHANNEL_ID = 987654321098765432

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')
    daily_reminder.start()

@tasks.loop(hours=24)
async def daily_reminder():
    global day_counter  # Tell Python we're using the global counter variable
    
    # Get the target channel
    channel = client.get_channel(TARGET_CHANNEL_ID)
    if not channel:
        print("Warning: Target channel not found!")
        return
    
    # Dynamically create the message with the current count
    reminder_msg = f"<@{TARGET_USER_ID}> {day_counter} days and counting: still waiting for {TARGET_USER_NAME} to post -`д´-"
    await channel.send(reminder_msg)
    
    # Increment the counter for the next day
    day_counter += 1

# Optional: Persist the counter between bot restarts
# Uncomment this block to save/load the counter to a text file
# try:
#     with open('day_counter.txt', 'r') as f:
#         day_counter = int(f.read().strip())
# except FileNotFoundError:
#     day_counter = 13  # Fallback to starting value if file doesn't exist
# 
# # Add this line right after day_counter += 1 to save the new value
# with open('day_counter.txt', 'w') as f:
#     f.write(str(day_counter))

my_secret = os.environ['TOKEN']
client.run(my_secret)

Key Fixes Explained

  1. Global Counter: By defining day_counter outside the task function and using the global keyword inside the loop, we ensure the variable's value persists across each daily run. Without global, Python would treat it as a new local variable, causing the "not defined" error.
  2. Dynamic Message: Instead of a fixed msg string, we build the message each time using the current counter value, so it updates automatically every day.
  3. Optional Persistence: The commented-out code saves the counter to a text file, so if your bot restarts, it won't reset the count back to the starting number. Just uncomment those lines to enable this.

This should solve your counting issues and get the bot sending correctly updated daily reminders!

内容的提问来源于stack exchange,提问作者Curulian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:12:43