Beispiel #1
0
    async def wiki(self, ctx):
        # ---------------------------------------------------- HELPER METHODS

        # Find an article with a matching title
        async def search_for_term(term):
            wiki_search_url = (
                "http://en.wikipedia.org/w/api.php?action=query&format=json" +
                "&prop=&list=search&titles=&srsearch=" + quote(term))
            # Looks for articles matching the search term
            wiki_search_json = await utils.get_json_with_get(wiki_search_url)
            if wiki_search_json[0]['query']['searchinfo']['totalhits'] == 0:
                return None
            return wiki_search_json[0]['query']['search'][0]['title']

        # Gets the details of an article with an exact URL title (not always the same as the article title)
        # Returns a tuple of the article's title, its extract, and a brief description of the subject
        # Returns None if no article was found or the result has no extract
        async def query_article(querytitle):
            # Makes the title URL friendly
            quoted_article_title = quote(querytitle)
            wiki_query_url = (
                "http://en.wikipedia.org/w/api.php?action=query&format=json" +
                "&prop=info%7Cextracts%7Cdescription&titles=" +
                quoted_article_title +
                "&exlimit=max&explaintext=1&exsectionformat=plain")
            # Gets the article details
            response = await utils.get_json_with_get(wiki_query_url)
            # If Wikipedia found nothing
            if "-1" in response[0]['query']['pages'].keys():
                return None
            # Gets the first result
            response = list(response[0]['query']['pages'].values())[0]
            # If the returned result isn't usable
            if "extract" not in response.keys():
                await utils.report(
                    utils.trim_to_len(response, 2000),
                    source="Wiki command found no useful article",
                    ctx=ctx)
                return None
            response_title = response['title']
            response_extract = response['extract']
            if 'description' in response.keys():
                response_description = response['description']
            else:
                response_description = None
            return response_title, response_extract, response_description

        # ---------------------------------------------------- COMMAND LOGIC

        try:
            # WIKI -------------------------------- SET-UP

            (arguments, search_term) = parse.args(ctx.message.content)

            # WIKI -------------------------------- ARGUMENTS

            # Act on arguments
            if "help" in arguments:  # provides help using this command
                title = "`!wiki` User Guide"
                description = "Wikipedia search engine. Searches wikipedia for an article with the title provided " \
                              "and returns the opening section or the full article text. Additionally, it can " \
                              "return the sections of an article or the text of a designated section."
                helpdict = {
                    "-help":
                    "Displays this user guide. Gives instructions on how to use the command and its features",
                    "-full <title>":
                    "Displays the full extract of the article, up to the embed character limit"
                }
                await ctx.send(embed=utils.embed_from_dict(
                    helpdict,
                    title=title,
                    description=description,
                    thumbnail_url=COMMAND_THUMBNAILS["wiki"]))
                return

            # Performs article search
            if search_term == "":
                await ctx.send("I need a term to search")
                return
            article_title = await search_for_term(search_term)
            if article_title is None:
                await ctx.send("I found no articles matching the term '" +
                               search_term + "'")
                return

            # Shows the text of the article searched for
            [title, extract, summary] = await query_article(article_title)
            wiki_embed = Embed()
            wiki_embed.title = title
            wiki_embed.set_footer(
                text="Wikipedia",
                icon_url="https://dwcamp.net/logos/wikipedia.png")
            if "full" in arguments or "f" in arguments:
                description = utils.trim_to_len(extract, 2048)
            else:
                description = utils.trim_to_len(extract[:extract.find("\n")],
                                                2048)
            wiki_embed.description = description
            wiki_embed.add_field(name="Summary", value=summary, inline=False)
            wiki_embed.add_field(name="Full Article",
                                 value="http://en.wikipedia.org/wiki/" +
                                 quote(title),
                                 inline=False)
            wiki_embed.colour = EMBED_COLORS['wiki']  # Make the embed white
            await ctx.send(embed=wiki_embed)
        except Exception as e:
            await utils.report(str(e), source="Wiki command", ctx=ctx)
