语法错误:在异步函数中使用 Await 时语法无效

问题描述 投票:0回答:1

错误代码:

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)

错误:

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

我会注意到,我使用 python 版本 3.10.0 是为了与 Heroku 和 Discord.py 兼容。我尝试搜索有类似问题的人,但他们在异步函数之外使用 Await 时都会收到错误。我还会注意到,当使用 Await 执行除内置的 Discord.py 函数之外的任何内容时,我会收到此错误。以防万一,我也会在这里提供完整的代码:

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'))

python asynchronous async-await discord discord.py
1个回答
0
投票

正确的语法是

async with
而不是
await with.

用此替换现有的添加命令功能:

@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)
© www.soinside.com 2019 - 2024. All rights reserved.