繁体   English   中英

你如何摆脱“SyntaxError: 'await' outside function”

[英]How do you get rid of “SyntaxError: 'await' outside function”

我正在尝试将 discord 机器人更改为在线状态

我一直在使用 pycharm 和终端。 我已经尝试以多种不同的方式重新排序代码,但这就是我现在所拥有的

import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
   print('Bot is ready.')
await client.run(bot token)

我也试过这些:

import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
   print('Bot is ready.')
   await client.run(bot token)
on_ready

import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
   print('Bot is ready.')
await client.run(bot token)
on_ready

我得到了这些错误:

:8: RuntimeWarning: coroutine 'on_ready' 从未等待 RuntimeWarning: Enable tracemalloc to get the object allocation traceback

语法错误:在 function 之外“等待”

请帮我让机器人上线

首先, await不能在async def function 之外,您等待的东西没有缩进到 function on_ready内部。

其次,你不应该尝试手动调用on_ready ,一旦机器人运行,它会自己调用on_ready

第三,永远不要把on_ready放在client.run里面! 而是把它放在文件的末尾,如果你把它放在 on_ready 里面,它就永远不会运行。

所以,这将是理想的代码:

@client.event
async def on_ready():
    print('Bot is ready!')

client.run(TOKEN)

至于存储你的机器人令牌,我会把它放在一个数据库中,比如 replit 或 mongoDB 数据库。

client.run() put 不需要 await function

async def on_ready():
        print("Bot is ready.")

并将 client.run 放在文件末尾。 在我的例子中,我使用了一个名为 config.py 的文件,我在其中声明了 token 的值

token = "Enter your token here" 

要导入变量,我使用import config了配置,因为它在配置文件中,所以我输入client.run(config.token)

在此处输入图像描述

打印 function 需要另外 4 个空格,如下所示:

async def on_ready():
        print("Bot is ready.")

如果问题仍然存在,请尝试安装 asyncio

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM