【问题标题】:SyntaxError: 'await' outside async function discord.pySyntaxError: \'await\' 在异步函数 discord.py 之外
【发布时间】:2022-08-21 10:33:09
【问题描述】:
import discord.ext
import discord
from discord.ext import commands
from discord.ext import tasks
from keep_alive import keep_alive
import os
import schedule
client = discord.Client()


client = commands.Bot(command_prefix=\"\")

channel_id = 927272717227528262

channel = client.get_channel(channel_id)

@tasks.loop(seconds=1.0)
@client.event
async def on_message(message):
    if message.author == client.user:
        return
def job2():
    await message.channel.send(\"message\")

schedule.every(10).seconds.do(job2)
while True:
    schedule.run_pending()
    time.sleep(0)


keep_alive()
client.run(os.getenv(\'TOKEN\'))

每次我运行它时,我都会得到:

SyntaxError: \'await\' outside async function

我也遇到消息未定义job2 的定义的问题,即使它只是在上面的行中定义。

  • 您永远不会在 async 函数内部等待。以后不能在 job2() 中调用它。它必须在 async def 中

标签: discord discord.py


【解决方案1】:

您可能应该使用discord.ext.tasksschedule 并不真正支持异步函数。

事实上,你的机器人永远无法运行,因为你的schedule.run_pending() 在无限循环中永远不会结束。

为了保留您的message,您需要将其放入某种类型的全局变量中。

the_message = None

@tasks.loop(seconds=1.0)
@client.event
async def on_message(message):
    global the_message
    if message.author == client.user:
        return
    the_message = message

async def job2():
    if the_message is None:
        return
    await the_message.channel.send("message")

@tasks.loop(seconds=10.0)  # you can do other things like `minutes=5` or `hours=1.75`
async def my_task():
    await client.wait_until_ready()
    await job2()

my_task.start()

# then the bot runs fine after
keep_alive()
client.run(os.getenv('TOKEN'))

请注意,这可能会在您的客户端尚未准备好和初始化之前运行。如果您打算对 API 做任何事情,就像您的情况一样,您可能还想检查wait_until_ready。您还可以找到其他示例here

【讨论】:

  • 消息未在 job2 中定义
  • @ŁukaszKwieciński 在 OP 提供的代码中,我不确定这是全球性的还是 get_channel/message/guild 的东西。
  • “我还有一个问题,即 message 未定义 job2 的定义,即使它刚刚在上面的行中定义。”
  • 啊,我错过了。不过确实需要更多澄清,我怀疑他们想要发送最后一条消息,我想这会使其成为全球性的。一旦我有空,我会更新这个。
【解决方案2】:
  1. await 用于异步函数中以等待函数执行其操作。但是,您已在同步函数中使用它 (def job2)

  2. message 不是变量。 messageon_message 函数的参数。参数只能在提供给它的函数中使用。

    希望这回答了你的问题。

【讨论】:

    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多