Beispiel #2
0
    async def tag(self, ctx):
        """
        Tag command

        Parameters
        ------------
        ctx : discord.context
            The message context object
        """
        try:
            # -------------------------------- SET-UP

            # Makes the apostrophe types consistent
            # (See function documentation for explanation)
            parsed_ctx = parse.sanitize_apos(ctx.message.content)
            # Parses CLI arguments
            (arguments, message) = parse.args(parsed_ctx)

            # -------------------------------- ARGUMENTS

            # Acting on arguments
            if "help" in arguments or (len(message) == 0 and len(arguments) == 0):
                title = "!tag - User Guide"
                description = (
                            "Bot call and response. Allows the user to pair a message or attached image with a tag. " +
                            "These tags can then be used to have the bot respond with the associated content. By " +
                            "default, these tags are guild wide, but by using the user list argument (`-u`, e.g. " +
                            "`!tag -u [base] All your base are belong to us`) the user can specify personal tags. " +
                            "This allows a user to store a different value for a key than the guild value and to " +
                            "make tags that will be available for that user across guilds and in DMs.")
                helpdict = {
                    "-ap [<key>] <value>": "If the tag entered already exists, the " +
                                           "new text will be appended to the end after a space",
                    "-apnl [<key>] <value>": "If the tag entered already exists, " +
                                             "the new text will be appended to the end after a line break",
                    "-edit [<key>] <value>": "If the tag entered already exists, " +
                                             "the existing tag will be overwritten",
                    "-help": "Show this guide",
                    "-ls": "Lists the tags within the selected group. Overrides any " +
                           "other argument",
                    "-rm <key>": "removes a tag from the group",
                    "-u": "Selects your specific tag group instead of the guild " +
                          "tags for the following command"}
                await ctx.send(embed=utils.embed_from_dict(helpdict,
                                                           title=title,
                                                           description=description,
                                                           thumbnail_url=COMMAND_THUMBNAILS["tag"]))
                return

            # Rejects ambiguous argument pairs
            if "rm" in arguments and "edit" in arguments:
                await ctx.send("`-rm` and `-edit` are incompatible arguments")
                return
            elif ("apnl" in arguments or "ap" in arguments) and ("edit" in arguments or "rm" in arguments):
                await ctx.send("`ap` or `apnl` are incompatible with the arguments `-rm` or `-edit`")
                return
            elif "ap" in arguments and "apnl" in arguments:
                await ctx.send("`-ap` and `-apnl` is an ambiguous argument pair")
                return

            # flag for if the user is overwriting an existing tag
            edit = False
            # flag for if the user is appending to an existing tag
            append = False
            # flag for if the user wants a line break before their append is added
            newline = False
            # String specifying tag domain
            domain = "server"

            if ctx.guild is None or "u" in arguments:
                domain = "user"
                # MySQL parameter to specify owner of the tag
                tagowner = ctx.author.id
                # if user does not have a user tag group
                if ctx.author.id not in self.tags["user"].keys():
                    # Creates a user tag group
                    self.tags["user"][ctx.author.id] = {}
                # Changes the selected tag group to the user's tags
                selected_tags = self.tags["user"][ctx.author.id]
            else:
                # Selecting tag group (default is 'server')
                if ctx.guild.id not in self.tags["server"].keys():
                    self.tags["server"][ctx.guild.id] = {}
                # Gets domain tag group
                selected_tags = self.tags["server"][ctx.guild.id]
                # MySQL parameter to specify owner of the tag
                tagowner = ctx.guild.id

            # Adds global tags to guild tag group
            for key in self.tags["global"].keys():
                selected_tags[key] = self.tags["global"][key]

            # List the saved tags in the selected tag group
            if "ls" in arguments:
                taglist = ""
                for tagkey in sorted(selected_tags.keys()):
                    if tagkey in self.tags["global"].keys():
                        taglist += ", `" + tagkey + "`"
                    else:
                        taglist += ", " + tagkey
                if taglist == "":
                    if domain == "user":
                        await ctx.send("You do not have any saved tags")
                    else:
                        await ctx.send("This server does not have any saved tags")
                    return
                taglist = taglist[2:]  # pulls the extraneous comma off
                await ctx.send("**The tags I know are**\n" + taglist + "")
                return

            # Reject empty messages (`-ls` calls have already been handled)
            if len(message) == 0:
                await ctx.send("I see some arguments `` " + str(arguments) +
                                   " ``, but no key or value to work with :/")
                return

            # Deletes a saved tag
            if "rm" in arguments:
                key = message.lower()
                if key in selected_tags.keys():
                    del selected_tags[key]
                    await ctx.send("Okay. I deleted it")
                    self.update_tag_remove(key, tagowner, domain)
                else:  # If that tag didn't exist
                    await ctx.send("Hmmm, that's funny. I didn't see the tag `` " + message +
                                       " `` in the saved tags list.")
                return

            # ------ Set or Get ------

            # Check for modification flags
            if any(edit_arg in arguments for edit_arg in ["edit", "apnl", "ap"]):
                edit = True  # Allows modification of existing tag
            if any(append_arg in arguments for append_arg in ["apnl", "ap"]):
                append = True  # Adds new text to end of existing tag
            if "apnl" in arguments:
                newline = True  # Adds a new line before appending text

            # Setting
            if message[0] is "[":
                tag_keyvalue = parse.key_value(message, ctx.message.attachments)
                if tag_keyvalue[0] is None:
                    error_messages = {"EMPTY KEY": "There was no key to store",
                                      "UNCLOSED KEY": "You didn't close your brackets",
                                      "NO VALUE": "There was no text to save for the key provided",
                                      "WHITESPACE KEY": "Just because this bot is written in Python " +
                                                        "does not mean whitespace is an acceptable tag",
                                      "KEY STARTS WITH -": "The `-` character denotes the start of " +
                                                           "an argument and cannot be used in tag keys"}
                    await ctx.send(error_messages[tag_keyvalue[1]])
                    return
                else:
                    tagkey = tag_keyvalue[0].lower()
                    tagvalue = tag_keyvalue[1]
                    if tagkey in selected_tags.keys():
                        if tagkey in self.tags["global"].keys():
                            await ctx.send(
                                "I'm sorry, but the key `` " + tagkey +
                                " `` has already been reserved for a global tag")
                            return
                        elif edit is False:
                            await ctx.send(f"I already have a value stored for the tag `{tagkey}`. "
                                           f"Add `-edit` to overwrite existing tags")
                            return
                        elif append is True:
                            if newline is True:
                                selected_tags[tagkey] = selected_tags[tagkey] + "\n" + tagvalue
                            else:
                                selected_tags[tagkey] = selected_tags[tagkey] + " " + tagvalue
                            self.update_tag_edit(tagkey, selected_tags[tagkey], tagowner, domain)
                            await ctx.send("Edited!")
                            return
                        else:
                            selected_tags[tagkey] = tagvalue
                            self.update_tag_edit(tagkey, tagvalue, tagowner, domain)
                            await ctx.send("Edited!")
                            return
                    selected_tags[tagkey] = tagvalue
                    self.update_tag_add(tagkey, tagvalue, tagowner, domain)
                    await ctx.send("Saved!")
            # Getting
            else:
                key = message.lower()
                if key in selected_tags.keys():
                    await ctx.send(utils.trim_to_len(selected_tags[key], 2000))
                elif domain == "user":
                    await ctx.send(f"I don't think your account has a tag `{key}`. "
                                   "Type `!tag -u -ls` to see the tags I have saved for you")
                else:
                    await ctx.send(f"I don't think I have a tag `{key}` for this guild. "
                                   f"Type `!tag -ls` to see a list of this guild's tags")
        except Exception as e:
            await utils.report(str(e), source="Tag command", ctx=ctx)
