Skip to content

Commit

Permalink
Adding apex legend stats bot
Browse files Browse the repository at this point in the history
  • Loading branch information
hhollenstain committed Jul 21, 2019
1 parent 5ab5707 commit c13c9fa
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 50 deletions.
2 changes: 1 addition & 1 deletion tamago/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
init - version info
"""
VERSION_INFO = (1, 0, 1)
VERSION_INFO = (1, 1, 0)
VERSION = '.'.join(str(c) for c in VERSION_INFO)
182 changes: 144 additions & 38 deletions tamago/lib/plugins/apex.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,67 @@
import discord
import logging
from discord.ext import commands
from apex_legends import ApexLegends
from apex_legends import AsyncLegends
from apex_legends import exceptions as ApexExceptions
from apex_legends.domain import Platform
from tamago.lib import utils

LOG = logging.getLogger(__name__)

RANKS = (
(0, 29, 'bronze4'),
(30, 59, 'bronze3'),
(60, 89, 'bronze2'),
(90, 119, 'bronze1'),
(120, 159, 'silver4'),
(160, 199, 'silver3'),
(200, 239, 'silver2'),
(240, 279, 'silver1'),
(280, 199, 'gold4'),
(330, 199, 'gold3'),
(380, 199, 'gold2'),
(430, 199, 'gold1'),
(480, 199, 'platinum4'),
(540, 199, 'platinum3'),
(600, 199, 'platinum2'),
(660, 199, 'platinum1'),
(720, 199, 'diamond4'),
(790, 199, 'diamond3'),
(860, 199, 'diamond2'),
(930, 199, 'diamond1'),
(1000, 20000, 'apex'),
)

LEGENDS = [
'bangalore',
'bloodhound',
'caustic',
'gibraltar',
'lifeline',
'mirage',
'octane',
'pathfinder',
'wattson',
'wraith',
]


def rank_lookup(value, ranges):
left, right = 0, len(ranges)
while left != right - 1:
mid = left + (right - left) // 2
if int(value) <= ranges[mid - 1][1]: # Check left split max
right = mid
elif int(value) >= ranges[mid][0]: # Check right split min
left = mid
else: # We are in a gap
return None

if ranges[left][0] <= int(value) <= ranges[left][1]:
# Return the code
return ranges[left][2]


class ApexUnkownPlayerError(commands.CommandError):
"""Custom Exception class for no players errors."""
Expand All @@ -18,14 +72,44 @@ def __init__(self, tamago, player):
self.tamago = tamago

async def apex_get_player(self, player):
LOG.info(f"{self.tamago.apex_api_key}, {player}")
"""
returns Apex player object of requested player
:param: object self: discord client
:param: string player: player string
:sends an apex player object
"""
# try:
# async with AsyncLegends(self.tamago.apex_api_key) as apexData:
# player_data = await apexData.player(player, platform=Platform.PC)
# return player_data
# except ApexExceptions.UnknownPlayerError:
# raise ApexUnkownPlayerError(f'Unknown Apex Player: {player}')
try:
async with AsyncLegends(self.tamago.apex_api_key) as apexData:
player_data = await apexData.player(player, platform=Platform.PC)
apex = ApexLegends(self.tamago.apex_api_key)
player_data = apex.player(player, platform=Platform.PC)
return player_data
except ApexExceptions.UnknownPlayerError:
raise ApexUnkownPlayerError(f'Unknown Apex Player: {player}')

async def apex_get_legends(self, player):
"""
returns Apex player legends object of requested player
:param: object self: discord client
:param: string player: player string
:sends an apex player legends object
"""
# try:
# async with AsyncLegends(self.tamago.apex_api_key) as apexData:
# player_data = await apexData.player(player, platform=Platform.PC)
# return player_data.legends
# except ApexExceptions.UnknownPlayerError:
# raise ApexUnkownPlayerError(f'Unknown Apex Player: {player}')
try:
apex = ApexLegends(self.tamago.apex_api_key)
player_data = apex.player(player, platform=Platform.PC)
return player_data.legends
except ApexExceptions.UnknownPlayerError:
raise ApexUnkownPlayerError(f'Unknown Apex Player: {player}')

class Apex(commands.Cog):
def __init__(self, tamago):
Expand All @@ -41,35 +125,79 @@ async def apex(self, ctx, player):
:param: string player: player string
:sends an embed discord message of player stats
"""
player_info = await self.parse(player)
player_data = await ApexPlayerSource.apex_get_player(self, player_info['player'])
embed = discord.Embed(
title = 'Stats for {}'.format(player),
title = f'Stats for {player.upper()}',
url = f'https://apex.tracker.gg/profile/pc/{player_info["player"]}',
colour = discord.Colour.purple()
)
player_data = await ApexPlayerSource.apex_get_player(self, player)
embed.add_field(name="player-test", value=player_data)

