“...从未等待过”错误(Discord-Bot,Python)

时间:2020-12-21 11:59:31

标签: python async-await discord discord.py

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'表达式中使用”有人可以请告诉我我做错了什么或我必须把它放在哪里?

2 个答案:

答案 0 :(得分:1)

据我所知,“schedule”模块不支持异步任务。您可以尝试使用 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')

答案 1 :(得分:0)

也许是这样的:

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)