为什么我的代码打印 "if" 结果和 "else" 结果?

Why is my code printing the "if" result and the "else" result?

我正在尝试编写一个非常基本的 slackbot,首先查找机器人的 user_id,这已经比我预期的要难了。我可以从 documentation 中得出的唯一方法是提取每个用户的列表,然后在该列表中搜索我的机器人用户。这看起来已经有点奇怪了,所以如果有人能提出更好的方法,我会洗耳恭听。

但是现在发生的事情是它找到 user_id 然后继续窒息:

Ready to look for REDACTED
<type 'dict'>
2016-06-27 20:22:05.380408 DEBUG REDACTED : ABC123
2016-06-27 20:22:05.381173 DEBUG No user found named REDACTED
2016-06-27 20:22:05.385158 DEBUG ABC123

这是我的代码:

from slackclient import SlackClient
import re

class Bot(object):

    def __init__(self, token, username):
        self.client = SlackClient(token)
        self.username = username
        self.user_id = {}


    def run(self):
        if self.client.rtm_connect():
            self.user_id = self.whoami(self.client.server.username)
        else:
            print("Connection failed.")

    def whoami(self, username):
        """
        finds the ID for this username.
        """
        all_users = self.client.api_call("users.list")
        print "Ready to look for " + username

        for user in all_users['members']:
            if re.match(username, user['name']):
                print(user['name'] + " : " + user['id'])
                user_id = user['id']
        if (user_id not in locals()):
            print("No user found named " + username) 
        else:
            print(user_id)
        return user_id

然后我调用它:

api_token = 'redacted'
username = 'redacted'

first_bot = Bot(api_token, username)
first_bot.run()

我想弄清楚为什么它找到用户然后立即说 "No user found"——然后打印 user_id——我希望它打印一个或另一个。

我认为 if ("user_id" not in locals()):(注意 user_id 周围的引号)可以解决问题,但我强烈建议 不要 使用 locals().

这是许多可能的修复方法之一:

def whoami(self, username):
    """
    finds the ID for this username.
    """
    all_users = self.client.api_call("users.list")
    print "Ready to look for " + username

    user_id = None

    for user in all_users['members']:
        if re.match(username, user['name']):
            self._log(user['name'] + " : " + user['id'])
            user_id = user['id']

    if user_id is None:
        self._log("No user found named ") 

    return user_id

编辑

此外,完全未经测试,但这是获取机器人用户 ID 的更好方法:

def whoami(self):
    """
    finds the bot's user ID
    """

    return self.client.api_call("auth.test")["user_id"]