Python 使用discord.py进行API调用
因此,我尝试使用discord机器人进行一个简单的API调用,以获取Steam上游戏的价格。我有API请求工作,但当我尝试触发bot为我检查价格时,什么都没有发生。我没有在控制台中得到错误,机器人也没有发布任何东西来聊天 我知道它很难看,等我把它发出去后,我会回去把它清理干净Python 使用discord.py进行API调用,python,discord.py,Python,Discord.py,因此,我尝试使用discord机器人进行一个简单的API调用,以获取Steam上游戏的价格。我有API请求工作,但当我尝试触发bot为我检查价格时,什么都没有发生。我没有在控制台中得到错误,机器人也没有发布任何东西来聊天 我知道它很难看,等我把它发出去后,我会回去把它清理干净 if message.content.startswith('!pricecheck'): game = message.content[11:] gres = requests.get('https://
if message.content.startswith('!pricecheck'):
game = message.content[11:]
gres = requests.get('https://api.steampowered.com/ISteamApps/GetAppList/v2/')
gdata = gres.json()
for i in gdata["applist"]["apps"]:
if (i["name"] == game):
app = (i["appid"])
priceres = requests.get(f"https://store.steampowered.com/api/appdetails/?appids={app}")
priced = priceres.json()
price = (priced[f"{app}"]["data"]["price_overview"].get("final"))
msg = f"{game} is currently{price}".format(message)
await client.send_message(message.channel, msg)
假设命令由调用!价格检查,游戏=消息。内容[11:]包括空格。请参阅下面的测试用例,其中空格替换为u,因此易于阅读
>>> test = '!pricecheck_gamename'
>>> print(test[11:])
_gamename
因此,如果i[name]==游戏永远不会为真,那么wait client.send_消息将永远不会执行
将其更改为message.content[12:]将删除该空格
建议
添加检查以查看是否找到游戏将允许您查看所有if的计算结果何时为False。当命令不起作用时,它还会向用户提供反馈,可能是因为使用不当
您还可以将请求库更改为异步版本的库。请求可能是危险的,因为它是阻塞的,这意味着如果需要很长时间,它可能会导致代码崩溃
下面是如何将这些建议用于代码的示例
game_found = False
for i in gdata["applist"]["apps"]:
if (i["name"] == game):
game_found = True
app = (i["appid"])
session = aiohttp.ClientSession()
priceres = await session.get(f"https://store.steampowered.com/api/appdetails/?appids={app}")
priced = await priceres.json()
session.close()
price = (priced[f"{app}"]["data"]["price_overview"].get("final"))
msg = f"{game} is currently{price}".format(message)
await client.send_message(message.channel, msg)
if not game_found:
await client.send_message(message.channel, f"Could not find info on {game}"
太好了,谢谢!我将结帐的aiohttp图书馆,我从来没有听说过。我目前正在使用requests\u cache来加速对主游戏列表的搜索。我已经更新了我的答案,将aiohttp包含在示例代码中