Reputation: 295
So I'm trying to do a simple API call with a discord bot to get the prices of games on Steam. I have the API request working but when I try and trigger the bot to check the price for me nothing happens. I don't get an error in the console and the bot doesn't post anything to chat.
I know it's pretty ugly I'll go back and clean it up after I can get it to post.
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)
Upvotes: 1
Views: 9816
Reputation: 3497
Assuming that the command is called by !pricecheck <game>
, game = message.content[11:]
is including the space. See test case below, where space is replaced with _ so it's easily readable.
>>> test = '!pricecheck_gamename'
>>> print(test[11:])
_gamename
Because of this, if (i["name"] == game)
is never True, so await client.send_message
will never execute.
Changing it to message.content[12:]
will remove the space.
Suggestions
Adding a check to see if a game was found will allow you to see when all your if
evaluates to False
. It also gives users feedback when the command did not work, possibly because of incorrect usage.
You can also change the requests
library to the aiohttp
library, which is the asynchronous version. requests
can be dangerous as it is blocking, meaning that if it takes to long it can cause your code to crash.
Below is an example of how these suggestions can be used with your code.
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}"
Upvotes: 2