async def TwitterAPI(self, ctx, *, user): """Gets information about twitter users.""" twitter = TwitterClient( consumer_key=getAPIKey('twitterConsKey'), consumer_secret=getAPIKey('twitterConsSecret'), oauth_token=getAPIKey('twitterAccToken'), oauth_token_secret=getAPIKey('twitterAccSecret')) userfields = [ 'created_at', 'description', 'location', 'name', 'profile_image_url', 'protected', 'public_metrics', 'url', 'username', 'verified', 'withheld' ] data = await twitter.request( 'GET', f'../2/users/by/username/{escapeURL(user)}', params={ 'expansions': 'author_id', 'user.fields': ",".join(userfields) }) data = data[0] embed = discord.Embed(title=f"{data['name']} (@{data['username']})", url=data['url'], description=data['description'], color=0x1DA1F2) embed.set_thumbnail(url=data['profile_image_url']) embed.add_field(name='Tweets', value=str(data['public_metrics.tweet_count'])) embed.add_field(name='Followers', value=str(data['public_metrics.followers_count'])) embed.add_field(name='Following', value=str(data['public_metrics.following_count'])) if data['location']: embed.add_field(name='Location', value=data['location']) if data['withheld'] and data['withheld.scope'] == 'user': embed.add_field(name='Banned in countries:', value=data['withheld.country_codes']) extra = [] if data['verified']: extra.append('Verified') if data['protected']: extra.append('Private') if extra: embed.add_field(name='+', value='\n'.join(extra)) embed.set_footer( icon_url= 'https://about.twitter.com/etc/designs/about-twitter/public/img/favicon-32x32.png', text='Twitter • Account created') embed.timestamp = datetime.strptime(data['created_at'], '%a %b %d %H:%M:%S %z %Y') await ctx.send(embed=embed)
async def TwitterAPI(self, ctx, *, user): """Gets information about twitter users.""" twitter = TwitterClient( consumer_key=getAPIKey('twitterConsKey'), consumer_secret=getAPIKey('twitterConsSecret'), oauth_token=getAPIKey('twitterAccToken'), oauth_token_secret=getAPIKey('twitterAccSecret')) data = await twitter.request('GET', 'users/search.json', params={ 'count': 1, 'q': escapeURL(user) }) data = data[0] embed = discord.Embed(title=f"{data['name']} (@{data['screen_name']})", url=f"https://twitter.com/{data['screen_name']}", description=data['description'], color=0x1DA1F2) embed.set_thumbnail(url=data['profile_image_url_https']) embed.add_field(name='Tweets', value=str(data['statuses_count'])) embed.add_field(name='Followers', value=str(data['followers_count'])) embed.add_field(name='Following', value=str(data['friends_count'])) embed.add_field(name='Liked posts', value=str(data['favourites_count'])) if data['location']: embed.add_field(name='Location', value=data['location']) extra = [] if data['verified']: extra.append('Verified') if data['protected']: extra.append('Private') if extra: embed.add_field(name='+', value='\n'.join(extra)) embed.set_footer( icon_url= 'https://about.twitter.com/etc/designs/about-twitter/public/img/favicon-32x32.png', text='Twitter • Account created') embed.timestamp = datetime.strptime(data['created_at'], '%a %b %d %H:%M:%S %z %Y') await ctx.send(embed=embed)
async def screenshot(self, ctx, *, url, size="1920x1080"): if not url.startswith("http"): url = "http://" + url # Download file to website.png async with aiohttp.ClientSession() as s: async with s.get( "http://api.screenshotlayer.com/api/capture?viewport=" + size + "&access_key=" + getAPIKey("screenshotlayer") + "&url=" + url) as r: with open("website.png", "wb") as f: f.write(await r.read()) shot = discord.File("website.png", filename="website.png") await ctx.send(files=[shot])
async def OCRSPACE(self, ctx, *, args=None): """ocr.space engine V1. Results not what you expected? Try ocr2 command. args = [link] [language] or args = [language] if image as attachment or args = [link] if language is english args can also be empty if language is english (default) and image in attachment Use ocrlangs command to see supported languages. """ if args: args = args.split(' ') else: args = [] if '-v2' in args: engine = 2 del args[-1] lang = 'eng' if not args and len(ctx.message.attachments) == 0: raise commands.MissingRequiredArgument(args) elif not args: link = ctx.message.attachments[0].url elif isURL(args[0]): link = args[0] else: raise commands.ArgumentParsingError() else: engine = 1 if not args and len(ctx.message.attachments) == 0: raise commands.MissingRequiredArgument(args) elif not args: link = ctx.message.attachments[0].url lang = 'eng' elif isURL(args[0]) and len(args) == 1: link = args[0] lang = 'eng' elif len(args) == 1 and len(ctx.message.attachments) != 0: link = ctx.message.attachments[0].url lang = self.getLang(args[0]) elif len(args) == 2 and isURL(args[0]): link = args[0] lang = self.getLang(args[1]) elif len(args) == 2 and isURL(args[1]): lang = self.getLang(args[0]) link = args[1] else: raise commands.ArgumentParsingError() data = await REST('https://api.ocr.space/parse/image', method='POST', headers={'apikey': getAPIKey('ocrspace')}, data={ 'url': link, 'language': lang, 'OCREngine': engine }) if data['OCRExitCode'] != 1: await ctx.send(f"`{data['ErrorMessage']}`") else: await ctx.send(f"```{data['ParsedResults'][0]['ParsedText']} ```")
async def TwitchAPI(self, ctx, *, user): """Gets information about twitch users""" token = await getTwitchToken() data = await REST( f"https://api.twitch.tv/helix/users?login={escapeURL(user)}", headers={ 'Authorization': 'Bearer ' + token, 'Client-ID': getAPIKey('twitchID') }) data = data['data'][0] stream = await REST( f"https://api.twitch.tv/helix/streams?user_login={escapeURL(user)}", headers={ 'Authorization': 'Bearer ' + token, 'Client-ID': getAPIKey('twitchID') }) live = True try: stream = stream['data'][0] except: live = False name = data['display_name'] if data['login'].lower() != data['display_name'].lower(): name = data['display_name'] + ' (' + data['login'] + ')' embed = discord.Embed(title='Twitch - ' + name, color=0x6441A4, url='https://twitch.tv/' + data['login']) embed.set_thumbnail(url=data['profile_image_url']) if live: embed.set_image(url=stream['thumbnail_url'].replace( '{width}', '1920').replace('{height}', '1080')) elif data['offline_image_url']: embed.set_image(url=data['offline_image_url']) if data['broadcaster_type']: utype = data['broadcaster_type'].title() if data['type']: utype += '\n' + data['type'].title() embed.add_field(name='User Type', value=utype) if data['description']: embed.add_field(name='Description', value=data['description']) embed.add_field(name='Total views', value=str(data['view_count'])) if live: embed.add_field(name='Currently ' + stream['type'], value=f"Title: **{stream['title']}**", inline=False) embed.add_field(name='Current viewers', value=stream['viewer_count']) embed.add_field( name='Live for', value=self.td_format( datetime.now() - datetime.fromisoformat(stream['started_at'][:-1]))) embed.set_footer( icon_url= 'https://static.twitchcdn.net/assets/favicon-32-d6025c14e900565d6177.png', text='User ID ' + data['id']) await ctx.send(embed=embed)
async def IGDBAPI(self, ctx, *, title): """Gets information about videogames using IGDB.com""" token = await getTwitchToken() title = title.replace("'", "\\'").replace('"', '\\"') exactmatch = f'where name ~ "{title}";sort url asc;' closematch = f'search "{title}";' body = '''fields name,cover.image_id,release_dates.date,release_dates.platform.name,genres.name,rating,summary,age_ratings.category,age_ratings.rating,game_modes.name,involved_companies.*,involved_companies.company.name,websites.url,url,artworks.image_id,status; limit 1;''' data = await REST(f"https://api.igdb.com/v4/games", method='POST', data=exactmatch + body, headers={ 'Authorization': 'Bearer ' + token, 'Client-ID': getAPIKey('twitchID') }) if not len(data): # Couldn't find exact match, check for close match then data = await REST(f"https://api.igdb.com/v4/games", method='POST', data=closematch + body, headers={ 'Authorization': 'Bearer ' + token, 'Client-ID': getAPIKey('twitchID') }) if not len(data): raise commands.BadArgument(message='Could not find game') data = data[0] embed = discord.Embed(title=data['name'], colour=0xf5c518, url=data['url']) if 'cover' in data: embed.set_thumbnail( url='https://images.igdb.com/igdb/image/upload/t_original/' + data['cover']['image_id'] + '.jpg') if 'artworks' in data: embed.set_image( url='https://images.igdb.com/igdb/image/upload/t_original/' + data['artworks'][0]['image_id'] + '.jpg') if 'summary' in data: embed.description = data['summary'] if 'status' in data: if data['status'] == 2: temp = 'Alpha' elif data['status'] == 3: temp = 'Beta' elif data['status'] == 4: temp = 'Early Access' elif data['status'] == 5: temp = 'Offline' elif data['status'] == 6: temp = 'Cancelled' elif data['status'] == 7: temp = 'Rumored' embed.add_field(name='Status', value=temp) if 'rating' in data: embed.add_field(name='Rating', value=f"{round(data['rating'], 2)}/100") if 'release_dates' in data: # [(date, platform names),] releases = [] for date in data['release_dates']: new = True if 'date' in date: human = datetime.fromtimestamp( date['date']).strftime('%Y-%m-%d') else: human = 'TBD' for release in releases: if date['platform']['name'] == release[1]: # Don't show duplicate platform names new = False elif human == release[0]: release[1] += ', ' + date['platform']['name'] new = False if new: releases.append([human, date['platform']['name']]) temp = [] for release in sorted(releases): temp.append(f"**{release[1]}** ({release[0]})") embed.add_field(name='Platforms', value='\n'.join(temp), inline=False) if 'involved_companies' in data: temp = [] for company in data['involved_companies']: roles = [] if company['developer']: roles.append('Developer') if company['publisher']: roles.append('Publisher') if company['porting']: roles.append('Porting') if company['supporting']: roles.append('Supporting') temp.append( f"**{company['company']['name']}** ({' & '.join(roles)})") embed.add_field(name='Developers', value='\n'.join(temp), inline=False) if 'age_ratings' in data: temp = [] for rating in data['age_ratings']: if rating['category'] == 1: tmp = '**ESRB** ' elif rating['category'] == 2: tmp = '**PEGI** ' else: raise Exception() # TODO: Clean this code up im too lazy rn if rating['rating'] == 1: tmp += '3+' elif rating['rating'] == 2: tmp += '7+' elif rating['rating'] == 3: tmp += '12+' elif rating['rating'] == 4: tmp += '16+' elif rating['rating'] == 5: tmp += '18+' elif rating['rating'] == 6: tmp += 'Rating Pending' elif rating['rating'] == 7: tmp += 'Early Childhood' elif rating['rating'] == 8: tmp += 'Everyone' elif rating['rating'] == 9: tmp += 'Everyone 10+' elif rating['rating'] == 10: tmp += 'Teen' elif rating['rating'] == 11: tmp += 'Mature' elif rating['rating'] == 12: tmp += 'Adults Only' temp.append(tmp) embed.add_field(name='Age Ratings', value='\n'.join(temp)) if 'genres' in data: temp = [] for genre in data['genres']: temp.append(genre['name']) embed.add_field(name='Genres', value='\n'.join(temp)) if 'game_modes' in data: temp = [] for gamemode in data['game_modes']: temp.append(gamemode['name']) embed.add_field(name='Game Modes', value='\n'.join(temp)) if 'websites' in data: temp = [] for website in data['websites']: temp.append(website['url']) embed.add_field(name='External Links', value='\n'.join(temp[:3])) await ctx.send(embed=embed)