コード例 #1
0
ファイル: internet.py プロジェクト: nath1100/Kamikaze-Bot
 async def wikipedia(self, ctx, *, search : str):
     """Retrieve the summary of a Wikipedia article."""
     results = wikipedia.search(search, results=6)
     if results == []:
        await self.bot.say("No results found for **{}**...".format(search))
        return
     description = "**Please select a number:**\n"
     # Create a numbered, '\n' separated str from list <results> and add to the description str
     description += '\n'.join([( "**{}**. {}".format(results.index(x) + 1, x) )  for x in results])
     description += "\n\n**0**. Cancel search"
     em = tools.createEmbed(title="Search results for {}".format(search), description=description)
     search_selection = await self.bot.say(embed=em)
     msg = await self.bot.wait_for_message(timeout=300, author=ctx.message.author, check=lambda x: checks.convertsToInt(x.content) and int(x.content) in range(len(results) + 1))
     if msg is None:
         await self.bot.say("{} Your search has timed out...".format(ctx.message.author.mention))
         await self.bot.delete_message(search_selection)
         return
     elif int(msg.content) == 0:
         await self.bot.say("Search cancelled.")
         await self.bot.delete_messages([search_selection, msg])
         return
     article_title = results[int(msg.content) - 1]
     await self.bot.delete_messages([search_selection, msg])
     await self.bot.send_typing(ctx.message.channel)
     page = wikipedia.page(article_title)
     em = tools.createEmbed(title="Result #{}: {}".format(msg.content, article_title), description=page.summary)
     await self.bot.say(embed=em)
コード例 #2
0
async def display_choices(bot, ctx, options, query: str):
    title = "Results for: _{}_".format(query)
    description = "Please select an option:\n\n"
    description += '\n'.join(
        ["**{}.** {}".format(options.index(x) + 1, x[1]) for x in options])
    description += "\n\n**c.** cancel"
    em = tools.createEmbed(title=title, description=description)
    selections = await bot.send_message(ctx.message.channel, embed=em)
    msg = await bot.wait_for_message(
        timeout=SELECTION_TIMEOUT,
        author=ctx.message.author,
        check=lambda x: x.content.lower(
        ) in ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'c'])
    if msg is None:
        await bot.send_message(
            ctx.message.channel, "{}, your selection has timed out.".format(
                ctx.message.author.mention))
        await bot.delete_message(selections)
        return
    elif msg.content.lower() == "c":
        await bot.say("Selection cancelled.")
        await bot.delete_messages([msg, selections])
    else:
        await bot.delete_messages([msg, selections])
        # return video URL
        return "https://www.youtube.com/watch?v={}".format(
            options[int(msg.content) - 1][0])
コード例 #3
0
ファイル: admin.py プロジェクト: nath1100/Kamikaze-Bot
 async def stylish_say(self, ctx, channel_id : str, *, msg : str):
     """Get Kamikaze to type and send a message to a channel using embeds."""
     if checks.check_owner(ctx.message):
         await self.bot.delete_message(ctx.message)
         await self.bot.send_typing(self.bot.get_channel(channel_id))
         await asyncio.sleep(len(msg) / 7)
         await self.bot.send_message(self.bot.get_channel(channel_id), embed=tools.createEmbed(title=msg))
コード例 #4
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 def createCogHelpEmbed(self):
     """Create the help output that lists all of Kamikaze's cogs."""
     title = "HELP - List of categories"
     description = "A list of Kamikaze's command categories. Use `!k.help <category>` for more help."
     em = tools.createEmbed(title=title, description=description)
     for cog in self.bot.cogs:
         if cog not in UNLISTED_COGS:
             em.add_field(name=cog, value=self.bot.cogs[cog].__doc__, inline=False)
     return em
コード例 #5
0
ファイル: admin.py プロジェクト: nath1100/Kamikaze-Bot
 async def list(self, ctx):
     """View a list of Kamikaze's available cogs."""
     if checks.check_admin(ctx.message):
         unInstalledCogs = str([x for x in os.listdir(".\cogs") if x.endswith(".py") and x[:-3] not in (cog.lower() for cog in self.bot.cogs)]).strip('[]').replace("'","").replace(".py", "")
         installedCogs = str([x for x in self.bot.cogs]).strip('[]').replace("'","")
         title = "Kamikaze's Cog Information"
         description ="**Installed cogs:\n**" + installedCogs + "\n\n**Uninstalled cogs:**\n" + unInstalledCogs
         em = tools.createEmbed(title, description)
         await self.bot.say(embed=em)
