async def duels(self, ctx, playerName, game=None): color_db = db.find_one({"_id": ctx.author.id}) if color_db is None: color = 0 else: color = color_db['color'] playerData = hypixel.Player(playerName).JSON duelsData = hypixel.Player(playerName).JSON['stats']['Duels'] print(duelsData) if not game: embed = discord.Embed( title=f"{playerData['displayname']}'s Duels Stats", color=color) embed.set_thumbnail( url=f"https://crafatar.com/avatars/{playerData['uuid']}?overlay" ) embed.set_author( name= f"Overall Duels Title - {await getOverallTitle(duelsData['wins'])}" ) embed.add_field(name="Coins", value=f"`{duelsData['coins']:,}`") embed.add_field(name="Games Played", value=f"`{duelsData['games_played_duels']:,}`") embed.add_field(name="Current Winstreak", value=f"`{duelsData['current_winstreak']:,}`") embed.add_field(name="Wins", value=f"`{duelsData['wins']:,}`") embed.add_field(name="Losses", value=f"`{duelsData['losses']:,}`") embed.add_field( name="WLR", value=f"`{round(duelsData['wins']/duelsData['losses'], 2)}`") embed.add_field(name="Kills", value=f"`{duelsData['kills']:,}`") embed.add_field(name="Deaths", value=f"`{duelsData['deaths']:,}`") embed.add_field( name="KDR", value=f"`{round(duelsData['kills']/duelsData['deaths'], 2)}`") await ctx.send(embed=embed) elif game.lower() == "bridge": embed = discord.Embed( title=f"{playerData['displayname']}'s Bridge Duels Stats", color=color) embed.set_thumbnail( url=f"https://crafatar.com/avatars/{playerData['uuid']}?overlay" ) embed.set_author( name= f"Bridge Duels Title - The Bridge {await getDivisionTitle(playerData['achievements']['duels_bridge_wins'])}" ) embed.add_field( name="Overall:", value=f"""- **Best WS**: `{duelsData['best_bridge_winstreak']:,}` - **Current WS**: `{duelsData['current_bridge_winstreak']:,}` - **Wins**: `{playerData['achievements']['duels_bridge_wins']:,}` - **Losses**: `{duelsData['bridge_duel_rounds_played']-playerData['achievements']['duels_bridge_wins']:,}`""" ) await ctx.send(embed=embed)
async def hypixelinfo(self, ctx, username: str): try: player = hypixel.Player(username) embed = discord.Embed(description=None) flogin = player.JSON['firstLogin'] cflogin = datetime.fromtimestamp(flogin/1000.0).strftime('%A, %B %#d, %Y at %#I:%M %p %Z') if ctx.me.color is not None: embed.color = ctx.me.color try: ltu = hypixel.Player(player.JSON['mostRecentlyTippedUuid']).getName() #deprecated? constantly doesn't work except KeyError: ltu = "They haven't tipped anyone recently." try: guildname = hypixel.Guild(player.getGuildID()).JSON['name'] except Exception: #shut up code convention i dont care guildname = "They aren't in a gang." try: lmv = player.JSON['mcVersionRp'] #deprecated? constantly doesn't work except KeyError: lmv = "They haven't played Minecraft in years, I guess." try: llogin = player.JSON['lastLogin'] cllogin = datetime.fromtimestamp(llogin / 1000.0).strftime('%A, %B %#d, %Y at %#I:%M %p %Z') except KeyError: cllogin = "******" plevel = player.getLevel() cplevel = '{:,.0f}'.format(plevel) embed.title = f"{player.getName()}'s Hypixel Stats" embed.set_thumbnail(url=f"https://crafatar.com/avatars/{player.UUID}?size=64") embed.add_field(name="Rank", value=f"{player.getRank()['rank']}") embed.add_field(name="Level", value=f"{cplevel}") embed.add_field(name="Guild Name", value=f"{guildname}") embed.add_field(name="First Login", value=f"{cflogin}") embed.add_field(name="Last Login", value=f"{cllogin}") embed.add_field(name="Last Minecraft Version played", value=f"{lmv}") embed.add_field(name="Last Tipped User", value=f"{ltu}") if sys.platform == "windows": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %#d, %Y at %#I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) elif sys.platform == "linux": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %-d, %Y at %-I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: await ctx.send("Player not found! Try another UUID or username.") except Exception: await ctx.send(traceback.print_exc())
async def guild(self, ctx, guild): cluster = pymongo.MongoClient('mongodb+srv://PvP_Bot:[email protected]/<dbname>?retryWrites=true&w=majority') db = cluster['data'] color_db = db['colors'] color = color_db.find_one({"_id": ctx.author.id}) if color is None: colors = 0 else: colors = color['color'] data = requests.get(f'https://api.hypixel.net/guild?key=20935b96-fb6f-434d-a28a-e28abee6af8f&name={guild}').json() guild_member_list = [] for x in data['guild']['members']: player_name = hypixel.Player(x['uuid']).JSON['displayname'] guild_member_list.append(f"{discord.utils.escape_markdown(player_name)} - {datetime.strftime(datetime.fromtimestamp(x['joined']/1000), '%Y-%m-%d')}") embed = discord.Embed(color=colors) embed.add_field(name="Member List", value=str('\n'.join(guild_member_list))[0:1023]) embed.add_field(name="Created At", value=datetime.strftime(datetime.fromtimestamp(data['guild']['created']/1000), '%A, %B %-d, %Y at %-I:%M %p UTC')) await ctx.send(embed=embed)
def ausgabe(self): name = self.input1.text() Player = hypixel.Player(name) PlayerInfo = Player.getPlayerInfo() PlayerGilde = Player.getGuildID() Gilde = hypixel.Guild(PlayerGilde) GildenMember = Gilde.getMembers() print(PlayerGilde)
async def hdebug(self, ctx, *, shit: str): try: player = hypixel.Player("Premintex") guild = hypixel.Guild("Abu Salha Industries") rebug = eval(shit) if asyncio.iscoroutine(rebug): rebug = await rebug else: await ctx.send(py.format(rebug)) except Exception as damnit: await ctx.send(py.format("{}: {}".format(type(damnit).__name__, damnit)))
async def bedwars(self, ctx, player): colors = color_db.find_one({"_id": ctx.author.id}) if colors is None: color = 0 else: color = colors['color'] try: user = hypixel.Player(player).JSON print(user) displayName = user['displayname'] bedwars = user['stats']['Bedwars'] gamesPlayed = bedwars['games_played_bedwars_1'] deaths = bedwars['deaths_bedwars'] bedsLost = bedwars['beds_lost_bedwars'] kills = bedwars["kills_bedwars"] winstreak = bedwars["winstreak"] bedsBroken = bedwars["beds_broken_bedwars"] wins = bedwars['wins_bedwars'] finalDeaths = bedwars['final_deaths_bedwars'] finalKills = bedwars['final_kills_bedwars'] gamesLost = gamesPlayed - wins embed = discord.Embed(title=f'{displayName}\'s BedWars Stats', color=discord.Color(color)) kdr = kills / deaths kdr_rounded = round(kdr, 2) fkdr = round((finalKills / finalDeaths), 2) embed.add_field(name="Total Games Played", value=gamesPlayed) embed.add_field(name="Kills", value=kills) embed.add_field(name="Wins/Losses", value=f'{wins}-{gamesLost}') embed.add_field(name="Winstreak", value=winstreak) embed.add_field(name="Beds Broken", value=bedsBroken) embed.add_field(name="Deaths", value=deaths) embed.add_field(name="Beds Lost", value=bedsLost) embed.add_field(name="KDR (Kill Death Ratio)", value=kdr_rounded) embed.add_field(name="FKDR (Final Kill Death Ratio)", value=fkdr) embed.set_thumbnail(url=f'https://minotar.net/avatar/{player}/200') await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: e2 = discord.Embed( title=':x: Player Not Found', description= f"{ctx.author.mention}, {player} was nowhere to be found :O", color=0xff0000) await ctx.send(embed=e2) except KeyError: e2 = discord.Embed( title=':x: Hypixel Error', description= f"{ctx.author.mention}, there was an error. Either {player} has not played BedWars before, or something is wrong with the Hypixel API.", color=0xff0000) await ctx.send(embed=e2)
async def hduels(self, ctx, username: str): try: player = hypixel.Player(username) embed = discord.Embed(description=f"They've played {player.JSON['stats']['Duels']['games_played_duels']} times.") embed.title = f"{username}'s Duels Stats" embed.set_thumbnail(url=f"https://crafatar.com/avatars/{player.UUID}?size=64") embed.add_field(name="Coins", value=f"{player.JSON['stats']['Duels']['coins']}") embed.add_field(name="Wins", value=f"{player.JSON['stats']['Duels']['wins']}") embed.add_field(name="Losses", value=f"{player.JSON['stats']['Duels']['losses']}") embed.add_field(name="Deaths", value=f"{player.JSON['stats']['Duels']['deaths']}") try: embed.add_field(name="Kills", value=f"{player.JSON['stats']['Duels']['kills']}") except KeyError: embed.add_field(name="Kills", value="0") try: embed.add_field(name="Cosmetic Title", value=f"{player.JSON['stats']['Duels']['active_cosmetictitle']}") except KeyError: pass embed.add_field(name="Goals Hit", value=f"{player.JSON['stats']['Duels']['goals']} times") embed.add_field(name="Bow Shots", value=f"{player.JSON['stats']['Duels']['bow_shots']}") embed.add_field(name="Bow Hits", value=f"{player.JSON['stats']['Duels']['bow_hits']}") wdr = int(player.JSON['stats']['Duels']['wins'])/int(player.JSON['stats']['Duels']['losses']) try: kdr = int(player.JSON['stats']['Duels']['kills'])/int(player.JSON['stats']['Duels']['deaths']) except KeyError: kdr = int(0/int(player.JSON['stats']['Duels']['deaths'])) awdr = '{:,.2f}'.format(wdr) akdr = '{:,.2f}'.format(kdr) if akdr == "0.00": akdr = "0" else: pass embed.add_field(name='Win/Loss Ratio', value=f"{awdr}") embed.add_field(name='Kill/Death Ratio', value=f"{akdr}") if sys.platform == "windows": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %#d, %Y at %#I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) elif sys.platform == "linux": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %-d, %Y at %-I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: await ctx.send("Player not found! Try another UUID or username.") except KeyError: await ctx.send("This user has never played Duels (of any kind) before.") except Exception: await ctx.send(traceback.print_exc())
async def hskywars(self, ctx, username: str): try: player = hypixel.Player(username) embed = discord.Embed(description=None) embed.title = f"{player.getName()}'s Skywars Stats" embed.set_thumbnail(url=f"https://crafatar.com/avatars/{player.UUID}?size=64") if ctx.me.color is not None: embed.color = ctx.me.color embed.add_field(name="Coins", value=f"{player.JSON['stats']['SkyWars']['coins']}") embed.add_field(name="Kills (Solo)", value=f"{player.JSON['achievements']['skywars_kills_solo']}") embed.add_field(name="Kills (Teams)", value=f"{player.JSON['achievements']['skywars_kills_team']}") embed.add_field(name="Wins (Solo)", value=f"{player.JSON['achievements']['skywars_wins_solo']}") embed.add_field(name="Wins (Teams)", value=f"{player.JSON['achievements']['skywars_wins_team']}") embed.add_field(name="Kills (Solo)", value=f"{player.JSON['achievements']['skywars_kills_solo']}") embed.add_field(name="Deaths", value=f"{player.JSON['stats']['SkyWars']['deaths']}") embed.add_field(name="Games Played", value=f"{player.JSON['stats']['SkyWars']['games']}") try: embed.add_field(name="Lucky Blocks Wins", value=f"{player.JSON['stats']['SkyWars']['lab_win_lucky_blocks_lab']}") except KeyError: embed.add_field(name="Lucky Blowck Wins", value="They have not won in LUCKY BLOWCKS") wdr = (int(player.JSON['achievements']['skywars_wins_solo'])+int(player.JSON['achievements']['skywars_wins_team']))/(int(player.JSON['stats']['SkyWars']['deaths'])) kdr = (int(player.JSON['achievements']['skywars_kills_solo'])+int(player.JSON['achievements']['skywars_kills_team']))/(int(player.JSON['stats']['SkyWars']['deaths'])) awdr = '{:,.2f}'.format(wdr) akdr = '{:,.2f}'.format(kdr) embed.add_field(name='Win/Loss Ratio (Overall)', value=f"{awdr}") embed.add_field(name='Kill/Death Ratio (Overall)', value=f"{akdr}") if sys.platform == "windows": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %#d, %Y at %#I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) elif sys.platform == "linux": embed.set_footer( text=f"Requested by: {ctx.message.author} / {datetime.fromtimestamp(time.time()).strftime('%A, %B %-d, %Y at %-I:%M %p %Z')}", icon_url=ctx.message.author.avatar_url) await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: await ctx.send("Player not found! Try another UUID or username.") except KeyError: await ctx.send("This user has never played Skywars before.") except Exception: await ctx.send(traceback.print_exc())
async def profile(self, ctx, user): colors = color_db.find_one({"_id": ctx.author.id}) if colors is None: color = 0 else: color = colors['color'] try: player = hypixel.Player(user).JSON aliases = player['knownAliases'] aliasesProper = ', '.join(aliases) name = player['displayname'] socialLinks = [] try: socialMedia = list( player['socialMedia'] ['links'])[0:len(player['socialMedia']['links'])] for x in socialMedia: socialLinks.append(player['socialMedia']['links'][x]) except: socialLinks.append('None') print(socialLinks) if socialLinks[0] == 'None': socialLinks = ''.join(socialLinks) else: socialLinks = '\n'.join(socialLinks) firstLogin = datetime.fromtimestamp(player['firstLogin'] / 1000) firstLoginProper = datetime.strftime( firstLogin, '%A, %B %-d, %Y at %-I:%M %p UTC') recentLogin = datetime.fromtimestamp(player['lastLogin'] / 1000) recentLoginProper = datetime.strftime( recentLogin, '%A, %B %-d, %Y at %-I:%M %p UTC') uuid = player['uuid'] embed = discord.Embed(title=f"{name}'s Hypixel Profile", color=discord.Color(color)) embed.add_field(name="First Login", value=firstLoginProper) embed.add_field(name="Most Recent Login", value=recentLoginProper) embed.add_field(name="Old Usernames", value=aliasesProper) embed.add_field(name="UUID", value=uuid) embed.add_field(name="Social Media Links", value=socialLinks) await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: e2 = discord.Embed( title=':x: Player Not Found', description= f"{ctx.author.mention}, {user} was nowhere to be found :O", color=0xff0000) await ctx.send(embed=e2)
async def skywars(self, ctx, player): colors = color_db.find_one({"_id": ctx.author.id}) if colors is None: color = 0 else: color = colors['color'] try: user = hypixel.Player(player).JSON displayName = user['displayname'] skywars = user['stats']['SkyWars'] gamesPlayed = skywars['games_played_skywars'] chestsOpened = skywars['chests_opened'] lastMode = skywars['lastMode'] losses = skywars['losses'] quits = skywars['quits'] winStreak = skywars['win_streak'] arrowsShot = skywars['arrows_shot'] wins = gamesPlayed - losses embed = discord.Embed(title=f"{displayName}'s SkyWars Stats", color=discord.Color(color)) embed.add_field(name="Total Games Played", value=gamesPlayed) embed.add_field(name="Chests Opened", value=chestsOpened) embed.add_field(name="Last Mode Played", value=lastMode) embed.add_field(name="Winstreak", value=winStreak) embed.add_field(name="Wins/Losses", value=f"{wins}-{losses}") embed.add_field(name="Quits", value=quits) embed.add_field(name="Arrows Shot", value=arrowsShot) embed.set_thumbnail(url=f'https://minotar.net/avatar/{player}/200') await ctx.send(embed=embed) except hypixel.PlayerNotFoundException: e2 = discord.Embed( title=':x: Player Not Found', description= f"{ctx.author.mention}, {player} was nowhere to be found :O", color=0xff0000) await ctx.send(embed=e2) except KeyError: e2 = discord.Embed( title=':x: Hypixel Error', description= f"{ctx.author.mention}, there was an error. Either {player} has not played SkyWars before, or something is wrong with the Hypixel API.", color=0xff0000) await ctx.send(embed=e2)
async def hystats(arg): """Gets stats from Hypixel for a user""" try: player = hypixel.Player(arg) PlayerName = player.getName() PlayerLevel = player.getLevel() PlayerRank = player.getRank() embed = discord.Embed( title='Hypixel Stats', colour= discord.Colour.red() ) embed.set_thumbnail(url='https://hypixel.net/attachments/621065/') embed.add_field(name='Player Name:', value=PlayerName, inline=False) embed.add_field(name='Player Rank:', value=PlayerRank['rank'], inline=False) embed.add_field(name='Player Level:', value=PlayerLevel, inline=False) await client.say(embed=embed) except: await client.say("The user you put in doesn't have data/does not exist...")
""" This is an example of how you can use this API to create cool things. Just run this and you should see cool stuff. c:""" import hypixel API_KEYS = ['API_KEY_HERE_PLS', 'ANOTHER_API_KEY?', 'Etc.'] hypixel.setKeys(API_KEYS) # This sets the API keys that are going to be used. options = ['rank', 'level', 'karma', 'twitter'] while True: mahInput = input("\nPlease give me a Minecraft username/UUID: ") optionInput = input("Please select from list: {}\n> ".format(options)) player = hypixel.Player( mahInput) # Creates a hypixel.Player object using the input. try: if optionInput.lower() == "rank": # If user selects rank, print("The player is rank: " + player.getRank()['rank']) # Get the rank and print it. print("Were they previously a staff member? {}".format( player.getRank()['wasStaff'])) elif optionInput.lower() == "level": print("The player is level: " + str(player.getLevel())) # Print the player's low level! elif optionInput.lower() == "karma": print("The player has {} karma.".format( player.JSON['karma'])) # +25 karma ;) elif optionInput.lower(
""" Travis Ci Tests """ import os import hypixel API_KEY = os.environ['apikey'] hypixel.setKeys([API_KEY]) Snuggle = hypixel.Player('8998bcff9765438bb6089ab93bfad4d3') SnuggleLevel = Snuggle.getLevel() if SnuggleLevel > 0: print("Snuggle's is level {}.".format(SnuggleLevel)) else: raise ValueError(SnuggleLevel) SnuggleRank = Snuggle.getRank() if SnuggleRank['rank'] == "Moderator": print("Snuggle's is a {}.".format(SnuggleRank)) else: raise ValueError(SnuggleRank) SnuggleKarma = Snuggle.JSON['karma'] if SnuggleKarma > 0: print("Snuggle has {} karma.".format(SnuggleKarma)) else: raise ValueError(SnuggleKarma) SnuggleGuildID = Snuggle.getGuildID() SnuggleGuild = hypixel.Guild(SnuggleGuildID) print("Snuggle's guild is called {}.".format(SnuggleGuild.JSON['name']))
async def hypixel(self, ctx, arg1: str = None, arg2: str = None): if arg1 is None: return await ctx.send("I need an IGN or `watchdog`", delete_after=5) arg1 = arg1.lower().replace('-', '') if arg2: arg2 = arg2.lower() if arg1.lower() == "watchdog": route = Route('GET', '/watchdogstats') watchdog = await self.bot.http.hypixel.request(route) color = ctx.author.color embed = discord.Embed(title="Watchdog Stats", colour=color, timestamp=datetime.datetime.now( datetime.timezone.utc)) embed.set_thumbnail( url="https://hypixel.net/attachments/cerbtrimmed-png.245674/") embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) embed.add_field(name="Watchdog Bans in the last minute", value=watchdog['watchdog_lastMinute'], inline=False) embed.add_field(name="Staff bans in the last day", value=format(watchdog['staff_rollingDaily'], ',d'), inline=False) embed.add_field(name="Watchdog bans in the last day", value=format(watchdog['watchdog_rollingDaily'], ',d'), inline=False) embed.add_field(name="Staff Total Bans", value=format(watchdog['staff_total'], ',d'), inline=False) embed.add_field(name="Watchdog Total Bans", value=format(watchdog['watchdog_total'], ',d'), inline=False) return await ctx.send(embed=embed) elif arg1.lower() == 'skyblock': if not arg2 or arg2 == 'news': route = Route('GET', '/skyblock/news') sbnews = await self.bot.http.hypixel.request(route) paginator = WrappedPaginator(prefix='', suffix='', max_size=250) for entry in sbnews['items']: paginator.add_line( f'[{entry["title"]}]({entry["link"]})\n{entry["text"]}\n' ) embed = discord.Embed(color=ctx.author.color, timestamp=datetime.datetime.now( datetime.timezone.utc)) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) return await interface.send_to(ctx) if arg2 is None: channel = ctx.message.channel color = ctx.author.color async with channel.typing(): try: player = hypixel.Player(arg1) except hypixel.PlayerNotFoundException: raise commands.ArgumentParsingError( 'Couldn\'t find that player...') except AttributeError: raise commands.ArgumentParsingError( 'Couldn\'t find that player...') p = player.JSON tributes = p.get('tourney', {}).get('total_tributes', 0) # TOURNAMENT TRIBUTES level = str(player.getLevel()).split('.')[0] lastlogin = p.get('lastLogin', 0) lastlogout = p.get('lastLogout', 1) if lastlogin > lastlogout: status = "Online!" else: status = "Offline!" tag = None route = Route('GET', f'/guild/player/{player.UUID}') guild = await self.bot.http.sk1er.request(route) if guild.get('success', False): guild = guild['guild'] tag = guild['tag'] if 'tag' in guild else None if tag: tagcolor = guild[ 'tagColor'] if 'tagColor' in guild else 'GRAY' if tagcolor == 'GRAY' or tagcolor == 'GREY': tag = f'§7[{tag}]' elif tagcolor == 'GOLD': tag = f'§6[{tag}]' elif tagcolor == 'DARK_GREEN': tag = f'§2[{tag}]' elif tagcolor == 'YELLOW': tag = f'§e[{tag}]' elif tagcolor == 'DARK_AQUA': tag = f'§3[{tag}]' if not tag: tag = f'§7[{tag}]' route = Route('GET', f'/player/{player.UUID}') apiplayer = await self.bot.http.sk1er.request(route) if apiplayer['success']: try: nametag = apiplayer['player']['playerdisplay'].replace( '§0YOUTUBE', '§fYOUTUBE' ) if 'playerdisplay' in apiplayer else apiplayer[ 'player']['display'].replace( '§0YOUTUBE', '§fYOUTUBE') except Exception: displayname = p['displayname'] nametag = f'§f{displayname}' if tag: nametag = f'{nametag} {tag}' if nametag: parsedtxt = mcfont.parse(nametag) width = mcfont.get_width(parsedtxt) img = Image.new('RGBA', (width + 25, 42)) mcfont.render((5, 0), parsedtxt, img) buf = BytesIO() img.save(buf, format='PNG') buf.seek(0) customtag = discord.File(buf, 'imaginereadingthefilename.png') if arg2 is None: msg = await ctx.send( f"Retrieving {discord.utils.escape_mentions(discord.utils.escape_markdown(p['displayname']))}'s info..." ) uuid = player.UUID embed = discord.Embed( title= f"{discord.utils.escape_markdown(p['displayname'])}'s Info", colour=color, timestamp=datetime.datetime.now(datetime.timezone.utc)) if nametag: embed.set_image( url=f'attachment://imaginereadingthefilename.png') embed.set_thumbnail( url=f"https://crafatar.com/avatars/{uuid}?overlay=true" ) embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) embed.add_field(name="Online Status", value=status, inline=True) language = p.get('userLanguage', 'Not Set') embed.add_field(name="Language", value=language, inline=True) channel = p.get('channel', 'ALL') embed.add_field(name="Chat Channel", value=channel, inline=True) embed.add_field(name="Level", value=level, inline=True) embed.add_field(name="Karma", value=format(p.get('karma', 0), ',d'), inline=True) if 'twitter' not in ctx.config.get('mod.linkfilter'): twitter = p.get('socialMedia', {}).get('TWITTER', 'Not Set') else: twitter = 'Hidden' if 'youtube' not in ctx.config.get('mod.linkfilter'): yt = p.get('socialMedia', {}).get('links', {}).get('YOUTUBE', 'Not Set') else: yt = 'Hidden' insta = p.get('socialMedia', {}).get('INSTAGRAM', 'Not Set') if 'twitch' not in ctx.config.get('mod.linkfilter'): twitch = p.get('socialMedia', {}).get('TWITCH', 'Not Set') else: twitch = 'Hidden' beam = p.get('socialMedia', {}).get('BEAM', 'Not Set') if 'discord' not in ctx.config.get('mod.linkfilter'): dscrd = p.get('socialMedia', {}).get('links', {}).get('DISCORD', 'Not Set') else: dscrd = 'Hidden' embed.add_field( name="Social Media", value= f"Twitter: {twitter}\nYouTube: {yt}\nInstagram: {insta}\nTwitch: {twitch}\nBeam: {beam}\nDiscord: {dscrd}", inline=False) if tributes != 0: embed.add_field(name="Tournament Tributes", value=tributes, inline=False) if customtag: await msg.delete() await ctx.send(embed=embed, file=customtag) else: await msg.edit(content=None, embed=embed) elif arg2 == 'friends': uuid = await self.name_to_uuid(arg1) if not uuid: return await ctx.error(f'Couldn\'t find that player') route = Route('GET', f'/friends/{uuid}') friends = await self.bot.http.sk1er.request(route) paginator = WrappedPaginator( prefix=f'''----------------------------------------------------- Friends ({len(friends)}) >>''', suffix='-----------------------------------------------------', max_size=512) for uuid in friends: friend = friends[uuid] try: name = re.sub(remcolor, '', friend['display'], 0, re.IGNORECASE) time = str( datetime.datetime.fromtimestamp( friend['time'] / 1000, datetime.timezone.utc)).split('.')[0] except TypeError: raise commands.ArgumentParsingError( 'Couldn\'t find that persons friends. Check the name and try again' ) return paginator.add_line( discord.utils.escape_markdown(f'{name} added on {time}')) embed = discord.Embed(color=ctx.author.color, timestamp=datetime.datetime.now( datetime.timezone.utc)) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await interface.send_to(ctx) elif arg2 == 'guild': uuid = await self.name_to_uuid(arg1) if not uuid: return await ctx.error(f'Couldn\'t find that player') route = Route('GET', f'/guild/player/{uuid}') guild = await self.bot.http.sk1er.request(route) if guild['success'] != True: raise commands.ArgumentParsingError( 'Couldn\'t find a guild. Maybe they aren\'t in one...') guild = guild['guild'] embed = discord.Embed(colour=ctx.author.color, timestamp=datetime.datetime.now( datetime.timezone.utc)) embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) gtagcolor = guild.get('tagColor', 'GRAY').lower().replace('_', ' ').capitalize() gtag = guild.get('tag', '') if gtag: gtag = f'[{gtag}] ({gtagcolor})' desc = guild.get('description', 'No Description Set.') embed.add_field( name=f"{arg1}'s guild", value= f"{guild['name']} {gtag}\n{desc}\n\nLevel: {guild['level_calc']}" ) embed.add_field(name="Joinable?", value=guild.get('joinable', 'False'), inline=False) embed.add_field(name="Publicly Listed?", value=guild.get('publiclyListed', 'False'), inline=False) embed.add_field(name="Legacy Rank", value=format(guild.get('legacyRanking', -1), ',d'), inline=False) games = [] for game in guild.get('preferredGames', ['this is a placeholder']): games.append(picklegames.get(game, 'Preferred Games not set.')) embed.add_field(name="Preferred Games", value=', '.join(games) if games else 'Preferred Games not set.', inline=False) ranks = [] for rank in guild.get('ranks', { 'name': 'No custom ranks', 'tag': '' }): name = rank['name'] if not rank.get('tag', ''): tag = '' else: tag = rank['tag'] tag = f'[{tag}]' ranks.append(f'{name} {tag}') embed.add_field( name="Ranks", value='\n'.join(ranks) if ranks else 'No custom ranks', inline=False) await ctx.send(embed=embed) gname = guild['name'] paginatorembed = discord.Embed( title=f'{gname}\'s Members ({len(guild["members"])})', color=ctx.author.color, timestamp=datetime.datetime.now(datetime.timezone.utc)) ranktags = {} for rank in ranks: ranktags[rank.split(' ')[0]] = rank.split(' ')[1] paginator = WrappedPaginator(prefix='', suffix='', max_size=380) for member in guild['members']: name = re.sub( remcolor, '', member.get('displayname', member.get('name', 'Unknown Player')), 0, re.IGNORECASE) joined = str( datetime.datetime.fromtimestamp( member['joined'] / 1000, datetime.timezone.utc)).split('.')[0] try: ranktag = ranktags[member['rank']] except KeyError: ranktag = '' if ranktag != '': paginator.add_line(f'{name} {ranktag} joined on {joined}') else: paginator.add_line(f'{name} joined on {joined}') interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=paginatorembed) await interface.send_to(ctx)
import discord import discord.client from discord.ext import commands import asyncio import hypixel client = commands.Bot(command_prefix='!') API_KEYS = ['399ada7a-43ae-4363-a159-7d873f25fba7'] hypixel.setKeys(API_KEYS) Player = hypixel.Player('UHCHighlights') @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) # Going to add the main commands down here. @client.command() async def shutdown(ctx): await client.close() print("the client has disconnected itself") @client.command() async def ping(ctx): await ctx.send('Pong!') @client.command()
def checkuser(username): try: player = hypixel.Player(username) except hypixel.PlayerNotFoundException: return False
""" This is an example of how you can use this API to create cool things. Just run this and you should see cool stuff. c:""" import hypixel API_KEYS = ['API_KEY_HERE_PLS'] hypixel.setKeys(API_KEYS) # This sets the API keys that are going to be used. Player = hypixel.Player( 'Snuggle' ) # This creates a Player-object and puts it to a variable called "Player". PlayerName = Player.getName( ) # This gets the player's name and puts it in a variable called "PlayerName". :3 print("Player is called ", end='') print(PlayerName) PlayerLevel = Player.getLevel() print(PlayerName + " is level: ", end='') print(PlayerLevel) # This prints the level that we got, two lines up! PlayerRank = Player.getRank() print(PlayerName + " is rank: ", end='') print(PlayerRank['rank'])
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) import hypixel import time print("Test \"{}\" is now running...\n".format(os.path.basename(__file__))) API_KEY = os.environ['apikey'] hypixel.setKeys([API_KEY]) TestFailed = False for player in ActualData: TestPlayer = hypixel.Player(player['Name']) for test in player: method_to_call = getattr(TestPlayer, 'get' + test) testdata = method_to_call() if testdata == player[test]: print("\U00002714 {}".format(testdata)) else: print("\U0000274C {}, Expected: {} [FAILED]".format( testdata, player[test])) TestFailed = True print("UUID: {}\n".format(TestPlayer.UUID)) if TestFailed is True: raise ValueError print("\nDone! All tests finished.")
import hypixel API_KEYS = [''] hypixel.setKeys(API_KEYS) Username = input('Enter Username: '******'stats']['UHC'] UHCKills = UHCStats['kills'] UHCWins = UHCStats['wins'] UHCScore = UHCStats['score'] UHCCoins = UHCStats['coins'] UHCDeaths = UHCStats['deaths'] UHCKills = str(UHCKills) UHCWins = str(UHCWins) UHCScore = str(UHCScore) UHCCoins = str(UHCCoins) UHCDeaths = str(UHCDeaths) UHC_Stats = Username + "'s UHC Stats: \n" + 'Kills: ' + UHCKills + '\n' + 'Wins: ' + UHCWins + '\n' + 'Score: ' + UHCScore + '\n' + 'Coins: ' + UHCCoins + '\n' + 'Deaths: ' + UHCDeaths + '\n\n' print(UHC_Stats) file1 = 'uhcstats.txt' with open(file1, 'a') as file_object: file_object.write(UHC_Stats) """file_object.write("bw wins: {}".format(BwStats['wins_bedwars']))"""
async def hypixel(self, ctx, arg1: str = None, arg2: str = None): if arg1 is None: msg = await ctx.send("I need an IGN, `key` or `watchdog`", delete_after=5) return arg1 = arg1.lower() if arg2: arg2 = arg2.lower() if arg1.lower() == "watchdog": async with aiohttp.ClientSession() as session: async with session.get( f'https://api.hypixel.net/watchdogstats?key={hypixelkey}' ) as resp: watchdog = await resp.json() color = ctx.author.color embed = discord.Embed(title="Watchdog Stats", colour=color, timestamp=datetime.datetime.utcnow()) embed.set_thumbnail( url="https://hypixel.net/attachments/cerbtrimmed-png.245674/") embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) embed.add_field(name="Watchdog Bans in the last minute", value=watchdog['watchdog_lastMinute'], inline=False) embed.add_field(name="Staff bans in the last day", value=format(watchdog['staff_rollingDaily'], ',d'), inline=False) embed.add_field(name="Watchdog bans in the last day", value=format(watchdog['watchdog_rollingDaily'], ',d'), inline=False) embed.add_field(name="Staff Total Bans", value=format(watchdog['staff_total'], ',d'), inline=False) embed.add_field(name="Watchdog Total Bans", value=format(watchdog['watchdog_total'], ',d'), inline=False) await ctx.send(embed=embed) return if arg1.lower() == "key": lastmin = "0" async with aiohttp.ClientSession() as session: async with session.get( f'https://api.hypixel.net/key?key={hypixelkey}' ) as resp: key = await resp.json() lastmin = key.get('record', {}).get('queriesInPastMin', 0) color = ctx.author.color embed = discord.Embed(title="My API Key Stats", colour=color, timestamp=datetime.datetime.utcnow()) embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) embed.add_field( name="Owner", value="GamingGeeek (4686e7b58815485d8bc4a45445abb984)", inline=False) embed.add_field(name="Total Requests", value=format(key['record']['totalQueries'], ',d'), inline=False) embed.add_field(name="Requests in the past minute", value=lastmin, inline=False) await ctx.send(embed=embed) return if arg1.lower() == 'leaderboard': if arg2 is None: return #Make available leaderboards embed elif arg2.lower() == 'level': msg = await ctx.send(f"Generating Network Level leaderboard..." ) headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/LEVEL' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Level', 'Karma', 'Kills', 'Wins' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] level = player['Level'] paginator.add_line(f'[{pos}] {name} - {level}') except Exception as e: pass embed = discord.Embed(title='Network Level Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'karma': msg = await ctx.send(f"Generating Karma leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/KARMA' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Karma', 'Level', 'Kills', 'Wins' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] karma = player['Karma'] paginator.add_line(f'[{pos}] {name} - {karma}') except Exception as e: pass embed = discord.Embed(title='Karma Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'coins': msg = await ctx.send(f"Generating Coins leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/COINS' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Coins', 'Karma', 'Kills', 'Wins' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] coins = player['Coins'] paginator.add_line(f'[{pos}] {name} - {coins}') except Exception as e: pass embed = discord.Embed(title='Coins Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'kills': msg = await ctx.send(f"Generating Total Kills leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/TOTAL_KILLS' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Kills', 'Level', 'Wins', 'Quests' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] kills = player['Kills'] paginator.add_line(f'[{pos}] {name} - {kills}') except Exception as e: pass embed = discord.Embed(title='Total Kills Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'wins': msg = await ctx.send(f"Generating Total Wins leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/TOTAL_WINS' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Wins', 'Level', 'Kills', 'Quests' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] wins = player['Wins'] paginator.add_line(f'[{pos}] {name} - {wins}') except Exception as e: pass embed = discord.Embed(title='Total Wins Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'glevel': msg = await ctx.send(f"Generating Guild Level leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/GUILD_LEVEL' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Level', 'Wins', 'Exp', 'Legacy', 'Created' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] level = player['Level'] paginator.add_line(f'[{pos}] {name} - {level}') except Exception as e: pass embed = discord.Embed(title='Guild Level Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'gexperience': msg = await ctx.send( f"Generating Guild Experience leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/GUILD_LEVEL' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Level', 'Wins', 'Exp', 'Legacy', 'Created' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] exp = player['Exp'] paginator.add_line(f'[{pos}] {name} - {exp}') except Exception as e: pass embed = discord.Embed(title='Guild Experience Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) elif arg2.lower() == 'gwins': msg = await ctx.send(f"Generating Guild Wins leaderboard...") headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://sk1er.club/leaderboards/newdata/GUILD_WINS' ) as resp: content = await resp.read() lbjson = table2json(content, [ 'Position', 'Change', 'Name', 'Wins', 'Level', 'Exp', 'Legacy', 'Created' ]) paginator = WrappedPaginator( prefix='```vbs\n-------------------------------------', suffix='-------------------------------------\n```', max_size=420) for player in lbjson: try: pos = player['Position'] name = player['Name'] wins = player['Wins'] paginator.add_line(f'[{pos}] {name} - {wins}') except Exception as e: pass embed = discord.Embed(title='Guild Wins Leaderboard', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await msg.delete() return await interface.send_to(ctx) else: return await ctx.send('Unknown leaderboard.') elif arg1 == 'skyblock': if not arg2 or arg2 == 'news': async with aiohttp.ClientSession() as session: async with session.get( f'https://api.hypixel.net/skyblock/news?key={hypixelkey}' ) as resp: sbnews = await resp.json() paginator = WrappedPaginator(prefix='', suffix='', max_size=250) for entry in sbnews['items']: paginator.add_line( f'[{entry["title"]}]({entry["link"]})\n{entry["text"]}\n' ) embed = discord.Embed(color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) return await interface.send_to(ctx) if arg2 is None: cleaned = discord.utils.escape_mentions( discord.utils.escape_markdown(arg1)) msg = await ctx.send( f"Requesting info about {cleaned} from the Hypixel API!") channel = ctx.message.channel color = ctx.author.color async with channel.typing(): try: player = hypixel.Player(arg1) except hypixel.PlayerNotFoundException: raise commands.ArgumentParsingError( 'Couldn\'t find that player...') except AttributeError: raise commands.ArgumentParsingError( 'Couldn\'t find that player...') p = player.JSON headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } tributes = p.get('tourney', {}).get('total_tributes', 0) # TOURNAMENT TRIBUTES level = str(player.getLevel()).split('.')[0] lastlogin = p.get('lastLogin', 0) lastlogout = p.get('lastLogout', 1) if lastlogin > lastlogout: status = "Online!" else: status = "Offline!" tag = None async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://api.sk1er.club/guild/player/{player.UUID}' ) as resp: guild = await resp.json() if guild['success']: guild = guild['guild'] tag = guild['tag'] if 'tag' in guild else None if tag: tagcolor = guild[ 'tagColor'] if 'tagColor' in guild else 'GRAY' if tagcolor == 'GRAY' or tagcolor == 'GREY': tag = f'§7[{tag}]' elif tagcolor == 'GOLD': tag = f'§6[{tag}]' elif tagcolor == 'DARK_GREEN': tag = f'§2[{tag}]' elif tagcolor == 'YELLOW': tag = f'§e[{tag}]' elif tagcolor == 'DARK_AQUA': tag = f'§3[{tag}]' if not tag: tag = f'§7[{tag}]' async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://api.sk1er.club/player/{arg1}') as resp: apiplayer = await resp.json() if apiplayer['success']: try: nametag = apiplayer['player']['playerdisplay'].replace( '§0YOUTUBE', '§fYOUTUBE' ) if 'playerdisplay' in apiplayer else apiplayer[ 'player']['display'].replace( '§0YOUTUBE', '§fYOUTUBE') except Exception: displayname = p['displayname'] nametag = f'§f{displayname}' if tag: nametag = f'{nametag} {tag}' if nametag: parsedtxt = mcfont.parse(nametag) width = mcfont.get_width(parsedtxt) img = Image.new('RGBA', (width + 25, 42)) mcfont.render((5, 0), parsedtxt, img) buf = BytesIO() img.save(buf, format='PNG') buf.seek(0) customtag = discord.File(buf, 'imaginereadingthefilename.png') if arg2 is None: msg = await ctx.send( f"Retrieving {discord.utils.escape_mentions(discord.utils.escape_markdown(p['displayname']))}'s info..." ) uuid = player.UUID embed = discord.Embed( title= f"{discord.utils.escape_markdown(p['displayname'])}'s Info", colour=color, timestamp=datetime.datetime.utcnow()) if nametag: embed.set_image( url=f'attachment://imaginereadingthefilename.png') embed.set_thumbnail( url=f"https://crafatar.com/avatars/{uuid}?overlay=true" ) embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) embed.add_field(name="Online Status", value=status, inline=True) language = p.get('userLanguage', 'Not Set') embed.add_field(name="Language", value=language, inline=True) channel = p.get('channel', 'ALL') embed.add_field(name="Chat Channel", value=channel, inline=True) embed.add_field(name="Level", value=level, inline=True) embed.add_field(name="Karma", value=format(p.get('karma', 0), ',d'), inline=True) if 'twitter' not in self.bot.configs[ctx.guild.id].get( 'mod.linkfilter'): twitter = p.get('socialMedia', {}).get('TWITTER', 'Not Set') else: twitter = 'Hidden' if 'youtube' not in self.bot.configs[ctx.guild.id].get( 'mod.linkfilter'): yt = p.get('socialMedia', {}).get('links', {}).get('YOUTUBE', 'Not Set') else: yt = 'Hidden' insta = p.get('socialMedia', {}).get('INSTAGRAM', 'Not Set') if 'twitch' not in self.bot.configs[ctx.guild.id].get( 'mod.linkfilter'): twitch = p.get('socialMedia', {}).get('TWITCH', 'Not Set') else: twitch = 'Hidden' beam = p.get('socialMedia', {}).get('BEAM', 'Not Set') if 'discord' not in self.bot.configs[ctx.guild.id].get( 'mod.linkfilter'): dscrd = p.get('socialMedia', {}).get('links', {}).get('DISCORD', 'Not Set') else: dscrd = 'Hidden' embed.add_field( name="Social Media", value= f"Twitter: {twitter}\nYouTube: {yt}\nInstagram: {insta}\nTwitch: {twitch}\nBeam: {beam}\nDiscord: {dscrd}", inline=False) if tributes != 0: embed.add_field(name="Tournament Tributes", value=tributes, inline=False) if customtag: await msg.delete() await ctx.send(embed=embed, file=customtag) else: await msg.edit(content=None, embed=embed) elif arg2 == 'friends': headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://api.sk1er.club/friends/{arg1}') as resp: friends = await resp.json() paginator = WrappedPaginator( prefix= f'-----------------------------------------------------\n Friends ({len(friends)}) >>', suffix='-----------------------------------------------------', max_size=512) for uuid in friends: friend = friends[uuid] try: name = re.sub(remcolor, '', friend['display'], 0, re.IGNORECASE) time = str( datetime.datetime.utcfromtimestamp(friend['time'] / 1000)).split('.')[0] except TypeError: raise commands.ArgumentParsingError( 'Couldn\'t find that persons friends. Check the name and try again' ) return paginator.add_line( discord.utils.escape_markdown(f'{name} added on {time}')) embed = discord.Embed(color=ctx.author.color, timestamp=datetime.datetime.utcnow()) interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=embed) await interface.send_to(ctx) elif arg2 == 'guild': uuid = await self.nameToUUID(arg1) headers = { 'USER-AGENT': 'Fire (Python 3.7.2 / aiohttp 3.3.2) | Fire Discord Bot', 'CONTENT-TYPE': 'application/json' } async with aiohttp.ClientSession(headers=headers) as session: async with session.get( f'https://api.sk1er.club/guild/player/{uuid}') as resp: guild = await resp.json() if guild['success'] != True: raise commands.ArgumentParsingError( 'Couldn\'t find a guild. Maybe they aren\'t in one...') guild = guild['guild'] embed = discord.Embed(colour=ctx.author.color, timestamp=datetime.datetime.utcnow()) embed.set_footer( text= "Want more integrations? Use the suggest command to suggest some" ) gtagcolor = guild.get('tagColor', 'GRAY').lower().replace('_', ' ').capitalize() gtag = guild.get('tag', '') if gtag: gtag = f'[{gtag}] ({gtagcolor})' desc = guild.get('description', 'No Description Set.') embed.add_field( name=f"{arg1}'s guild", value= f"{guild['name']} {gtag}\n{desc}\n\nLevel: {guild['level_calc']}" ) embed.add_field(name="Joinable?", value=guild.get('joinable', 'False'), inline=False) embed.add_field(name="Publicly Listed?", value=guild.get('publiclyListed', 'False'), inline=False) embed.add_field(name="Legacy Rank", value=format(guild.get('legacyRanking', -1), ',d'), inline=False) games = [] for game in guild.get('preferredGames', ['this is a placeholder']): games.append(picklegames.get(game, 'Preferred Games not set.')) embed.add_field(name="Preferred Games", value=', '.join(games) if games else 'Preferred Games not set.', inline=False) ranks = [] for rank in guild.get('ranks', { 'name': 'No custom ranks', 'tag': '' }): name = rank['name'] if not rank.get('tag', ''): tag = '' else: tag = rank['tag'] tag = f'[{tag}]' ranks.append(f'{name} {tag}') embed.add_field( name="Ranks", value='\n'.join(ranks) if ranks else 'No custom ranks', inline=False) await ctx.send(embed=embed) gname = guild['name'] paginatorembed = discord.Embed( title=f'{gname}\'s Members ({len(guild["members"])})', color=ctx.author.color, timestamp=datetime.datetime.utcnow()) ranktags = {} for rank in ranks: ranktags[rank.split(' ')[0]] = rank.split(' ')[1] paginator = WrappedPaginator(prefix='', suffix='', max_size=380) for member in guild['members']: name = re.sub( remcolor, '', member.get('displayname', member.get('name', 'Unknown Player')), 0, re.IGNORECASE) joined = str( datetime.datetime.utcfromtimestamp(member['joined'] / 1000)).split('.')[0] try: ranktag = ranktags[member['rank']] except KeyError: ranktag = '' if ranktag != '': paginator.add_line(f'{name} {ranktag} joined on {joined}') else: paginator.add_line(f'{name} joined on {joined}') interface = PaginatorEmbedInterface(ctx.bot, paginator, owner=ctx.author, _embed=paginatorembed) await interface.send_to(ctx)
import PySimpleGUI as sg import hypixel import json API_KEYS = [] hypixel.setKeys(API_KEYS) layout = [[sg.Text('bedwars stats')], [sg.Text('username: '******'ok'), sg.Button('cancel')]] window = sg.Window('uwu', layout).Finalize() while True: event, values = window.read() if event in (None, 'cancel'): break username = str(values[0]) player = hypixel.Player(username) Blitz = player.JSON['stats']['HungerGames'] BlitzKills = str(Blitz['kills']) BlitzWinsSolo = str(Blitz['wins']) BlitzWinsTeam = str(Blitz['wins_teams']) BlitzCoins = str(Blitz['coins']) BlitzChests = str(Blitz['chests_opened']) BlitzTaunt = str(Blitz['chosen_taunt']) blitz = 'blitz kills: ' + BlitzKills + '\nblitz wins solo: ' + BlitzWinsSolo + '\nblitz wins teams: ' + BlitzWinsTeam + '\nblitz coins: ' + BlitzCoins + '\nblitz chests: ' + BlitzChests + '\nblitz taunt: ' + BlitzTaunt print(blitz)
] Repeats = 5 import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) import hypixel from time import time from random import shuffle print("Test \"{}\" is now running...\n".format(os.path.basename(__file__))) API_KEY = os.environ['apikey'] hypixel.setKeys([API_KEY]) start = time() # Start timer. for i in range(0, Repeats - 1): shuffle(ActualData) # Randomize the order of the data for InputUUID in ActualData: Player = hypixel.Player(InputUUID) print(Player.getPlayerInfo()) end = time() totalTime = start - end print("\nDone! Speed test finished. Time taken: {}".format(end - start))
async def lvl(ctx, username): player = hypixel.Player(username) HyLevel = str(player.getLevel()) await ctx.send("```" + str(username) + "'s level is > " + str(HyLevel) + "```")