为什么我的代码会打印" if"结果和"其他"结果?

时间:2016-06-27 20:37:18

标签: python python-2.7 slack-api

我试着写一个非常基本的slackbot,从查找机器人开始 user_id,已经比我想象的更难了。我可以从documentation中找到的唯一方法是提取每个用户的列表,然后为我的bot用户搜索该列表。这似乎有点奇怪,所以如果有人能提出更好的方法,我全都听见了。

但是现在发生的事情是它找到了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()

我试图弄清楚为什么它找到了用户然后立即说&#34;没有用户找到&#34; - 然后打印user_id - 我希望它打印一个或另一个。

1 个答案:

答案 0 :(得分:0)

我认为if ("user_id" not in locals()):(请注意user_id周围的引号)可以解决问题,但我强烈建议使用locals() 。< / p>

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

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"]