Exemplo n.º 1
0
    async def debug(self, ctx: utils.CustomContext):
        """Base Command for the Debug cog."""

        description = list()
        description.append(
            f"This bot runs on Python {platform.python_version()} `[{platform.python_compiler()}]`\n")

        process = psutil.Process(os.getpid())
        memory_used = process.memory_info().rss / 1024 ** 2
        memory_info = psutil.virtual_memory()

        memory_fmt = (
            "The bot is currently using: "
            f"{memory_used:,.2f}/{memory_info.total / 1024 ** 2:,.2f} MB of memory"
        )
        description.append(memory_fmt)

        can_see_fmt = (
            "The bot can currently see: "
            f"{sum(g.member_count for g in self.bot.guilds):,} Members in {len(self.bot.guilds)} Guilds."
        )
        description.append(can_see_fmt)

        with ctx.embed() as embed:
            embed.description = "\n".join(description)
            await ctx.send(embed=embed)
Exemplo n.º 2
0
    async def do_zane(self, ctx: utils.CustomContext, what: str,
                      method: callable, gif_or_png: str):
        async with ctx.typing():
            get_image = await method(what)
            discord_file = discord.File(get_image,
                                        f"hellomagicman.{gif_or_png}")

            await ctx.send(file=discord_file)
Exemplo n.º 3
0
 async def wanted(self, ctx: utils.CustomContext, *, target: emoji_user):
     """Puts a given emoji, attachment or member on a wanted poster."""
     image = await self.get_image_url(ctx, target)
     async with ctx.timeit:
         img = await self.do_dagpi(image, "wanted")
         with ctx.embed() as e:
             e.set_image(url=f"attachment://{img.filename}")
             await ctx.send(file=img, embed=e)
def a4c_uninstall(**kwargs):
    graph = ctx.graph_mode()
    nodes = _get_all_nodes(ctx)
    instances = _get_all_nodes_instances(ctx)
    custom_context = CustomContext(ctx, instances, nodes)
    ctx.internal.send_workflow_event(event_type='a4c_workflow_started', message=build_pre_event(WfStartEvent('uninstall')))
    _a4c_uninstall(ctx, graph, custom_context)
    return graph.execute()
Exemplo n.º 5
0
 async def colours(self, ctx: utils.CustomContext, *, target: emoji_user):
     """Gets the 5 most relevant colours on a given emoji, attachment or member."""
     image = await self.get_image_url(ctx, target)
     async with ctx.timeit:
         img = await self.do_dagpi(image, "colors")
         with ctx.embed() as e:
             e.set_image(url=f"attachment://{img.filename}")
             await ctx.send(file=img, embed=e)
Exemplo n.º 6
0
def a4c_uninstall(**kwargs):
    graph = ctx.graph_mode()
    custom_context = CustomContext(ctx)
    ctx.internal.send_workflow_event(
        event_type='workflow_started',
        message="Starting A4C generated '{0}' workflow execution".format(ctx.workflow_id))
    _a4c_uninstall(ctx, graph, custom_context)
    return graph.execute()
Exemplo n.º 7
0
 async def alwayshasbeen(self, ctx: utils.CustomContext, *, text: Optional[str]):
     """It always has been..."""
     text = text or "I'm dumb and didn't put any text..."
     async with ctx.timeit:
         img = await Manipulation.alwayshasbeen(text)
         file = discord.File(img, "travis_bott_ahb.png")
         with ctx.embed() as e:
             e.set_image(url="attachment://travis_bott_ahb.png")
             await ctx.send(file=file, embed=e)
Exemplo n.º 8
0
 async def swirl(self, ctx: utils.CustomContext, amount: Optional[int], *, target: emoji_user):
     """Swirls a given attachment, emoji or member."""
     image = await self.get_image(ctx, target)
     async with ctx.timeit:
         img = await Manipulation.swirl(BytesIO(image), amount or 90)
         file = discord.File(img, "travis_bott_swirl.png")
         with ctx.embed() as e:
             e.set_image(url="attachment://travis_bott_swirl.png")
             await ctx.send(file=file, embed=e)
