コード例 #1
0
ファイル: VoiceCommands.py プロジェクト: dss285/4Ever
class Sound(Command):
    def __init__(self, command_key, client):
        self.client = client
        super().__init__(command_key, "sound", """Plays a certain sound""",
                         f"{command_key} sound <*list*|*sound name*>", [])
        self.args = Args(sound=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            if message.author.voice.channel:
                if server:
                    if not server.voice:
                        vc = await message.author.voice.channel.connect()
                        server.voice = VoicePlayer(vc, message.channel,
                                                   self.client)
                    if server.voice.vc.is_connected():
                        if parse.get("sound") == "list":
                            em = EmbedTemplate(
                                title="Sounds",
                                description="\n".join(
                                    sorted(server.voice.sounds.keys())))
                            await message.channel.send(embed=em)
                        elif parse.get("sound") in server.voice.sounds.keys():
                            await server.voice.playFile(
                                server.voice.sounds[parse.get("sound")])
                    else:
                        server.voice = None
                        await self.run(message, server)
コード例 #2
0
ファイル: GFLCommands.py プロジェクト: dss285/4Ever
class ProductionDolls(Command):
    def __init__(self, command_key, client, database):
        self.client = client
        self.database = database
        super().__init__(command_key, "production", """Production Dolls""",
                         f"{command_key} production",
                         ["production", "prod", "pr"])
        self.args = Args()
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message: discord.Message, server: Server):
        parsed = self.args.parse(message.content)
        if parsed:
            tmp = list(self.database.runtime["gfl"]["dolls"]["names"].values())
            tmp = [x for x in tmp if x.production_timer]
            tmp_str = []
            for doll in sorted(tmp, key=lambda x: x.production_timer):
                tmp_str.append(
                    f"{datetime.timedelta(seconds=doll.production_timer)} {doll.name} {doll.doll_type}"
                )
            lists = [tmp_str[i:i + 30] for i in range(0, len(tmp_str), 30)]
            em = EmbedTemplate(title="Production Dolls")
            for i in lists:
                em.add_field(name="PRODUCTION",
                             value="\n".join(i),
                             inline=True)
            await message.channel.send(embed=em)
