【问题标题】:RuntimeError: Event loop stopped before Future completedRuntimeError:事件循环在 Future 完成之前停止
【发布时间】:2019-10-29 15:00:34
【问题描述】:

我正在尝试设置一个时间表来运行一个子例程。我正在尝试使用子例程示例在触发计划时向不和谐频道发送消息。起初我试图尝试发送消息,但出现错误。然后我尝试研究如何解决这个问题,并尝试了使用 asyncio 的不同方法,所有这些都没有奏效。

如果有人能给我任何关于我如何做到这一点的指示,那将不胜感激。

import discord
import asyncio
import time
import schedule # pip install schedule

client = discord.Client()
@client.event
async def on_ready():
    print("Connected!")

async def example(message):
    await client.get_channel(CHANNEL ID).send(message)

client.run(SECRET KEY)

def scheduledEvent():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(example("Test Message"))
    loop.close()

schedule.every().minute.do(scheduledEvent)

while True:
    schedule.run_pending()
    time.sleep(1)

【问题讨论】:

    标签: python python-3.x discord.py schedule python-asyncio


    【解决方案1】:

    您不能在与异步事件循环相同的线程中运行阻塞 schedule 代码(您当前的代码甚至不会尝试安排任务,直到机器人已经断开连接)。相反,您应该使用内置的 tasks 扩展,它允许您安排任务。

    import discord
    from discord.ext import tasks, commands
    
    CHANNEL_ID = 1234
    TOKEN = 'abc'
    
    client = discord.Client()
    
    @client.event
    async def on_ready():
        print("Connected!")
    
    @tasks.loop(minutes=1)
    async def example():
        await client.get_channel(CHANNEL_ID).send("Test Message")
    
    @example.before_loop
    async def before_example():
        await client.wait_until_ready()
    
    example.start()
    
    clinet.run(TOKEN)
    

    【讨论】:

    • 感谢您的回复。 After looking at this documentation, I just had to add example.start()。如果我可以问另一个问题:有没有办法让这个函数在每天的某个时间运行?
    • 在您的before_loop 中,您将计算直到下一个上午 8 点(或任何时间)的时间,然后 asyncio.sleep 那个时间。您可以将任务设置为每 24 小时重复一次。
    • 感谢您的帮助,谢谢。我使用(timedelta(hours=24) - (datetime.now()- datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))).total_seconds() % (24 * 3600) 找出距离我想要的时间的秒数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2014-12-31
    相关资源
    最近更新 更多