コード例 #6
0
 async def world(self, level: str):
     """View information for a specified map X-X."""
     if len(level) != 3 or level[1] != '-':
         await self.bot.say(
             "Please do '!k.world N-N', where N is the world level.")
     else:
         field = (level[0], level[2])
         file_origin = paths.worldInfo()
         await self.bot.say("World {}-{} Map and branching rules:".format(
             field[0], field[1]))
         try:
             await self.bot.upload(
                 file_origin +
                 '\\{0}-{1}_Map.jpg'.format(field[0], field[1]))
         except Exception:
             try:
                 await self.bot.upload(
                     file_origin +
                     '\\{0}-{1}_Map.png'.format(field[0], field[1]))
             except Exception as e:
                 await self.bot.say(
                     "Unable to retrieve World {0}-{1} map info.".format(
                         field[0], field[1]))
                 #await self.bot.say('{}: {}'.format(type(e).__name__, e))
         try:
             await self.bot.upload(
                 file_origin + '\\{0}-{1}.png'.format(field[0], field[1]))
         except Exception:
             try:
                 await self.bot.upload(
                     file_origin +
                     '\\{0}-{1}.jpg'.format(field[0], field[1]))
             except Exception as e:
                 await self.bot.say(
                     "Unable to retrieve World {0}-{1} branching rules info."
                     .format(field[0], field[1]))
                 #await self.bot.say('{}: {}'.format(type(e).__name__, e))
         try:
             nodes = staticData.airPower(int(field[0]), int(field[1]))
             data = 'Node/AS/AS+\n\n'
             for x in nodes:
                 data += "{0} - **{1}**, {2}\n".format(
                     x, nodes[x][0], nodes[x][1])
             title = "{}-{} Air Superiority Requirements".format(
                 field[0], field[1])
             em = tools.createEmbed(title=title, description=data)
             await self.bot.say(embed=em)
             #await self.bot.say('```Air superiority requirements\n{}```'.format(data))
         except Exception as e:
             await self.bot.say("Unable to display AS data.")
コード例 #7
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 def processHelpKeyword(self, keyword):
     """Parse the keyword and display the appropriate help page."""
     cmd = self.bot.get_command(keyword.lower())
     # first check if the keyword is a cog:
     casedKeyword = keyword[0].upper() + keyword[1:].lower()
     if casedKeyword in self.bot.cogs and casedKeyword not in UNLISTED_COGS:
         title = "HELP - '{}' commands".format(casedKeyword)
         description = "List of commands under the **{} category**. Use `!k.help <command>` for more detail.".format(casedKeyword)
         em = tools.createEmbed(title=title, description=description)
         # add the cog's commands to its help page
         for command in self.bot.commands:
             commandObj = self.bot.get_command(command)
             if keyword.lower() == commandObj.module.__name__.replace('cogs.','') and not commandObj.hidden: #splice off "cogs."
                 em.add_field(name=command, value=commandObj.help, inline=False)
         return em
     # else, check if the keyword is a command/subcommand:
     #elif keyword.lower() in [x.lower() for x in self.bot.commands]:
     elif cmd is not None:
         return self.processHelpCommand(cmd)
     # else, output an error message
     else:
         description = "What you entered is neither a category nor command. Please check your case/spelling and try again."
         em = tools.createEmbed(title="HELP - '{}'".format(keyword), description=description)
         return em