embed.add_field(name="**Level**", value=f'{player_data.level}', inline=False)
embed.add_field(name="**Rank**", value=f'{player_data.rankscore} ({rank_lookup(player_data.rankscore,RANKS)})', inline=True)
embed.add_field(name="**Kills**", value=f'{player_data.kills}', inline=False)
embed.add_field(name="**Damage**", value=f'{player_data.damage}', inline=True)
embed.set_thumbnail(url=f'https://trackercdn.com/cdn/apex.tracker.gg/ranks/{rank_lookup(player_data.rankscore,RANKS)}.png')

await ctx.send(embed=embed)

@commands.command(pass_context=True)
@utils.block_check()
async def apexlegends(self, ctx, player, *legends):
async def apexlegends(self, ctx, *, info: str=''):
"""
prints a discord embed with apex stats details of requested player
:param: object self: discord client
:param: dict ctx: dictionary of message passed
:param: string player: player string
:sends an embed discord message of player stats
"""
player_data = await self.parse(info)
if not player_data['player']:
raise ApexUnkownPlayerError(f'No player provided')

legend_data = await ApexPlayerSource.apex_get_legends(self, player_data['player'])
legend_embed_data = {}
if player_data['legends']:
for legend in player_data['legends']:
legend_embed_data[legend] = {}
try:
current_legend_filter = filter(lambda x: x.legend_name.lower() == legend, legend_data)
current_legend = next(current_legend_filter)
for meta in current_legend._stats:
legend_embed_data[legend][meta['metadata']['name']] = meta['value']
except StopIteration:
legend_embed_data[legend]['error'] = f'Legend for {player_data["player"]}, please update at `https://apex.tracker.gg/`'


embed = discord.Embed(
title = f'Legends for {player_data["player"]}',
colour = discord.Colour.orange()
)

for legend in legend_embed_data:
embed.add_field(name='Legend', value=legend.upper(), inline=False)
for stat in legend_embed_data[legend]:
embed.add_field(name=stat.upper(), value=legend_embed_data[legend][stat], inline=True)

if len(player_data['legends']) == 1:
embed.set_thumbnail(url=f'{current_legend.bgimage}')


await ctx.send(embed=embed)

await ctx.send('This is for apexlegends')
# embed = discord.Embed(
# title = 'Stats for {}'.format(player),
# colour = discord.Colour.purple()
# )
# player_data = await ApexPlayerSource.apex_get_player(self, player)
# embed.add_field(name="player-test", value=player_data)
#
# await ctx.send(embed=embed)
async def parse(self, message):
legends = []
player = None
message = message.lower().split()
data = {}
for info in message:
if info in LEGENDS:
legends.append(info)
if info not in LEGENDS:
player = info
data['player'] = player
data['legends'] = legends
return data


@apex.error
Expand All @@ -88,25 +216,3 @@ async def apex_handler(self, ctx, error):

