无法使用 API 获取松弛用户配置文件信息

Can't fetch slack user profile information with API

非常感谢您。我正在尝试通过 slack_authentication 获取用户个人资料信息。尽管该应用已成功通过 Slack 进行身份验证,但无法获取 emailusername.

{'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': None, '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)

但是出现这个错误:

The server responded with: {'ok': False, 'error': 'not_authed'}

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

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

示例:

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

为了检索用户的个人资料和电子邮件地址,您需要这些范围: - users:read - users:read. 电子邮件

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

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

更新为"Additional"

您没有正确使用 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)