【问题标题】:How do you get rid of "SyntaxError: 'await' outside function"你如何摆脱“SyntaxError:'await'外部函数”
【发布时间】:2021-04-25 02:04:57
【问题描述】:

我正在尝试将不和谐机器人更改为在线状态

我一直在使用 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: E​​nable tracemalloc 获取对象分配回溯

和

SyntaxError: 'await' 外部函数

请帮我让机器人上线

【问题讨论】:

    标签: python terminal pycharm discord bots


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

      【解决方案2】:

      client.run() 不需要 await 函数 放

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

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

      token = "Enter your token here" 
      

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

      【讨论】:

        【解决方案3】:

        打印功能需要另外4个空格:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-29
          • 2021-03-05
          • 2022-08-21
          • 1970-01-01
          • 2016-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多