Beispiel #3
0
    async def ud(self, ctx):
        # Removes the brackets around words, which UD puts around words in definitions
        # and examples that have their own definitions
        def strip_brackets(text):
            text = text.replace("[", " ").replace("]", "")
            return text

        """ Query the UrbanDictionary API """
        try:
            # removes the invocation portion of the message
            message = parse.strip_command(ctx.message.content)

            max_definitions = 4

            # Reject empty messages
            if message == "":
                await ctx.send("You must pass in a term to get a definition")
                return

            # Query the API and post its response
            url = "http://api.urbandictionary.com/v0/define?term=" + quote(
                message)
            (ud_json, response) = await utils.get_json_with_get(url)
            if response is not 200:
                await ctx.send(
                    "There was an error processing your request. I apologize for the inconvenience."
                )
                return
            if len(ud_json["list"]) > 0:
                ud_embed = Embed()
                ud_embed.set_footer(
                    text="UrbanDictionary",
                    icon_url="https://dwcamp.net/logos/urbanDictionary.jpg")
                counter = 0
                first_result = ""
                while counter < len(
                        ud_json["list"]) and counter <= max_definitions:
                    definition = ud_json["list"][counter]
                    if counter == 0:
                        first_result = definition["word"]
                        ud_embed.title = utils.trim_to_len(first_result,
                                                           256).capitalize()
                    if definition["word"] == first_result:
                        def_text = definition["definition"].replace("*", "\\*")
                        example_text = "**Example: " + definition[
                            "example"].replace("*", "\\*") + "**"
                        ud_embed.add_field(
                            name=str(counter + 1),
                            value=utils.trim_to_len(
                                strip_brackets(def_text + "\n\n" +
                                               example_text), 1024),
                            inline=False)
                    counter += 1
                ud_embed.colour = EMBED_COLORS['ud']  # Make the embed white

                await ctx.send(embed=ud_embed)
            else:
                await ctx.send(
                    "I can't find any UrbanDictionary results for `" +
                    message + "`")
        except Exception as e:
            await utils.report(str(e), source="ud command", ctx=ctx)
