def fetchGame(query): uri = "https://www.giantbomb.com/api/search/" helpText = ("[Click here](https://giantbomb.com/search/?q={})".format( query.replace(' ', '+')) + " for the full search results.") searchField = {"name": "Wrong result?", "value": helpText} params = { 'query': query, 'api_key': g.props['giantbomb_key'], 'format': 'json', 'limit': '5', 'resources': 'game', 'field_list': 'api_detail_url,site_detail_url,platforms' } try: response = requests.get(url=uri, headers=g.apiHeaders, params=params) res = response.json() for i in range(res['number_of_total_results']): if "pinball" not in [ p['name'].lower() for p in res['results'][i]['platforms'] ]: toReturn = __formatResult(res['results'][i]['api_detail_url'], res['results'][i]['site_detail_url']) toReturn.addField(searchField) return toReturn return embed.empty("Sorry, I couldn't find \"{}\"!".format(query)) except Exception as e: h.logException(e) return embed.empty( "Sorry, something went wrong finding \"{}\"!".format(query))
def calc(message): toReturn = "" #Parse arguments try: eq = h.parseArgs(message.content, "calc", 1, 1) for r in eq: eq = r #Convert to string except errors.Error as e: raise e try: answer = ca.calculate(eq) toReturn = "Here's what I calculated:" + c.LINE_BREAK toReturn = toReturn + "`" + " ".join(eq.split()) + "`\n= %s" % answer return toReturn except errors.Error as e: raise e except ZeroDivisionError: return "It's not possible to divide by zero. Are you trying to end the world?! %s" % c.RETRY_EQUATION except Exception as e: if str(e) == "math domain error": #Probably sqrt of negative return "It's not possible to take the square root of a negative number. %s" % c.RETRY_EQUATION elif isinstance(e, OverflowError): return "Sorry, the answer was too big for me to calculate." else: if not isinstance(e, IndexError) or not isinstance(e, ValueError): h.logException(e) return "Sorry, I couldn't finish the calculation. %s" % c.RETRY_EQUATION
def startReminder(timer): timer.beginThread() g.db.insertReminder(timer) try: if timer.live: return "Ok, I set a reminder for you!" else: raise RuntimeError("Reminder timer wasn't live") except Exception as e: h.logException(e) return "Sorry, I couldn't make the reminder!"
def fetchArticle(query): uri = "https://en.wikipedia.org/api/rest_v1/page/summary/" notFound = "https://mediawiki.org/wiki/HyperSwitch/errors/not_found" try: response = requests.get(url=uri + query.replace(' ', '_'), headers=g.apiHeaders) results = response.json() if results['type'] == notFound: return embed.empty("Sorry, I couldn't find \"{}\"!".format(query)) else: return __formatArticle(results) except Exception as e: h.logException(e) return embed.empty( "Sorry, something went wrong finding \"{}\"!".format(query))
async def on_message(message): try: if message.author == globs.client.user: #Do not refer to self return elif str(message.author.id ) in globs.denylist: #User not allowed to use Funky return #Check if a command exists, and if not, suggest one if message.content.startswith('!'): corrected = False #Only used for commands that delete messages cmd = message.content.split(' ', 1)[0].lower()[1:] expected = helpers.parseCommand(cmd) if expected == None: #Contextual command, ignore it return elif cmd != expected: corrected = True suggestion = (constant.UNKNOWN_COMMAND % cmd + "\n\n" + constant.SUGGESTED_COMMAND % expected) def pred(msg): return (msg.author == message.author and msg.channel == message.channel) try: await message.channel.send(suggestion) reply = await globs.client.wait_for('message', check=pred, timeout=15) if reply.content.lower().startswith('!yes'): cmd = expected else: return except asyncio.TimeoutError: return else: return #Check if command is enabled if helpers.isDisabled(cmd): await message.channel.send("Sorry, that command is disabled.") return helpers.logCommand(cmd) #Information commands if cmd == 'hello': await i.hello(message) elif cmd == 'help': await i.help(message) #Useful commands elif cmd == 'announce': await u.announce(message) elif cmd == 'binary': await u.binary(message) elif cmd == 'calc': await u.calc(message) elif cmd == 'hex': await u.hexadec(message) elif cmd == 'game': await u.game(message) elif cmd == 'magic': await u.magic(message) elif cmd == 'poll': await u.poll(message) elif cmd == 'remind': await u.remind(message, time=False) elif cmd == 'roll': await u.roll(message) elif cmd == 'time': await u.remind(message, time=True) elif cmd == 'wiki': await u.wiki(message) #Fun commands elif cmd == 'ask': await f.ask(message) elif cmd == 'choose': await f.choose(message) elif cmd == 'cute': await f.cute(message, corrected) elif cmd == 'joke': await f.joke(message) elif cmd == 'react': await f.react(message, corrected) elif cmd == 'rate': await f.rate(message) elif cmd == 'rps': await f.rps(message) else: return except Exception as e: #If an exception makes it all the way here, output it to a log file helpers.logException(e)
def fetchCard(query): name = "https://api.scryfall.com/cards/named" search = "https://api.scryfall.com/cards/search" random = "https://api.scryfall.com/cards/random" mod = "" try: if '|' in query: mod = query.split('|')[1].strip() query = query.split('|')[0].strip() if query.lower() == "random": if g.props['magic_ignore_digital']: mod += " not:digital" response = requests.get(url=random, params={'q':mod}, headers = g.apiHeaders) #Find by name first else: response = requests.get(url = name, params = {'fuzzy':query, 'set': mod}, headers = g.apiHeaders) #Try finding by name without set code if response.status_code == 404 and mod != "": response = requests.get(url = name, params = {'fuzzy':query}, headers = g.apiHeaders) #Try general search if response.status_code == 404: response = requests.get(url = search, params = {'q':query}, headers = g.apiHeaders) results = response.json() #If found multiple cards, take the first if results['object'] == "list": card = results['data'][0] #Single card found elif results['object'] == "card": card = results #Nothing found else: return emb.empty("Sorry, I couldn't find \"{}\"!".format(query)) #If digital prints not allowed, get a paper one if g.props['magic_ignore_digital'] and card['digital'] and mod == "": newQuery = ("oracleid:" + card['oracle_id'] + " not:back" + " not:digital") response = requests.get(url = search, params = {'q':newQuery}, headers = g.apiHeaders) results = response.json() try: for c in results['data']: if not c['digital'] and c['set_type'] != "memorabilia": card = c break except KeyError: #No non-digital print found, so just send it pass return __formatCard(card) except Exception as e: h.logException(e) return emb.empty("Sorry, something went wrong finding \"{}\"!".format(query))