python - 使用 Discord.py 制作一个在预定日期发送消息的机器人

标签 python timer bots discord discord.py

我正在尝试制作一个将预定消息发送到特定文本 channel 的机器人。 例如在我生日那天说“生日快乐”,或者每天早上说“早上好”。 该机器人似乎无法正常工作,因为我的文本 channel 中没有显示任何内容。

import discord,random,asyncio,os
from datetime import datetime
from discord.ext import commands

token = '#mytokenhere'
bot=commands.Bot(command_prefix='!')

send_time='01:41' #time is in 24hr format
message_channel_id='0000000000000' #channel ID to send images to

@bot.event
async def on_ready():
    print(bot.user.name)
    print(bot.user.id)

async def time_check():
    await bot.wait_until_ready()
    message_channel=bot.get_channel(message_channel_id)
    while not bot.is_closed:
        now=datetime.strftime(datetime.now(),'%H:%M')
        if now.hour() == 1 and now.minute() == 52:
            message= 'a'
            await message_channel.send(message)
            time=90
        else:
            time=1
        await asyncio.sleep(time)

bot.loop.create_task(time_check())


bot.run('token')

最佳答案

以下是使用 tasks extension 执行此类操作的方法

from discord.ext import commands, tasks

bot = commands.Bot("!")

target_channel_id = 1234

@tasks.loop(hours=24)
async def called_once_a_day():
    message_channel = bot.get_channel(target_channel_id)
    print(f"Got channel {message_channel}")
    await message_channel.send("Your message")

@called_once_a_day.before_loop
async def before():
    await bot.wait_until_ready()
    print("Finished waiting")

called_once_a_day.start()
bot.run("token")

关于python - 使用 Discord.py 制作一个在预定日期发送消息的机器人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57631314/

相关文章:

python - 使用 pexpect 执行多个命令

python - 如何使 tkinter 窗口在 i3 窗口管理器中 float

javascript - 如何在用户不活动时自动注销?

python - Python钢琴瓷砖机器人

node.js - 如何创建带有memberCount 的机器人状态?

python - 如何在 PyCharm 中远程调试 uWSGI 后面的 Flask 请求

python - 如何运行位于子目录中的脚本?导入错误 : No module named x

javascript - 如何实时暂停/停止视频(例如 3.00 秒)

Swift RunLoop 阻止 TableView

xcode - 在 Xcode 服务器中找不到代码签名身份