How do you get rid of "SyntaxError: 'await' outside function"

Viewed 2861

I am trying to make a discord bot change to online status

I have been using pycharm and terminal. I have tried reordering the code multiple different ways, but here is what I have right now

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)

I also tried these:

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

and

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

I got these errors:

:8: RuntimeWarning: coroutine 'on_ready' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback

and

SyntaxError: 'await' outside function

Please help me get the bot online

3 Answers

Firstly, await cannot be outside of an async def function, the thing your awaiting is not indented enough to be inside the function on_ready.

Secondly, you shouldn't try to call on_ready manually, once the bot runs, it'll call on_ready itself.

Thirdly, Never put client.run inside of on_ready! Instead put it at the end of the file, if you do put it inside of on_ready, it'll never run.

so, this would be the ideal code:

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

client.run(TOKEN)

And as for storing your bot token, i would put it inside a database, like the replit or mongoDB database.

the await function is not needed for client.run() put

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

and put client.run at the end of the file. In my case, I use a file called config.py in which I have declared the value of token

token = "Enter your token here" 

to import the variable, I did imported config with import config and since it's in config file, I entered client.run(config.token)

enter image description here

The print function needs to be intended another 4 spaces to be like:

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

Try to install asyncio if the problem still occurs

Related