SyntaxError: invalid syntax when using Await inside an asynchronous function

Bugged Code:

async def add(ctx, *, newalbum):
    current_month = str(datetime.now().month)
    await ctx.send(f'{newalbum} has been added to the queue')
    await with open("albums.json", "r") as albumfile:
        data = json.load(albumfile)
    await with open("albums.json", "w") as albumfile:
        data[current_month] = str(newalbum)

Error:

    await with open("albums.json", "r") as albumfile:
          ^^^^
SyntaxError: invalid syntax

I will note that I am using python version 3.10.0 for compatibility with Heroku and discord.py. I’ve tried to search for people with similar problems but all of them receive the error when using Await outside of a Async function. I’ll also note that I get this error when using Await for ANYTHING other than a built in discord.py function. Just in case I will provide the full code here as well:

import discord
from discord.ext import commands
from datetime import datetime
import json
import os

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='!', intents=intents)


def manage_albumfile():
    current_month = str(datetime.now().month)
    with open("albums.json", "r") as f:
        data = json.load(f)
        current_album = data[current_month]

    return current_album


@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')


@bot.command()
async def add(ctx, *, newalbum):
    current_month = str(datetime.now().month)
    await ctx.send(f'{newalbum} has been added to the queue')
    await with open("albums.json", "r") as albumfile:
        data = json.load(albumfile)
    await with open("albums.json", "w") as albumfile:
        data[current_month] = str(newalbum)


@bot.command()
async def current(ctx):
    await ctx.send(f'The current album is {manage_albumfile()}')

bot.run(os.environ.get('TORTIE_TOKEN'))

>Solution :

The correct syntax is async with not await with.

Replace your existing add command function with this:

@bot.command()
async def add(ctx, *, newalbum):
    current_month = str(datetime.now().month)
    await ctx.send(f'{newalbum} has been added to the queue')
    async with open("albums.json", "r") as albumfile:
        data = json.load(albumfile)
    async with open("albums.json", "w") as albumfile:
        data[current_month] = str(newalbum)

Leave a Reply