def setup(tamago):
tamago.add_cog(Apex(tamago))
#
#
#
#
#
# my_api_key = 'https://apex.tracker.gg api key here'
#
#
# async def main(api_key, player_name, platform=None):
# async with AsyncLegends(api_key) as apex:
# player = await apex.player(player_name, platform=platform if platform else Platform.PC)
# return player
#
# loop = asyncio.get_event_loop()
# result = loop.run_until_complete(main(my_api_key, player_name='NRG_dizzy'))
#
# print(result)
#
# for legend in result.legends:
# print(legend.legend_name)
# print(legend.icon)
# print(getattr(legend, 'damage', 'Damage not found.'))
18 changes: 9 additions & 9 deletions tamago/lib/plugins/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@
LOG = logging.getLogger(__name__)

class Server(commands.Cog):
def __init__(self, client):
self.client = client
def __init__(self, tamago):
self.tamago = tamago

async def on_ready(self):
await self.client.change_presence(status=discord.Status.idle, activity=Game(name='Waking up, making coffee...'))
LOG.info('Logged in as {}'.format(self.client.user.name))
self.client.loop.create_task(utils.change_status(self.client))
self.client.loop.create_task(utils.list_servers(self.client))
await self.tamago.change_presence(status=discord.Status.idle, activity=Game(name='Waking up, making coffee...'))
LOG.info('Logged in as {}'.format(self.tamago.user.name))
self.tamago.loop.create_task(utils.change_status(self.tamago))
self.tamago.loop.create_task(utils.list_servers(self.tamago))

async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandInvokeError):
Expand Down Expand Up @@ -53,10 +53,10 @@ async def tamago(self, ctx):

embed.set_author(name='Benidct Tamago')
embed.set_thumbnail(url=random.choice(tamago_avatar))
embed.add_field(name='description', value='Bot is a WIP, have fun! Use !help for commands', inline=True)
embed.add_field(name='description', value=f'Tamago is a WIP, add Tamago to your server! [add me]( https://discordapp.com/oauth2/authorize?client_id={self.tamago.app_id}&scope=bot)', inline=True)
embed.add_field(name='Version', value=VERSION, inline=True)

await ctx.send(embed=embed)

def setup(client):
client.add_cog(Server(client))
def setup(tamago):
tamago.add_cog(Server(tamago))
3 changes: 2 additions & 1 deletion tamago/tamago.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ class Tamago(discord.ext.commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.apex_api_key = kwargs.get('apex_api_key')
self.app_id = kwargs.get('app_id')
self.dd_agent_url = kwargs.get('dd_agent_url')
self.owm_api_key = kwargs.get('owm_api_key')
self.stats = DDAgent(self.dd_agent_url)

async def send_message(self, *args, **kwargs):
self.stats.incr('mee6.sent_messages')
self.stats.incr('tamago.sent_messages')
return await super().send_message(*args, **kwargs)
3 changes: 2 additions & 1 deletion tamago/tamago_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

LOG = logging.getLogger(__name__)

APP_ID = os.getenv('APP_ID') or 'fakeid'
BOT_PREFIX = ("?", "!")
DD_AGENT_URL = os.getenv('DD_AGENT_URL')
OWM_API_KEY = os.getenv('OWM_API_KEY') or '123456'
Expand Down Expand Up @@ -63,7 +64,7 @@ def main():
LOG.info("LONG LIVE TAMAGO")
tamago = Tamago(shard_id=int(SHARD), shard_count=int(SHARD_COUNT), redis_url=REDIS_URL,
dd_agent_url=DD_AGENT_URL, owm_api_key=OWM_API_KEY, command_prefix=BOT_PREFIX,
apex_api_key=APEX_API_KEY)
apex_api_key=APEX_API_KEY, app_id=APP_ID)

for extension in EXTENSIONS:
plugin.load('tamago.lib.plugins.{}'.format(extension), tamago)
Expand Down

0 comments on commit c13c9fa

Please sign in to comment.