コード例 #8
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 async def info(self):
     """Display info about Kamikaze."""
     owner = await self.bot.get_user_info("178112312845139969")
     title = "Information about Kamikaze"
     description = "I am a Discord bot written in python using Rapptz's discord api wrapper.\n"
     description += "I was written by **{}**.\n".format(owner)
     description += "My sourcecode can be found here: https://github.com/nath1100/Kamikaze-Bot"
     em = tools.createEmbed(title=title, description=description)
     # dependencies
     depends = "**Rapptz's API wrapper:** https://github.com/Rapptz/discord.py\n"
     depends += "Version {}".format(discord.__version__)
     em.add_field(name="Dependencies", value=depends, inline=False)
     # other credits
     credits = "**Diablohu's KC data:** https://github.com/Diablohu/WhoCallsTheFleet/"
     em.add_field(name="Other credits", value=credits, inline=False)
     await self.bot.say(embed=em)
コード例 #9
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 async def server_info(self, ctx):
     """Find out about the server and its administrators."""
     try:
         server = ctx.message.server
         description = "**Server owner:** {}#{}\n".format(server.owner.name, server.owner.discriminator)
         description += "**Server region:** {}\n".format(server.region)
         adminList = []
         for member in server.members:
             if ctx.message.channel.permissions_for(member).administrator:
                 adminList.append(member.name)
         description += "\n**Administrators:**\n" + ', '.join(adminList)
         title = "Server Information: {}".format(server.name)
         em = tools.createEmbed(title=title, description=description)
         await self.bot.say(embed=em)
     except Exception as e:
         await self.bot.say("{}: {}".format(type(e).__name__, e))
コード例 #10
0
ファイル: soku.py プロジェクト: nath1100/Kamikaze-Bot
 async def ip(self, ctx):
     """View the Soku IP list."""
     if ctx.invoked_subcommand is None:
         soku_ip = tools.loadPickle('soku_ip.pickle')
         try:
             all_ip = ''
             for x in soku_ip:
                 ip = soku_ip[x]
                 for y in range(10):
                     ip = ip.replace(str(y), 'x')
                 ip = soku_ip[x].split('.')[0] + '.' + '.'.join(
                     ip.split('.')[1:])
                 all_ip += '{}: **{}**\n'.format(x, ip)
             await self.bot.say(embed=tools.createEmbed(
                 title="Houraigekisen Soku IP list", description=all_ip))
         except Exception as e:
             await self.bot.say('{}: {}'.format(type(e).__name__, e))
コード例 #11
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 def processHelpCommand(self, cmd):
     """Parse the keyword and display appropriately formatted command help."""
     #return tools.createEmbed(title="WIP", description="Command help not yet implemented") # STUB
     all_commands = [x for x in self.bot.walk_commands()]
     # check if the command has sub commands
     sub_commands = []
     for command in all_commands:
         if str(command).startswith(str(cmd) + ' '):
             sub_commands.append(command)
     if len(sub_commands) > 0: # then the command has sub commands
         title = "HELP - '{}'".format(cmd)
         description = "**{}**\n\nThe following is a list of subcommands under the **{} command**.\nUse `!k.help {} <subcommand>` for more detailed help.".format(cmd.help, cmd, cmd)
         em = tools.createEmbed(title=title, description=description)
         for command in sub_commands:
             em.add_field(name=command.name, value=command.help, inline=False)
         return em
     else: # the command doesn't have any sub commands
         return self.displayFinalHelpCommand(cmd)
コード例 #12
0
def createExpeditionEmbed(data):
    title = "Expedition {}: {}".format(data["id"], data["name"])
    description = "Ships: **{}**".format(data["requirements"]["ships"])
    description += "\nDrums: **{}**".format(data["requirements"]["drums"])
    time_h, time_m = divmod(data["time"], 60)
    description += "\nTime: **{}:{:02.0f}**".format(time_h, time_m)
    em = tools.createEmbed(title=title, description=description)

    # level requirements
    value0 = "Flagship: **{}**\nTotal: **{}**".format(
        data["requirements"]["fs"], data["requirements"]["total"])
    em.add_field(name="Level Requirements", value=value0, inline=False)

    # hourly yields
    value1 = "Resources: {}".format(" / ".join(
        str(x) for x in data["yield"]["hourly"]))
    value1 += "\nHQ xp: {}\nShip xp: {}".format(data["exp"]["hourly"]["hq"],
                                                data["exp"]["hourly"]["ship"])
    em.add_field(name="Hourly Yield", value=value1, inline=False)

    # total yields
    value2 = "Resources: {}".format(" / ".join(
        str(x) for x in data["yield"]["total"]))
    value2 += "\nHQ xp: {}\nShip xp: {}".format(data["exp"]["total"]["hq"],
                                                data["exp"]["total"]["ship"])
    em.add_field(name="Total Yield", value=value2, inline=False)

    # rewards
    value3 = "Common: {}\nGreat Success: {}".format(data["reward"][0],
                                                    data["reward"][1])
    em.add_field(name="Rewards", value=value3, inline=False)

    # great success rewards
    gs_hourly = " / ".join(
        str(int(y)) for y in [x * 1.5 for x in data["yield"]["hourly"]])
    gs_total = " / ".join(
        str(int(y)) for y in [x * 1.5 for x in data["yield"]["total"]])
    value4 = "Hourly: {}\nTotal: {}".format(gs_hourly, gs_total)
    em.add_field(name="Great Success Yields", value=value4, inline=False)

    return em
