如何在没有命令或事件discord.py的情况下发送消息

时间:2020-09-11 12:04:46

标签: python discord discord.py

我正在使用日期时间文件进行打印:现在是早上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点触发警报的原因,我只想知道触发该消息时如何发出不一致的消息。

如果您需要任何澄清,请询问。 谢谢!

3 个答案:

答案 0 :(得分:0)

在设置了客户端的情况下,从Discord.py docs可以使用以下格式直接向通道发送消息:

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

一旦拥有频道(在设置客户端之后),就可以根据需要放置该代码段,以选择适当的频道以及所需的消息。请记住"You can only use await inside async def functions and nowhere else.",因此您需要设置一个异步函数来这样做,并且简单的While True:循环可能无法正常工作

答案 1 :(得分:0)

从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')

希望,这会有所帮助。

答案 2 :(得分:0)

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

您还需要使用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')