首页 > 解决方案 > 为什么我的机器人没有在 discord py 中发送消息

问题描述

我的代码基本上是对当前时区进行条件语句。如果该时区条件中的时间为真,则它会发送一条消息来锁定角色。但是,当我将代码放入 discord 的 py 函数中时,它不会发送消息

import os
import discord
from discord.ext import commands 
import datetime
import pytz


intents = discord.Intents.default() 
intents.members = True
client = commands.Bot(command_prefix = '?',intents=intents) #sets prefix 
client.remove_command('help')


f = 19
m = 0 
@client.event
async def on_ready():
    await client.change_presence(status=discord.Status.do_not_disturb, activity= discord.Activity(name="Around ;)", type=discord.ActivityType.watching))
    print('ready')

@client.event
async def time_check():
    await client.wait_until_ready()
    while not client.is_closed:
        cst = datetime.datetime.now(tz=pytz.timezone('US/Central')).time()
        if cst.hour == 19 and cst.minute == 35:
            channel = client.get_channel(760182149839716423)
            await channel.send("<@&811801850771800134>")
            await channel.send("<@&811808231218610266>")
            await channel.send("<@&811802000463101963>")
        elif cst.hour == 19 and cst.minute == 40:
            channel = client.get_channel(760182149839716423)
            await channel.send("<@&811801850771800134>")
            await channel.send("<@&811808231218610266>")
            await channel.send("<@&811802000463101963>")
        elif cst.hour == 9 and cst.minute == 00:
            channel = client.get_channel(760182149839716423)
            await channel.send("<@&811801850771800134>")
            await channel.send("<@&811808231218610266>")
            await channel.send("<@&811802000463101963>")
        elif cst.hour == 13 and cst.minute == 00:
            channel = client.get_channel(760182149839716423)
            await channel.send("<@&811801850771800134>")
            await channel.send("<@&811808231218610266>")
            await channel.send("<@&811802000463101963>")
            break
        elif cst.hour == 18 and cst.minute == 00:
            channel = client.get_channel(760182149839716423)
            await channel.send("<@&811801850771800134>")
            await channel.send("<@&811808231218610266>")
            await channel.send("<@&811802000463101963>")
            break

client.loop.create_task(time_check())

          
client.run('TOKEN') 

标签: pythonpython-3.xdiscorddiscord.py

解决方案


因为“time_check”不是一个有效的事件。

您可能希望将其作为循环运行。

就这样做吧。

from discord.ext import tasks
 # then on your time_check function, change @client.event for:

@tasks.loop(minutes=1)
async def time_check():
    # the rest of your function

#before client.run()
time_check.start()

希望有效


推荐阅读