问题描述
我正在尝试制作一个 discord 机器人,以便在您输入“$live”时检查 Twitch 上的主播是否在线,但我无法让它工作。我正在使用 discord.py。我的主要问题是使用标头调用 API 来提供我的授权。此外,使用我目前编写的代码,它会发送此错误。我的主要问题是,我如何提供授权密钥,以便它不会出现以下错误或说需要 OAuth。 TIA!
忽略 on_message 中的异常 回溯(最近一次调用最后一次): _run_event 中的文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py”,第 343 行 等待 coro(*args,**kwargs) 文件“main.py”,第 19 行,在 on_message 中 response = requests.get(url,headers=headers) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/api.py”,第 76 行,在 get 返回请求('get',url,params=params,**kwargs) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/api.py”,第 61 行,请求 返回 session.request(method=method,url=url,**kwargs) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py”,第 528 行,请求 prep = self.prepare_request(req) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py”,第456行,在prepare_request中 p.准备( 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py”,第317行,准备 self.prepare_headers(标题) 文件“/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py”,第449行,在prepare_headers中 对于 headers.items() 中的标题: AttributeError: 'set' 对象没有属性 'items'
下面的代码。
import discord
import os
import requests
client = discord.Client()
url = 'https://api.twitch.tv/helix/search/channels?query=whyoscar'
headers = {'client_id:' '*******************','Authorization:' 'Bearer **********************'}
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$live'):
response = requests.get(url,headers=headers)
details = response.json()
await message.channel.send(details)
client.run(os.getenv('TOKEN'))
解决方法
根据 Twitch 论坛上的 this post,您需要一个用户令牌,而不是应用程序令牌。
Twitch API 文档说
需要 OAuth 或应用访问令牌
...但它没有指定令牌必须是用户令牌。
无论如何,转到 TwitchTokenGenerator,选择 Bot Chat Token,使用您的 Twitch 信息登录,它应该可以工作。
,如果您使用 OAuth 来访问 Twitch API,那么流程应该是这样的:
authURL = 'https://id.twitch.tv/oauth2/token'
client_ID = 'xxx'
secret = 'xxx'
AutParams = {'client_id': client_ID,'client_secret': secret,'grant_type': 'client_credentials'
}
AutCall = requests.post(url=authURL,params=AutParams)
access_token = AutCall.json()['access_token']
head = {
'Client-ID' : client_ID,'Authorization' : "Bearer " + access_token
}
,
答案是,您想像这样定义标头:url = 'https://api.twitch.tv/helix/search/channels?query=<channel you want to search for>&first=1' headers = {"client-id": os.getenv('CLIENT_ID_TOKEN'),"Authorization": os.getenv('ACCESS_TOKEN')}
然后将它们放入 response = requests.get(url,headers=headers)
中,然后以 JSON 格式获取响应并检查 is_live=true
的响应。就这些!