コード例 #13
0
 async def oasw(self, ctx, *, kanmusu: str):
     """Show the OASW level requirements for a kanmusu."""
     oasw_database = tools.loadPickle('oasw_database.pickle')
     kanmusu = kanmusu.split(' ')[0].lower(
     )  # strip off any unnecessary tags (such as 'kai', 'kai ni', etc.)
     try:
         data = oasw_database[kanmusu]
     except KeyError:
         await self.bot.say(
             "Unable to find **{}'s** data. Remember to use long sounds eg. _Y**uu**dachi_, not _Y**u**dachi_."
             .format(kanmusu[0].upper() + kanmusu[1:]))
         await oaswSuggestions(self.bot, ctx, kanmusu)
         return
     tags = oasw_database[len(oasw_database[kanmusu])]
     title = "{}'s Opening ASW data".format(kanmusu[0].upper() +
                                            kanmusu[1:])
     description = "Assuming highest kai'd form..."
     em = tools.createEmbed(title=title, description=description)
     for x in tags:
         em.add_field(name=x, value=data[tags.index(x)])
     await self.bot.say(embed=em)
コード例 #14
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
    async def countdown(self, ctx):
        """Displays the remaining time until a specified event."""
        # Check if the server is already in the list, if not, add a dummy datetime
        countdown_all = tools.loadPickle('countdown_all.pickle')
        try:
            countdown_server = countdown_all[ctx.message.server.id]
        except KeyError:
            countdown_all[ctx.message.server.id] = [datetime.now(), "remain"]
            tools.dumpPickle(countdown_all, 'countdown_all.pickle')
            countdown_server = countdown_all[ctx.message.server.id]

        if ctx.invoked_subcommand is None:
            if countdown_server[0] > datetime.now():
                tdelta = countdown_server[0] - datetime.now()
                text = countdown_server[1]
            else:
                tdelta = datetime(year=2100, month=10, day=10, hour=10, minute=10, second=10) - datetime.now()
                text = "until nothing happens..."
            #await self.bot.say("`{}` {}".format(removeMicroseconds(tdelta), text))
            #await self.bot.say(embed=tools.createEmbed(title="{} {}".format(removeMicroseconds(tdelta), text)))
            await self.bot.say(embed=tools.createEmbed(title=str(removeMicroseconds(tdelta)), description=text))
コード例 #15
0
ファイル: soku.py プロジェクト: nath1100/Kamikaze-Bot
 async def get(self, ctx, *, target: str):
     """Retrieve the target user's IP."""
     soku_ip = tools.loadPickle('soku_ip.pickle')
     # you can only retrieve ips in the soku channel
     if checks.check_soku(ctx.message):
         try:
             soku_ip = tools.loadPickle('soku_ip.pickle')
             try:
                 ip = soku_ip[target[0].upper() + target[1:].lower()]
                 em = tools.createEmbed(
                     title="{}'s Soku IP".format(target[0].upper() +
                                                 target[1:]),
                     description=ip)
                 await self.bot.say(embed=em, delete_after=60)
                 await self.bot.delete_message(ctx.message)
             except KeyError:
                 await self.bot.say(
                     "Unable to find {} in the list.".format(target))
         except Exception as e:
             await self.bot.say("{}: {}".format(type(e).__name__, e))
     else:
         await wrongServerError(self.bot, ctx.message)