Beispiel #4
0
    async def say(self, ctx):
        """
        Makes SuitsBot say a stored audio clip in voice via a tag system. (e.g. `!say anthem`)
        The command also supports several CLI arguments for different tasks

        "-help": Shows the command's help embed
        "-ls": Lists all audio clip tags
        "-stop": Stops the current audio clip
        """

        # List of quote files
        quotes = {
            "ah f**k":
            ["Ah f**k. I can't believe you've done this", "ah-f**k.mp3"],
            "anthem": [
                "**SOYUZ NERUSHIMY RESPUBLIK SVOBODNYKH SPLOTILA NAVEKI VELIKAYA RUS'!**",
                "anthem.mp3"
            ],
            "austin": ["IT'S ME, AUSTIN!", "itsMeAustin.mp3"],
            "bold strategy": [
                "It's a bold strategy cotton, let's see if it pays off for 'em",
                "bold-strategy-cotton.mp3"
            ],
            "careless whisper":
            ["*sexy sax solo intensifies*", "careless_whispers.mp3"],
            "cavalry": ["*britishness intensifies*", "cheersLove.ogg"],
            "deja vu": ["Ever get that feeling of deja vu?", "dejaVu.ogg"],
            "disco": [
                "Reminder: You can stop media using the `!say -stop` command",
                "platinumDisco.mp3"
            ],
            "do it": ["*Do it*", "doIt.mp3"],
            "everybody": ["Se *no*!", "everybody.wav"],
            "ftsio": ["F**k this shit I'm out", "f**k-this-shit-im-out.mp3"],
            "f**k you": ["**F**k yoooooou!**", "fuckYou.mp3"],
            "gfd": ["God *f*****g* dammit!", "gfd.mp3"],
            "hentai":
            ["It's called hentai, and it's *art*", "itsCalledHentai.mp3"],
            "hello darkness":
            ["*Hello darkness my old friend...*", "helloDarkness.mp3"],
            "hello there": ["**GENERAL KENOBI**", "hello_there_obi.mp3"],
            "heroes never die": ["Heroes never die!", "heroesNeverDie.ogg"],
            "high noon": ["It's hiiiiiigh nooooooon...", "itsHighNoon.ogg"],
            "how": ["**I MADE MY MISTAKES**", "howCould.mp3"],
            "i tried so hard":
            ["Woah there, don't cut yourself on that edge", "inTheEnd.mp3"],
            "it was me": ["Ko! No! Dio! Da!", "itWasMeDio.mp3"],
            "jokerfied": ["**HAHAHAHAHAHAHAHAHAHAAAAHAHA**", "jokerfied.mp3"],
            "laser sights":
            ["*Fooking laser sights*", "fookin-laser-sights.mp3"],
            "leroy": ["LEEEEEEROOOOOOOOOOOOOY", "leroy.mp3"],
            "love": [
                "AND IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII...",
                "iWillAlwaysLoveYou.mp3"
            ],
            "morning": [
                "Let's get this shit. Let's get this shit. Let's—HUNH! Top of the mornin'. "
                "Top of the mornin'. Top of the mornin'. Top of the mornin'. Top of the mornin'. "
                "Top of the mornin'. Top of the mornin'. HO—",
                "TopOfTheMorning.mp3"
            ],
            "my power": [
                "*You underestimate my power!*",
                "you-underestimate-my-power.mp3"
            ],
            "nerf this": ["It's nerf or nothing", "nerfThis.ogg"],
            "nani": ["NANI SORE!?", "nani-sore.mp3"],
            "nico":
            [("Nico Nico-nii~ Anata no Heart ni Nico Nico-nii, Egao todokeru Yazawa "
              + "Nico Nico~ Nico-nii te oboeteru Love Nico~ XD"),
             "nico_nico_nii.mp3"],
            "nyan": [("Naname nanajyuunana-do no narabi de nakunaku inanaku " +
                      "nanahan nanadai nannaku narabete naganagame.\nOwO"),
                     "nyan.mp3"],
            "omg": ["OH MY GOD!", "omg.mp3"],
            "oof": ["OOF!", "oof.mp3"],
            "over 9000": ["It's over **9000!!!**", "over9000.mp3"],
            "pingas": ["Pingas.", "pingas.mp3"],
            "rimshot": ["Badum, tiss", "rimshot.mp3"],
            "roundabout": ["To be continued...", "roundabout.mp3"],
            "sanic": ["goTtA gO faSt!", "sanic.mp3"],
            "satania": ["BWAHAHAHA!", "sataniaLaugh.mp3"],
            "sob": ["SON OF A BITCH!", "sob.mp3"],
            "somebody":
            ["What are you doing in my swamp?!", "somebodyClipping.wav"],
            "star destroyers":
            ["**IT BROKE NEW GROUND**", "starDestroyers.mp3"],
            "stop": ["It's time to stop!", "stop.mp3"],
            "take a sip": ["Take a f****n' sip, babes...", "takeASip.mp3"],
            "tea": ["I've got f*****g tea, ya dickhead!", "gotTea.wav"],
            "trash": ["**Endless trash**", "Endless Trash.mp3"],
            "tuturu": ["TUTURUUUUUUUU", "tuturu.mp3"],
            "violin": ["*sadness intensifies*", "sadViolin.mp3"],
            "wake me up": ["**I CAN'T WAKE UP**", "wakeMeUp.mp3"],
            "winky face": [":wink:", "winkyFace.ogg"],
            "woomy": ["Woomy!", "woomy.mp3"],
            "wow": ["Wow", "wow.mp3"],
            "wtf": ["**Hey Todd?!**", "whatTheFuck.mp3"],
            "yeah": ["*Puts on sunglasses*", "yeah.mp3"],
            "yes": ["YES YES YES YES... **YES**!", "yes.mp3"],
            "your way":
            ["Don't lose your waaaaaaaaay!", "dontloseyourway.mp3"],
            "zaworldo": ["ZA WARLDO!", "za_warudo.mp3"]
        }
        try:
            (arguments, key) = parse.args(ctx.message.content)

            # ------------------------------ NO AUDIO ARGUMENTS

            # Acting on arguments
            if "help" in arguments:  # provides help using this command
                title = "`!say` User Guide"
                description = (
                    "Plays an audio clip in voice. If not already in the user's voice channel, the bot "
                    +
                    "will automatically join the voice channel of the user issuing the command. The bot "
                    +
                    "holds a list of stored audio files which can be summoned using predefined tags "
                    +
                    "(the list of tags can be viewed using the `!say -ls` command). If an audio clip is "
                    +
                    "currently playing, another tag cannot be started. If all users leave the audio "
                    +
                    "channel the bot is in, the bot will leave as well. If the user is not in a voice "
                    + "channel, the command will be rejected")
                helpdict = {
                    "<tag>":
                    ("Plays the predetermined audio clip for that tag. Tags are case-insensitive, but make "
                     + "sure your spelling is right!"),
                    "-help":
                    "Shows this list",
                    "-ls":
                    "Lists the tags for all the available audio clips",
                    "-stop":
                    "Stops the current voice clip"
                }
                await ctx.send(embed=utils.embed_from_dict(
                    helpdict,
                    title=title,
                    description=description,
                    thumbnail_url=COMMAND_THUMBNAILS["say"]))
                return
            if "ls" in arguments:
                message = "The audio clips I know are: \n" + ", ".join(
                    quotes.keys())
                await ctx.send(utils.trim_to_len(message, 2000))
                return
            if "stop" in arguments:
                if not self.bot.voice.is_playing():
                    await ctx.send("I'm not saying anything...")
                else:
                    self.bot.voice.stop()
                    await ctx.send("Shutting up.")
                return

            # ------------------------------ VALIDATING KEY

            if key == "":
                await ctx.send(
                    "You need to type the name of an audio clip for me to say. Type `!say -ls` for "
                    +
                    "a list of my audio clips or type `!say -help` for a full list of my arguments"
                )
                return

            if key not in quotes.keys():
                await ctx.send("I don't see an audio clip tagged '" + key +
                               "'. Type `!say -ls` for a list of tags")
                return

            # ------------------------------ VALIDATING BOT AVAILABILITY

            # Gets the voice channel the author is in. If the author is not in voice, author_voice_channel is `None`
            author_voice_channel = ctx.author.voice.channel if ctx.author.voice is not None else None
            # Ignores the command if the author is not in voice
            if author_voice_channel is None:
                await ctx.send("You are not in a voice channel right now")
                return

            # Ignores command if bot is already playing a voice clip
            if self.bot.voice and self.bot.voice.is_playing():
                await ctx.send("Currently processing other voice command")
                return

            # ------------------------------ AUDIO INITIALIZATION

            self.bot.voice = await join_audio_channel(author_voice_channel)

            if self.bot.voice is None:  # If bot failed to join, show error message
                await ctx.send(
                    f"I'm sorry {ctx.author.mention}, but I was not able to join {author_voice_channel}"
                )
                return

            # ------------------------------ PLAYING AUDIO

            # Play audio clip
            self.bot.voice.play(FFmpegPCMAudio(SOUNDS_DIR + quotes[key][1]))
            await ctx.send(quotes[key][0]
                           )  # Responds with the text of the voice clip

        except Exception as e:
            await utils.report(str(e), source="say command", ctx=ctx)
