簡體   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