2017-02-07 14 views
0

私は、それを楽しむためにdiscord.pyを使って単純なdiscordボットを作成しようとしています。 asyncioの動作を完全に理解するのには苦労しています。変数の上書き/再割り当てに問題があります。変数をasync/awaitに再割り当てしますか?

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変数を上書きしようとすると、「割り当て前に参照される」例外が発生します。上書きしようとしないと、変数fineの値を取得できます。

私はこれが非同期の仕組みであると考えていますが、私はこれを完全には理解していませんが、私は参考にしています。

答えて

0

これは、async/awaitとは関係ありません。関数スコープのどこにでも名前を代入すると、その名前は関数全体のローカルなものになります(実際に割り当てられる前であっても)。したがって、log_channelという2つのバージョンがあります:ローカルのものとグローバルなもの(ローカルマスク)です。例外は、elseケースの最後の行にのみ割り当てられている場合に、elseケースの最初の行としてローカルを読み込もうとしたために発生します。

追加、その名前のローカルオーバーライドを作成しないようにしたい場合:log_channelにあなたの関数内の最初の行として

global log_channel 

を、そしてすべての参照(ロードとストアは)グローバルバージョンが使用されます。

関連する問題