python - 无法使用 API 获取松弛的用户个人资料信息
问题描述
非常感谢你。我正在尝试通过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'}
解决方案
您的代码看起来像是使用 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.email
身份范围与用户配置文件无关。它们仅用于“使用 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)
推荐阅读
- javascript - Angular 不会返回内部嵌套的 for 循环
- python - 循环函数查找数字的平方根
- openstack - Openstack Neutron:通过rest api为路由器添加静态路由器
- spring - 如何使用 spring 存储库进行 bean 验证?
- cpanel - 当我遇到一些电子邮件问题时如何配置 WHM 服务器
- php - 电子邮件进入收件箱,但显示垃圾邮件
- mysql - MySQL:检查一列是否具有基于另一列的值
- html-table - Gmail 在我的 HTML 签名的第一行之后的行上添加 STRANGE 填充
- php - 从我的数据库中获取个人资料图片以显示在 php 页面上
- javascript - Laravel FatalErrorException:内存不足