【发布时间】:2017-02-07 11:14:09
【问题描述】:
我正在尝试使用 discord.py 创建一个简单的 discord 机器人来获得乐趣。 我正在努力完全理解 asyncio 的工作方式,并且在覆盖/重新分配变量时遇到问题。
log_channel = "8765327525217520521501"
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!logchannel'):
if message.content == "!logchannel":
await client.send_message(message.channel, "```\n logchannel:
\r - Changes the channel this bot logs to.
\r - Takes the numerical channel ID as an argument
\r - E.g. !logchannel 123456789 ```")
else:
nc = message.content.split()[1]
try:
await client.send_message(client.get_channel(nc), "Testing new channel to be used for logs...")
except discord.NotFound:
await client.send_message(message.channel, "No channel was found with that ID.")
except discord.Forbidden:
await client.send_message(message.channel, "I Don't have permissions to use that channel!")
except discord.HTTPException:
await client.send_message(message.channel, "There was an error communciating with the server, please try again.")
except InvalidArgument:
await client.send_message(message.channel, "No channel was found with that ID.")
else:
await client.send_message(client.get_channel(log_channel), "Logging Channel Updated.")
await client.send_message(message.channel, "Logging Channel Updated.")
lmsg = 'Logging channel was updated to {} on {}'
log.write(lmsg.format(message.channel,logtime))
log_channel = nc
尝试覆盖 log_channel 变量会导致“分配前引用”异常。如果我不尝试覆盖,那么它可以很好地获取变量的值。
我认为这是因为异步的工作方式,但我并不完全理解这一点,我使用示例作为指导。
【问题讨论】:
标签: python python-3.x async-await