我正在使用Discord API对Discord机器人进行编程。我正在尝试执行从英语到西班牙语的翻译命令,但是当我运行代码时,出现以下错误:
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添加到列表“西班牙语”。
实际结果:
它什么也没做
编辑:
当我在代码中添加
global Spanish
时,出现以下错误:NameError: name 'Spanish' is not defined
最佳答案
如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))
关于python - UnboundLocalError:在Discord.py中分配之前引用了局部变量'x',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50246752/