discord.py如何每天在特定时间发送消息

时间:2020-09-06 23:14:37

标签: python discord.py

我想创建一个Discord机器人,该机器人每天在特定时间每天发送2条消息。例如,以下代码将使消息进入循环,并且每5秒发送一次消息。如何设置每天发送邮件的特定时间,例如下午6点的消息1和上午10点的消息2。 我找到了这段代码Here,但没有找到我想要的。

squares

4 个答案:

答案 0 :(得分:1)

这是一个简单的实现 - 每天,它会休眠到目标时间,然后发送您的消息

from discord.ext import commands
from datetime import datetime, time, timedelta
import asyncio

bot = commands.Bot(command_prefix="$")
WHEN = time(18, 0, 0)  # 6:00 PM
channel_id = 1 # Put your channel id here

async def called_once_a_day():  # Fired every day
    await bot.wait_until_ready()  # Make sure your guild cache is ready so the channel can be found via get_channel
    channel = bot.get_channel(channel_id) # Note: It's more efficient to do bot.get_guild(guild_id).get_channel(channel_id) as there's less looping involved, but just get_channel still works fine
    await channel.send("your message here")

async def background_task():
    now = datetime.utcnow()
    if now.time() > WHEN:  # Make sure loop doesn't start after {WHEN} as then it will send immediately the first time as negative seconds will make the sleep yield instantly
        tomorrow = datetime.combine(now.date() + timedelta(days=1), time(0))
        seconds = (tomorrow - now).total_seconds()  # Seconds until tomorrow (midnight)
        await asyncio.sleep(seconds)   # Sleep until tomorrow and then the loop will start 
    while True:
        now = datetime.utcnow() # You can do now() or a specific timezone if that matters, but I'll leave it with utcnow
        target_time = datetime.combine(now.date(), WHEN)  # 6:00 PM today (In UTC)
        seconds_until_target = (target_time - now).total_seconds()
        await asyncio.sleep(seconds_until_target)  # Sleep until we hit the target time
        await called_once_a_day()  # Call the helper function that sends the message
        tomorrow = datetime.combine(now.date() + timedelta(days=1), time(0))
        seconds = (tomorrow - now).total_seconds()  # Seconds until tomorrow (midnight)
        await asyncio.sleep(seconds)   # Sleep until tomorrow and then the loop will start a new iteration


if __name__ == "__main__":
    bot.loop.create_task(background_task())
    bot.run('token')

答案 1 :(得分:0)

您必须制作一个before_loop,以便它第一次运行时才准时运行,然后每24小时循环一次。这是一个例子。

import asyncio
import datetime as dt


@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print("------")
    msg1.start()


# Message 1
@tasks.loop(hours=24)
async def msg1():
    message_channel = bot.get_channel(705524214270132367)
    await message_channel.send("test 1")


@msg1.before_loop
async def before_msg1():
    for _ in range(60*60*24):  # loop the hole day
        if dt.datetime.now().hour == 10+12:  # 24 hour format
            print('It is time')
            return
        await asyncio.sleep(1)# wait a second before looping again. You can make it more 

答案 2 :(得分:0)

我创建了一个 [Discord-bot],它会在特定时间发送消息,并且在那个时间到来之前它将处于睡眠状态。我创建的代码很小而且很容易理解
代码:

import discord
from datetime import datetime

client = discord.Client()
token = "" #enter your bot's token and it should be a string
channel_id = #enter your channel id and it should be a integer   

def time_module():
    print("time module in use")
    while True:created
        current_time = datetime.now().strftime("%H:%M")#hour %H min %M sec %S am:pm %p 
        if current_time == "00:00": # enter the time you wish 
            print("time module ended")
            break

time_module()

@client.event
async def on_ready():

    print("bot:user ready == {0.user}".format(client))
    channel = client.get_channel(channel_id)
    await channel.send("message")
    

client.run(token)

答案 3 :(得分:0)

您需要计算现在的时间,以及您安排的时间,然后每隔大约 10 分钟检查一次安排的时间是否符合现在.

检查此链接以查看 Python https://docs.python.org/3/library/datetime.html#datetime.datetime.now 的 DateTime 库

并检查此链接以查看如何使用@tasks.loop(后台任务)的示例 https://github.com/Rapptz/discord.py/blob/master/examples/background_task.py

使用 dateTime 库获取现在的时间

now=datetime.datetime.now() #will store the time of when it is called
#if you want to put specific time:
remindMeAT =datetime.datetime(2021,5,4,17,24)  #year,month,day,hour,min,sec