Exemplo n.º 9
0
 async def solarize(self, ctx: utils.CustomContext, *, target: emoji_user):
     """Applies a solarize effect to a given emoji, attachment or member."""
     image = await self.get_image(ctx, target)
     async with ctx.timeit:
         img = await Manipulation.solarize(image)
         file = discord.File(img, "travis_bott_solarize.png")
         with ctx.embed() as e:
             e.set_image(url="attachment://travis_bott_solarize.png")
             await ctx.send(file=file, embed=e)
Exemplo n.º 10
0
 async def facetime(self, ctx: utils.CustomContext, target: emoji_user):
     """Gives a neat facetime effect to a given emoji, attachment or member."""
     image = await self.get_image(ctx, target)
     async with ctx.timeit:
         thumbnail = await ctx.author.avatar_url_as(format="png").read()
         img = await Manipulation.facetime(image, thumbnail)
         file = discord.File(img, "travis_bott_ft.png")
         with ctx.embed() as e:
             e.set_image(url="attachment://travis_bott_ft.png")
             await ctx.send(file=file, embed=e)
Exemplo n.º 11
0
 async def brighten(self, ctx: utils.CustomContext, amount: Optional[int], *, target: emoji_user):
     """Applies a brighten effect to a given emoji, attachment or member."""
     amount = 250 if amount > 250 else amount
     image = await self.get_image(ctx, target)
     async with ctx.timeit:
         img = await Manipulation.brighten(image, amount or 50)
         file = discord.File(img, "travis_bott_brighten.png")
         with ctx.embed() as e:
             e.set_image(url="attachment://travis_bott_brighten.png")
             await ctx.send(file=file, embed=e)
Exemplo n.º 12
0
def a4c_heal(ctx, node_instance_id, diagnose_value='Not provided', **kwargs):
    """Reinstalls the whole subgraph of the system topology

    The subgraph consists of all the nodes that are hosted in the
    failing node's compute and the compute itself.
    Additionally it unlinks and establishes appropriate relationships

    :param ctx: cloudify context
    :param node_id: failing node's id
    :param diagnose_value: diagnosed reason of failure
    """

    ctx.logger.info("Starting 'heal' workflow on {0}, Diagnosis: {1}".format(
        node_instance_id, diagnose_value))
    failing_node = ctx.get_node_instance(node_instance_id)
    host_instance_id = failing_node._node_instance.host_id
    failing_node_host = ctx.get_node_instance(host_instance_id)
    node_id = failing_node_host.node_id
    subgraph_node_instances = failing_node_host.get_contained_subgraph()
    added_and_related = _get_all_nodes(ctx)
    try:
        graph = ctx.graph_mode()
        ctx.internal.send_workflow_event(event_type='a4c_workflow_started',
                                         message=build_pre_event(
                                             WfStartEvent('heal',
                                                          'uninstall')))
        custom_context = CustomContext(ctx, subgraph_node_instances,
                                       added_and_related)
        uninstall_host(ctx, graph, custom_context, node_id)
        graph.execute()
    except:
        ctx.logger.error('Uninstall while healing failed.')
    graph = ctx.internal.task_graph
    for task in graph.tasks_iter():
        graph.remove_task(task)
    ctx.internal.send_workflow_event(event_type='a4c_workflow_started',
                                     message=build_pre_event(
                                         WfStartEvent('heal', 'install')))
    custom_context = CustomContext(ctx, subgraph_node_instances,
                                   added_and_related)
    install_host(ctx, graph, custom_context, node_id)
    graph.execute()
Exemplo n.º 13
0
async def do_polaroid_image(ctx: utils.CustomContext, method: callable,
                            image: bytes, name: str, *args):
    async with ctx.timeit:
        async with ctx.typing():
            func = functools.partial(method, image)
            buffer = await ctx.bot.loop.run_in_executor(None, func, *args)

            embed = ctx.bot.embed(ctx)
            file = discord.File(fp=buffer, filename=f"{name}.png")
            embed.set_image(url=f"attachment://{name}.png")

            await ctx.send(file=file, embed=embed)
Exemplo n.º 14
0
    async def zip_all_emojis(self, ctx: utils.CustomContext):
        """Compress all of the servers emojis into one ZIP file."""

        await ctx.send("Alright, this may take a while!")

        async with ctx.timeit:
            async with ctx.typing():
                zip_file = await self._zip_all_guild_emojis(ctx.guild)
                file = discord.File(zip_file, "emojis.zip")

            await ctx.reply(
                "Hey, here's all the guilds emojis you called for!", file=file)
