async def dashboard(self, ctx):
     if ctx.author.id !=464954455029317633:
         return await ctx.send(embed=embeds.simple_embed(False, "only eulerthedestroyer#2074 can use admin commands"))
     start = d.timestamp(d.now())
     ret_dict={}
     ret_dict["uptime"]=f':green_circle: Online for {seconds_to_time(math.floor(time()-self.bot.startup_time))}'
     ret_dict["Commands responded"] = self.bot.commands_responded
     ret_dict["errors"] = self.bot.command_errors
     ret_dict["servers"] = len(self.bot.guilds)
     ret_dict["unit tests"] = self.bot.tests
     ret_dict["latency"] = "pinging...."
     msg = await ctx.send(embed=embeds.dict_to_embed(ret_dict ))
     ret_dict["latency"] =f'{math.floor((d.timestamp(d.now())-start) * 1000)} ms'
     await msg.edit(embed=embeds.dict_to_embed(ret_dict ))
Example #2
0
 async def list_games(self,
                      ctx,
                      sort="newest",
                      *,
                      format: converters.FormatConverter = "all"):
     result = await get_global_games()
     games = result["result"]["games"]
     if format != "all":
         print("format is ", format)
         games = list(
             filter(lambda game: game["properties"]["title"] == format,
                    games))
     if sort == "newest":
         sorted_games = sorted(
             games,
             key=lambda game: -int(game["properties"]["startofgame2"]))
     elif sort == "empty":
         sorted_games = sorted(
             games, key=lambda game: -int(game["properties"]["openSlots"]))
     else:
         return await ctx.send(embed=embeds.simple_embed(
             False, "invalid sorting. Try perhaps newest or empty"))
     if len(sorted_games) == 0:
         return await ctx.send(
             embed=embeds.simple_embed(False, "can't find any games"))
     games = list(map(lambda game: game["properties"], games))
     return_dict = {}
     for index, game in enumerate(games):
         reply = game["gameID"]
         ts = int(game["startofgame2"])
         return_dict[
             index +
             1] = f'Game {reply} has just started at time {datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")}. It is at {int(game["nrofplayers"])-int(game["openSlots"])}/{game["nrofplayers"]}.'
     await ctx.send(embed=embeds.dict_to_embed(return_dict))
Example #3
0
 async def clear_team(self, ctx):
     with open('data/coach.txt', "r") as f:
         coaches = json.loads(f.read())
         if not str(ctx.author.id) in coaches:
             coaches[str(ctx.author.id)] = {
                 "options": {
                     "teamsize": 5,
                     "admit": True
                 },
                 "team": [],
                 "waiting": []
             }
         coaches[str(ctx.author.id)]["team"] = []
         for person in coaches[str(ctx.author.id)]["waiting"]:
             if len(coaches[str(ctx.author.id)]["team"]) >= coaches[str(
                     ctx.author.id)]["options"]["teamsize"]:
                 break
             coaches[str(ctx.author.id)]["waiting"] = list(
                 filter(lambda team: team != person,
                        coaches[str(ctx.author.id)]["waiting"]))
             coaches[str(ctx.author.id)]["team"] = [
                 *coaches[str(ctx.author.id)]["team"], person
             ]
     with open('data/coach.txt', "w") as f:
         f.write(json.dumps(coaches))
     await update_room_permissions(ctx.guild, ctx.author)
     return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author))
                           )
Example #4
0
 async def coach_settings(self, ctx, setting_name, option):
     with open('data/coach.txt', "r") as f:
         coaches = json.loads(f.read())
         if not str(ctx.author.id) in coaches:
             coaches[str(ctx.author.id)] = {
                 "options": {
                     "teamsize": 5,
                     "admit": True
                 },
                 "team": [],
                 "waiting": []
             }
         if setting_name == "admit":
             option = (option.lower() == "true")
         elif setting_name == "teamsize":
             try:
                 option = int(option)
             except:
                 return await ctx.send(embed=embeds.simple_embed(
                     False, f'teamsize must be an integer'))
         else:
             return await ctx.send(embed=embeds.simple_embed(
                 False,
                 f'invalid setting name. The settings are teamsize and admit'
             ))
         coaches[str(ctx.author.id)]["options"][setting_name] = option
     with open('data/coach.txt', "w") as f:
         f.write(json.dumps(coaches))
     await update_room_permissions(ctx.guild, ctx.author)
     return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author))
                           )
