【问题标题】:How to send message without command or event discord.py如何在没有命令或事件 discord.py 的情况下发送消息
【发布时间】:2020-12-29 23:00:28
【问题描述】:

我正在使用 datetime 文件来打印:现在是早上 7 点,每天早上 7 点。现在因为这超出了命令或事件引用,我不知道如何发送一条不和谐的消息说现在是早上 7 点.只是为了澄清一下,这不是警报,它实际上是为我的学校服务器发送的,它会在早上 7 点发送一份我们需要的所有东西的清单。

import datetime
from time import sleep
import discord

time = datetime.datetime.now


while True:
    print(time())
    if time().hour == 7 and time().minute == 0:
        print("Its 7 am")
    sleep(1)

这就是早上 7 点触发警报的原因。我只想知道如何在触发时不和谐地发送消息。

如果您需要任何说明,请询问。 谢谢!

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    Discord.py docs 开始,当您设置客户端时,您可以使用以下格式直接向频道发送消息:

    channel = client.get_channel(12324234183172)
    await channel.send('hello')
    

    一旦你有了你的频道(在你设置好你的客户端之后),你可以根据需要编辑代码的 sn-p 以选择适当的频道以及所需的消息。请记住"You can only use await inside async def functions and nowhere else.",因此您需要设置一个异步函数来执行此操作,而您的简单While True: 循环可能无法正常工作

    【讨论】:

      【解决方案2】:

      从discord.py的文档中,你首先需要通过它的id来获取频道,然后你可以发送一个消息。

      见:https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-send-a-message-to-a-specific-channel

      您必须直接获取频道,然后调用相应的方法。示例:

      channel = client.get_channel(12324234183172)
      await channel.send('hello')
      

      希望,这会有所帮助。

      【讨论】:

      • 它给出错误SyntaxError: 'await' outside function
      【解决方案3】:

      您可以创建一个后台任务来执行此操作并将消息发布到所需的频道。

      您还需要使用asyncio.sleep() 而不是time.sleep(),因为后者会阻塞并且可能会冻结和崩溃您的机器人。

      我还添加了一项检查,以便频道不会在早上 7 点每秒都发送垃圾邮件。

      from discord.ext import commands
      import datetime
      import asyncio
      
      time = datetime.datetime.now
      
      bot = commands.Bot(command_prefix='!')
      
      async def timer():
          await bot.wait_until_ready()
          channel = bot.get_channel(123456789) # replace with channel ID that you want to send to
          msg_sent = False
      
          while True:
              if time().hour == 7 and time().minute == 0:
                  if not msg_sent:
                      await channel.send('Its 7 am')
                      msg_sent = True
              else:
                  msg_sent = False
      
          await asyncio.sleep(1)
      
      bot.loop.create_task(timer())
      bot.run('TOKEN')
      

      【讨论】:

      • 只是出于好奇,这段代码每秒都在刷新,对吧? msg_sent 每天都会刷新吗?
      • 是的,await asyncio.sleep(1) 等待 1 秒。您可以根据需要增加。 msg_sent 将在早上 7 点第一次切换到 True,并在早上 7 点过去后切换到 False(所以在 07:01)
      猜你喜欢
      • 2018-09-24
      • 2021-07-23
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2020-09-24
      • 2021-06-23
      • 2022-01-04
      • 2022-08-06
      相关资源
      最近更新 更多