aboutsummaryrefslogtreecommitdiffstats
path: root/bot/exts/fun/fun.py
blob: e7337cb69459c7106993a12c2b71c1fe750e896d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import json
import logging
import random
from collections.abc import Iterable
from pathlib import Path
from typing import Literal

import pyjokes
from discord import Embed
from discord.ext import commands
from discord.ext.commands import BadArgument, Cog, Context, clean_content

from bot.bot import Bot
from bot.constants import Client, Colours, Emojis
from bot.utils import helpers, messages

log = logging.getLogger(__name__)


def caesar_cipher(text: str, offset: int) -> Iterable[str]:
    """
    Implements a lazy Caesar Cipher algorithm.

    Encrypts a `text` given a specific integer `offset`. The sign
    of the `offset` dictates the direction in which it shifts to,
    with a negative value shifting to the left, and a positive
    value shifting to the right.
    """
    for char in text:
        if not char.isascii() or not char.isalpha() or char.isspace():
            yield char
            continue

        case_start = 65 if char.isupper() else 97
        true_offset = (ord(char) - case_start + offset) % 26

        yield chr(case_start + true_offset)


class Fun(Cog):
    """A collection of general commands for fun."""

    def __init__(self, bot: Bot):
        self.bot = bot
        self._caesar_cipher_embed = json.loads(Path("bot/resources/fun/caesar_info.json").read_text("UTF-8"))

    @staticmethod
    def _get_random_die() -> str:
        """Generate a random die emoji, ready to be sent on Discord."""
        die_name = f"dice_{random.randint(1, 6)}"
        return getattr(Emojis, die_name)

    @commands.command()
    async def roll(self, ctx: Context, num_rolls: int = 1) -> None:
        """Outputs a number of random dice emotes (up to 6)."""
        if 1 <= num_rolls <= 6:
            dice = " ".join(self._get_random_die() for _ in range(num_rolls))
            await ctx.send(dice)
        else:
            raise BadArgument(f"`{Client.prefix}roll` only supports between 1 and 6 rolls.")

    @commands.command(name="randomcase", aliases=("rcase", "randomcaps", "rcaps",))
    async def randomcase_command(self, ctx: Context, *, text: clean_content(fix_channel_mentions=True)) -> None:
        """Randomly converts the casing of a given `text`."""
        def conversion_func(text: str) -> str:
            """Randomly converts the casing of a given string."""
            return "".join(
                char.upper() if round(random.random()) else char.lower() for char in text
            )
        text, embed = await messages.get_text_and_embed(ctx, text)
        # Convert embed if it exists
        if embed is not None:
            embed = messages.convert_embed(conversion_func, embed)
        converted_text = conversion_func(text)
        converted_text = helpers.suppress_links(converted_text)
        # Don't put >>> if only embed present
        if converted_text:
            converted_text = f">>> {converted_text.lstrip('> ')}"
        await ctx.send(content=converted_text, embed=embed)

    @commands.group(name="caesarcipher", aliases=("caesar", "cc",))
    async def caesarcipher_group(self, ctx: Context) -> None:
        """
        Translates a message using the Caesar Cipher.

        See `decrypt`, `encrypt`, and `info` subcommands.
        """
        if ctx.invoked_subcommand is None:
            await ctx.invoke(self.bot.get_command("help"), "caesarcipher")

    @caesarcipher_group.command(name="info")
    async def caesarcipher_info(self, ctx: Context) -> None:
        """Information about the Caesar Cipher."""
        embed = Embed.from_dict(self._caesar_cipher_embed)
        embed.colour = Colours.dark_green

        await ctx.send(embed=embed)

    @staticmethod
    async def _caesar_cipher(ctx: Context, offset: int, msg: str, left_shift: bool = False) -> None:
        """
        Given a positive integer `offset`, translates and sends the given `msg`.

        Performs a right shift by default unless `left_shift` is specified as `True`.

        Also accepts a valid Discord Message ID or link.
        """
        if offset < 0:
            await ctx.send(":no_entry: Cannot use a negative offset.")
            return

        if left_shift:
            offset = -offset

        def conversion_func(text: str) -> str:
            """Encrypts the given string using the Caesar Cipher."""
            return "".join(caesar_cipher(text, offset))

        text, embed = await messages.get_text_and_embed(ctx, msg)

        if embed is not None:
            embed = messages.convert_embed(conversion_func, embed)

        converted_text = conversion_func(text)

        if converted_text:
            converted_text = f">>> {converted_text.lstrip('> ')}"

        await ctx.send(content=converted_text, embed=embed)

    @caesarcipher_group.command(name="encrypt", aliases=("rightshift", "rshift", "enc",))
    async def caesarcipher_encrypt(self, ctx: Context, offset: int, *, msg: str) -> None:
        """
        Given a positive integer `offset`, encrypt the given `msg`.

        Performs a right shift of the letters in the message.

        Also accepts a valid Discord Message ID or link.
        """
        await self._caesar_cipher(ctx, offset, msg, left_shift=False)

    @caesarcipher_group.command(name="decrypt", aliases=("leftshift", "lshift", "dec",))
    async def caesarcipher_decrypt(self, ctx: Context, offset: int, *, msg: str) -> None:
        """
        Given a positive integer `offset`, decrypt the given `msg`.

        Performs a left shift of the letters in the message.

        Also accepts a valid Discord Message ID or link.
        """
        await self._caesar_cipher(ctx, offset, msg, left_shift=True)

    @commands.command()
    async def joke(self, ctx: commands.Context, category: Literal["neutral", "chuck", "all"] = "all") -> None:
        """Retrieves a joke of the specified `category` from the pyjokes api."""
        joke = pyjokes.get_joke(category=category)
        await ctx.send(joke)


def setup(bot: Bot) -> None:
    """Load the Fun cog."""
    bot.add_cog(Fun(bot))