async def subreddit(self, ctx, name: str): ''' Gets a random post from a subreddit ''' # Send typing to show that you're doing stuff await self.sparcli.send_typing(ctx.message.server) # Get the subreddit from the reddit instance subreddit = self.getSubreddit(name) # Get a random post try: postGen = subreddit.hot() except Exception as e: await self.sparlci.say('This subreddit could not be found.') return postList = [i for i in postGen] post = choice(postList) postValues = OrderedDict() # Format nicely for the embeds title = post.title link = post.shortlink score = post.score # Start formatting the embed postValues['Title'] = title postValues['Score'] = score postValues['Comments'] = '[Click here!]({})'.format(link) # Work out if it's an image or not if post.is_self: makeThumb = False if post.selftext != '': postValues['Body Text'] = post.selftext elif True in [ post.url.endswith(i) for i in ['.jpg', '.jpeg', '.png', '.gif'] ]: makeThumb = True else: makeThumb = True # Make the embed if makeThumb: e = makeEmbed(author=title, author_icon=self.redditIcon, colour=0xff4006, image=post.url, fields=postValues) else: e = makeEmbed(author=title, author_icon=self.redditIcon, colour=0xff4006, fields=postValues) # Return to user await self.sparcli.say('', embed=e)
async def bigemoji(self, ctx, emoji: str): ''' Gives you a larger picture of an emoji ''' # Set up the base URLs twitterBase = 'https://raw.githubusercontent.com/twitter/twemoji/gh-pages/72x72/{}.png' discordBase = 'https://cdn.discordapp.com/emojis/{}.png' # Format the actual emojis into realio things if len(emoji) <= 2: t = ord(emoji[0]) t = hex(t) t = t[2:] emojiUrl = twitterBase.format(t) else: t = emoji.split(':')[2][:-1] emojiUrl = discordBase.format(t) try: emojiUrl except Exception: await self.sparcli.say( 'I was unable to get the URL for that emoji.') return # Echo it back out to the user e = makeEmbed(image=emojiUrl) await self.sparcli.say(embed=e)
async def cat(self, ctx): ''' Gives a random picture of a cat ''' # Send typing, so you can see it's being processed await self.sparcli.send_typing(ctx.message.channel) while True: try: # async with get('http://thecatapi.com/api/images/get?format=src') as r: # page = r.url # break async with self.session.get('http://random.cat/meow') as r: data = await r.json() page = data['file'] break except Exception: pass # Give the url of the loaded page # await self.sparcli.say(page) em = makeEmbed(image=page, colour=randint(0, 0xFFFFFF)) await self.sparcli.say(embed=em)
async def netflix(self, ctx, *, showName: str): ''' Gives you the details of a show on Netflix ''' url = 'http://netflixroulette.net/api/api.php?title=' + showName async with self.session.get(url) as r: resp = r.status data = await r.json() if resp == 404: await self.sparcli.say( 'The show with the title `{}` could not be found.'.format( showName.title())) return # Process the data o = OrderedDict() o['Summary'] = (data.get('summary'), False) o['Release Year'] = data.get('release_year') o['Rating'] = data.get('rating') o['Runtime'] = data.get('runtime') o['Category'] = data.get('category') o['Link'] = '[Click here](https://www.netflix.com/title/{})'.format( data.get('show_id')) o['ID'] = data.get('show_id') e = makeEmbed(author=data.get('show_title'), image=data.get('poster'), fields=o) await self.sparcli.say(embed=e)
async def getbots(self, ctx, user: Member = None): ''' Gets the bots off of "bots.discord.pw" for a user ''' if user == None: user = ctx.message.author # Get the required token token = getTokens()['DiscordBotsPw'] # Set up the URL headers = {'Authorization': token['Key']} base = 'https://bots.discord.pw/api/users/{}/' url = base.format(user.id) async with self.session.get(url, headers=headers) as r: data = await r.json() # Set up the response q = '**Bot Name:** {}\n' \ '**Bot Description:** {}\n' \ '**Bot Prefix:** {}\n' \ '**Bot Library:** {}\n' \ '**Invite Link:** [Bwap]({})' o = OrderedDict() try: bots = data['bots'] except KeyError: await self.sparcli.say('This user has no registered bots.') return bots = sorted(bots, key=lambda i: i['name']) for i in bots: o[i['name']] = q.format(i['name'], i['description'], i['prefix'], i['library'], i['invite_url']) em = makeEmbed(fields=o) await self.sparcli.say(embed=em)
async def getQuran(self, number, mini, maxi, english=True): ''' Sends stuff off to the API to be processed, returns embed object ''' o = OrderedDict() if english: base = 'http://api.alquran.cloud/ayah/{}:{}/en.sahih' else: base = 'http://api.alquran.cloud/ayah/{}:{}' # Get the data from the API async with self.session.get(base.format(number, mini)) as r: data = await r.json() author = data['data']['surah']['englishName'] if english else data[ 'data']['surah']['name'] o['{}:{}'.format(number, mini)] = data['data']['text'] for verse in range(mini + 1, maxi): async with self.session.get(base.format(number, verse)) as r: data = await r.json() o['{}:{}'.format(number, verse)] = data['data']['text'] em = makeEmbed(fields=o, author=author, author_icon=self.quranPicture) return em
async def legoset(self, *, query: str): '''Searches for a LEGO set''' sets = self.brickClient.getSets(query=query, pageSize=200) try: r = choice(sets) except IndexError: await self.sparcli.say('That query returned no results.') return o = OrderedDict() name = r.name image = r.imageURL o['Year Released'] = r.year o['Theme'] = r.theme o['Pieces'] = r.pieces o['Minifigs'] = r.minifigs if r.priceUK != None and r.priceUS != None: z = '£{}\n${}'.format(r.priceUK, r.priceUS) elif r.priceUK != None: z = '£{}'.format(r.priceUK) elif r.priceUS != None: z = '${}'.format(r.priceUS) else: z = 'None available.' o['Price'] = z e = makeEmbed(author=name, image=image, fields=o) await self.sparcli.say('', embed=e)
async def randomSubredditImages(self, ctx, animal, subreddit): await self.sparcli.send_typing(ctx.message.channel) # Check the timeout on the last retreival if self.subredditCache.get('{}_Timeout'.format(animal), 10) == 10: # If triggered, set it to -1 self.subredditCache['{}_Timeout'.format(animal)] = -1 # Get new data async with self.session.get( 'https://www.reddit.com/r/{}/.json'.format(subreddit)) as r: data = await r.json() o = [] for i in data['data']['children']: if i['data'].get('post_hint', None) == 'image': o.append(i['data']['url']) # Store the gotten data self.subredditCache['{}'.format(animal)] = o # Get the random animal randomAnimal = choice(self.subredditCache['{}'.format(animal)]) self.subredditCache['{}_Timeout'.format(animal)] += 1 # Format and send em = makeEmbed(image=randomAnimal, colour=randint(0, 0xFFFFFF)) await self.sparcli.say(embed=em)
async def xkcd(self, ctx, comicNumber: int = 'Latest'): ''' Gets you an xkcd comic strip ''' # Parse the comic input into a URL if comicNumber == 'Latest': comicURL = 'http://xkcd.com/info.0.json' else: comicURL = 'https://xkcd.com/{}/info.0.json'.format(comicNumber) async with self.session.get(comicURL) as r: try: data = await r.json() except Exception: await self.sparcli.say( 'Comic `{}` does not exist.'.format(comicNumber)) return title = data['safe_title'] alt = data['alt'] image = data['img'] number = data['num'] url = 'https://xkcd.com/{}'.format(number) await self.sparcli.say(embed=makeEmbed( author=title, author_url=url, description=alt, image=image))
async def on_server_remove(self, server): ''' Triggered when the bot leaves a server ''' botServers = len(self.sparcli.servers) # await self.updateDiscordBots(botServers) allMembers = server.members userMembers = len([i for i in allMembers if not i.bot]) botMembers = len(allMembers) - userMembers o = OrderedDict() o['Server Name'] = server.name o['Server Amount'] = botServers o['Server ID'] = server.id o['Memebrs'] = '`{}` members (`{}` users, `{}` bots)'.format( len(allMembers), userMembers, botMembers ) em = makeEmbed(author='Server Leave :c', fields=o, colour=0xFF0000) await self.sparcli.send_message( self.logChannel, embed=em )
async def bible(self, ctx, *, script: str): ''' Gives you the Christian Bible quote from a specific script ''' # Check if it's a valid request matches = match(self.regexMatches['OriginalRequest'], script) if not matches: self.sparcli.say( 'That string was malformed, and could not be processed. Please try again.' ) return else: script = matches.group() # It is - send it to the API await self.sparcli.send_typing(ctx.message.channel) # Actually do some processing script = quote(script, safe='') async with self.session.get( 'https://getbible.net/json?scrip={}'.format(script)) as r: try: apiText = await r.text() apiData = loads(apiText[1:-2]) except Exception as e: apiData = None script = unquote(script) # Just check if it's something that we can process if not apiData: await self.sparcli.say( 'I was unable to get that paricular Bible passage. Please try again.' ) # Now we do some processin' # Get the max and the min verse numbers chapterMin = int( match(self.regexMatches['GetPassages'], script).group().split(':')[1]) chapterMax = match(self.regexMatches['GetMax'], script) if chapterMax: chapterMax = int(chapterMax.group()) + 1 else: chapterMax = chapterMin + 1 # Process them into an ordered dict o = OrderedDict() passages = apiData['book'][0]['chapter'] for verse in range(chapterMin, chapterMax): o[verse] = passages[str(verse)]['verse'] # Make it into an embed author = match(self.regexMatches['StripAuthor'], script).group().title() em = makeEmbed(fields=o, author=author, author_icon=self.biblePicture) # And done c: await self.sparcli.say(embed=em)
async def getSteamGameInfo(self, gameID:str=None): ''' Gets the data of a game on Steam. Can only be done through ID ''' # TODO: REDO THIS AS `dict.get(item, default)` SO AS TO MAKE IT CLEANER # Get the data from Steam async with self.session.get(self.gameInfo.format(gameID)) as r: steamData = await r.json() # Check to see if it was aquired properly if steamData[str(gameID)]['success'] == False: await self.sparcli.say('I was unable to find the ID of that game on the Steam API.') return # Get the embed information retData = OrderedDict() priceFormatter = lambda y, x: '{}{}.{}'.format(y, str(x)[:-2], str(x)[-2:]) if len(str(x)) > 2 else y + '0.' + str(x) gameData = steamData[gameID]['data'] retData['Name'] = gameData['name'] desc = gameData['short_description'] desc = htmlFixer(desc) retData['Description'] = (desc, False) retData['Game ID'] = gameID try: m = gameData['metacritic'] retData['Metacritic'] = '**{}**, [click here]({})'.format(m['score'], m['url']) except KeyError: pass retData['Categories'] = ', '.join([i['description'] for i in gameData['categories']]) retData['Platforms'] = ', '.join([i.title() for i in list(gameData['platforms'].keys())]) retData['Developer'] = ', '.join(gameData['developers']) retData['Publisher'] = ', '.join(gameData['publishers']) try: priceTemp = gameData['price_overview'] if priceTemp['initial'] != priceTemp['final']: retData['Price'] = '~~{}~~ {}'.format(priceFormatter(priceTemp['currency'], priceTemp['initial']), priceFormatter(priceTemp['currency'], priceTemp['final'])) else: retData['Price'] = priceFormatter(priceTemp['currency'], priceTemp['initial']) except KeyError: # The game is not released/does not have a price pass retData['Store Link'] = '[Open in Steam](steam://store/{0}/), [open in your browser](http://store.steampowered.com/app/{0}/)'.format(gameID) gameImage = choice(gameData['screenshots'])['path_full'] # Delete stuff that doesn't exist for i, o in retData.items(): if o == '': del retData[i] # Make it into an embed e = makeEmbed(author=retData['Name'], author_icon=self.steamIcon, colour=1, fields=retData, image=gameImage) # Return to user await self.sparcli.say('', embed=e)
async def anime(self, ctx, *, animeName: str): ''' Gives you the details of an anime ''' # Make sure there are the correct tokens in the bot tokens = getTokens() userPass = tokens['MyAnimeList'] # Authenticate auth = BasicAuth(userPass['Username'], userPass['Password']) url = 'https://myanimelist.net/api/anime/search.xml?q=' + animeName.replace( ' ', '+') # Send the request async with self.session.get(url, auth=auth) as r: resp = r.status data = await r.text() # Make sure everything's alright if resp == 204: await self.sparcli.say( 'The anime with the title `{}` could not be found.'.format( animeName.title())) return elif resp == 200: pass else: await self.sparcli.say( 'There was an error with this bot\'s authentication details.') return # Parse the XML data root = ET.fromstring(data) anime = root[0] o = OrderedDict() # Plonk it into an embed v = htmlFixer(anime[10].text) v = v if len(v) < 1000 else v[:1000] while v[-1] in ' .,?;\'"/!': v = v[:-1] v = v + '...' o['Summary'] = (v, False) o['Episodes'] = anime[4].text o['Rating'] = anime[5].text + '/10.00' o['Media Type'] = anime[6].text o['Status'] = anime[7].text image = anime[11].text title = anime[1].text # Echo out to the user e = makeEmbed(author=title, image=image, fields=o) await self.sparcli.say(embed=e)
async def pokemon(self, ctx, *, pokemonName: str): ''' Gives you information on a given Pokemon ''' await self.sparcli.send_typing(ctx.message.channel) pokeSite = 'http://pokeapi.co/api/v2/pokemon/{}'.format(pokemonName) typeColours = { 'Normal': 11052922, 'Fire': 15630640, 'Water': 6525168, 'Electric': 16240684, 'Grass': 8046412, 'Ice': 9886166, 'Fighting': 12725800, 'Poison': 10698401, 'Ground': 14860133, 'Flying': 11112435, 'Psychic': 16340359, 'Bug': 10926362, 'Rock': 11968822, 'Ghost': 7559063, 'Dragon': 7288316, 'Dark': 7362374, 'Steel': 12040142, 'Fairy': 14058925 } async with self.session.get(pokeSite) as r: data = await r.json() if data.get('detail', False): await self.sparcli.say('That Pokémon could not be found.') return # Format the information nicely o = OrderedDict() pokemonName = data['name'].title() o['Pokédex Number'] = data['id'] o['Types'] = ', '.join( [i['type']['name'].title() for i in data['types']]) colour = typeColours.get(data['types'][0]['type']['name'].title(), 0) o['Abilities'] = ', '.join([ i['ability']['name'].replace('-', ' ').title() for i in data['abilities'] ]) o['Height'] = '{}m'.format(data['height'] / 10.0) o['Weight'] = '{}kg'.format(data['weight'] / 10.0) image = 'https://img.pokemondb.net/artwork/{}.jpg'.format( pokemonName.lower()) e = makeEmbed(author=pokemonName, colour=colour, fields=o, image=image) await self.sparcli.say('', embed=e)
async def reddituser(self, ctx, username: str): ''' Gives info on a given redditor ''' # Send typing to show that you're doing stuff await self.sparcli.send_typing(ctx.message.server) # Get the redditor from using the reddit instance redditor = self.getRedditor(username) # Store data in a dict redditData = OrderedDict() try: redditData['Comment Karma'] = redditor.comment_karma redditData['Link Karma'] = redditor.link_karma except Exception as e: await self.sparlci.say('This user could not be found.') return tops = [i for i in redditor.top()] topComment = None topLink = None for i in tops: if type( i ) == praw.models.reddit.comment.Comment and topComment == None: topComment = i if type( i ) == praw.models.reddit.submission.Submission and topLink == None: topLink = i if topComment != None and topLink != None: break redditData[ 'Top Comment'] = '[Click here!]({0.link_url}{0.id}/?context=3)'.format( topComment) redditData[ 'Top Post'] = '[Click here!](http://reddit.com{0.permalink})'.format( topLink) # Make an embed from it e = makeEmbed(author=redditor.name, author_icon=self.redditIcon, colour=0xff4006, fields=redditData) # Print to user await self.sparcli.say('', embed=e)
async def colour(self, colour: str): ''' Gives the colour of a hex code in an embed ''' # Fix up the hex code, if necessary fixColour = colourFixer(colour) # Fix the hex to an int intColour = int(fixColour, 16) # Actually print it out await self.sparcli.say('', embed=makeEmbed(colour=intColour, author='#' + fixColour.upper()))
async def mycolour(self, ctx): ''' Gives you the hex colour that your user is displayed as ''' user = ctx.message.author colour = user.colour.value # Fix the hex to an int hexColour = hex(colour)[2:].upper() # Actually print it out await self.sparcli.say('', embed=makeEmbed(colour=colour, author='#' + hexColour))
async def define(self, ctx, *, wordToDefine: str): ''' Defines a word using the Oxford Dictionary ''' wordToDefine = wordToDefine.lower() # Make sure there are the correct tokens in the bot tokens = getTokens() userPass = tokens['OxfordDictionary'] # Send a request to the server base = 'https://od-api.oxforddictionaries.com/api/v1/entries/en/{}/definitions' url = base.format(wordToDefine) headers = {'app_id': userPass['ID'], 'app_key': userPass['Key']} async with self.session.get(url, headers=headers) as r: resp = r.status if resp == 404: pass else: data = await r.json() # Make sure there was a valid response if resp == 404: await self.sparcli.say( 'There were no definitions for the word `{}`.'.format( wordToDefine)) return # Format the data into an embed a = data['results'] b = a[0] c = b['lexicalEntries'] d = c[0] e = d['entries'] f = e[0] g = f['senses'] definitions = [i['definitions'][0] for i in g] o = OrderedDict() for i, p in enumerate(definitions): o['Definition #{}'.format(i + 1)] = p e = makeEmbed(author='Definition of {}'.format(wordToDefine), fields=o, inline=False) await self.sparcli.say(embed=e)
async def stats(self, ctx): ''' Gives you the stats of the bot ''' botServers = len(self.sparcli.servers) botChannels = sum([len(i.channels) for i in self.sparcli.servers]) botUsers = sum([len(i.members) for i in self.sparcli.servers]) botCogs = len(self.sparcli.cogs) botCommands = len(self.sparcli.commands) memoryUsage = round(Process(getpid()).memory_info().rss / (1024**2), 2) o = OrderedDict() o['Servers'] = 'I am in `{}` servers with `{}` channels.'.format( botServers, botChannels) o['Users'] = 'I am serving `{}` users.'.format(botUsers) o['Cogs'] = 'Running `{}` cogs.'.format(botCogs) o['Commands'] = '`{}` active commands.'.format(botCommands) o['Memory'] = 'Using {}MB of RAM.'.format(memoryUsage) em = makeEmbed(fields=o) await self.sparcli.say(embed=em)
async def currency(self, ctx, base: str, amount: str, target: str): ''' Converts from one currency to another ''' try: float(amount) except ValueError: try: float(base) b = base base = amount amount = b except ValueError: await self.sparcli.say('Please provide an amount to convert.') return base = base.upper() target = target.upper() url = 'http://api.fixer.io/latest?base={0}&symbols={0},{1}'.format( base, target) async with self.session.get(url) as r: data = await r.json() # Format the data into something useful if len(data['rates']) < 1: await self.sparcli.say( 'One or both of those currency targets aren\'t supported.') return # Get an output o = OrderedDict() o['Base'] = base o['Target'] = target o['Exchange Rate'] = '1:%.2f' % data['rates'][target] v = float(data['rates'][target]) * float(amount) o['Exchanged Price'] = '{}{} = {}{}'.format(base, amount, target, '%.2f' % v) e = makeEmbed(fields=o) await self.sparcli.say(embed=e)
async def info(self, ctx, user: Member = None): ''' Gives info on the mentioned user ''' # Get the user who was pinged u = user if user != None else ctx.message.author # Generate a dictionary of their information userInfo = OrderedDict() userIcon = u.avatar_url if u.avatar_url != None else u.default_avatar_url userIconPNG = userIcon.replace('.webp?size=', '.png?size=') userInfo['Username'] = u.name userInfo['Discriminator'] = u.discriminator userInfo['Icon'] = '[Click here!]({})'.format(userIconPNG) userInfo['Nickname'] = '{}'.format(u.display_name) userInfo['ID'] = u.id userInfo['Bot'] = u.bot userInfo['Join Date'] = str(u.joined_at)[:-10] + ' (' + str( datetime.now() - u.joined_at).split(',')[0] + ' ago)' userInfo['Creation Date'] = str(u.created_at)[:-10] + ' (' + str( datetime.now() - u.created_at).split(',')[0] + ' ago)' userInfo['Roles'] = ', '.join([g.name for g in u.roles][1:]) # Fix a possibly blank thing userInfo[ 'Roles'] = 'None' if userInfo['Roles'] == '' else userInfo['Roles'] # Get top role colour topColour = u.colour.value # Create an embed out of it embedMessage = makeEmbed(user=u, fields=userInfo, image=userIcon, colour=topColour) # Send it out to the user await self.sparcli.say('', embed=embedMessage)
async def colourof(self, ctx, *, roleName: str = None): ''' Gives you the colour of a role ''' # Get the role itself role = await getTextRoles(ctx, roleName, speak=True, sparcli=self.sparcli) if type(role) == int: return # Get the role colour colour = role.colour.value # Turn it to a hex digit hexColour = hex(colour)[2:].upper() # Actually print it out await self.sparcli.say('', embed=makeEmbed(colour=colour, author='#' + hexColour))
async def permissions(self, ctx, member: Member = None): ''' Checks what permissions a given user has in the mentioned channel ''' # Checks for a tagged member if member == None: member = ctx.message.author # ✅ TICK # ❎ CROSS # 💚 ❤ w = {True: '💚', False: '❤'} # Store the channel channel = ctx.message.channel p = channel.permissions_for(member) o = OrderedDict() o['Read Messages'] = w[p.read_messages] o['Send Messages'] = w[p.send_messages] o['TTS'] = w[p.send_tts_messages] o['Manage Messages'] = w[p.manage_messages] o['Embed Links'] = w[p.embed_links] o['Attach Files'] = w[p.attach_files] o['Read Message History'] = w[p.read_message_history] o['Mention Everyone'] = w[p.mention_everyone] o['Change Nickanme'] = w[p.change_nickname] o['Manage Nicknames'] = w[p.manage_nicknames] o['Manage Roles'] = w[p.manage_roles] o['Manage Emoji'] = w[p.manage_emojis] o['Manage Channels'] = w[p.manage_channels] o['Kick Members'] = w[p.kick_members] o['Ban Members'] = w[p.ban_members] o['Administrator'] = w[p.administrator] e = makeEmbed(fields=o) await self.sparcli.say(embed=e)
async def hadith(self, ctx, bookAuthor: str, bookNumber: str, hadithNumber: str = None): ''' Gets a particular hadith ''' # Get the hadith number and book numbers into the right variables if not hadithNumber: if not ':' in bookNumber: await self.bot.say( 'That is not a valid format to get a Hadith.' 'Please see this command\'s help message.') return bookNumber, hadithNumber = [ i.strip() for i in bookNumber.split(':') ] await self.bot.send_typing(ctx.message.channel) # Special case book authors are sucky bookAuthor = { 'qudsi': 'qudsi40', 'nawawi': 'nawawi40' }.get(bookAuthor.lower(), bookAuthor.lower()) # Grab the links from the site # print(f'https://sunnah.com/{bookAuthor}/{bookNumber}/{hadithNumber}') siteURL = f'https://sunnah.com/{bookAuthor}/{bookNumber}/{hadithNumber}' async with self.session.get(siteURL) as r: siteText = await r.text() # Make sure it's a valid set of text if 'You have entered an incorrect URL. Please use the menu above to navigate the website' in siteText: await self.bot.say('The URL parsed was invalid. Sorry :/') return # Parse from the site siteRaw = siteText.replace('\n', '').replace('<i>', '*').replace('</i>', '*') # Get the relevant snippet r = r'<div class=\"englishcontainer\" id=t[0-9]+><div class=\"english_hadith_full\"><div class=hadith_narrated>.+<\/div><div class=text_details>.+<\/b><\/div>' try: relevantSnippet = search(r, siteRaw).group() except Exception: await self.bot.say('The URL parsed was invalid. Sorry :/') return # Get the narrator r = r'<div class=hadith_narrated>.*<\/div><div class=text_details>' hadithNarrator = search(r, relevantSnippet).group().replace( '<p>', '').split('>')[1].split('<')[0].strip() # Get the Hadith text r = r'<div class=text_details>.*<\/b>' hadithText = search(r, relevantSnippet).group().replace( '<p>', '').split('>')[1].split('<')[0].strip() # Fix the author bookAuthor = { 'bukhari': 'Sahih Bukhari', 'muslim': 'Sahih Muslim', 'tirmidhi': 'Jami` at-Tirmidhi', 'abudawud': 'Sunan Abi Dawud', 'nasai': "Sunan an-Nasa'i", 'ibnmajah': 'Sunan Ibn Majah', 'malik': 'Muwatta Malik', 'riyadussaliheen': 'Riyad as-Salihin', 'adab': "Al-Adab Al-Mufrad", 'bulugh': 'Bulugh al-Maram', 'qudsi40': '40 Hadith Qudsi', 'nawawi40': '40 Hadith Nawawi' }.get(bookAuthor, bookAuthor) # Fix up some other stuff hadithText = hadithText.replace('<p>', '').replace('</p>', '').replace('`', '\\`') hadithNarrator = hadithNarrator.replace('<p>', '').replace('</p>', '') # Generate the embed properly author = f'{bookAuthor} {bookNumber}:{hadithNumber}'.title() em = makeEmbed(fields={hadithNarrator: hadithText}, author=author, colour=0x78c741, author_icon=self.hadithPicture, author_url=siteURL) try: await self.bot.say(embed=em) except Exception: em = makeEmbed(fields={hadithNarrator: hadithText[:500] + '...'}, author=author, colour=0x78c741, author_icon=self.hadithPicture, author_url=siteURL) await self.bot.say( 'That was too long to get fully. Here\'s the best I can do:', embed=em)
async def overwatchStats(self, ctx, battleTag, platform, playType): await self.sparcli.send_typing(ctx.message.channel) # Get the data from the server url = 'https://owapi.net/api/v3/u/{}/blob?platform={}'.format( battleTag.replace('#', '-'), platform) async with self.session.get(url, headers={ 'User-Agent': 'Discord bot Sparcli by Caleb#2831' }) as r: if str(r.status)[0] == '5': await self.sparcli.say( 'Oh. The service for this API is down. Sorry. Try again later, maybe?' ) return elif str(r.status)[0] == '4': await self.sparcli.say( 'That resource could not be found on the server.') return data = await r.json() # Determine which server to read from tempDat = [ data.get('us', {}), data.get('eu', {}), data.get('kr', {}), data.get('any', {}) ] adata = None for i in tempDat: # Set a default if adata == None: adata = i # Try - catch for keyerror try: # Determine their level l = i['stats']['quickplay']['overall_stats'] maxLev = (l.get('prestige', 0) * 100) + l.get('level', 0) # Determine the stored's level try: k = adata['stats']['quickplay']['overall_stats'] compLev = (k.get('prestige', 0) * 100) + k.get('level', 0) except (KeyError, TypeError): compLev = -10 # Restore the server with the largest level if maxLev > compLev: adata = i # Keyerror in comparison except (KeyError, TypeError): pass # Set this up for quick usage data = adata['stats'][playType] # Get the relevant data from the retrieved stuff o = OrderedDict() t = data['overall_stats'] # Temp variable avatar = t.get('avatar') o['Overall Stats'] = '{wins} wins vs {losses} losses over {games} games ({winrate}% win rate)'.format( wins=t.get('wins'), losses=t.get('losses'), games=t.get('games'), winrate=t.get('win_rate')) o['Rank'] = 'N/A' if not t.get('tier', 0) else t.get('tier').title() o['Level'] = '{}'.format( int((t.get('prestige') * 100) + t.get('level'))) o['SR'] = 'N/A' if not t.get('comprank', 0) else int(t.get('comprank')) t = adata['heroes']['playtime'][playType] v = [] b = [] for y, u in t.items(): v.append(y) b.append(u) mostUsed = v[b.index(max(b))] maxTime = timedelta(hours=max(b)) o['Most Used Hero'] = '{} ({})'.format(mostUsed.title(), str(maxTime)) t = data['game_stats'] o['Total Eliminations'] = 'N/A' if not t.get( 'eliminations', 0) else int(t.get('eliminations')) o['Total Deaths'] = 'N/A' if not t.get('deaths', 0) else int( t.get('deaths')) o['Total Solo Kills'] = 'N/A' if not t.get('solo_kills', 0) else int( t.get('solo_kills')) o['Total Final Blows'] = 'N/A' if not t.get('final_blows', 0) else int( t.get('final_blows')) o['Total Damage Done'] = 'N/A' if not t.get('damage_done', 0) else int( t.get('damage_done')) o['Total Healing Done'] = 'N/A' if not t.get( 'healing_done', 0) else int(t.get('healing_done')) o['Most Solo Kills in Game'] = 'N/A' if not t.get( 'solo_kills_most_in_game', 0) else int( t.get('solo_kills_most_in_game')) o['Most Final Blows in Game'] = 'N/A' if not t.get( 'final_blows_most_in_game', 0) else int( t.get('final_blows_most_in_game')) o['Most Damage Done in Game'] = 'N/A' if not t.get( 'damage_done_most_in_game', 0) else int( t.get('damage_done_most_in_game')) o['Most Healing Done in Game'] = 'N/A' if not t.get( 'healing_done_most_in_game', 0) else int( t.get('healing_done_most_in_game')) o['Best Killstreak in Game'] = 'N/A' if not t.get( 'kill_streak_best', 0) else int(t.get('kill_streak_best')) # Format into an embed e = makeEmbed(author='{} Overwatch Stats for {}'.format( playType.title(), battleTag), fields=o, author_icon=avatar) await self.sparcli.say('', embed=e)
async def on_message(self, message): ''' Implement "okay google" ''' return # Make sure it doesn't respond to a bot if message.author.bot: return checks = [ message.content.lower().startswith('okay google'), message.content.lower().startswith('ok google') ] # Make sure it only responds to "okay google" if True not in checks: return # Make sure the search wasn't *just* "okay google" messageCheck = message.content.split(' ', 2)[2] if messageCheck == False: return # Send typing await self.sparcli.send_typing(message.channel) # Create the URL base = 'https://api.cognitive.microsoft.com/bing/v5.0/search?q={}' url = base.format(quote(messageCheck, safe='')) tokens = getTokens()['BingAPI'] headers = { 'BingAPIs-Market': tokens['Market'], 'Ocp-Apim-Subscription-Key': tokens['Key'] } # Send the GET request async with self.session.get(url, headers=headers) as r: data = await r.json() # Try and get the results try: results = data['webPages']['value'] except KeyError: await self.sparcli.send_message( message.channel, 'I couldn\'t find any results for that query.') return # Get a tuple of results from the query resultList = [(i['name'], i['displayUrl'], i['snippet']) for i in results][:3] o = OrderedDict() for i in resultList: o[i[0]] = '[Link]({})\n{}'.format(i[1], i[2]) # Check if the results were changed at all additionalInfo = '' try: # Say what the changes were changeData = data['queryContext'] additionalInfo = 'Your query `{}` was changed to `{}`.'.format( changeData['originalQuery'], changeData['alteredQuery']) # Say how to force no changes try: forceSearch = changeData['alterationOverrideQuery'] additionalInfo = additionalInfo + ' To force search, send `{}`.'.format( forceSearch) except KeyError: pass except KeyError: pass # Boop it back to the user e = makeEmbed(fields=o) await self.sparcli.send_message(message.channel, additionalInfo, embed=e)
async def urban(self, ctx, *, searchTerm: str): ''' Allows you to search UrbanDictionary for a specific term ''' CHARACTER_LIMIT = 250 # Make the url nice and safe searchTerm = searchTerm.replace(' ', '%20') async with self.session.get(self.urbanSite.format(searchTerm)) as r: siteData = await r.json() # Get the definitions definitionList = siteData['list'] o = OrderedDict() counter = 0 url = None if definitionList == []: await self.sparcli.say( 'No definitions found for the search term `{}`.'.format( searchTerm)) return # Go through and get the definitions for definitionObject in definitionList: # Iterate the counter and setup some temp variables counter += 1 author = definitionObject['author'] definition = definitionObject['definition'] # Cut off the end of too-long definitions if len(definition) > CHARACTER_LIMIT: deflist = [] # Split it per word for q in definition.split(' '): # Check if it's above the limit if len(' '.join(deflist + [q])) > CHARACTER_LIMIT: break else: deflist.append(q) # Plonk some elipsies on the end definition = ' '.join(deflist) + '...' # Put it into the dictionary o['Definition #{} by {}'.format(counter, author)] = definition if counter == 3: break # Get a working URL if url == None: v = definitionObject['permalink'] url = '/'.join(v.split('/')[:-1]) # Return to user em = makeEmbed(fields=o, author_url=url, author='Click here for UrbanDictionary', inline=False) await self.sparcli.say(embed=em)