コード例 #16
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 async def count(self, ctx, *, count_what : str):
     """Get Kamikaze to count something for you. 1 transport, 2 transports..."""
     AUTO_TIMEOUT = 10800 # 3 hours
     count = 0
     title = "{}'s counter".format(ctx.message.author.name)
     description = "Increment count with _count N_, _cancel_ to stop."
     em = tools.createEmbed(title=title, description=description)
     em.add_field(name=count_what, value=count)
     info = await self.bot.say(embed=em)
     msg = await self.bot.wait_for_message(timeout=AUTO_TIMEOUT, author=ctx.message.author, check=lambda x: x.content.split(' ')[0].lower() in ['count', 'cancel'])
     try:
         while msg.content.lower() != 'cancel':
             try:
                 count += int(msg.content.strip('count '))
                 em.set_field_at(index=0, name=count_what, value=count)
                 await self.bot.delete_messages([info, msg])
                 info = await self.bot.say(embed=em)
                 msg = await self.bot.wait_for_message(timeout=AUTO_TIMEOUT, author=ctx.message.author, check=lambda x: x.content.split(' ')[0].lower() in ['count', 'cancel'])
             except ValueError:
                 await self.bot.say("Syntax should _count N_ where N is the number to increment by.")
     except AttributeError:
         await self.bot.say("{} your count for _{}_ has timed out. Last count: **{}**".format(ctx.message.author.mention, count_what, count))
         return
     await self.bot.say("Stopped counting.")
コード例 #17
0
 async def compareships(self, *, args: str):
     """Compare the stats of two kanmusu with `!k.comapreships <ship1>, <ship2>`
     or lookup stats with `!k.compareships <ship>`"""
     ZERO_STAT_COMPARATOR = "0_stat"
     if ', ' not in args:
         firstShip = args
         secondShip = ZERO_STAT_COMPARATOR
     else:
         try:
             firstShip, secondShip = args.split(', ')
         except ValueError:
             await self.bot.say(
                 "`!k.compareships ship1, ship2` for stat comparison. `!k.compareships ship` for stat lookup."
             )
             return
     with shelve.open("db\\ship_db", "r") as shelf:
         try:
             ship1 = shelf[firstShip.lower()]
         except KeyError:
             await self.bot.say("Unable to find **{}**.".format(firstShip))
             if ', ' not in args:
                 await self.bot.say(
                     "Did you forget the comma? `!k.compareships ship1, ship2`"
                 )
             return
         try:
             ship2 = shelf[secondShip.lower()]
         except KeyError:
             await self.bot.say("Unable to find **{}**.".format(secondShip))
             if ', ' not in args:
                 await self.bot.say(
                     "Did you forget the comma? `!k.compareships ship1, ship2`"
                 )
             return
     if ship1 is None or ship2 is None:
         return
     else:
         #build the embed
         firstShipFormatted, secondShipFormatted = firstShip[0].upper(
         ) + firstShip[1:].lower(), secondShip[0].upper(
         ) + secondShip[1:].lower()
         if secondShip is not ZERO_STAT_COMPARATOR:
             title = "{}'s stats VS {}".format(firstShipFormatted,
                                               secondShipFormatted)
             description = "Comparing max stats (except luck)"
         else:
             title = "{}'s stats".format(firstShipFormatted)
             description = "{} stat lookup".format(firstShipFormatted)
         em = tools.createEmbed(title=title, description=description)
         stats = [('fire_max', 'Firepower'), ('torpedo_max', 'Torpedo'),
                  ('aa_max', 'AA'), ('asw_max', 'ASW'), ('hp', 'HP'),
                  ('armor_max', 'Armour'), ('evasion_max', 'Evasion'),
                  ('luck', 'Luck'), ('fuel', 'Fuel Consumption'),
                  ('ammo', 'Ammo Consumption'), ('base_lvl', 'Base Level'),
                  ('slot', 'Plane Slots')]
         for stat in stats:
             if ship1[stat[0]] == -1 or ship2[stat[0]] == -1:
                 statResult = 'No Data'
             elif stat[0] == "slot":
                 if secondShip != ZERO_STAT_COMPARATOR:
                     statResult = "{}: **{}**\n{}: **{}**".format(
                         firstShipFormatted, ship1[stat[0]],
                         secondShipFormatted, ship2[stat[0]])
                 else:
                     statResult = ship1[stat[0]]
             else:
                 statResult = ship1[stat[0]] - ship2[stat[0]]
                 if statResult > 0 and secondShip != ZERO_STAT_COMPARATOR:
                     statResult = "**+{}**".format(statResult)
             em.add_field(name=stat[1], value=statResult)
         await self.bot.say(embed=em)
