所以我目前正在尝试创建一个监视频道的命令,如果在过去 x 分钟内没有发送消息,它将发送一条消息
我的代码是:
@client.command()
async def watch(ctx, time : int):
channel = ctx.channel
async for message in channel.history(limit = 1):
past_message = message.created_at
await asyncio.sleep(time)
async for message in channel.history(limit = 1):
new_message = message.created_at
if past_message == new_message:
if not new_message:
channel = client.get_channel(816741369682985012)
await channel.send("<@400349192125415436> bot is down")
我得到了代码 this post 但是只有在我使用该命令后没有发送任何消息时,此命令才会向我发送消息,如果有任何消息该命令将停止或发送警告消息后该命令停止观看,我想要让它一直在看频道
答案 0 :(得分:1)
如果要查看通道,执行命令后,可以简单地循环运行
@client.command()
async def watch(ctx, time : int):
channel = ctx.channel
while True:
async for message in channel.history(limit = 1):
past_message = message.created_at
await asyncio.sleep(time)
async for message in channel.history(limit = 1):
new_message = message.created_at
if past_message == new_message:
channel = client.get_channel(816741369682985012)
await channel.send("<@400349192125415436> bot is down")
然而,有了这个,你将不得不使用命令开始观看。
如果您想在不使用命令的情况下开始观看,则需要在客户端主循环中注册该函数。
async def watch():
channel = client.get_channel(816741369682985012)
while True:
async for message in channel.history(limit = 1):
past_message = message.created_at
await asyncio.sleep(time)
async for message in channel.history(limit = 1):
new_message = message.created_at
if past_message == new_message:
await channel.send("<@400349192125415436> bot is down")
然后通过
注册函数client.loop.create_task(watch())