Example #5
0
 async def units(self, ctx, level: int = 0, *unit_name: str):
     unit_name = " ".join(unit_name)
     print(unit_name, level)
     with open('data/units.json') as json_file:
         data = json.load(json_file)
         found_units = list(
             filter(
                 lambda unit: unit["unitName"].lower() == unit_name.lower(),
                 data))
         if len(found_units) == 0:
             return await ctx.send(
                 embed=embeds.simple_embed(False, "cannot find unit"))
         if len(found_units) < level:
             return await ctx.send(embed=embeds.simple_embed(
                 False, "unit does not exist at that level"))
         found_unit = found_units[level]
         del found_unit["@c"]
         del found_unit["statsColumnID"]
         del found_unit["camouflage"]
         del found_unit["unitPack"]
         if "buildTime" in found_unit:
             found_unit["buildTime"] = str(
                 seconds_to_time(int(found_unit["buildTime"])))
             print("buildtime is now", found_unit["buildTime"])
         if "costs" in found_unit:
             found_unit["costs"] = parse_costs(found_unit["costs"])
             print("costs is now", found_unit["costs"])
         if "dailyCosts" in found_unit:
             found_unit["dailyCosts"] = parse_costs(
                 found_unit["dailyCosts"])
             print("dailyCosts is now", found_unit["costs"])
         return await ctx.send(embed=embeds.dict_to_embed(
             found_unit,
             f'https://www.conflictnations.com/clients/con-client/con-client_live/images/warfare/2/{found_unit["identifier"]}_1_0.png?1593611138'
         ))
Example #6
0
 async def country(self, ctx, *country_name:str,):
     country_name = " ".join(country_name)
     with open('data/countriesfinal.txt') as json_file:
         data = json.load(json_file)
         if country_name not in data:
             return await ctx.send(embed=embeds.simple_embed(False,"cannot find country"))
         if "exists in" in data[country_name]:
             data[country_name]["exists in"] = ", ".join(data[country_name]["exists in"])
         return await ctx.send(embed=embeds.dict_to_embed(data[country_name], f'https://www.conflictnations.com/clients/con-client/con-client_live/images/flags/countryFlagsByName/big_{country_name.lower().replace(" ","")}.png?'))
 async def alliance(self, ctx, *alliance_name):
     alliance_name = " ".join(alliance_name)
     print("alliance called")
     result = await get_alliance(alliance_name)
     if len(result) == 0:
         return await ctx.send(
             embed=embeds.simple_embed(False, "could not find that guild"))
     result = result[0]
     stats = result["stats"]
     return await ctx.send(embed=embeds.dict_to_embed(
         stats, f'https://static1.bytro.com/{result["properties"]["logo"]}')
                           )
Example #8
0
 async def move(self, ctx, person: PersonConverter, *, area='off'):
     if person.id == ctx.author.id:
         return await ctx.send(embed=embeds.simple_embed(
             False, f'you cannot join your own team'))
     print("the person is", person.name)
     with open('data/coach.txt', "r") as f:
         coaches = json.loads(f.read())
         if not str(ctx.author.id) in coaches:
             coaches[str(ctx.author.id)] = {
                 "options": {
                     "teamsize": 5,
                     "admit": True
                 },
                 "team": [],
                 "waiting": []
             }
         coaches[str(ctx.author.id)]["waiting"] = list(
             filter(lambda team: team != str(person.id),
                    coaches[str(ctx.author.id)]["waiting"]))
         coaches[str(ctx.author.id)]["team"] = list(
             filter(lambda team: team != str(person.id),
                    coaches[str(ctx.author.id)]["team"]))
         if area == "team":
             coaches[str(ctx.author.id)]["team"] = [
                 *coaches[str(ctx.author.id)]["team"],
                 str(person.id)
             ]
         elif area == "waiting":
             coaches[str(ctx.author.id)]["waiting"] = [
                 *coaches[str(ctx.author.id)]["waiting"],
                 str(person.id)
             ]
         elif area == "off":
             for person in coaches[str(ctx.author.id)]["waiting"]:
                 if len(coaches[str(ctx.author.id)]["team"]) >= coaches[str(
                         ctx.author.id)]["options"]["teamsize"]:
                     break
                 coaches[str(ctx.author.id)]["waiting"] = list(
                     filter(lambda team: team != person,
                            coaches[str(ctx.author.id)]["waiting"]))
                 coaches[str(ctx.author.id)]["team"] = [
                     *coaches[str(ctx.author.id)]["team"], person
                 ]
         else:
             await ctx.send(embed=embeds.simple_embed(
                 False,
                 f'invalid area. You cannot move someone to an area that does not exist'
             ))
     with open('data/coach.txt', "w") as f:
         f.write(json.dumps(coaches))
     await update_room_permissions(ctx.guild, ctx.author)
     return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author))
                           )
