【问题标题】:Discord.py Bot send messages at certain timesDiscord.py Bot 在特定时间发送消息
【发布时间】:2022-02-05 17:33:46
【问题描述】:

我在服务器上为我和一些朋友托管了一个 discord.py 机器人,并且一直在尝试获得某个“功能”,该机器人将每天发送一条消息,每天两次,早上一次,一次在晚上,只是说一般的“早上好”和“晚安!”我花了几个小时查看其他人的代码和类似的问题,这是我能找到/得到的最好的(它取自另一个用户的“python 警报”,我试图将它连接到机器人。

from datetime import datetime
from threading import Timer
x = datetime.today()
y = x.replace(hour=21, minute=45, second=40, microsecond=0)
delta_t = y - x
secs = delta_t.seconds + 1

channel = client.get_channel(806702411808768023)

async def Goodnight():
    await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
    print("Night Working")


t = Timer(secs, Goodnight)
t.start()

我不断收到相同的错误,通常是关于消息不是异步或等待-'able' (?)。我对编码/python相当陌生,如果有什么明显的,我很抱歉。我真的不知道该怎么办,并且我找到了一些有希望的解决方案,尽管这些解决方案会使整个机器人发出警报,并在等待时强制它“睡觉”,虽然我希望我的仍然正常运行(运行其他命令),如果可能的话?任何帮助表示赞赏

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    这可以使用任务扩展来完成:

    import datetime
    import discord
    from discord.ext import tasks
    
    client = discord.Client()
    
    goodNightTime = datetime.time(hour=21, minute=45, second=40) #Create the time on which the task should always run
    
    @tasks.loop(time=goodNightTime) #Create the task
    async def Goodnight():
        channel = client.get_channel(806702411808768023)
        await channel.send("Good night! Make sure to go to sleep early, and get enough sleep!")
        print("Night Working")
    
    @client.event
    async def on_ready():
        if not Goodnight.is_running():
            Goodnight.start() #If the task is not already running, start it.
            print("Good night task started")
    
    client.run(TOKEN)
    
    

    请注意,要使其正常工作,您需要拥有最新版本的 discord.py 或支持 2.0 版的 fork。如果你还没有,你可以通过安装它

    pip install -U git+https://github.com/Rapptz/discord.py
    

    【讨论】:

    • 我不断收到错误消息: goodNightTime = datetime.time(hour=21, minute=45, second=40) #创建任务应该始终运行的时间 TypeError: unbound method datetime. time() 需要一个参数
    • 问题是你使用from datetime import datetime 尝试改用import datetime。 @Biiarde
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 2020-12-25
    • 2021-03-08
    • 1970-01-01
    • 2021-11-29
    • 2021-09-10
    • 2021-01-09
    相关资源
    最近更新 更多