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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
|
import functools
import json
import logging
import random
from typing import Callable, Tuple, Union
from discord import Embed, Message
from discord.ext import commands
from discord.ext.commands import Bot, Cog, Context, MessageConverter
from bot import utils
from bot.constants import Colours, Emojis
log = logging.getLogger(__name__)
UWU_WORDS = {
"fi": "fwi",
"l": "w",
"r": "w",
"some": "sum",
"th": "d",
"thing": "fing",
"tho": "fo",
"you're": "yuw'we",
"your": "yur",
"you": "yuw",
}
class Fun(Cog):
"""A collection of general commands for fun."""
def __init__(self, bot: Bot) -> None:
self.bot = bot
@commands.command()
async def roll(self, ctx: Context, num_rolls: int = 1) -> None:
"""Outputs a number of random dice emotes (up to 6)."""
output = ""
if num_rolls > 6:
num_rolls = 6
elif num_rolls < 1:
output = ":no_entry: You must roll at least once."
for _ in range(num_rolls):
terning = f"terning{random.randint(1, 6)}"
output += getattr(Emojis, terning, '')
await ctx.send(output)
@commands.command(name="uwu", aliases=("uwuwize", "uwuify",))
async def uwu_command(self, ctx: Context, *, text: str) -> None:
"""
Converts a given `text` into it's uwu equivalent.
Also accepts a valid discord Message ID or link.
"""
conversion_func = functools.partial(
utils.replace_many, replacements=UWU_WORDS, ignore_case=True, match_case=True
)
text, embed = await Fun._get_text_and_embed(ctx, text)
# Convert embed if it exists
if embed is not None:
embed = Fun._convert_embed(conversion_func, embed)
converted_text = conversion_func(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.command(name="randomcase", aliases=("rcase", "randomcaps", "rcaps",))
async def randomcase_command(self, ctx: Context, *, text: str) -> None:
"""
Randomly converts the casing of a given `text`.
Also accepts a valid discord Message ID or link.
"""
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 Fun._get_text_and_embed(ctx, text)
# Convert embed if it exists
if embed is not None:
embed = Fun._convert_embed(conversion_func, embed)
converted_text = conversion_func(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",))
async def caesarcipher_group(self, ctx: Context) -> None:
"""
Translates a message using the Caesar Cipher.
See `info` and `translate` subcommands.
"""
if ctx.invoked_subcommand is None:
await self.bot.get_cog("Help").new_help(ctx, "caesarcipher")
@caesarcipher_group.command(name="info")
async def caesarcipher_info(self, ctx: Context) -> None:
"""Information about the Caesar Cipher."""
with open("bot\\resources\\evergreen\\caesar_info.json", "r") as f:
data = json.load(f)
embed = Embed(
title=data["title"],
description="".join(data["description"]),
colour=Colours.dark_green,
)
await ctx.send(embed=embed)
@caesarcipher_group.command(name="translate")
async def caesarcipher_translate(self, ctx: Context, offset: int, *, text: str) -> None:
"""
Given an integer `offset`, translate the given `text`.
A positive `offset` will cause the letters to shift right,
while a negative `offset` will cause the letters to shift left.
Also accepts a valid discord Message ID or link.
"""
def cipher_func(text: str) -> str:
"""Implements a lazy Caesar Cipher algorithm."""
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
yield chr((ord(char) - case_start + offset) % 26 + case_start)
def conversion_func(text: str) -> str:
"""Encrypts the given string using the Caesar Cipher."""
return "".join(cipher_func(text))
text, embed = await Fun._get_text_and_embed(ctx, text)
# Convert embed if it exists
if embed is not None:
embed = Fun._convert_embed(conversion_func, embed)
converted_text = conversion_func(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)
@staticmethod
async def _get_text_and_embed(ctx: Context, text: str) -> Tuple[str, Union[Embed, None]]:
"""
Attempts to extract the text and embed from a possible link to a discord Message.
Returns a tuple of:
str: If `text` is a valid discord Message, the contents of the message, else `text`.
Union[Embed, None]: The embed if found in the valid Message, else None
"""
embed = None
message = await Fun._get_discord_message(ctx, text)
if isinstance(message, Message):
text = message.content
# Take first embed because we can't send multiple embeds
if message.embeds:
embed = message.embeds[0]
return (text, embed)
@staticmethod
async def _get_discord_message(ctx: Context, text: str) -> Union[Message, str]:
"""
Attempts to convert a given `text` to a discord Message object and return it.
Conversion will succeed if given a discord Message ID or link.
Returns `text` if the conversion fails.
"""
try:
text = await MessageConverter().convert(ctx, text)
except commands.BadArgument:
log.debug(f"Input '{text:.20}...' is not a valid Discord Message")
return text
@staticmethod
def _convert_embed(func: Callable[[str, ], str], embed: Embed) -> Embed:
"""
Converts the text in an embed using a given conversion function, then return the embed.
Only modifies the following fields: title, description, footer, fields
"""
embed_dict = embed.to_dict()
embed_dict["title"] = func(embed_dict.get("title", ""))
embed_dict["description"] = func(embed_dict.get("description", ""))
if "footer" in embed_dict:
embed_dict["footer"]["text"] = func(embed_dict["footer"].get("text", ""))
if "fields" in embed_dict:
for field in embed_dict["fields"]:
field["name"] = func(field.get("name", ""))
field["value"] = func(field.get("value", ""))
return Embed.from_dict(embed_dict)
def setup(bot: commands.Bot) -> None:
"""Fun Cog load."""
bot.add_cog(Fun(bot))
|