Exemplo n.º 15
0
    async def vote(self, ctx: utils.CustomContext):
        """Gives the link to vote for Travis"""

        fmt = (
            f"[Click here to vote for Travis Bott on top.gg](https://top.gg/bot/706530005169209386)\n"
            f"[Click here to vote for Travis Bott on discord.boats](https://discord.boats/bot/706530005169209386)\n"
            "If you genuinely enjoy the bot make sure to leave an honest review, thank you for using Travis Bott on top.gg."
        )

        with ctx.embed() as embed:
            embed.description = fmt
            await ctx.send(embed=embed)
Exemplo n.º 16
0
    async def polaroid(self,
                       ctx: utils.CustomContext,
                       user: discord.Member = None):
        """Puts someones profile picture in a polaroid.
        Powered by Dagpi."""

        async with ctx.timeit:
            async with ctx.typing():
                user = user or ctx.author
                img_file = await do_dagpi_stuff(ctx, user,
                                                ImageFeatures.polaroid())
                await ctx.send("*Look at this photograph*", file=img_file)
Exemplo n.º 17
0
    async def pixelate(self,
                       ctx: utils.CustomContext,
                       user: discord.Member = None):
        """Pixelates someones profile picture.
        Powered by Dagpi."""

        async with ctx.timeit:
            async with ctx.typing():
                user = user or ctx.author
                img_file = await do_dagpi_stuff(ctx, user,
                                                ImageFeatures.pixel())
                await ctx.send(file=img_file)
Exemplo n.º 18
0
    async def colours(self,
                      ctx: utils.CustomContext,
                      user: discord.Member = None):
        """Gives you the top 5 colours of your own or another persons profile picture.
        Powered by Dagpi."""

        async with ctx.timeit:
            async with ctx.typing():
                user = user or ctx.author
                img_file = await do_dagpi_stuff(ctx, user,
                                                ImageFeatures.colors())
                await ctx.send(f"Top 5 Colours for {user}", file=img_file)
Exemplo n.º 19
0
    async def wanted(self,
                     ctx: utils.CustomContext,
                     user: discord.Member = None):
        """Puts a members user avatar on a wanted poster.
        Powered by Dagpi."""

        async with ctx.timeit:
            async with ctx.typing():
                user = user or ctx.author
                img_file = await do_dagpi_stuff(ctx, user,
                                                ImageFeatures.wanted())
                await ctx.send(content=f"Hands up **{user.name}!**",
                               file=img_file)
Exemplo n.º 20
0
    async def screenshot(self, ctx: utils.CustomContext, url: str):
        """Screenshots a given URL.
        *Note: this is limited to NSFW channels.*"""

        async with ctx.typing():
            obj = await self.bot.loop.run_in_executor(
                None, BlockingFunctions.screenshot, url)
            embed = self.bot.embed(ctx)

            file = discord.File(obj, filename="scrape.png")
            embed.set_image(url="attachment://scrape.png")

            await ctx.send(file=file, embed=embed)
Exemplo n.º 21
0
    async def chroma(self, ctx: utils.CustomContext, what=None):
        """Adds a chroma gamma affect to a given image."""

        async with ctx.timeit:
            async with ctx.typing():
                image = await get_image(ctx, what)
                buffer = BytesIO(image)
                func = functools.partial(Manipulation.chroma, buffer)
                buffer = await self.bot.loop.run_in_executor(None, func)

                embed = self.bot.embed(ctx)
                file = discord.File(fp=buffer, filename="chroma.png")
                embed.set_image(url="attachment://chroma.png")

                await ctx.send(file=file, embed=embed)
Exemplo n.º 22
0
    async def privacy(self, ctx: utils.CustomContext):
        """Sends the bots privacy policy statement."""

        fmt = (
            "Travis Bott doesn't store much data, but here is what it *does* store and why:\n"
            "User ID's get stored for numerous things such as cookie clicker leaderboards, "
            "When someone gets muted in a server etc. Guild ID's get stored also for things "
            "such as configuration purposes e.g. prefixes and mute role ids. Message ID's get "
            "stored so we're able to corrolate them to roles for our verification command.\n"
            "If you have any questions or would like any of your data removed, contact kal#1806 "
            "via discord, either add them or via the support server.")

        with ctx.embed() as e:
            e.description = fmt
            await ctx.send(embed=e)
