async def assignGw2GuildRoles(self, ctx, member: discord.Member, new_server_role: discord.Guild.roles, api_key: str): gw2Api = Gw2Api(self.bot) if not member.bot: try: is_valid_key = await gw2Api.check_api_key(api_key) except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return if isinstance(is_valid_key, dict): try: endpoint = "account" api_req_acc = await gw2Api.call_api(endpoint, key=api_key) member_server_id = api_req_acc["world"] except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return try: endpoint = f"worlds/{member_server_id}" api_req_server = await gw2Api.call_api(endpoint, key=api_key) gw2_server_name = api_req_server["name"] except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return if new_server_role.name.lower() == gw2_server_name.lower(): if new_server_role not in member.roles: await member.add_roles(new_server_role)
async def insert_characters(self, member: discord.Member, api_key, type_session: str, ctx=None): if not (hasattr(self, "bot")): self.bot = self gw2Api = Gw2Api(self.bot) try: api_req_characters = await gw2Api.call_api("characters", key=api_key) insert_obj = BotUtils.Object() insert_obj.api_key = api_key insert_obj.ctx = ctx insert_obj.gw2Api = gw2Api insert_obj.discord_user_id = member.id if type_session == "start": gw2CharsStartSql = Gw2CharsStartSql(self.bot) await gw2CharsStartSql.insert_character(insert_obj, api_req_characters) else: gw2CharsEndSql = Gw2CharsEndSql(self.bot) await gw2CharsEndSql.insert_character(insert_obj, api_req_characters) except Exception as e: return self.bot.log.error(e)
async def get_world_id(self, world): if world is None: return None gw2Api = Gw2Api(self.bot) results = await gw2Api.call_api("worlds?ids=all") for name in results: if name["name"].lower() == world.lower(): return name["id"] return None
async def _daily_embed(self, ctx, daily_type: str): import datetime as dt await ctx.message.channel.trigger_typing() achiev_id_lst = [] todays_date = BotUtils.convert_date_toStr(dt.datetime.now()) gw2Api = Gw2Api(self.bot) try: endpoint = "achievements/daily" api_all_dailies = await gw2Api.call_api(endpoint) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) for achiev_id in api_all_dailies[daily_type]: achiev_id_lst.append(str(achiev_id["id"])) try: achiev_ids = ','.join(achiev_id_lst) endpoint = f"achievements?ids={achiev_ids}" api_daily_desc = await gw2Api.call_api(endpoint) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) color = self.bot.gw2_settings["EmbedColor"] embed = discord.Embed(color=color) embed.set_author(name=f"Today's {daily_type.upper()} Dailies ({todays_date})", icon_url=self.bot.user.avatar_url) for x in range(0, len(api_all_dailies[daily_type])): await ctx.message.channel.trigger_typing() name = str(api_daily_desc[x]["name"]) requirement = str(api_daily_desc[x]["requirement"]) reward_id = str(api_daily_desc[x]["rewards"][0]["id"]) try: endpoint = f"items/{reward_id}" api_items_desc = await gw2Api.call_api(endpoint) reward_name = api_items_desc["name"] reward_amount = str(api_daily_desc[x]["rewards"][0]["count"]) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) dt = x + 1 name = f"{dt}) {name} ({reward_amount} {reward_name})" value = Formatting.inline(requirement) embed.add_field(name=name, value=value, inline=False) await ctx.message.channel.trigger_typing() await BotUtils.send_embed(self, ctx, embed, False)
async def get_world_name(self, wids: str): try: endpoint = f"worlds?ids={wids}" gw2Api = Gw2Api(self.bot) results = await gw2Api.call_api(endpoint) if len(results) == 0: return None else: name = results["name"] except: name = None return name
async def gw2_worlds(self, ctx): """ (List all worlds) Example: gw2 worlds """ try: await ctx.message.channel.trigger_typing() endpoint = "worlds?ids=all" gw2Api = Gw2Api(self.bot) results = await gw2Api.call_api(endpoint) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) color = self.bot.gw2_settings["EmbedColor"] desc_na = "~~~~~ NA Servers ~~~~~" embed_na = discord.Embed(color=color, description=Formatting.inline(desc_na)) desc_eu = "~~~~~ EU Servers ~~~~~" embed_eu = discord.Embed(color=color, description=Formatting.inline(desc_eu)) for world in results: try: await ctx.message.channel.trigger_typing() wid = world["id"] endpoint = f"wvw/matches?world={wid}" matches = await gw2Api.call_api(endpoint) if wid < 2001: tier_number = matches["id"].replace("1-", "") embed_na.add_field( name=world["name"], value=Formatting.inline( f"T{tier_number} {world['population']}"), inline=True) else: tier_number = matches["id"].replace("2-", "") embed_eu.add_field( name=world["name"], value=Formatting.inline( f"T{tier_number} {world['population']}"), inline=True) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) await ctx.send(embed=embed_na) await ctx.send(embed=embed_eu)
async def get_world_name_population(self, wids: str): try: name = [] endpoint = f"worlds?ids={wids}" gw2Api = Gw2Api(self.bot) results = await gw2Api.call_api(endpoint) if len(results) == 0: return None else: for x in results: name.append(x["name"]) # name.append(x["name"]+" ("+x["population"]+")") except: name = None return name
async def check_gw2_roles(self, server: discord.Guild): gw2Api = Gw2Api(self.bot) gw2KeySql = Gw2KeySql(self.bot) for member in server.members: if not member.bot: # check each member has api key rs_api_key = await gw2KeySql.get_server_user_api_key( server.id, member.id) if len(rs_api_key) > 0: # user has api key in database api_key = rs_api_key[0]["key"] try: is_valid_key = await gw2Api.check_api_key(api_key) except Exception as e: self.bot.log.error(e) return if not isinstance(is_valid_key, dict): # key not valid anymore removeAllGw2RolesFromUser(self, member) else: try: endpoint = "account" api_req_acc = await gw2Api.call_api(endpoint, key=api_key) member_server_id = api_req_acc["world"] except Exception as e: self.bot.log.error(e) return try: endpoint = f"worlds/{member_server_id}" api_req_server = await gw2Api.call_api(endpoint, key=api_key) gw2_server_name = api_req_server["name"] except Exception as e: self.bot.log.error(e) return server_has_role = BotUtils.check_server_has_role( self, server, gw2_server_name) # discord doesnt have role that match gw2 member api key if server_has_role is None: await removeAllGw2RolesFromUser(self, member)
async def calculate_user_achiev_points(self, api_req_acc_achiev, api_req_acc): doc_user_achiev_id = [] temp_achiv = [] counter = 0 gw2Api = Gw2Api(self.bot) total = api_req_acc["daily_ap"] + api_req_acc["monthly_ap"] for ach in api_req_acc_achiev: temp_achiv.insert(counter, str(ach["id"])) counter = counter + 1 if counter == 200: all_user_achievs_ids = ','.join(temp_achiv) endpoint = f"achievements?ids={all_user_achievs_ids}" api_achiev = await gw2Api.call_api(endpoint) doc_user_achiev_id += api_achiev counter = 0 temp_achiv = [] for ach in api_req_acc_achiev: for doc in doc_user_achiev_id: if ach["id"] == doc["id"]: total += earned_ap(doc, ach) return total
async def gw2_account(self, ctx): """(General information about your GW2 account) Required API permissions: account Example: gw2 account """ await ctx.message.channel.trigger_typing() discord_user_id = ctx.message.author.id gw2Api = Gw2Api(self.bot) gw2KeySql = Gw2KeySql(self.bot) rs = await gw2KeySql.get_server_user_api_key(ctx.guild.id, discord_user_id) if len(rs) == 0: await ctx.message.channel.trigger_typing() await BotUtils.send_error_msg(self, ctx, "You dont have an API key registered in this server.\n" \ f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n" f"To check your API key use: `{ctx.prefix}gw2 key info`") else: permissions = str(rs[0]["permissions"]) api_key = str(rs[0]["key"]) is_valid_key = await gw2Api.check_api_key(api_key) if not isinstance(is_valid_key, dict): return await BotUtils.send_error_msg(self, ctx, is_valid_key.args[1] + "\n" \ "This API Key is INVALID or no longer exists in gw2 api database.\n\n" \ f"To add or replace an API key use: {ctx.prefix}gw2 key add <api_key>\n" f"To check your API key use: `{ctx.prefix}gw2 key info`") await ctx.message.channel.trigger_typing() if "account" not in permissions: return await BotUtils.send_private_error_msg(self, ctx, "Your API key doesnt have permission to access your gw2 account.\n" \ "Please add one key with account permission.") else: try: # getting infos gw2 api await ctx.message.channel.trigger_typing() endpoint = "account" api_req_acc = await gw2Api.call_api(endpoint, key=api_key) server_id = api_req_acc["world"] endpoint = f"worlds/{server_id}" api_req_server = await gw2Api.call_api(endpoint, key=api_key) if "pvp" in permissions: await ctx.message.channel.trigger_typing() endpoint = "pvp/stats" api_req_pvp = await gw2Api.call_api(endpoint, key=api_key) pvprank = api_req_pvp["pvp_rank"] + api_req_pvp["pvp_rank_rollovers"] # if "characters" in permissions: # api_req_characters= await gw2Api.call_api("characters", key=api_key) # char_names = dict() # for i, char_name in enumerate(api_req_characters): # await ctx.message.channel.trigger_typing() # endpoint = f"characters/{char_name}/core" # current_char = await gw2Api.call_api(endpoint, key=api_key) # char_names[char_name] = dict() # char_names[char_name]["race"] = current_char["race"] # char_names[char_name]["gender"] = current_char["gender"] # char_names[char_name]["profession"] = current_char["profession"] # char_names[char_name]["level"] = current_char["level"] # char_names[char_name]["age"] = current_char["age"] # char_names[char_name]["created"] = current_char["created"] # char_names[char_name]["deaths"] = current_char["deaths"] # # if "progression" in permissions: # await ctx.message.channel.trigger_typing() # endpoint = "account/achievements" # api_req_acc_achiev = await gw2Api.call_api(endpoint, key=api_key) # achiev_points = await Gw2Utils.calculate_user_achiev_points(self, api_req_acc_achiev, api_req_acc) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) await ctx.message.channel.trigger_typing() # acc_id = api_req_acc["id"] age = api_req_acc["age"] guilds = api_req_acc["guilds"] acc_name = api_req_acc["name"] access = ' | '.join(api_req_acc["access"]) access = access.replace("GuildWars2", "Guild Wars 2") access = access.replace("HeartOfThorns", "Heart Of Thorns") access = access.replace("PathOfFire", "Path Of Fire") is_commander = "Yes" if api_req_acc["commander"] else "No" created = api_req_acc["created"].split("T", 1)[0] server_name = api_req_server["name"] population = api_req_server["population"] color = self.bot.gw2_settings["EmbedColor"] embed = discord.Embed(title="Account Name", description=Formatting.inline(acc_name), color=color) embed.set_author(name=ctx.message.author.display_name, icon_url=ctx.message.author.avatar_url) await ctx.message.channel.trigger_typing() try: guilds_names = [] guild_leader_names = [] if "guilds" in api_req_acc: for i in range(0, len(guilds)): guild_id = guilds[i] try: endpoint = "guild/" + guild_id api_req_guild = await gw2Api.call_api(endpoint, key=api_key) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) name = api_req_guild["name"] tag = api_req_guild["tag"] full_name = f"[{tag}] {name}" guilds_names.insert(i, full_name) if "guild_leader" in api_req_acc: guild_leader = ','.join(api_req_acc["guild_leader"]) if len(guild_leader) > 0: if guild_id in guild_leader: guild_leader_names.insert(i, full_name) except APIError as e: return self.bot.log.error(ctx, e) if "progression" in permissions: await ctx.message.channel.trigger_typing() fractallevel = api_req_acc["fractal_level"] # daily_ap = api_req_acc["daily_ap"] # monthly_ap = api_req_acc["monthly_ap"] wvwrank = api_req_acc["wvw_rank"] wvw_title = Gw2Utils.get_wvw_rank_title(int(wvwrank)) embed.add_field(name="Fractal Level", value=Formatting.inline(fractallevel)) embed.add_field(name="WvW Rank", value=Formatting.inline(f"{wvw_title}\n({wvwrank})")) # embed.add_field(name="Achievements Points", value=Formatting.inline(achiev_points)) if "pvp" in permissions: pvp_title = str(Gw2Utils.get_pvp_rank_title(pvprank)) embed.add_field(name="PVP Rank", value=Formatting.inline(f"{pvp_title}\n({pvprank})")) embed.add_field(name="Commander Tag", value=Formatting.inline(is_commander)) embed.add_field(name="Server", value=Formatting.inline(f"{server_name}\n({population})")) embed.add_field(name="Access", value=Formatting.inline(access), inline=False) if len(guilds_names) > 0: embed.add_field(name="Guilds", value=Formatting.inline('\n'.join(guilds_names)), inline=False) if len(guild_leader_names) > 0: embed.add_field(name="Guild Leader", value=Formatting.inline('\n'.join(guild_leader_names)), inline=False) hours = age / 60 days = hours / 24 # years = days / 365.25 embed.add_field(name="Created", value=Formatting.inline(f"{created} ({round(days)} days ago)"), inline=False) await BotUtils.send_embed(self, ctx, embed, False)
async def gw2_wvwinfo(self, ctx, world: str = None): discord_user_id = ctx.message.author.id await ctx.message.channel.trigger_typing() gw2Api = Gw2Api(self.bot) if not world: try: gw2KeySql = Gw2KeySql(self.bot) rs = await gw2KeySql.get_server_user_api_key(ctx.guild.id, discord_user_id) if len(rs) == 1: api_key = rs[0]["key"] results = await gw2Api.call_api("account", key=api_key) wid = results["world"] else: return await BotUtils.send_error_msg(self, ctx, "You dont have an API key registered in this server.\n" f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n" f"To check your API key use: `{ctx.prefix}gw2 key info`") except APIKeyError as e: return await BotUtils.send_error_msg(self, ctx, "No world name or key associated with your account") except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) else: wid = await Gw2Utils.get_world_id(self, world) if not wid: return await BotUtils.send_error_msg(self, ctx, f"Invalid world name\n{world}") try: await ctx.message.channel.trigger_typing() endpoint = f"wvw/matches?world={wid}" matches = await gw2Api.call_api(endpoint) endpoint = f"worlds?id={wid}" worldinfo = await gw2Api.call_api(endpoint) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) if wid < 2001: tier_number = matches["id"].replace("1-", "") tier = f"North America Tier {tier_number}" else: tier_number = matches["id"].replace("2-", "") tier = f"Europe Tier {tier_number}" for key, value in matches["all_worlds"].items(): if wid in value: worldcolor = key if not worldcolor: await BotUtils.send_error_msg(self, ctx, "Could not resolve world's color") return if worldcolor == "red": color = discord.Color.red() elif worldcolor == "green": color = discord.Color.green() else: color = self.bot.gw2_settings["EmbedColor"] ppt = 0 score = format(matches["scores"][worldcolor], ',d') victoryp = matches["victory_points"][worldcolor] await ctx.message.channel.trigger_typing() for m in matches["maps"]: for objective in m["objectives"]: if objective["owner"].lower() == worldcolor: ppt += objective["points_tick"] population = worldinfo["population"] if population == "VeryHigh": population = "Very high" kills = matches["kills"][worldcolor] deaths = matches["deaths"][worldcolor] if kills == 0 or deaths == 0: kd = "0.0" else: kd = round((kills / deaths), 3) skirmish_now = len(matches["skirmishes"]) - 1 skirmish = format(matches["skirmishes"][skirmish_now]["scores"][worldcolor], ',d') kills = format(matches["kills"][worldcolor], ',d') deaths = format(matches["deaths"][worldcolor], ',d') _title = f"{worldinfo['name']}" embed = discord.Embed(title=_title, description=tier, color=color) embed.add_field(name="Score", value=Formatting.inline(score), inline=True) embed.add_field(name="Points per tick", value=Formatting.inline(ppt), inline=True) embed.add_field(name="Victory Points", value=Formatting.inline(victoryp), inline=True) embed.add_field(name="Skirmish", value=Formatting.inline(skirmish), inline=True) embed.add_field(name="Kills", value=Formatting.inline(kills), inline=True) embed.add_field(name="Deaths", value=Formatting.inline(deaths), inline=True) embed.add_field(name="K/D ratio", value=Formatting.inline(str(kd)), inline=True) embed.add_field(name="Population", value=Formatting.inline(population), inline=False) await BotUtils.send_embed(self, ctx, embed, False)
async def gw2_kdr(self, ctx, world: str = None): """(Info about a wvw kdr match. Defaults to account's world) Example: gw2 kdr gw2 kdr world_name """ discord_user_id = ctx.message.author.id await ctx.message.channel.trigger_typing() gw2Api = Gw2Api(self.bot) if not world: try: gw2KeySql = Gw2KeySql(self.bot) rs = await gw2KeySql.get_server_user_api_key(ctx.guild.id, discord_user_id) if len(rs) == 1: api_key = rs[0]["key"] results = await gw2Api.call_api("account", key=api_key) wid = results["world"] else: return await BotUtils.send_error_msg(self, ctx, f"""Invalid World Name Use {ctx.prefix}gw2 match <world_name> Or register an API key on your account.""") except APIKeyError as e: return await BotUtils.send_error_msg(self, ctx, "No world name or key associated with your account") except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) else: wid = await Gw2Utils.get_world_id(self, world) if not wid: return await BotUtils.send_error_msg(self, ctx, f"Invalid world: {world}") try: await ctx.message.channel.trigger_typing() endpoint = f"wvw/matches?world={wid}" matches = await gw2Api.call_api(endpoint) if wid < 2001: tier_number = matches["id"].replace("1-", "") tier = f"North America Tier {tier_number}" else: tier_number = matches["id"].replace("2-", "") tier = f"Europe Tier {tier_number}" green_worlds_names = await _get_map_names_embed_values(self, "green", matches) blue_worlds_names = await _get_map_names_embed_values(self, "blue", matches) red_worlds_names = await _get_map_names_embed_values(self, "red", matches) green_values = await _get_kdr_embed_values(self, "green", matches) blue_values = await _get_kdr_embed_values(self, "blue", matches) red_values = await _get_kdr_embed_values(self, "red", matches) except Exception as e: await BotUtils.send_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) color = self.bot.gw2_settings["EmbedColor"] embed = discord.Embed(title="WvW Kills/Death Ratings", description=tier, color=color) embed.add_field(name="Green", value=green_worlds_names, inline=True) embed.add_field(name="Blue", value=blue_worlds_names, inline=True) embed.add_field(name="Red", value=red_worlds_names, inline=True) embed.add_field(name="--------------------", value=green_values, inline=True) embed.add_field(name="--------------------", value=blue_values, inline=True) embed.add_field(name="--------------------", value=red_values, inline=True) await BotUtils.send_embed(self, ctx, embed, False)
async def get_last_session_user_stats(self, ctx, api_key): if not (hasattr(self, "bot")): self.bot = self gw2Api = Gw2Api(self.bot) user_obj = BotUtils.Object() user_obj.gold = 0 user_obj.karma = 0 user_obj.laurels = 0 user_obj.badges_honor = 0 user_obj.guild_commendations = 0 user_obj.wvw_tickets = 0 user_obj.proof_heroics = 0 user_obj.test_heroics = 0 user_obj.players = 0 user_obj.yaks_scorted = 0 user_obj.yaks = 0 user_obj.camps = 0 user_obj.castles = 0 user_obj.towers = 0 user_obj.keeps = 0 try: api_req_acc = await gw2Api.call_api("account", key=api_key) api_req_wallet = await gw2Api.call_api("account/wallet", key=api_key) api_req_achiev = await gw2Api.call_api("account/achievements", key=api_key) except Exception as e: if ctx is not None: await BotUtils.send_info_msg( self, ctx, "GW2 API is currently down. Try again later...") return self.bot.log.error(e) user_obj.acc_name = api_req_acc["name"] user_obj.wvw_rank = api_req_acc["wvw_rank"] if len(api_req_wallet) > 0: for wallet in api_req_wallet: if wallet["id"] == 1: user_obj.gold = wallet["value"] if wallet["id"] == 2: user_obj.karma = wallet["value"] if wallet["id"] == 3: user_obj.laurels = wallet["value"] if wallet["id"] == 15: user_obj.badges_honor = wallet["value"] if wallet["id"] == 16: user_obj.guild_commendations = wallet["value"] if wallet["id"] == 26: user_obj.wvw_tickets = wallet["value"] if wallet["id"] == 31: user_obj.proof_heroics = wallet["value"] if wallet["id"] == 36: user_obj.test_heroics = wallet["value"] if len(api_req_achiev) > 0: for achiev in api_req_achiev: if achiev["id"] == 283: user_obj.players = achiev["current"] if achiev["id"] == 285: user_obj.yaks_scorted = achiev["current"] if achiev["id"] == 288: user_obj.yaks = achiev["current"] if achiev["id"] == 291: user_obj.camps = achiev["current"] if achiev["id"] == 294: user_obj.castles = achiev["current"] if achiev["id"] == 297: user_obj.towers = achiev["current"] if achiev["id"] == 300: user_obj.keeps = achiev["current"] return user_obj
async def _info_key(self, ctx, sub_command=None): discord_user_id = ctx.message.author.id discord_server_id = ctx.message.guild.id author_icon_url = ctx.message.author.avatar_url color = self.bot.gw2_settings["EmbedColor"] gw2KeySql = Gw2KeySql(self.bot) gw2Api = Gw2Api(self.bot) serversSql = ServersSql(self.bot) if sub_command is not None and sub_command.lower() == "all": rs_all = await gw2KeySql.get_all_user_api_key(discord_user_id) if len(rs_all) == 0: await BotUtils.send_private_error_msg( self, ctx, "You dont have an API key registered in this server.\n" f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n" f"To check your API key use: `{ctx.prefix}gw2 key info`") else: for x in range(0, len(rs_all)): rs_guild_info = await serversSql.get_server_by_id( rs_all[x]["discord_server_id"]) footer_guild_name = rs_guild_info[0]["server_name"] footer_icon_url = rs_guild_info[0]["icon_url"] try: api_key = rs_all[x]["key"] is_valid_key = await gw2Api.check_api_key(api_key) if not isinstance(is_valid_key, dict): is_valid_key = "NO" name = "***This API Key is INVALID or no longer exists in gw2 api database***" else: is_valid_key = "YES" name = f"{ctx.message.author}" except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return _embed = discord.Embed(title="Account Name", description=Formatting.inline( rs_all[x]["gw2_acc_name"]), color=color) _embed.set_author(name=name, icon_url=author_icon_url) _embed.add_field(name="Server", value=Formatting.inline( rs_all[x]["server_name"]), inline=True) _embed.add_field(name="Key Name", value=Formatting.inline( rs_all[x]["key_name"]), inline=True) _embed.add_field(name="Valid", value=Formatting.inline(is_valid_key), inline=True) _embed.add_field(name="Permissions", value=Formatting.inline( rs_all[x]["permissions"].replace( ",", "|")), inline=False) _embed.add_field(name="Key", value=Formatting.inline(rs_all[x]["key"]), inline=False) _embed.set_footer(text=footer_guild_name, icon_url=footer_icon_url) await BotUtils.send_embed(self, ctx, _embed, True) elif sub_command is None: footer_guild_name = str(ctx.message.guild) footer_icon_url = ctx.message.guild.icon_url rs = await gw2KeySql.get_server_user_api_key(discord_server_id, discord_user_id) if len(rs) == 0: await BotUtils.send_private_error_msg( self, ctx, "You dont have an API key registered in this server.\n" f"To add or replace an API key use: `{ctx.prefix}gw2 key add <api_key>`\n" f"To check your API key use: `{ctx.prefix}gw2 key info`") else: try: api_key = rs[0]["key"] is_valid_key = await gw2Api.check_api_key(api_key) if not isinstance(is_valid_key, dict): is_valid_key = "NO" name = "***This API Key is INVALID (or no longer exists in gw2 api database)***" else: is_valid_key = "YES" name = f"{ctx.message.author}" except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return _embed = discord.Embed(title="Account Name", description=Formatting.inline( rs[0]["gw2_acc_name"]), color=color) _embed.set_author(name=name, icon_url=author_icon_url) _embed.add_field(name="Server", value=Formatting.inline(rs[0]["server_name"]), inline=True) _embed.add_field(name="Key Name", value=Formatting.inline(rs[0]["key_name"]), inline=True) _embed.add_field(name="Valid", value=Formatting.inline(is_valid_key), inline=True) _embed.add_field(name="Permissions", value=Formatting.inline( rs[0]["permissions"].replace(",", "|")), inline=False) _embed.add_field(name="Key", value=Formatting.inline(rs[0]["key"]), inline=False) _embed.set_footer(text=footer_guild_name, icon_url=footer_icon_url) await BotUtils.send_embed(self, ctx, _embed, True) else: raise commands.BadArgument(message="BadArgument")
async def _add_key(self, ctx, api_key: str): # if (isinstance(ctx.channel, discord.DMChannel)): # msg = "GW2 add api command needs to be used in a server channel for proper roles to be assign!!!" # await BotUtils.send_private_error_msg(self, ctx, msg) # return gw2Configs = Gw2ConfigsSql(self.bot) rs_gw2_sc = await gw2Configs.get_gw2_server_configs(ctx.guild.id) if len(rs_gw2_sc) == 0 or (len(rs_gw2_sc) > 0 and rs_gw2_sc[0]["last_session"] == "N"): return await BotUtils.send_error_msg( self, ctx, "Unable to add api key.\n" "Last session is not active on this server.\n" f"To activate use: `{ctx.prefix}gw2 config lastsession on`") discord_user_id = ctx.message.author.id discord_server_id = ctx.message.guild.id # searching if API key already exists in bot database gw2KeySql = Gw2KeySql(self.bot) rs = await gw2KeySql.get_api_key(discord_server_id, api_key) if len(rs) == 0: gw2Api = Gw2Api(self.bot) is_valid_key = await gw2Api.check_api_key(api_key) if not isinstance(is_valid_key, dict): return await BotUtils.send_private_error_msg( self, ctx, f"{is_valid_key.args[1]}\n`{api_key}`") key_name = is_valid_key["name"] permissions = ','.join(is_valid_key["permissions"]) try: # getting gw2 acc name api_req_acc_info = await gw2Api.call_api("account", key=api_key) gw2_acc_name = api_req_acc_info["name"] member_server_id = api_req_acc_info["world"] except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) return self.bot.log.error(ctx, e) try: # getting gw2 server name endpoint = f"worlds/{member_server_id}" api_req_server = await gw2Api.call_api(endpoint, key=api_key) gw2_server_name = api_req_server["name"] except Exception as e: await BotUtils.send_private_error_msg(self, ctx, e) self.bot.log.error(ctx, e) return # searching if user has 1 api key already rs = await gw2KeySql.get_server_user_api_key(discord_server_id, discord_user_id) if len(rs) > 0: # update key updateObject = BotUtils.Object() updateObject.discord_user_id = discord_user_id updateObject.discord_server_id = discord_server_id updateObject.key_name = key_name updateObject.gw2_acc_name = gw2_acc_name updateObject.permissions = permissions updateObject.key = api_key updateObject.server_name = gw2_server_name await gw2KeySql.update_api_key(updateObject) msg = "Your API key was **replaced**.\n" \ f"Server: `{gw2_server_name}`\n" \ f"To get info about your new api key use: `{ctx.prefix}gw2 key info`" color = self.bot.gw2_settings["EmbedColor"] await BotUtils.send_private_msg(self, ctx, color, msg) else: # insert key insertObject = BotUtils.Object() insertObject.discord_user_id = discord_user_id insertObject.discord_server_id = discord_server_id insertObject.key_name = key_name insertObject.gw2_acc_name = gw2_acc_name insertObject.permissions = permissions insertObject.key = api_key insertObject.server_name = gw2_server_name await gw2KeySql.insert_api_key(insertObject) msg = "Your key was verified and was **added** to your discord account.\n" \ f"Server: `{gw2_server_name}`\n" \ f"To get info about your api key use: `{ctx.prefix}gw2 key info`" color = self.bot.gw2_settings["EmbedColor"] await BotUtils.send_private_msg(self, ctx, color, msg) # checking if the bot needs to assign gw2 server roles to user gw2Roles = Gw2RolesSql(self.bot) rs = await gw2Roles.get_gw2_server_role(ctx.message.channel.guild.id, gw2_server_name.lower()) if len(rs) > 0: new_role = BotUtils.check_server_has_role(self, ctx.guild, gw2_server_name.lower()) if new_role is not None: await Gw2Utils.assignGw2GuildRoles(self, ctx, ctx.message.author, new_role, api_key) else: await Gw2Utils.removeAllGw2RolesFromUser(self, ctx.message.author) elif len(rs) == 1 and rs[0]["discord_user_id"] == discord_user_id: msg = "That API key is already registered by you or someone else.\n" \ f"To get info about your api key use: `{ctx.prefix}gw2 key info`" await BotUtils.send_private_error_msg(self, ctx, msg) else: await BotUtils.send_private_error_msg( self, ctx, "That API key is already in use by someone else.")