Beispiel #5
0
    async def anime(self, ctx):
        """
        anime command

        Parameters
        ------------
        ctx : discord.context
            The message context object
        """

        try:
            # Gets the arguments from the message
            (arguments, searchterm) = parse.args(ctx.message.content)

            if "dev" in arguments:
                await ctx.send(self.character_synonyms)
                return

            # Explain all the arguments to the user
            if "help" in arguments or searchterm == "help":
                title = "!anime - User Guide"
                description = (
                    "A search tool for anime shows and characters. This command uses the AniList.co API to "
                    +
                    "return details on the search term provided for the show/character whose name is provide "
                    +
                    "with the command (e.g. `!anime Kill la Kill`). For shows, information like a show "
                    +
                    "description, air date, rating, and genre information will be returned. For characters, "
                    +
                    "the bot provides a description, their nicknames, and the media they've been in.\n\nThe "
                    +
                    "bot uses a synonym engine to make it easier to find popular characters and allow for "
                    +
                    "searching for entries using unofficial nicknames (e.g. `!anime klk` redirects to "
                    +
                    "`!anime Kill la Kill`). The bot's synonym table can be modified by users to allow for a "
                    + "more complete table of synonyms")
                helpdict = {
                    "<search>":
                    "Searches the database for an anime",
                    "-help":
                    "Displays this message",
                    "-add [<Synonym>] <Value>":
                    ("Adds a synonym to the list. Will search for " +
                     "`Value` when a user types `Synonym`. Can be used " +
                     "with the `-char` command to create character " +
                     "synonyms. `<Synonym>` also supports semicolon-" +
                     "delineated lists"),
                    "-char <search>":
                    "Searches the database for a character page",
                    "-info <search>":
                    ("Shows the complete details for an anime. Has no effect on "
                     + "`-char` searches"),
                    "-ls":
                    ("Lists the anime synonym table. If used with the `-char` command, it "
                     + "lists the character synonym table"),
                    "-raw <search>":
                    "Disables synonym correction for search terms",
                    "-remove <Search Value>":
                    ("Removes a synonym from the list. Can be used with " +
                     "the `-char` command to remove character synonyms")
                }
                await ctx.send(embed=utils.embed_from_dict(
                    helpdict,
                    title=title,
                    description=description,
                    thumbnail_url=COMMAND_THUMBNAILS["anime"]))
                return

            if "ls" in arguments:
                if "char" in arguments:
                    searchdict = self.character_synonyms
                    title = "Character name synonyms"
                else:
                    searchdict = self.anime_synonyms
                    title = "Anime title synonyms"
                message = ""
                for changeto in sorted(list(searchdict.keys())):
                    message += "**" + changeto + "** <- " + ", ".join(
                        searchdict[changeto]) + "\n"
                embed = Embed()
                embed.title = title
                embed.description = utils.trim_to_len(message, 2040)
                embed.colour = EMBED_COLORS["anime"]
                await ctx.send(embed=embed)
                return

            if "add" in arguments and "remove" in arguments:
                await ctx.send(
                    "I don't know how you possibly expect me to both add and "
                    + "remove a synonym in the same command")

            if "char" in arguments:
                synonymdict = self.character_synonyms
                searchtype = "character"
            else:
                synonymdict = self.anime_synonyms
                searchtype = "anime"

            # Add search synonym
            if "add" in arguments:
                tag_kv = parse.key_value(searchterm)
                if tag_kv[0] is None:
                    errormessages = {
                        "EMPTY KEY":
                        "There was no synonym for the search value",
                        "UNCLOSED KEY":
                        "You didn't close your brackets",
                        "NO VALUE":
                        "There was no search value to save for the synonym",
                        "WHITESPACE KEY":
                        ("Just because this bot is written in Python does not mean whitespace is an "
                         + "acceptable synonym"),
                        "KEY STARTS WITH -":
                        ("The `-` character denotes the start of an argument and cannot be used to "
                         + "start a synonym")
                    }
                    await ctx.send(errormessages[tag_kv[1]])
                    return
                changefrom = tag_kv[0].lower()
                changeto = tag_kv[1]
                collision = checkforexistingsynonym(changefrom, synonymdict)
                if collision is None:
                    if changeto not in synonymdict.keys():
                        synonymdict[changeto] = list()
                    changefromlist = changefrom.split(";")
                    for element in changefromlist:
                        synonymdict[changeto].append(element.strip())
                        self.add_synonym(searchtype.upper(), changeto, element)
                    await ctx.send("All " + searchtype + " searches for `" +
                                   "` or `".join(changefromlist) +
                                   "` will now correct to `" + changeto + "`")
                else:
                    await ctx.send(
                        "The synonym `` {} `` already corrects to `` {} ``. Pick a different "
                        +
                        "word/phrase or remove the existing synonym with the command "
                        + "``!anime -remove {} ``".format(
                            changefrom, collision, changefrom))
                return

            # Remove search synonym
            if "remove" in arguments:
                correction = checkforexistingsynonym(searchterm, synonymdict)
                if correction is not None:
                    synonymdict[correction].remove(searchterm)
                    if len(synonymdict[correction]) == 0:
                        del synonymdict[correction]
                    self.remove_synonym(searchtype.upper(), searchterm)
                    await ctx.send("Alright, `" + searchterm +
                                   "` will no longer correct to `" +
                                   correction + "` for " + searchtype +
                                   " searches")
                else:
                    await ctx.send((
                        "The synonym you searched for does not exist. Check your use "
                        +
                        "(or lack thereof) of the `-char` command, or use the `-ls` command to check "
                        + "that everything is spelled correctly"))
                return

            if searchterm == "":
                await ctx.send(
                    "I don't see a search term to look up. Type `!anime -help` for a user guide"
                )
                return

            embedgenerator = None
            if "char" in arguments:
                if "raw" not in arguments:
                    for key in self.character_synonyms.keys():
                        if searchterm.lower() in self.character_synonyms[key]:
                            searchterm = key
                char_var = {'name': searchterm}
                [json,
                 status] = await utils.get_json_with_post(self.api_url,
                                                          json={
                                                              'query':
                                                              self.char_query,
                                                              'variables':
                                                              char_var
                                                          })
                if "json" in arguments:
                    await ctx.send(utils.trim_to_len(json, 2000))
                if status == 200:
                    embedgenerator = Character(json['data']['Character'])
            else:
                if "raw" not in arguments:
                    for key in self.anime_synonyms.keys():
                        if searchterm.lower() in self.anime_synonyms[key]:
                            searchterm = key
                anime_var = {'title': searchterm}
                [json,
                 status] = await utils.get_json_with_post(self.api_url,
                                                          json={
                                                              'query':
                                                              self.anime_query,
                                                              'variables':
                                                              anime_var
                                                          })
                if "json" in arguments:
                    await ctx.send(utils.trim_to_len(json, 2000))
                if status == 200:
                    embedgenerator = Anime(json['data']['Media'])

            if status != 200:
                if status == 500:
                    await utils.flag("500 Server Error on search term " +
                                     searchterm,
                                     description=str(json),
                                     ctx=ctx)
                    await ctx.send(
                        "`500 Server Error`. The AniList servers had a brief hiccup. Try again in a little bit"
                    )
                elif status == 404:
                    await utils.flag("Failed to find result for search term " +
                                     searchterm,
                                     description=str(json),
                                     ctx=ctx)
                    await ctx.send("I found no results for `" + searchterm +
                                   "`")
                elif status == 400:
                    await utils.report(
                        str(json),
                        source="Error in `!anime` search for term " +
                        searchterm,
                        ctx=ctx)
                    await ctx.send(
                        "The bot made an error. My bad. A bug report has been automatically submitted"
                    )
                else:
                    await utils.report(str(json),
                                       source="Unknown Error Type",
                                       ctx=ctx)
                    await ctx.send("Something went wrong and I don't know why")
                return

            if "info" in arguments:
                await ctx.send(embed=embedgenerator.info_embed())
            else:
                await ctx.send(embed=embedgenerator.embed())
        except Exception as e:
            await utils.report(str(e), source="!anime command", ctx=ctx)
