コード例 #1
0
    async def wolf(self, ctx):
        """ Query the Simple Wolfram|Alpha API """
        try:
            # removes the "!wolf" portion of the message
            message = parse.stripcommand(ctx.message.content)

            # Reject empty messages
            if message == "":
                await self.bot.say(
                    "You must pass in a question to get a response")
                return

            # Query the API and post its response
            async with aiohttp.ClientSession(headers=HEADERS) as session:
                async with session.get(
                        "http://api.wolframalpha.com/v1/result?appid=" +
                        credentials.tokens["WOLFRAMALPHA_APPID"] + "&i=" +
                        quote(message)) as resp:
                    if resp.status is 501:
                        await self.bot.say(
                            "WolframAlpha could not understand the question '{}' because {}"
                            .format(message, resp.reason))
                        return
                    data = await resp.content.read()
                    await self.bot.say(data.decode("utf-8"))
        except Exception as e:
            await utils.report(self.bot,
                               str(e),
                               source="wolf command",
                               ctx=ctx)
コード例 #2
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 stripBrackets(text):
            text = text.replace("[", " ").replace("]", "")
            return text

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

            maxdefinitions = 4

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

            # Query the API and post its response
            (ud_json, response) = await utils.get_json_with_get("http://api.urbandictionary.com/v0/define?term=" + quote(message))
            if response is not 200:
                await bot.say("There was an error processing your request. I apologize for the inconvenience.")
                return
            if len(ud_json["list"]) > 0:
                embed = Embed()
                ud_embed = Embed()
                ud_embed.set_footer(text="UrbanDictionary", icon_url="https://firebounty.com/image/635-urban-dictionary")
                counter = 0
                firstResult = ""
                while counter < len(ud_json["list"]) and counter <= maxdefinitions:
                    definition = ud_json["list"][counter]
                    if counter == 0:
                        firstResult = definition["word"]
                        ud_embed.title = utils.trimtolength(firstResult, 256).capitalize()
                    if definition["word"] == firstResult:
                        defText = definition["definition"].replace("*", "\\*")
                        exampleText = "**Example: " + definition["example"].replace("*", "\\*") + "**"
                        ud_embed.add_field(name=str(counter + 1),
                                             value=utils.trimtolength(stripBrackets(defText + "\n\n" + exampleText), 1024),
                                             inline=False)
                    counter += 1
                ud_embed.colour = EMBED_COLORS['ud']  # Make the embed white

                await self.bot.say(embed=ud_embed)
            else:
                await self.bot.say("I can't find any UrbanDictionary results for `" + message + "`")
        except Exception as e:
            await utils.report(self.bot, str(e), source="ud command", ctx=ctx)
コード例 #3
0
    async def picture(self, ctx):
        try:
            unsplash_icon = (
                'https://image.winudf.com/v2/image/Y29tLmFwcHlidWlsZGVyLmFmYXFsZW8xMDIuVW5zcG'
                +
                'xhc2hfaWNvbl8xNTMxMTA2MTg5XzA5OQ/icon.png?w=170&fakeurl=1&type=.png'
            )
            headers = {
                "User-Agent":
                "suitsBot Discord Bot - https://github.com/DWCamp",
                "Authorization":
                "Client-ID " + credentials.tokens["UNSPLASH_CLIENT_ID"],
                "Accept-Version":
                "v1"
            }

            # Parse command
            content = parse.stripcommand(ctx.message.content)

            # Query defaults to a picture of a snake
            if content == "":
                query = "snake"
            else:
                query = quote(content)

            # Get the image URL
            json = await utils.get_json_with_get(
                'https://api.unsplash.com/photos/random?query=' + query,
                headers=headers)
            author_url = json[0]['user']['links'][
                'html'] + "?utm_source=SuitsBot&utm_medium=referral"
            pic_embed = Embed().set_image(url=json[0]['urls']['full'])
            pic_embed.description = "Photo credit: " + author_url
            pic_embed.colour = EMBED_COLORS['picture']
            pic_embed.set_footer(
                icon_url=unsplash_icon,
                text=
                "https://unsplash.com/?utm_source=SuitsBot&utm_medium=referral"
            )
            await self.bot.say(embed=pic_embed)
        except Exception as e:
            await utils.report(self.bot,
                               str(e),
                               source="picture command",
                               ctx=ctx)
