【问题标题】:Bot sends a message if there have been no messages sent in a channel for a specified time如果在指定时间内没有在频道中发送消息,Bot 会发送消息
【发布时间】:2021-07-16 17:31:19
【问题描述】:

所以我目前正在尝试制作一个监视频道的命令,如果在最后 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 但是这个命令只会在我使用命令后没有发送消息的情况下向我发送消息,如果有任何消息命令将停止或在发送警告消息后命令停止观看,我想做所以它一直在看频道

【问题讨论】:

    标签: python discord discord.py


    【解决方案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())
    

    【讨论】:

    • 呃,命令和函数我都试过了,都没有工作,他们没有给我发消息警告我不活动,也许我太笨了
    • 啊,可以试试不带if not new_message:
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2013-02-27
    • 2021-10-25
    • 2023-03-07
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多