Exemplo n.º 23
0
    async def chatbot(self,
                      ctx: utils.CustomContext,
                      emotion: EmotionConverter = None):
        """Starts an interactive session with the chat bot.
        Type `cancel` to quit talking to the bot."""

        cb = async_cleverbot.Cleverbot(
            self.bot.settings["keys"]["chatbot_api"])
        not_ended = True

        emotion = emotion or async_cleverbot.Emotion.neutral

        await ctx.send(
            "I have started a chat bot session for you, type away! Type `cancel` to end the session."
        )

        while not_ended:
            try:
                message = await self.bot.wait_for(
                    "message",
                    timeout=30.0,
                    check=lambda m: m.author == ctx.author and m.channel == ctx
                    .channel)
            except asyncio.TimeoutError:
                await cb.close()
                not_ended = False
                return await ctx.send(
                    "You took a very long time to talk to the bot, so I ended the session."
                )
            else:
                async with ctx.typing():
                    if message.content.lower() == "cancel":
                        await cb.close()
                        not_ended = False
                        return await ctx.send(
                            "Good bye! \N{SLIGHTLY SMILING FACE}")
                    response = await cb.ask(message.content,
                                            ctx.author.id,
                                            emotion=emotion)

                    try:
                        text = utils.owoify_text(
                            response.text) if self.bot.config[
                                ctx.guild.id]["owoify"] else response.text
                    except (KeyError, AttributeError):
                        text = response.text

                    await message.reply(text)
Exemplo n.º 24
0
    async def solarize(self, ctx: utils.CustomContext,
                       what: typing.Optional[str]):
        """Solarizes your own or someone else's profile picture or even a given picture."""

        async with ctx.timeit:
            async with ctx.typing():
                what = await get_image(ctx, what)

                func = functools.partial(Manipulation.solarize_image, what)
                image_bytes = await self.bot.loop.run_in_executor(None, func)

                embed = self.bot.embed(ctx)
                file = discord.File(image_bytes, filename="solarize.png")
                embed.set_image(url="attachment://solarize.png")

                await ctx.send(file=file, embed=embed)
Exemplo n.º 25
0
    async def reddit(self, ctx: utils.CustomContext, subreddit: str):
        """Browse your favourite sub-reddit, gives a random submission from it."""

        async with ctx.typing():
            url = f"https://www.reddit.com/r/{subreddit}/random.json"
            async with self.bot.session.get(url) as resp:
                if resp.status != 200:
                    return await ctx.send(
                        "That subreddit doesn't exist or something severely wrong just happened."
                    )
                data = await resp.json()
                try:
                    data = data[0]["data"]["children"][0]["data"]
                except KeyError:
                    return await ctx.send(
                        "That subreddit doesn't exist or something severely wrong just happened."
                    )

                title, author, ups, downs, score, over_18, url, perma_link, subs, created_at = (
                    data["title"], data["author"], data["ups"], data["downs"],
                    data["score"], data["over_18"], data["url"],
                    data["permalink"], data["subreddit_subscribers"],
                    data["created_utc"])

                if over_18:
                    if not ctx.channel.is_nsfw():
                        return await ctx.send("Bonk! Go to horny jail.")

                embed = self.bot.embed(
                    ctx,
                    title=title,
                    url=f"https://www.reddit.com{perma_link}")

                embed.add_field(name="\N{UPWARDS BLACK ARROW}", value=ups)
                embed.add_field(name="\N{DOWNWARDS BLACK ARROW}", value=downs)

                embed.set_image(url=url)
                embed.set_author(name=f"Poster: {author}")
                embed.set_footer(
                    text=
                    f"Subreddit Subs: {subs} | Post score: {score} | Posted at"
                )
                embed.timestamp = datetime.datetime.fromtimestamp(created_at)

                await ctx.send(embed=embed)
