【问题标题】:How to call async function in a synchronus function?如何在同步函数中调用异步函数?
【发布时间】:2020-12-20 14:17:46
【问题描述】:

我正在尝试制作一个不和谐的机器人来发送嘿!每天特定时间的特定频道。 但它给了我一个错误

import discord
import schedule
    
bot = commands.Bot(command_prefix = "^")
    
@bot.event
async def on_ready():
   schedule.every().day.at("18:00").do(job)
        
   while 1:
       schedule.run_pending()
       time.sleep(1)

async def job():
        channel = bot.get_channel(72246xxxxxxxxx)
        await channel.send("Hey!!")
    

RuntimeWarning: coroutine 'job' was never awaited

【问题讨论】:

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


    【解决方案1】:
    @bot.event
    async def on_ready():
        while True:
            await asyncio.sleep(1)
            x=datetime.today() #identify the time right now
            y=x.replace(hour=18, minute=0, second=0) #here you can modify time
            delta_t=y-x
            secs=delta_t.seconds
            print(secs) #you can delete this line if you would like to disable visual countdown
            if secs == 0: #when countdown have 0 seconds left it sends the message
                channel = bot.get_channel(1234567890) #your channel id
                await channel.send("Hey!!") #your message
    

    我知道我对您的代码进行了很多修改,但我更喜欢使用内置日期时间库。如果你想使用schedule library,你可以尝试使用asyncio.run(job),但我不确定这是否可行。

    【讨论】:

    • 感谢您的回复,计划在 on_ready 事件中,但问题是它没有在同步函数中使用异步函数。我尝试使用 async.create_task() 和 async.run() 但没有任何效果。编辑代码
    • 您的代码有效,谢谢。我也尝试过使用nest_async,但它给出了错误。
    猜你喜欢
    • 2012-07-25
    • 2020-04-20
    • 1970-01-01
    • 2020-03-09
    • 2013-07-12
    • 2022-07-11
    • 1970-01-01
    • 2015-03-19
    • 2020-10-13
    相关资源
    最近更新 更多