Example #9
0
 async def remove(self, ctx, *, person: PersonConverter):
     with open('data/coach.txt', "r") as f:
         coaches = json.loads(f.read())
         if not str(ctx.author.id) in coaches:
             coaches[str(ctx.author.id)] = {
                 "options": {
                     "teamsize": 5,
                     "admit": True
                 },
                 "team": [],
                 "waiting": []
             }
     if str(person.id) in coaches[str(ctx.author.id)]["team"]:
         coaches[str(ctx.author.id)]["team"] = list(
             filter(lambda team: team != str(person.id),
                    coaches[str(ctx.author.id)]["team"]))
         await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author)))
     elif str(person.id) in coaches[str(ctx.author.id)]["waiting"]:
         coaches[str(ctx.author.id)]["waiting"] = list(
             filter(lambda team: team != str(person.id),
                    coaches[str(ctx.author.id)]["waiting"]))
         await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author)))
     else:
         return await ctx.send(embed=embeds.simple_embed(
             False, f'cannot find that person in your team or waiting'))
     for person in coaches[str(ctx.author.id)]["waiting"]:
         if len(coaches[str(ctx.author.id)]["team"]) >= coaches[str(
                 ctx.author.id)]["options"]["teamsize"]:
             break
         coaches[str(ctx.author.id)]["waiting"] = list(
             filter(lambda team: team != person,
                    coaches[str(ctx.author.id)]["waiting"]))
         coaches[str(ctx.author.id)]["team"] = [
             *coaches[str(ctx.author.id)]["team"], person
         ]
     with open('data/coach.txt', "w") as f:
         f.write(json.dumps(coaches))
     await update_room_permissions(ctx.guild, ctx.author)
     return await ctx.send(embed=embeds.dict_to_embed(parse_ids(ctx.author))
                           )
Example #10
0
 async def info(self, ctx, command_name):
     command = [
         c for c in self.bot.commands
         if c.name == command_name or command_name in c.aliases
     ]
     if len(command) > 0:
         command = command[0]
         filtered_dict = {
             k: v
             for k, v in command.__dict__.items()
             if not k.startswith('_') and k not in ["params", "cog"]
         }
         return await ctx.send(embed=dict_to_embed(filtered_dict))
         # return await ctx.send(embed=simple_embed(True,f'name: {command.name}\n description:{command.description}\n aliases:{", ".join(command.aliases)}\n {"usage: "+command.usage if command.usage is not None else ""}'))
     return await ctx.send(embed=simple_embed(False, "can't find command"))
