【问题标题】:"... has never been awaited" Error (Discord-Bot, Python)“......从未等待”错误(Discord-Bot,Python)
【发布时间】:2021-03-31 04:41:24
【问题描述】:
async def on_ready():
  print('We have logged in as {0.user}'.format(client))
  schedule.every(5).seconds.do(job)
  while True:
    schedule.run_pending()
    time.sleep(1)
    
      
async def job():
  print("I'm working...")
  channel = client.get_channel(651895929426673704)
  await channel.send('hello')

因此我收到错误“从未等待协程'job' self._run_job(job)”,但是无论我添加它,我总是得到“对象函数不能在'await'表达式中使用”有人可以吗请告诉我我做错了什么或者我必须把它放在哪里?

【问题讨论】:

  • 看起来schedule 不是一个异步库
  • @Grismar 不,它来自github.com/dbader/schedule
  • 不要使用time.sleep 这将停止你的整个代码。使用await asyncio.sleep(1) 仅休眠该功能。另外看看discord.ext.tasks

标签: python async-await discord discord.py


【解决方案1】:

据我所知,“计划”模块不支持异步任务。您可以尝试使用aioschedule,它是从 dbader 的存储库中派生出来的。工作方式相同,仅适用于 async 函数。

discord API 中已经内置了另一个选项,使用 tasks

from discord.ext import tasks
...

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))
    job.start() # To start the loop when your bot starts

@task.loop(seconds=5)
async def job():
    print("I'm working...")
    channel = client.get_channel(651895929426673704)
    await channel.send('hello')


# You can also add commands to start and stop the task loop
@client.command()
async def job_start(ctx):
    job.start()

@client.command()
async def job_stop(ctx):
    job.stop()

在给定时间每天安排任务的示例,使用aioschedule

import aioschedule as schedule
...

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))
  schedule.every().day.at("20:00").do(job) # "job" is scheduled for 8pm every day
  while True:
    await schedule.run_pending()
    await asyncio.sleep(1)

async def job():
  print("I'm working...")
  channel = client.get_channel(channel_id)
  await channel.send('hello')

【讨论】:

  • @LordofDarkness 如果您不指定任何时区,它将使用本地时间。确保使用 24 小时制,而不是 12 小时制。我刚刚测试了它,它工作正常。编辑我的答案以显示schedule.every().day.at("time").do(job)
【解决方案2】:

可能是这样的:

import asyncio
async def on_ready():
  print('We have logged in as {0.user}'.format(client))
  schedule.every(5).seconds.do(job)
  while True:
    schedule.run_pending()
    time.sleep(1)
    
      
async def job2():
  print("I'm working...")
  channel = client.get_channel(651895929426673704)
  await channel.send('hello')
def job():
    asyncio.gather(job)

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2022-01-09
    • 2021-08-20
    • 2017-11-05
    • 2022-01-21
    • 2021-02-16
    • 2021-02-07
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多