Exemplo n.º 26
0
    async def facetime(self, ctx: utils.CustomContext, what: str):
        """Facetime with another user or even an image if you're really that lonely, I guess."""

        async with ctx.timeit:
            async with ctx.typing():
                author_image = await ctx.author.avatar_url_as(
                    static_format="png", size=1024).read()
                what = await get_image(ctx, what)

                func = functools.partial(Manipulation.facetime, what,
                                         author_image)
                image_bytes = await self.bot.loop.run_in_executor(None, func)

                embed = self.bot.embed(ctx)
                file = discord.File(image_bytes, filename="facetime.png")
                embed.set_image(url="attachment://facetime.png")

                await ctx.send(file=file, embed=embed)
Exemplo n.º 27
0
    async def dev_stats(self, ctx: utils.CustomContext):
        """Gives some stats on the bot."""

        p = pathlib.Path('./')
        cm = cr = fn = cl = ls = fc = 0
        for f in p.rglob('*.py'):
            if str(f).startswith("env"):
                continue
            fc += 1
            with f.open() as of:
                for l in of.readlines():
                    l = l.strip()
                    if l.startswith('class'):
                        cl += 1
                    if l.startswith('def'):
                        fn += 1
                    if l.startswith('async def'):
                        cr += 1
                    if '#' in l:
                        cm += 1
                    ls += 1

        code_count = (f"Files: {fc}\n"
                      f"Lines: {ls}\n"
                      f"Classes: {cl}\n"
                      f"Functions: {fn}\n"
                      f"Coroutines: {cr}\n"
                      f"Comments: {cm}\n")
        server_count = sum(1 for g in self.bot.guilds)
        user_count = sum(g.member_count for g in self.bot.guilds)
        command_count = sum(1 for cmd in self.bot.walk_commands())
        ping = round(self.bot.latency * 1000)
        uptime = utils.format_time(self.bot.start_time)

        fields = [["Server Count", server_count, True],
                  ["User Count", user_count, True],
                  ["Command Count", command_count, True],
                  ["Command Usage (last restart)", self.bot.cmd_usage, True],
                  ["Ping", ping, True], ["Uptime", uptime["precise"], True],
                  ["Code Count", f"```\n{code_count}```", False]]

        with ctx.embed() as embed:
            [embed.add_field(name=n, value=v, inline=i) for n, v, i in fields]
            await ctx.send(embed=embed)
Exemplo n.º 28
0
    async def brighten(self,
                       ctx: utils.CustomContext,
                       what: typing.Optional[str],
                       amount: int = 50):
        """Brightens a given picture or your own or even someone else's profile picture by a given amount"""

        async with ctx.timeit:
            async with ctx.typing():
                what = await get_image(ctx, what)

                func = functools.partial(Manipulation.brighten_image, what,
                                         amount)
                image_bytes = await self.bot.loop.run_in_executor(None, func)

                embed = self.bot.embed(ctx)
                file = discord.File(image_bytes, filename="brightened.png")
                embed.set_image(url="attachment://brightened.png")

                await ctx.send(file=file, embed=embed)
Exemplo n.º 29
0
    async def swirl(self,
                    ctx: utils.CustomContext,
                    degrees: typing.Optional[int] = 90,
                    what: str = None):
        """Adds a swirl affect to a given image."""

        async with ctx.timeit:
            async with ctx.typing():
                image = await get_image(ctx, what)
                buffer = BytesIO(image)

                func = functools.partial(Manipulation.swirl, buffer, degrees)
                buffer = await self.bot.loop.run_in_executor(None, func)

                embed = self.bot.embed(ctx)
                file = discord.File(fp=buffer, filename="swirl.png")
                embed.set_image(url="attachment://swirl.png")

                await ctx.send(file=file, embed=embed)
Exemplo n.º 30
0
    async def ping(self, ctx: utils.CustomContext):
        """Get the bots ping."""

        typing_start = time.perf_counter()
        await ctx.trigger_typing()
        typing_time_ms = ("Typing Latency",
                          (time.perf_counter() - typing_start) * 1000)

        db_start = time.perf_counter()
        await ctx.db.fetch("SELECT 1;")
        db_time_ms = ("DB Latency", (time.perf_counter() - db_start) * 1000)

        heartbeat_ms = ("Heartbeat Latency", self.bot.latency * 1000)

        with ctx.embed() as e:
            for typeof, result in typing_time_ms, db_time_ms, heartbeat_ms:
                e.add_field(name=typeof,
                            value=f"{result:,.2f} ms",
                            inline=False)

            await ctx.send(embed=e)