UnboundLocalError:局部变量' x'在Discord.py中赋值之前引用

时间:2018-05-09 06:23:46

标签: python discord.py

我使用Discord API编写了一个不和谐机器人。我正在尝试从英语到西班牙语执行翻译命令,但是当我运行我的代码时,我收到以下错误:

UnboundLocalError: local variable 'Spanish' referenced before assignment

我的代码:

if message.content.upper().startswith("P$LANG"):
    lang = message.content[7:]
    """
    user1 = {
        "Language" : lang = message.content[7:],
        "ID" : user == message.author.id,
    }
    """
    global Spanish
    Spanish = []

    if lang.upper() == "SPANISH" or lang.upper() == "SPAIN" or lang.upper() == "ESPAÑOL":
        xcm = "<@!" + message.author.id + "> Ahora Phantom está en Español. Ten en cuenta que los comandos seguiran siendo en Inglés, solo que la respuesta será en Español."
        Spanish.append(message.author.id)
        await client.send_message(channel, xcm)
if message.content.upper().startswith('P$POLLHELP'):
  # await client.add_reaction(message, ":radio_button:")
    if message.author.id in Spanish:
        await client.send_message(
            channel,
            "**Uso:** P$~<x>poll <pregunta> | reemplaza <x> con el número, min - 1 || máx - 5 |-|-| reemplaza <pregunta> con tu pregunta.*"
        )
    else:
        await client.send_message(
            channel,
            "**Usage:** P$~<x>poll <question> | replace the <x> with the number, min - 1 || max - 5 |-|-| replace <question> with your question.*"
        )
    print("P$pollhelp was used by " + str(author.name))

预期成果: 将用户ID添加到列表&#39;西班牙语&#39;。

实际结果: 它什么都不做

修改 当我向代码添加global Spanish时,它会给我以下错误:

NameError: name 'Spanish' is not defined

1 个答案:

答案 0 :(得分:1)

正如metatoaster所说,你需要在if语句之外定义全局西班牙语数组。

global Spanish
Spanish = []

if message.content.upper().startswith("P$LANG"):
lang = message.content[7:]
"""
user1 = {
    "Language" : lang = message.content[7:],
    "ID" : user == message.author.id,
}
"""


if lang.upper() == "SPANISH" or lang.upper() == "SPAIN" or lang.upper() == "ESPAÑOL":
    xcm = "<@!" + message.author.id + "> Ahora Phantom está en Español. Ten en cuenta que los comandos seguiran siendo en Inglés, solo que la respuesta será en Español."
    Spanish.append(message.author.id)
    await client.send_message(channel, xcm)
if message.content.upper().startswith('P$POLLHELP'):
  # await client.add_reaction(message, ":radio_button:")
    if message.author.id in Spanish:
        await client.send_message(
            channel,
            "**Uso:** P$~<x>poll <pregunta> | reemplaza <x> con el número, min - 1 || máx - 5 |-|-| reemplaza <pregunta> con tu pregunta.*"
        )
    else:
        await client.send_message(
            channel,
            "**Usage:** P$~<x>poll <question> | replace the <x> with the number, min - 1 || max - 5 |-|-| replace <question> with your question.*"
        )
    print("P$pollhelp was used by " + str(author.name))