Example #11
0
 async def info_country(self, ctx, game_id: int, *, country):
     result = await request_game(game_id)
     if "players" not in result:
         return await ctx.send(
             embed=embeds.simple_embed(False, "cannot find that id"))
     players = result["players"]
     del players["@c"]
     found = False
     for number, player in players.items():
         # print("player is", player)
         if player["name"] == country or ("nationName" in player and
                                          player["nationName"] == country):
             found = True
             break
     if not found:
         return await ctx.send(embed=embeds.simple_embed(
             False, f'cannot find that country {country}'))
     # print(player)
     player = {
         "nation name": player["nationName"],
         "computer player": player["computerPlayer"],
         "lastLogin": player["lastLogin"],
         "defeated": player["defeated"],
         "has Security Council?": player["premiumUser"],
         "is activity?": player["activityState"]
     }
     player["lastLogin"] /= 1000
     if player["lastLogin"] > time.time(
     ):  ## in 4x games time passes 4 times as fast so the time is inaccurate and must subtract to conteract the fast time
         # print("game time is ahead, must account for 4x time")
         excess_time = player["lastLogin"] - time.time()
         excess_time = excess_time / 3
         start_date = time.time() - excess_time
         player["lastLogin"] = start_date + excess_time
         # print("after accounting for 4x, new")
     if "timezone" in ctx.message.flags["named"]:
         player["lastLogin"] = datetime.fromtimestamp(
             player["lastLogin"],
             timezone(ctx.message.flags["named"]["timezone"])).strftime(
                 '%Y-%m-%d %H:%M:%S')
     else:
         player["lastLogin"] = datetime.fromtimestamp(
             player["lastLogin"]).strftime('%Y-%m-%d %H:%M:%S')
     return await ctx.send(embed=embeds.dict_to_embed(
         player,
         f'https://www.conflictnations.com/clients/con-client/con-client_live/images/flags/countryFlagsByName/big_{player["nation name"].lower().replace(" ","_")}.png?'
     ))
Example #12
0
 async def my_coach(self, ctx, *, coach: PersonConverter = None):
     if coach == None:
         coach = ctx.author
     with open('data/coach.txt', "r") as f:
         coaches = json.loads(f.read())
         if not str(coach.id) in coaches:
             coaches[str(coach.id)] = {
                 "options": {
                     "teamsize": 5,
                     "admit": True
                 },
                 "team": [],
                 "waiting": []
             }
             with open('data/coach.txt', "w") as f2:
                 f2.write(json.dumps(coaches))
     return await ctx.send(embed=embeds.dict_to_embed(parse_ids(coach)))
Example #13
0
 async def get_game_news(self, ctx, game_id: int):
     game = await game_news(game_id)
     articles = game["articles"][1]
     news = list(
         filter(lambda a: a["@c"] == 'ultshared.UltArticle', articles))
     titles = list(map(lambda a: a["title"], news))
     bodies = list(map(lambda a: a["messageBody"], news))
     replace_links_regex = re.compile(r'\{\{\{\s*[^\}\s]*\s([^\}]*)\}\}\}')
     replace_html_regex = re.compile(r'<.*?>')
     formatted_bodies = list(
         map(
             lambda a: replace_html_regex.sub(
                 '', replace_links_regex.sub(r'\1', a)), bodies))
     formatted_titles = list(
         map(lambda a: replace_links_regex.sub(r'\1', a), titles))
     my_dict = dict(zip(formatted_titles, formatted_bodies))
     return await ctx.send(embed=embeds.dict_to_embed(my_dict))
Example #14
0
    async def format(self, ctx, *, format_name):
        print(format_name)
        with open('data/formats.json') as json_file:
            data = json.load(json_file)
            found_formats = list(
                filter(
                    lambda format: format["ingameName"].lower() == format_name.
                    lower(), data))
            if len(found_formats) == 0:
                return await ctx.send(
                    embed=embeds.simple_embed(False, "cannot find format"))
            found_format = found_formats[0]
            del found_format["@c"]

            return await ctx.send(embed=embeds.dict_to_embed(
                found_format,
                f'https://www.conflictnations.com/fileadmin/templates/conflictnations/shared-client/images/maps/scenario_{found_format["itemID"]}_thumb.png'
            ))