Beispiel #6
0
    async def unfurl(cls, triggers: [str], msg: Message) -> [Embed]:
        discord_logo = "https://cdn3.iconfinder.com/data/icons/logos-and-brands-adobe/512/91_Discord-512.png"

        embed_list = []
        for trigger in triggers:
            (guild_id, channel_id, message_id) = trigger.split("/")

            # Cast id values to int
            guild_id = int(guild_id)
            channel_id = int(channel_id)
            message_id = int(message_id)

            # Find message
            bot = utils.get_bot()
            message_channel = bot.get_channel(channel_id)
            if message_channel is None:
                return
            linked_message = await message_channel.fetch_message(message_id)
            if linked_message is None:
                return

            """ Make the Embed """
            embed = Embed()
            embed.url = f"http://discord.com/channels/{guild_id}/{channel_id}/{message_id}"
            embed.colour = EMBED_COLORS['discord']

            # Count embeds/attachments
            if len(linked_message.embeds) > 0:
                embed.add_field(name="Embeds", value=f"{len(linked_message.embeds)}", inline=True)
            if len(linked_message.attachments) > 0:
                embed.add_field(name="Attachments", value=f"{len(linked_message.attachments)}", inline=True)

            # Set image from attachments or embeds
            for attach in linked_message.attachments:
                if attach.height:  # Non-null height attribute indicates attachment is an image
                    embed.set_image(url=attach.url)
                    break
            else:
                # If the attachments didn't work, try embeds
                for message_embed in linked_message.embeds:
                    if message_embed.type == "image":
                        embed.set_image(url=message_embed.url)
                        break

            # Set message text
            text = utils.trim_to_len(linked_message.content, 2048)
            if len(text) == 0:  # If message empty, check embeds
                if len(linked_message.embeds) > 0:
                    embed_as_text = utils.embed_to_str(linked_message.embeds[0])
                    text = utils.trim_to_len(f"**Message contained embed**\n```\n{embed_as_text}\n```", 2048)
                elif embed.image.url is Embed.Empty:  # Description doesn't need to be modified if an image is attached
                    text = "```(Message was empty)```"

            embed.description = text

            # Try and use author's nickname if author is a Member object
            if isinstance(linked_message.author, Member):
                embed.title = linked_message.author.name \
                    if linked_message.author.nick is None \
                    else linked_message.author.nick
            else:
                embed.title = linked_message.author.name

            if linked_message.author.avatar_url:
                embed.set_thumbnail(url=linked_message.author.avatar_url)

            # Collapse Reactions to a single list
            if linked_message.reactions:
                react_str = " ‍ ‍ ".join(
                    [f"{reaction.emoji} **{reaction.count}**" for reaction in linked_message.reactions])
                embed.add_field(name="Reactions", value=utils.trim_to_len(react_str, 1024))

            # Add timestamp to footer
            if linked_message.edited_at:
                timestamp = linked_message.edited_at
                verb = "Edited"
            else:
                timestamp = linked_message.created_at
                verb = "Sent"
            embed.set_footer(text=f"{verb} at {timestamp.strftime('%H:%M  %Y-%m-%d')}",
                             icon_url=discord_logo)
            embed_list.append(embed)
        return embed_list
