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

新手上路,请多包涵

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

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

原文由 matteobelleri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 610
2 个回答

以下是您如何使用 tasks 扩展 来做这样的事情

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")

原文由 Patrick Haugh 发布,翻译遵循 CC BY-SA 4.0 许可协议

你也可以这样做(以防有人踩这篇文章):

 import discord
import os
import asyncio
from discord.ext import commands, tasks
from datetime import datetime, timedelta
client = discord.Client()

def seconds_until_midnight():
    now = datetime.now()
    target = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
    diff = (target - now).total_seconds()
    print(f"{target} - {now} = {diff}")
    return diff

@tasks.loop(seconds=1)
async def called_once_a_day_at_midnight():
    await asyncio.sleep(seconds_until_midnight())
    message_channel = client.get_channel(CHANNEL_ID)
    print(f"Got channel {message_channel}")
    await message_channel.send("Your message here")

@called_once_a_day_at_midnight.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")

client = discord.Client()
called_once_a_day_at_midnight.start()
client.run(os.environ['BOT_TOKEN'])

原文由 Denis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题