コード例 #4
0
    async def handle_rss_feed(self, feed, ctx):
        """
        The universal rss feed handler. Takes in an RSSFeed object
        then does all the magic
        :param feed: The RSSFeed
        :param ctx: The ctx object of the inciting message
        """
        try:
            message = parse.stripcommand(ctx.message.content)

            # Update feed
            feed.refresh_if_stale()

            # Show most recent episode
            if message == "":
                episode = feed.items[0]
                await self.bot.say(embed=feed.get_embed(episode))
                return

            # check for subcommand and parse it out
            subcommand = ""
            parameter = message
            if message[0] == "-":
                whitespace = utils.first_whitespace(message)
                if whitespace == -1:
                    subcommand = message[1:]
                    parameter = ""
                else:
                    subcommand = message[1:whitespace]
                    parameter = message[whitespace:].strip()

            # Teach the person how to use this thing
            if subcommand == "help":
                command_name = ctx.invoked_with
                title = f"!{command_name} - User Guide"
                description = f"Searches the RSS feed for {feed.title}"
                helpdict = {
                    f"!{command_name}": "Post the most recent item in the feed",
                    f"!{command_name} <word>": "Post the most recent item whose title contains the whole word <word>",
                    f"!{command_name} -help": "Posts this message",
                    f"!{command_name} -reg <regex>": "Perform a regular expression search for the most "
                                                     "recent item title matching <regex>",
                    f"!{command_name} -refresh": "Force the bot to refresh its cache"}
                thumbnail = feed.image if feed.image is not None else COMMAND_THUMBNAILS["rssfeed"]
                await self.bot.say(embed=utils.embedfromdict(helpdict,
                                                             title=title,
                                                             description=description,
                                                             thumbnail_url=thumbnail))
                return

            # Dump all the info about the feed
            if subcommand == "details":
                await self.bot.say(feed.to_string())
                return

            # Test an embed for a given feed
            if subcommand == "embed":
                await self.bot.say(embed=feed.get_embed(feed.items[0]))
                return

            # Test an embed for a given feed
            if subcommand == "image":
                embed = Embed()
                embed.set_image(url=feed.image)
                await self.bot.say(embed=embed)
                return

            # If some nerd like Kris or Pat wants to do regex search
            if subcommand == "reg":
                episode = feed.search(parameter, regex=True)
                if episode:
                    await self.bot.say(embed=feed.get_embed(episode))
                    return
                await self.bot.say(f"I couldn't find any results for the regex string `{parameter}`")

            # Force a refresh on the feed
            if subcommand == "refresh":
                feed.refresh()
                await self.bot.say(f"Alright, I have refreshed the feed `{feed.feed_id}`")
                return

            # Returns search results that the user can select
            if subcommand == "search":
                await self.bot.say("This has not been implemented yet :sad:")
                return

            # If there was a subcommand but it was unrecognized
            if subcommand != "":
                await self.bot.say(f"I'm sorry, I don't understand the subcommand `{subcommand}`. " +
                                   f"Please consult `-help` for more information")
                return

            # Search for the term
            episode = feed.search(parameter)
            if episode:
                await self.bot.say(embed=feed.get_embed(episode))
                return
            await self.bot.say(f"I couldn't find any results in the {feed.title} feed "
                               f"for the term `{parameter}` :worried:")

        except Exception as e:
            await utils.report(self.bot, str(e), source=f"handle_rss_feed() for '{feed.feed_id}'", ctx=ctx)