コード例 #3
0
class ShellCommand(Command):
    def __init__(self, command_key, client):
        self.client = client
        super().__init__(command_key, "shell", """Shell""",
                         f"{command_key} shell *shell command*",
                         ['bash', 'sh'])
        self.args = Args(shell=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            splitted = parse["shell"].split(" ")
            output = subprocess.run(splitted,
                                    stdout=subprocess.PIPE,
                                    text=True,
                                    universal_newlines=True)
            if output.returncode == 0:
                if len(output.stdout) < 1975:
                    await message.reply(f"""```{output.stdout}```""")
                else:
                    fo = open("tmp.txt", "w+")
                    fo.write(output.stdout)
                    fo.close()
                    await message.reply(file=discord.File("tmp.txt"))
            else:
                await message.reply(
                    f"Error from shell command: {output.stderr}")
コード例 #4
0
ファイル: WarframeCommands.py プロジェクト: dss285/4Ever
class WorldState(Command):
    UPDATED_MESSAGE_REGEX = "(?P<{}>nightwave|sorties|poe|invasions|fissures)"
    def __init__(self, command_key, database, client):
        self.client = client
        self.database = database
        super().__init__(command_key, "worldstate", """Creates an message where X thing is updated from Warframe Worldstate""", f"{command_key} worldstate *<nightwave|sorties|poe|invasions|fissures>*", ["worldstate"])
        self.args = Args(message=WorldState.UPDATED_MESSAGE_REGEX)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        if message.author.guild_permissions.administrator:
            parse = self.args.parse(message.content)
            if parse:
                em = EmbedTemplate(title="WorldState Message", description="Updating soon..")
                new_message = None
                msg_type = None
                msg = await message.channel.send(embed=em)
                if parse.get("message") == "nightwave":
                    new_message = NightwaveMessage(msg)
                elif parse.get("message") == "sorties":
                    new_message = SortieMessage(msg)
                elif parse.get("message") == "fissures":
                    new_message = FissureMessage(msg, [])
                elif parse.get("message") == "poe":
                    new_message = CetusMessage(msg, [], self.client)
                elif parse.get("message") == "invasions":
                    new_message = InvasionMessage(msg, [])
                if new_message:
                    
                    msg_type = parse.get("message")
                    await self.database.create_updated_message(server.server_id, msg_type, msg.channel.id, msg.id)
                    server.updated_messages["name"][msg_type] = new_message
                    server.updated_messages["id"][msg.id] = new_message
コード例 #5
0
ファイル: VoiceCommands.py プロジェクト: dss285/4Ever
class Play(Command):
    YOUTUBE_REGEX = "(?P<{}>http[s]?:\/\/(www\.)?(youtube\.com|youtu\.be)\/(watch\?.*v=)?.*)"

    def __init__(self, command_key, client):
        self.client = client
        super().__init__(command_key, "play", """Play music, by giving URLs""",
                         f"{command_key} play *<url>*", ["test"])
        self.args = Args(url=Play.YOUTUBE_REGEX)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            if message.author.voice.channel:
                if server:
                    if not server.voice:
                        vc = await message.author.voice.channel.connect()
                        server.voice = VoicePlayer(vc, message.channel,
                                                   self.client)
                    if server.voice.vc.is_connected():
                        if parse.get("url"):
                            await server.voice.handle(parse.get("url"))
                    else:
                        server.voice = None
                        await self.run(message, server)
コード例 #6
0
ファイル: RoleCommands.py プロジェクト: dss285/4Ever
class ListRoles(Command):
    def __init__(self, command_key):
        super().__init__(command_key, "list", """Lists roles""", f"{command_key} list", [])
        self.args = Args()
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            em = EmbedTemplate(title="Role list", description="\n".join(server.joinable_roles["name"].keys()))
            await message.channel.send(embed=em)
コード例 #7
0
class DotaHeroProfile(Command):
    def __init__(self, command_key, database, steam_api):
        self.database = database
        self.steam_api = steam_api
        super().__init__(command_key, "dotaheroprofile", """Testing""",
                         f"{command_key} dotaheroprofile", [])
        self.args = Args(steamarg=SteamCommands.STEAM_URL_REGEX,
                         hero=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            steam_32id = None
            steam_64id = None
            hero_name = parse.get("hero")
            hero_id = self.database.runtime["dota"]["heroes"]["name"].get(
                hero_name)

            if hero_id:
                vanity_url = parse.get("profile")
                steam_profile_id = parse.get("steamid")
                steam_id = parse.get("steamarg")
                if vanity_url is not None:
                    if vanity_url[len(vanity_url) - 1] == '/':
                        vanity_url = vanity_url[:len(vanity_url) - 1]
                    steam_64id = await self.steam_api.resolve_vanity_url(
                        vanity_url)
                    steam_32id = self.steam_api.steam_64bit_id_to_32bit(
                        steam_64id)
                elif steam_profile_id is not None:
                    steam_32id = self.steam_api.steam_64bit_id_to_32bit(
                        steam_profile_id)
                    steam_64id = int(steam_profile_id)
                elif steam_id is not None:
                    steam_32id = int(
                        steam_id
                    ) if steam_id < 76561197960265728 else self.steam_api.steam_32bit_id_to_64bit(
                        steam_id)
                    steam_64id = int(
                        steam_id
                    ) if steam_id > 76561197960265728 else self.steam_api.steam_64bit_id_to_32bit(
                        steam_id)
                await message.reply("> Might take a while, sit tight")
                account, new_matches = await self.steam_api.get_complete_account(
                    steam_64id, hero_id, True)
                for i in new_matches:
                    await self.database.create_dota_match(i)
                em = EmbedTemplate(
                    title=account.steam_profile.name,
                    description=
                    f"Win rate: {account.win_rate()*100}%\nWins: {account.match_history.wins}\nLosses: {account.match_history.losses}\nTotal matches:{account.match_history.total_matches}"
                )
                em.set_thumbnail(url=account.steam_profile.get_full_avatar())
                await message.reply(embed=em)
コード例 #8
0
class CreateTable(Command):
    def __init__(self, command_key, client: discord.Client, database: DB_API):
        self.database = database
        self.client = client
        super().__init__(command_key, "createtable", """Create table""",
                         f"{command_key} createtable *tablename*", [])
        self.args = Args(table_name=Args.STRING_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message: discord.Message, server: Server) -> None:
        def check_author(m: discord.Message):
            if message.author == m.author:
                return True
            return False

        parse = self.args.parse(message.content)
        if parse:
            table_name = parse['table_name']
            i = 1
            columns = []
            while True:
                em = EmbedTemplate(
                    title=f"Column {i}",
                    description=
                    f"syntax: \*column name\*:\*column type\*:\*extra detail\*\nExtra detail is for example, PRIMARY, not null etc.\nType 'END;' to stop"
                )
                em.add_field(
                    name="Data types",
                    value="https://www.postgresql.org/docs/9.5/datatype.html")
                await message.channel.send(embed=em)
                msg = await self.client.wait_for('message',
                                                 timeout=120.0,
                                                 check=check_author)
                if msg:
                    content = msg.content
                    if content == 'END;':
                        break
                    splitted = content.split(":")
                    merged = f"{' '.join(splitted)}"
                    columns.append(merged)
                    i += 1
                else:
                    break
            if columns:
                nl = ',\n'
                query = f"CREATE TABLE {table_name} IF NOT EXISTS (\n{f'{nl}'.join(columns)}\n);"
                sql = f"```sql\n{query}\n```"
                await message.channel.send(sql)
                await message.channel.send(
                    "Is this ok ? Y for Yes, anything for No")
                msg = await self.client.wait_for('message', timeout=60.0)
                if msg:
                    if "y" in msg.content.lower():
                        await self.database.query(query)
コード例 #9
0
ファイル: NSFWCommands.py プロジェクト: dss285/4Ever
class Gelbooru(Command):
    def __init__(self, command_key):
        super().__init__(command_key, "gelbooru", """Gelbooru Search""",
                         f"{command_key} gelbooru *<tags>*", ["gel"])
        self.args = Args(tags=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            em = await NSFW.gelbooru(parse["tags"])
            await message.channel.send(embed=em)
コード例 #10
0
ファイル: NSFWCommands.py プロジェクト: dss285/4Ever
class Rule34(Command):
    def __init__(self, command_key):
        super().__init__(command_key, "rule34", """Rule34 Search""",
                         f"{command_key} rule34 *<tags>*", ["r34"])
        self.args = Args(tags=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            em = await NSFW.rule34XXX(parse["tags"])
            await message.channel.send(embed=em)
コード例 #11
0
class DBQuery(Command):
    def __init__(self, command_key: str, database: DB_API):
        self.database = database
        super().__init__(command_key, "dbquery", """Query to DB""",
                         f"{command_key} dbquery *query*", ["query"])
        self.args = Args(query=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message: discord.Message, server: Server) -> None:
        parse = self.args.parse(message.content)
        if parse:
            qr = parse['query']
            data = await self.database.query(qr)
            await message.channel.send(f"{data}")
コード例 #12
0
ファイル: WarframeCommands.py プロジェクト: dss285/4Ever
class RelicSearch(Command):
    def __init__(self, command_key, droptables, client):
        self.client = client
        self.droptables = droptables
        super().__init__(command_key, "relic", """Relic search""", f"{command_key} relic *<relic name>*", ["relicsearch"])
        self.args = Args(relic=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        parse = self.args.parse(message.content)
        xx = time.time()
        if parse:
            if not self.droptables.data or xx-self.droptables.timeupdated > self.droptables.interval:
                await self.droptables.getData()
            await message.channel.send(embed=self.droptables.relicSearch(parse.get("relic")))
コード例 #13
0
class ResourceSearch(Command):
    def __init__(self, command_key: str, client: discord.Client,
                 database: DB_API):
        self.client = client
        self.database = database
        super().__init__(
            command_key, "resourcesearch",
            """Search AK resources, their sanitycosts /per stage""",
            f"{command_key} resourcesearch", ["rs", "resource", "item"])
        self.args = Args(resource=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message: discord.Message, server: Server):
        parsed = self.args.parse(message.content)
        if parsed:
            res = dict_search(self.database["arknights"]["items"]["names"],
                              parsed["resource"])
            if res:
                if isinstance(res, str):
                    em = self.database["arknights"]["items"]["names"][
                        res].get_embed()
                    await message.channel.send(embed=em)
                elif isinstance(res, list):
                    em = EmbedTemplate(title="Did you mean?",
                                       description="\n".join([
                                           f"{i}. {res[i-1]}"
                                           for i in range(1,
                                                          len(res) + 1)
                                       ]))
                    await message.channel.send(embed=em)
                    msg = await self.client.wait_for(
                        'message',
                        check=lambda x: x.author == message.author,
                        timeout=30)
                    if msg:
                        if msg.content.isdigit():
                            tmp = int(msg.content)
                            if 1 <= tmp <= len(res):
                                em = self.database["arknights"]["items"][
                                    "names"][res[tmp - 1]].get_embed()
                                await message.channel.send(embed=em)
            else:
                em = EmbedTemplate(
                    title="Not found",
                    description=
                    "Resource wasn't found in the database, if you think this is an error, contact bot owner."
                )
                await message.channel.send(embed=em)
コード例 #14
0
ファイル: RoleCommands.py プロジェクト: dss285/4Ever
class Remove(Command):
    def __init__(self, command_key, database):
        self.database = database
        super().__init__(command_key, "remove", """Removes X role""", f"{command_key} remove *<role mention>*", [])
        self.args = Args(role=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        if message.author.guild_permissions.administrator:
            parse = self.args.parse(message.content)
            if parse:
                for i in message.role_mentions:
                    if i in server.joinable_roles["set"]:
                        await self.database.delete_joinable_role(i.id)
                        server.joinable_roles["set"].remove(i)
                        del server.joinable_roles["id"][i.id]
                        del server.joinable_roles["name"][i.name]
コード例 #15
0
ファイル: RoleCommands.py プロジェクト: dss285/4Ever
class Add(Command):
    def __init__(self, command_key, database):
        self.database = database
        super().__init__(command_key, "add", """Adds X role""", f"{command_key} add *<role mention>*", [])
        self.args = Args(role=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        if message.author.guild_permissions.administrator:
            parse = self.args.parse(message.content)
            if parse:
                for i in message.role_mentions:
                    if i not in server.joinable_roles["set"]:
                        await self.database.create_joinable_role(i.id, server.server_id)
                        server.joinable_roles["set"].add(i)
                        server.joinable_roles["id"][i.id] = i
                        server.joinable_roles["name"][i.name] = i                      
コード例 #16
0
ファイル: RoleCommands.py プロジェクト: dss285/4Ever
class Leave(Command):
    def __init__(self, command_key):
        super().__init__(command_key, "leave", """Leaves X role""", f"{command_key} leave *<role name>*", [])
        self.args = Args(role=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            if message.role_mentions:
                for i in message.role_mentions:
                    if i in server.joinable_roles["set"]:
                        await message.author.remove_roles(i)
            elif parse["role"] in server.joinable_roles["name"]:
                await message.author.add_roles(server.joinable_roles["name"][parse["role"]])
            elif parse["role"] in server.joinable_roles["id"]:
                await message.author.add_roles(server.joinable_roles["id"][parse["role"]])
コード例 #17
0
ファイル: RoleCommands.py プロジェクト: dss285/4Ever
class CreateRoleMessage(Command):
    def __init__(self, command_key, database, client):
        self.client = client
        self.database = database
        super().__init__(command_key, "rolemessage", """Assign role reaction to message or send new message to be reacted.""", f"{command_key} rolemessage *<channel mention>* *<role mention>*", [])
        self.args = Args(channel=Args.CHANNEL_MENTION_ARG, role=Args.MENTION_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        if message.author.guild_permissions.administrator:
            parse = self.args.parse(message.content)
            if parse:
                if message.channel_mentions and message.role_mentions:
                    channel = message.channel_mentions[0]
                    role = message.role_mentions[0]
                    try:
                        await message.channel.send("> Which style")
                        msg = await self.client.wait_for('message', check=lambda m: m.content in ['1', '2'] and m.author == message.author and m.channel == message.channel, timeout=60.0)
                        if msg and msg.content == '1': # Existing message to have role reaction
                            await message.channel.send("> Message ID, please")
                            messageid = await self.client.wait_for('message', check=lambda m: Utilities.is_int(m.content) and m.channel == message.channel and m.author == message.author, timeout=60.0)
                            if messageid:
                                try:
                                    role_msg = await channel.fetch_message(int(messageid.content))
                                    await message.channel.send("> Reaction to be assigned, react to this message.")
                                    reaction, user = await self.client.wait_for('reaction_add', check=lambda r, u: u.author == message.author, timeout=60.0)
                                    if user and reaction:
                                        server.joinable_roles["reactions"][role_msg.id] = {
                                            "message" : role_msg,
                                            "emoji" : str(reaction.emoji),
                                            "role_id" : role.id
                                        }
                                        await self.database.create_role_message(role.id, role_msg.id, channel.id, str(reaction.emoji), server.server_id)
                                        await role_msg.add_reaction(reaction.emoji)
                                except discord.NotFound:
                                    await message.channel.send("> Message couldn't be found")
                            else:
                                await message.channel.send("> Command execution failed, wrong input")                      
                        elif msg and msg.content == '2': # New message to have role reaction
                            pass
                        else:
                            await message.channel.send("> Command execution failed, wrong input")
                    except asyncio.TimeoutError:
                        await message.channel.send("> Too slow")
                    else:
                        await message.channel.send("> Command execution failed, wrong input")
コード例 #18
0
class EvalCommand(Command):
    def __init__(self, command_key: str, client: discord.Client) -> None:
        self.client = client
        super().__init__(command_key, "eval", """Eval""",
                         f"{command_key} eval *evaled statement*", ['ev'])
        self.args = Args(shell=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    async def run(self, message: discord.Message, server: Server) -> None:
        parse = self.args.parse(message.content)
        if parse:
            output = str(eval(parse["shell"]))
            if len(output) < 1975:
                await message.reply(f"""```{output}```""")
            else:
                fo = open("tmp.txt", "w+")
                fo.write(output)
                fo.close()
                await message.reply(file=discord.File("tmp.txt"))
コード例 #19
0
ファイル: ForeverCommands.py プロジェクト: dss285/4Ever
class CrissCross(Command):
    def __init__(self, command_key, client):
        self.client = client
        super().__init__(command_key, "crisscross", """Start a game of crisscross""", f"{command_key} crisscross *<challenged user>*", [])
        self.args = Args(mention=Args.MENTION_ARG, size=Args.OPTIONAL_INT_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        pattern = re.escape(self.prefix)+"\s("+"|".join(self.aliases)+")\s(?:<@!?(?:\d+)>)\s?(\d{1,2})?"
        parse = self.args.parse(message.content)
        if parse:
            if len(message.mentions) == 1:
                user = message.mentions[0]
                await message.channel.send("Would you like to accept this challenge ? (y) for yes, and anything to reject")
                response = await self.client.wait_for('message', timeout=30.0, check=lambda x: x.author == user and x.channel == message.channel)
                if "y" in response.content.lower():
                    size = int(parse.get("size")) or 3
                    game = CC(message.author, response.author, self.client, size)
                    await game.StartGame(message.channel)
                else:
                    await message.channel.send("Challenge denied.")
            else:
                await message.channel.send("Only 1 user may be challenged at once.")
コード例 #20
0
ファイル: ForeverCommands.py プロジェクト: dss285/4Ever
class GTANewswire(Command):
    def __init__(self, command_key, database, newswire):
        self.database = database
        self.newswire = newswire
        super().__init__(command_key, "gtanw", """GTA V newswire""", f"{command_key} gtanw", [])
        self.args = Args(message=Args.OPTIONAL_STRING_ARG)
        self.args.set_pattern(command_key, self.aliases)
    async def run(self, message, server):
        parse = self.args.parse(message.content)
        if parse:
            if parse.get("message") == "message":
                em = EmbedTemplate(title="GTANW Message", description="Updating soon..")
                msg = await message.channel.send(embed=em)
                nwmessage = NewswireMessage(msg)
                await self.database.create_updated_message(msg.guild.id, "gtanw", msg.channel.id, msg.id)
                server.updated_messages["name"]["gtanw"] = nwmessage
                server.updated_messages["id"][nwmessage.id] = nwmessage
            else:
                x = 5
                posts = await self.newswire.getEmbeds(x)
                for i in posts:
                    await message.channel.send(embed=i)
                    x+=1
コード例 #21
0
ファイル: GFLCommands.py プロジェクト: dss285/4Ever
class SFCapture(Command):
    def __init__(
        self,
        command_key,
    ):
        super().__init__(command_key, "sfsim", """SF Capture sim""",
                         f"{command_key} sfsim", ["sfcap"])
        self.args = Args(banner=Args.STRING_ARG, amount=Args.OPTIONAL_INT_ARG)
        self.args.set_pattern(command_key, self.aliases)

    def combine_results(
        self, data: list[dict[str, dict[str, Any]]]
    ) -> tuple[dict[str, dict[str, Any]], int]:
        combined_results = {}
        total_svarogs = 0
        for results in data:
            for banner_unit_name, banner_unit_data in results.items():
                if banner_unit_name not in combined_results:
                    combined_results[banner_unit_name] = {}
                    combined_results[banner_unit_name]["failures"] = 0
                    combined_results[banner_unit_name]["successes"] = 0
                    combined_results[banner_unit_name]["total"] = 0
                    combined_results[banner_unit_name][
                        "item"] = banner_unit_data["item"]
                combined_results[banner_unit_name][
                    "failures"] += banner_unit_data["failures"]
                combined_results[banner_unit_name][
                    "successes"] += banner_unit_data["successes"]
                combined_results[banner_unit_name][
                    "total"] += banner_unit_data["total"]
                if 'svarogs' in banner_unit_data:
                    if 'svarogs' not in combined_results[banner_unit_name]:
                        combined_results[banner_unit_name]["svarogs"] = 0
                    combined_results[banner_unit_name][
                        "svarogs"] += banner_unit_data["svarogs"]
                    total_svarogs += banner_unit_data["svarogs"]
        return combined_results, total_svarogs

    async def run(self, message: discord.Message, server: Server) -> None:
        parse = self.args.parse(message.content)
        if parse:
            amount = int(parse['amount']) if parse['amount'] else 1
            banner = parse['banner']
            items = None
            if banner == "hunter":
                items = Banners.hunter()
            if amount > 500:
                amount = 500
            if items:
                sim = ProtocolAssimilationBanner(
                    ProtocolAssimilationBanner.MONTHLY_SVAROGS)
                sim.set_names(items)
                sim.set_prioritize([
                    "Manticore", "Nemeum",
                    ProtocolAssimilationBanner.PRIORITIZE_WEIGHT
                ])
                total_pulls = 0
                total_results = []
                for i in range(amount):
                    pulls, results = sim.run()
                    total_pulls += pulls
                    total_results.append(results)
                    sim.reset()
                combined_results, used_svarogs = self.combine_results(
                    total_results)
                total_svarogs = sim.svarog_tickets * amount

                em = EmbedTemplate(
                    title="Sim",
                    description=
                    f"Across {amount} banners, you got:\nTotal pulls: {total_pulls}\nTotal SVAROG tickets used: {used_svarogs}/{total_svarogs}"
                )
                for banner_item_name, banner_item_data in combined_results.items(
                ):
                    em.add_field(name=banner_item_name,
                                 value=f"""
                    {f"Svarogs: {banner_item_data['svarogs']}" if 'svarogs' in banner_item_data else ""}
                    {f"Failures: {banner_item_data['failures']}" if banner_item_data['failures'] > 0 else ""}
                    Successes: {banner_item_data['successes']}
                    Total: {banner_item_data['total']}
                    Got {banner_item_data['successes']}/{banner_item_data['item']._original_amount*amount}
                    """)
                await message.channel.send(embed=em)
コード例 #22
0
ファイル: GFLCommands.py プロジェクト: dss285/4Ever
class DollInfo(Command):
    def __init__(self, command_key: str, client: discord.Client,
                 database: DB_API):
        self.client = client
        self.database = database
        super().__init__(command_key, "doll", """Info of dolls""",
                         f"{command_key} doll", ["d", "tdoll"])
        self.args = Args(doll=Args.ANY_ARG)
        self.args.set_pattern(command_key, self.aliases)

    def find_doll(self, parse: str) -> Union[Doll, list[str]]:
        aliases = dict_search(self.database["gfl"]["dolls"]["aliases"],
                              parse['doll'])
        names = dict_search(self.database["gfl"]["dolls"]["names"],
                            parse['doll'])
        if aliases and names:
            if isinstance(aliases, list) and isinstance(names, list):
                return aliases + names
            elif isinstance(aliases, list) and isinstance(names, str):
                aliases.append(names)
                return aliases
            elif isinstance(aliases, str) and isinstance(names, list):
                names.append(aliases)
                return names
            elif isinstance(aliases, str) and isinstance(names, str):
                return [names, aliases]
        elif aliases:
            if isinstance(aliases, str):
                return self.database.runtime["gfl"]["dolls"]["aliases"][
                    aliases]
            elif isinstance(aliases, list):
                return aliases
        elif names:
            if isinstance(names, str):
                return self.database["gfl"]["dolls"]["names"][names]
            elif isinstance(names, list):
                return names

        else:
            return []
        # if parse['doll'].lower() in self.database.runtime["gfl"]["dolls"]["names"]:
        #     return self.database.runtime["gfl"]["dolls"]["names"].get(parse['doll'].lower())
        # elif parse['doll'].lower() in self.database.runtime["gfl"]["dolls"]["aliases"]:
        #     return self.database.runtime["gfl"]["dolls"]["aliases"].get(parse['doll'].lower())
        # else:
        #     return None
    async def run(self, message: discord.Message, server: Server) -> None:
        parse = self.args.parse(message.content)
        if parse:
            doll = self.find_doll(parse)
            if doll:
                if isinstance(doll, Doll):
                    em = doll.get_embed()
                    image = discord.File(doll.get_image_path(),
                                         filename="doll.png")
                    em.set_image(url="attachment://doll.png")
                    await message.channel.send(file=image, embed=em)
                elif isinstance(doll, list):
                    em = EmbedTemplate(title="Did you mean?",
                                       description="\n".join([
                                           f"{i}. {doll[i-1]}"
                                           for i in range(1,
                                                          len(doll) + 1)
                                       ]))
                    await message.channel.send(embed=em)
                    msg = await self.client.wait_for(
                        'message',
                        check=lambda x: x.author == message.author,
                        timeout=30)
                    if msg:
                        if msg.content.isdigit():
                            tmp = int(msg.content)
                            if 1 <= tmp <= len(doll):
                                chosen_doll = doll[tmp - 1]
                                if chosen_doll in self.database["gfl"][
                                        "dolls"]["names"]:
                                    chosen_doll = self.database["gfl"][
                                        "dolls"]["names"].get(chosen_doll)
                                elif chosen_doll in self.database["gfl"][
                                        "dolls"]["aliases"]:
                                    chosen_doll = self.database["gfl"][
                                        "dolls"]["aliases"].get(chosen_doll)
                                if isinstance(chosen_doll, Doll):
                                    em = chosen_doll.get_embed()
                                    image = discord.File(
                                        chosen_doll.get_image_path(),
                                        filename="doll.png")
                                    em.set_image(url="attachment://doll.png")
                                    await message.channel.send(file=image,
                                                               embed=em)

            else:
                em = EmbedTemplate(
                    title="Not found",
                    description=
                    "Doll wasn't found in the database, if you think this is an error, contact bot owner."
                )
                await message.channel.send(embed=em)