Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

python - Making a bot that sends messages at a scheduled date with Discord.py

I'm trying to make a bot that sends a scheduled message to a specific text channel. for example at the date of my birthday saying "happy birthday", or also every morning saying "Good morning". The bot seems to don't work since nothing appears in my text 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')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's how you would do something like this using the 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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...