如何在discord.py中编写可在指定日期时间自动执行的后台任务?已尝试代码但遭遇协程未等待警告
Hey there! Let's break down what's going wrong and get your scheduled background task working properly.
Why You're Seeing That Error
The RuntimeWarning: coroutine 'sometask' was never awaited happens because:
- You defined an async function (
sometask) but never actually started it. Discord.py's background tasks need to be registered and launched properly with the library's task system. - Your code has a few syntax/setup issues (like invalid time definitions) that are preventing the task from running as intended.
Step-by-Step Fix & Correct Implementation
Here's the revised code with clear explanations:
1. Import Required Modules
Make sure you have all necessary imports at the top of your file:
import discord import datetime from discord.ext import tasks, commands
2. Initialize Your Bot/Client
Don't forget to enable the necessary intents (you'll need message send permissions at minimum):
# Enable intents - adjust based on your bot's needs intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix="!", intents=intents)
3. Define Your Scheduled Task
We'll use discord.py's @tasks.loop() system, and handle the scheduled time correctly (note: discord.utils.sleep_until uses UTC time, so adjust your target time accordingly):
# Define your target time in UTC (adjust hours/minutes to your desired UTC time) TARGET_TIME = datetime.time(hour=21, minute=20, tzinfo=datetime.timezone.utc) async def get_next_run_time(): """Calculate the next time the task should run (handles if current time is past target)""" now = datetime.datetime.now(datetime.timezone.utc) next_run = datetime.datetime.combine(now.date(), TARGET_TIME, tzinfo=datetime.timezone.utc) # If current time is already past today's target, schedule for tomorrow if now > next_run: next_run += datetime.timedelta(days=1) return next_run @tasks.loop(count=None) # Infinite loop to run daily async def sometask(): # Get the channel - make sure the bot has access to it valid_channel = client.get_channel(814734276439441461) if not valid_channel: print("Could not find the target channel!") return # Send your scheduled message await valid_channel.send("It's time!") print("Task executed successfully") # Wait until the next scheduled time next_run = await get_next_run_time() await discord.utils.sleep_until(next_run)
4. Start the Task When the Bot is Ready
Launch the task only after the bot has fully connected to Discord (otherwise, get_channel might return None):
@client.event async def on_ready(): print(f"Logged in as {client.user}") # Start the scheduled task await sometask.start()
5. Run Your Bot
Don't forget to add your bot token at the end:
client.run("YOUR_BOT_TOKEN_HERE")
Key Notes to Remember
- Time Zones: Discord.py's
sleep_untiluses UTC. If you want to use your local time, convert it to UTC first (e.g., if your local time is 3:48 PM UTC+5, that's 10:48 AM UTC). - Channel Access: Ensure your bot has the
SendMessagespermission in the target channel, and that the channel ID is correct. - Task Management: If you need to stop the task later, you can use
sometask.stop()in another command or event.
内容的提问来源于stack exchange,提问作者Haider Nawaz