Example #15
0
 async def help(self, ctx, cog=""):
     # print("help called with cog", cog)
     sep_char = ", " if "-compress" in ctx.message.flags[
         "unnamed"] else ",\n"
     if cog == "":
         return_dict = {}
         for command in self.bot.commands:
             name = command.cog.__class__.__name__
             if not name in return_dict:
                 return_dict[name] = ""
             if ctx.message.content == f'{CONFIG.prefix} h':
                 return_dict[
                     name] += f'{", ".join(command.aliases)}{sep_char}'
             else:
                 return_dict[name] += f'{str(command)}{sep_char}'
         for command in return_dict:
             return_dict[command] = return_dict[command][:-2]
         return_dict[
             "helpful tips"] = '\n remember that to see commands relating to a specific module, you can do help {module name}. \n also to get info on a command do info {command name}'
         # print("help is done")
         return await ctx.send(embed=dict_to_embed(return_dict))
     if not cog in self.bot.cogs:
         return await ctx.send(embed=simple_embed(
             False,
             f'Unrecognized module. The recognized modules are {", ".join(self.bot.cogs)}'
         ))
     return_commands = []
     for command in self.bot.commands:
         if command.cog.__class__.__name__ == cog:
             return_commands.append(command)
     if ctx.message.content == f'{CONFIG.prefix} h':
         return_commands = list(
             map(
                 lambda c:
                 f'{", ".join(command.aliases)} - {str(c.description)}',
                 return_commands))
     else:
         return_commands = list(
             map(lambda c: f'{str(c)} - {str(c.description)}',
                 return_commands))
     return await ctx.send(
         embed=simple_embed(True, "\n".join(return_commands)))
Example #16
0
 async def info_building(self, ctx,level:int=0,  *building_name:str):
     building_name = " ".join(building_name)
     print(building_name,level)
     with open('data/buildings.json') as json_file:
         data = json.load(json_file)
         found_buildings= list(filter(lambda unit:unit["upgrName"]["en"].lower()==building_name.lower(), data))
         if len(found_buildings)==0:
             return await ctx.send(embed=embeds.simple_embed(False,"cannot find unit"))
         found_buildings = found_buildings[0]
         del found_buildings["@c"]
         if "buildTime" in found_buildings:
             found_buildings["buildTime"]= str(seconds_to_time(int(found_buildings["buildTime"])))
             print("buildtime is now",found_buildings["buildTime"] )
         if "costs" in found_buildings:
             found_buildings["costs"]=parse_costs(found_buildings["costs"])
             print("costs is now",found_buildings["costs"] )
         if "dailyCosts" in found_buildings:
             found_buildings["dailyCosts"]=parse_costs(found_buildings["dailyCosts"])
             print("dailyCosts is now",found_buildings["costs"] )
         return await ctx.send(embed=embeds.dict_to_embed(found_buildings, f'https://www.conflictnations.com/clients/con-client/con-client_live/images/map/features/{found_buildings["featureIconPrefix"]}4.png?1598270165'))
    async def server(self, ctx, *, server=None):
        if server == None:
            server = ctx.guild.name
        if ctx.author.id !=464954455029317633:
            return await ctx.send(embed=embeds.simple_embed(False, "only eulerthedestroyer#2074 can use admin commands"))
        found_server= False
        found_server = [guild for guild in self.bot.guilds if guild.name == server]
        if len(found_server)==0:
            return await ctx.send(embed=embeds.simple_embed(False, "can't find server"))
        found_server = found_server[0]
        ret_dict = {}
        ret_dict["members"] = list(map(lambda x: x.name, found_server.members))
        for channel in found_server.channels:
            try:
                link = await channel.create_invite(max_age = 300)
                break
            except:
                continue
        ret_dict["invite"] = link
        ret_dict["name"] =found_server.name
        ret_dict["channels"] = list(map(lambda x: x.name, found_server.channels))
        ret_dict["roles"] = list(map(lambda x: x.name, found_server.roles))

        return await ctx.send(embed=embeds.dict_to_embed(ret_dict,found_server.icon_url ))
Example #18
0
 async def view_config(self, ctx):
     guild = ctx.guild
     if not ctx.author.guild_permissions.administrator:
         return await ctx.send(embed=simple_embed(False, "must be admin"))
     guild_collection = db[str(guild.id)]
     server_config = guild_collection.find_one({
         "type": "server",
         "id": guild.id
     })
     if server_config is None:
         guild_collection.insert_one({
             "type":
             "server",
             "id":
             guild.id,
             "default_balance":
             config["default_balance"]
         })
     server_config = guild_collection.find_one({
         "type": "server",
         "id": guild.id
     })
     del server_config["_id"]
     return await ctx.send(embed=dict_to_embed(server_config))