【问题标题】:Can't fetch slack user profile information with API无法使用 API 获取松弛的用户个人资料信息
【发布时间】:2019-12-01 06:04:11
【问题描述】:

提前非常感谢您。我正在尝试通过slack_authentication 获取用户个人资料信息。尽管该应用已成功通过 Slack 身份验证,但它无法获取 电子邮件用户名

{'ok': True, 'access_token': 'xoxp-xXXXXXXXXXXXXXXXX', 'scope': 'identify,channels:read,users.profile:read,chat:write:bot,identity.basic', 'user_id ':'XXXXXXXXX','team_id':'XXXXXXXX','enterprise_id':无,'team_name':'test','warning':'superfluous_charset','response_metadata':{'warnings':['superfluous_charset'] }}

我尝试添加 identify 范围而不是 identity.basic,因为 slack 不允许您同时使用 identity.basic 和其他范围。

代码如下:

@bp.route('/redirect', methods=['GET'])
def authorize():
    authorize_url = f"https://slack.com/oauth/authorize?scope={ oauth_scope }&client_id={ client_id }"

    return authorize_url

@bp.route('/callback', methods=["GET", "POST"])
def callback():
    auth_code = request.args['code']
    client = slack.WebClient(token="")
    response = client.oauth_access(
        client_id=client_id,
        client_secret=client_secret,
        code=auth_code
    )
    print(response)

附加

我已经知道如何获取users info。我将代码更新为这样。

代码更新如下:

    oauth = client.oauth_access(
        client_id=client_id,
        client_secret=client_secret,
        code=auth_code
    )
    user_id = oauth['user_id']
    response = client.users_info(user=user_id)

但是出现这个错误:

服务器响应:{'ok': False, 'error': 'not_authed'}

【问题讨论】:

    标签: python slack


    【解决方案1】:

    您的代码看起来像是使用 OAuth 的 Slack 应用程序的安装例程。但它不包含获取用户配置文件的调用。

    要获取用户的个人资料,您可以致电users.info 并提供您感兴趣的用户的 ID。

    例子:

    response = client.users_info(user=ID_OF_USER)
    assert(response)
    profile = response['user']['profile']
    email = response['user']['profile']['email']
    

    为了检索用户的个人资料和电子邮件地址,您需要以下范围: - 用户:阅读 - 用户:read.email

    身份范围与用户配置文件无关。它们仅用于“Sign-in with Slack”方法,您可以在其中与第三方网站上的 Slack 用户进行身份验证。

    最后,澄清一下,因为这经常被误解:您只需要运行一次 OAuth 安装例程。该例程将为您生成工作区的令牌,您可以存储该令牌并将其用于对该工作区的 API 的任何进一步调用。

    更新到“附加”

    您没有正确使用 API。

    您需要先完成 Oauth 流程并收集访问令牌,该令牌位于来自 client.oauth_access 的响应中。

    然后你需要用你收到的令牌初始化一个新的 WebClient。使用新客户端,您可以访问所有 API 方法,例如 users.info 等。

    再次重申:您应该只运行一次 OAuth 过程并存储收到的令牌以供以后使用。

    例子:

    oauth_info = client.oauth_access(
        client_id=client_id,
        client_secret=client_secret,
        code=auth_code
    )
    access_token = oauth_info['access_token'] # you want to store this token in a database
    
    client = slack.WebClient(token=access_token)
    user_id = oauth_info['user_id']
    response = client.users_info(user=user_id)
    print(response)
    

    【讨论】:

    • 非常感谢您的帮助。我有道理。顺便问一下,我怎样才能得到 ID_OF_USER?我尝试使用从 oauth_access 获取的user_id,但它没有用......
    • 来自 OAuth 的用户 ID 应该可以工作。你从 API 得到什么错误?另外,请查看此处以获取有关如何获取 ID 的详细信息:stackoverflow.com/questions/40940327/…
    • 非常感谢您的额外指出。我更新了一个问题。
    • 我完全明白了!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多