如何在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
- Global Counter: By defining
day_counteroutside the task function and using theglobalkeyword inside the loop, we ensure the variable's value persists across each daily run. Withoutglobal, Python would treat it as a new local variable, causing the "not defined" error. - Dynamic Message: Instead of a fixed
msgstring, we build the message each time using the current counter value, so it updates automatically every day. - 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
相关产品推荐
相关产品推荐