Beispiel #7
0
    async def unfurl(cls, triggers: [str], msg: Message) -> [Embed]:

        embed_color = EMBED_COLORS["reddit"]
        nsfw_thumbnail = "https://cdn2.iconfinder.com/data/icons/freecns-cumulus/32/519791-101_Warning-512.png"
        default_thumbnail = "https://cdn.discordapp.com/attachments/341428321109671939/490654122941349888/unknown.png"
        embed_icon = "https://s18955.pcdn.co/wp-content/uploads/2017/05/Reddit.png"

        embed_list = []
        for trigger in triggers:
            post_url = "https://" + trigger

            print(f"post_url: '{post_url}'")
            # Get data from post
            if post_url[-1] == "/":  # Strip trailing forward slash
                json_url = post_url[:-1] + ".json?raw_json=1"
            else:
                json_url = post_url + ".json"
            [json, response] = await utils.get_json_with_get(json_url)
            if response is not 200:
                print("not 202")
                continue
            post_data = json[0]['data']['children'][0]['data']

            if not post_data["is_self"]:  # Don't expand link posts
                print("is self")
                continue

            # Embed data

            embed = Embed()
            embed.colour = embed_color
            embed.url = post_url
            embed.title = utils.trim_to_len(post_data['title'], 256)

            embed.set_footer(text="via Reddit.com", icon_url=embed_icon)
            embed.add_field(name="Author", value=post_data['author'])
            embed.add_field(name="Subreddit",
                            value=post_data['subreddit_name_prefixed'])
            if not post_data['hide_score']:
                scoreText = f"{post_data['score']} ({post_data['upvote_ratio'] * 100}%)"
                embed.add_field(name="Score", value=scoreText)
            embed.add_field(name="Comments", value=post_data['num_comments'])

            # Hide other details if NSFW
            if post_data['over_18']:
                embed.description = "This post has been tagged as NSFW"
                embed.set_thumbnail(url=nsfw_thumbnail)
                embed_list.append(embed)
                continue
            if post_data['spoiler']:
                embed.title = "SPOILER!"
                embed.set_thumbnail(url=nsfw_thumbnail)
                embed_list.append(embed)
                continue

            embed.add_field(name="Posted",
                            value=utils.time_from_unix_ts(
                                post_data['created_utc']))

            text = post_data['selftext'].replace('&#x200B;', '')
            embed.description = utils.trim_to_len(text, 2048)

            if "preview" in post_data and len(
                    post_data["preview"]["images"]) > 0:
                embed.set_thumbnail(
                    url=post_data["preview"]["images"][0]["source"]["url"])
            else:
                embed.set_thumbnail(url=default_thumbnail)

            # Guildings
            gildings = list()
            if 'gid_3' in post_data['gildings'].keys():
                gildings.append("Platinum x" +
                                str(post_data['gildings']['gid_3']))
            if 'gid_2' in post_data['gildings'].keys():
                gildings.append("Gold x" + str(post_data['gildings']['gid_2']))
            if 'gid_1' in post_data['gildings'].keys():
                gildings.append("Silver x" +
                                str(post_data['gildings']['gid_1']))

            if gildings:
                embed.add_field(name="Gildings", value=", ".join(gildings))

            embed_list.append(embed)
        return embed_list