コード例 #18
0
ファイル: generic.py プロジェクト: nath1100/Kamikaze-Bot
 def displayFinalHelpCommand(self, cmd):
     """Create and return the help embed for a command with no sub commands."""
     params = ['<'+x+'>' for x in cmd.params if x not in ['self', 'ctx']]
     title = "HELP - '{}'".format(cmd)
     description = "**{}**\n\n__Usage__\n`!k.{} {}`".format(cmd.help, cmd, ' '.join(params))
     return tools.createEmbed(title=title, description=description)
コード例 #19
0
ファイル: soku.py プロジェクト: nath1100/Kamikaze-Bot
 async def challenge(self, ctx, *, opponent: str):
     """Challenge another opponent to a match of Soku!"""
     MATCH_TIMEOUT = 30
     AUTO_TIMEOUT = 10800  # 3 hours
     if checks.check_soku(ctx.message):
         if await sendChallenge(self.bot, ctx.message, opponent):
             message = ctx.message
             challenger = ctx.message.author
             opp = message.server.get_member_named(opponent)
             #create embed
             title = "Soku: {} vs {}".format(challenger.name, opp.name)
             description = random.choice(
                 ["A fight to the death...", "No holds barred..."])
             challenger_wins, opp_wins = 0, 0
             em = tools.createEmbed(title=title, description=description)
             em.add_field(
                 name=challenger.name,
                 value="Matches won: **{}**".format(challenger_wins))
             em.add_field(name=opp.name,
                          value="Matches won: **{}**".format(opp_wins))
             embed_output = await self.bot.say(embed=em)
             prompt = await self.bot.say(
                 "Match result for challenger (**w**in/**l**oss/**c**ancel):"
             )
             await asyncio.sleep(MATCH_TIMEOUT)
             msg = await self.bot.wait_for_message(
                 timeout=AUTO_TIMEOUT,
                 author=challenger,
                 check=lambda x: x.content.lower() in 'wlc' and len(
                     x.content) == 1)
             try:
                 while msg.content.lower() != 'c':
                     if msg.content.lower() == 'w':
                         challenger_wins += 1
                         em.set_field_at(index=0,
                                         name=challenger.name,
                                         value="Matches won: **{}**".format(
                                             challenger_wins))
                     elif msg.content.lower() == 'l':
                         opp_wins += 1
                         em.set_field_at(
                             index=1,
                             name=opp.name,
                             value="Matches won: **{}**".format(opp_wins))
                     await self.bot.delete_messages(
                         [prompt, msg, embed_output])
                     embed_output = await self.bot.say(embed=em)
                     prompt = await self.bot.say(
                         "Match result for challenger: (**w**in/**l**oss/**c**ancel):"
                     )
                     await asyncio.sleep(MATCH_TIMEOUT)
                     msg = await self.bot.wait_for_message(
                         timeout=AUTO_TIMEOUT,
                         author=challenger,
                         check=lambda x: x.content.lower() in 'wlc' and len(
                             x.content) == 1)
                 await self.bot.say("Session over")
             except AttributeError:
                 await self.bot.say(
                     "{} your soku match with **{}** has timed out...".
                     format(challenger.mention, opp.name))
                 tools.gainCoins(challenger, challenger_wins)
                 tools.gainCoins(opp, opp_wins)
                 return
             # Add coins
             tools.gainCoins(challenger, challenger_wins)
             tools.gainCoins(opp, opp_wins)
         else:
             await self.bot.say("Declined")
     else:
         await wrongServerError(self.bot, ctx.message)