|
| 1 | +import requests |
| 2 | + |
| 3 | +from cloudbot import hook |
| 4 | + |
| 5 | +api_url = "http://api.brewerydb.com/v2/search?format=json" |
| 6 | + |
| 7 | + |
| 8 | +@hook.on_start() |
| 9 | +def load_key(bot): |
| 10 | + global api_key |
| 11 | + api_key = bot.config.get("api_keys", {}).get("brewerydb", None) |
| 12 | + |
| 13 | + |
| 14 | +@hook.command('brew') |
| 15 | +def brew(text, bot): |
| 16 | + """<query> - returns the first brewerydb search result for <query>""" |
| 17 | + |
| 18 | + if not api_key: |
| 19 | + return "No brewerydb API key set." |
| 20 | + |
| 21 | + params = {'key': api_key, 'type': 'beer', 'withBreweries': 'Y', 'q': text} |
| 22 | + request = requests.get(api_url, params=params) |
| 23 | + |
| 24 | + if request.status_code != requests.codes.ok: |
| 25 | + return "Failed to fetch info ({})".format(request.status_code) |
| 26 | + |
| 27 | + response = request.json() |
| 28 | + |
| 29 | + output = "No results found." |
| 30 | + |
| 31 | + try: |
| 32 | + if 'totalResults' in response: |
| 33 | + beer = response['data'][0] |
| 34 | + brewery = beer['breweries'][0] |
| 35 | + |
| 36 | + style = 'unknown style' |
| 37 | + if 'style' in beer: |
| 38 | + style = beer['style']['shortName'] |
| 39 | + |
| 40 | + abv = '?.?' |
| 41 | + if 'abv' in beer: |
| 42 | + abv = beer['abv'] |
| 43 | + |
| 44 | + url = '[no website found]' |
| 45 | + if 'website' in brewery: |
| 46 | + url = brewery['website'] |
| 47 | + |
| 48 | + content = { |
| 49 | + 'name': beer['nameDisplay'], |
| 50 | + 'style': style, |
| 51 | + 'abv': abv, |
| 52 | + 'brewer': brewery['name'], |
| 53 | + 'url': url |
| 54 | + } |
| 55 | + |
| 56 | + output = "{name} by {brewer} ({style}, {abv}% ABV) - {url}" \ |
| 57 | + .format(**content) |
| 58 | + |
| 59 | + except Exception as e: |
| 60 | + print(e) |
| 61 | + output = "Error parsing results." |
| 62 | + |
| 63 | + return output |
0 commit comments