Beispiel #8
0
    async def code(self, ctx):
        """
        code command

        Parameters
        ------------
        ctx : discord.context
            The message context object
        """
        try:
            (arguments, message) = parse.args(ctx.message.content)

            # Explain all the arguments to the user
            if "help" in arguments or (len(message) == 0
                                       and len(arguments) == 0):
                title = "!code - User Guide"
                description = (
                    "Remote code execution. Allows users to write code and submit it to the bot for "
                    +
                    "remote execution, after which the bot prints out the results, any error codes, "
                    +
                    "the execution time, and memory consumption. The command supports 65 different "
                    +
                    "languages, including Java, Python 2/3, PHP, Swift, C++, Rust, and Go.\n\nTo invoke "
                    +
                    "execution, include a block of code using the multi-line Discord code format "
                    +
                    "( https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-"
                    +
                    "Formatting-Bold-Italic-Underline- ). To use this formatting, use three backticks "
                    +
                    "(`, the key above the tab key), followed immediately (no spaces!) by the language "
                    +
                    "tag, followed by a linebreak, followed by your code. Close off the code block with "
                    +
                    "three more backticks. It's a little complicated, I apologize. It's Discord's "
                    +
                    "formatting rules, not mine.\n\n**Be advised**\nRemote execution will time out after "
                    +
                    "5 seconds and does not support external libraries or access to the internet."
                )

                helpdict = {
                    "-help":
                    "Shows this user guide",
                    "-full":
                    "Shows the full list of supported languages",
                    "-lang":
                    "Shows the common languages supported by this command",
                }
                await ctx.send(embed=utils.embed_from_dict(
                    helpdict,
                    title=title,
                    description=description,
                    thumbnail_url=COMMAND_THUMBNAILS["code"]))
                return

            if "ls" in arguments or "full" in arguments:
                message = "`Name` (`compiler version`) - `tag`\n---------"
                for langname in self.langs.keys():
                    name = self.langs[langname][0]  # Name
                    message += "\n**" + name + "** : " + langname
                if "full" in arguments:
                    message += "\n---------"
                    for langname in self.esolangs.keys():
                        name = self.esolangs[langname][0]  # Name
                        message += "\n**" + name + "** : " + langname
                await ctx.send(utils.trim_to_len(message, 2000))
                return

            if "dev" in arguments:
                [json, resp_code
                 ] = await utils.get_json_with_post(url=self.credits_check_url,
                                                    json={
                                                        "clientId":
                                                        self.JDOODLE_ID,
                                                        "clientSecret":
                                                        self.JDOODLE_SECRET
                                                    })
                if resp_code != 200:
                    await utils.report("Failed to check credits\n" + str(json),
                                       source="!code dev",
                                       ctx=ctx)
                    return
                if "used" not in json.keys():
                    await utils.report(
                        json,
                        "Failed to get credit count for JDOODLE account",
                        ctx=ctx)
                    await ctx.send(
                        "Forces external to your request have caused this command to fail."
                    )
                    return
                await ctx.send(json['used'])
                return

            if "```" in message:
                trimmedmessage = message[message.find("```") + 3:]
                if "```" not in trimmedmessage:
                    await ctx.send("You didn't close your triple backticks")
                    return
                trimmedmessage = trimmedmessage[:trimmedmessage.find("```")]
                splitmessage = trimmedmessage.split("\n", maxsplit=1)
                if len(trimmedmessage) == 0:
                    await ctx.send("You need to put code inside the backticks")
                    return
                if trimmedmessage[0] not in [" ", "\n"
                                             ] and len(splitmessage) > 1:
                    [language, script] = splitmessage
                    language = language.strip()
                    for key in self.esolangs.keys():
                        self.langs[key] = self.esolangs[key]
                    if language.lower() in self.langs.keys():
                        response = await utils.get_json_with_post(
                            url=self.execute_url,
                            json={
                                "clientId": self.JDOODLE_ID,
                                "clientSecret": self.JDOODLE_SECRET,
                                "script": script,
                                "language": self.langs[language.lower()][1],
                                "versionIndex": self.langs[language.lower()][2]
                            })
                        [json, resp_code] = response
                        if resp_code == 429:
                            await utils.report(
                                json,
                                "Bot has reached its JDOODLE execution limit",
                                ctx=ctx)
                            await ctx.send(
                                "The bot has reached its code execution limit for the day."
                            )
                            return
                        output_embed = Embed()
                        if "error" in json.keys():
                            output_embed.description = json['error']
                            output_embed.title = "ERROR"
                            output_embed.colour = EMBED_COLORS["error"]
                            await ctx.send(embed=output_embed)
                            return
                        output_embed.title = "Output"
                        output_embed.colour = EMBED_COLORS["code"]
                        output_embed.add_field(
                            name="Language",
                            value=self.langs[language.lower()][0])
                        output_embed.add_field(name="CPU Time",
                                               value=str(json['cpuTime']) +
                                               " seconds")
                        output_embed.add_field(name="Memory Usage",
                                               value=json['memory'])
                        if len(json['output']) > 2046:
                            output_embed.description = "``` " + utils.trim_to_len(
                                json['output'], 2040) + "```"
                        else:
                            output_embed.description = "``` " + json[
                                'output'] + "```"
                        await ctx.send(embed=output_embed)
                    else:
                        await ctx.send(
                            "I don't know the language '" + language +
                            "'. Type `!code -full` " +
                            "to see the list of languages I support, or type `!code -ls` to see "
                            + "the most popular ones")
                else:
                    await ctx.send(
                        "There was no language tag. Remember to include the language tag "
                        +
                        "immediately after the opening backticks. Type `!code -ls` or "
                        + "`!code -full` to find your language's tag")
            else:
                await ctx.send("I don't see any code")
        except Exception as e:
            await utils.report(str(e), source="!code command", ctx=ctx)