-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathcog.py
258 lines (209 loc) · 9.34 KB
/
cog.py
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
Cog containing commands that call random APIs for fun things.
"""
import contextlib
import os
import random
import re
from datetime import datetime
from io import BytesIO
from random import randint
import aiohttp
import disnake
from disnake.ext import commands
import utils
from cogs.base import Base
from rubbergod import Rubbergod
from utils import cooldowns
from utils.errors import ApiError
from .messages_cz import MessagesCZ
fuchs_path = "cogs/fun/fuchs/"
fuchs_list = os.listdir(fuchs_path)
class Fun(Base, commands.Cog):
def __init__(self, bot: Rubbergod):
super().__init__()
self.bot = bot
def custom_footer(self, author, url) -> str:
return f"📩 {author} | {url} • {datetime.now().strftime('%d.%m.%Y %H:%M')}"
async def get_image(self, inter, url) -> tuple[BytesIO, str]:
async with aiohttp.ClientSession() as session:
# get random image url
async with session.get(url) as response:
if response.status != 200:
raise ApiError(response.status)
image = await response.json()
# get image url
if isinstance(image, list):
url = image[0]["url"]
else:
url = image.get("url")
if not url:
url = image.get("image")
# get image bytes
async with session.get(url) as response:
if response.status != 200:
raise ApiError(response.status)
file_name = url.split("/")[-1]
return BytesIO(await response.read()), file_name
async def get_fact(self, url, key) -> str:
async with aiohttp.ClientSession() as session:
with contextlib.suppress(OSError):
async with session.get(url) as response:
if response.status == 200:
fact_response_ = await response.json()
fact_response = fact_response_[key][0]
return fact_response
@cooldowns.default_cooldown
@commands.slash_command(name="cat", description=MessagesCZ.cat_brief)
async def cat(self, inter: disnake.ApplicationCommandInteraction):
"""Get random image of a cat"""
await inter.response.defer()
image_bytes, file_name = await self.get_image(inter, "https://api.thecatapi.com/v1/images/search")
image_file = disnake.File(image_bytes, filename=file_name)
fact_response: str = ""
if random.randint(0, 9) == 1:
fact_response = await self.get_fact("https://meowfacts.herokuapp.com/", "data")
image_embed = disnake.Embed(color=disnake.Color.blue())
image_embed.set_footer(text=self.custom_footer(inter.author, "thecatapi.com"))
image_embed.set_image(file=image_file)
embeds: list[disnake.Embed] = [image_embed]
if fact_response:
fact_embed = disnake.Embed(
title="Cat fact",
description=fact_response,
color=disnake.Color.blue(),
)
fact_embed.set_footer(text=self.custom_footer(inter.author, "thecatapi.com"))
embeds.append(fact_embed)
await inter.send(embeds=embeds)
@cooldowns.default_cooldown
@commands.slash_command(name="dog", description=MessagesCZ.dog_brief)
async def dog(self, inter: disnake.ApplicationCommandInteraction):
"""Get random image of a dog"""
await inter.response.defer()
image_bytes, file_name = await self.get_image(inter, "https://api.thedogapi.com/v1/images/search")
image_file = disnake.File(image_bytes, filename=file_name)
fact_response: str = ""
if random.randint(0, 9) == 1:
fact_response = await self.get_fact("https://dogapi.dog/api/facts/", "facts")
image_embed = disnake.Embed(color=disnake.Color.blue())
image_embed.set_footer(text=self.custom_footer(inter.author, "thedogapi.com"))
image_embed.set_image(file=image_file)
embeds: list[disnake.Embed] = [image_embed]
if fact_response:
fact_embed = disnake.Embed(
title="Dog fact",
description=fact_response,
color=disnake.Color.blue(),
)
fact_embed.set_footer(text=self.custom_footer(inter.author, "thedogapi.com"))
embeds.append(fact_embed)
await inter.send(embeds=embeds)
@cooldowns.default_cooldown
@commands.slash_command(name="fox", description=MessagesCZ.fox_brief)
async def fox(self, inter: disnake.ApplicationCommandInteraction):
"""Get random image of a fox"""
await inter.response.defer()
image_bytes, file_name = await self.get_image(inter, "https://randomfox.ca/floof/")
image_file = disnake.File(image_bytes, filename=file_name)
embed = disnake.Embed(color=disnake.Color.blue())
embed.set_footer(text=self.custom_footer(inter.author, "randomfox.ca"))
embed.set_image(file=image_file)
await inter.send(embed=embed)
@cooldowns.default_cooldown
@commands.slash_command(name="duck", description=MessagesCZ.duck_brief)
async def duck(self, inter: disnake.ApplicationCommandInteraction):
"""Get random image of a duck"""
await inter.response.defer()
image_bytes, file_name = await self.get_image(inter, "https://random-d.uk/api/v2/random")
image_file = disnake.File(image_bytes, filename=file_name)
embed = disnake.Embed(color=disnake.Color.blue())
embed.set_footer(text=self.custom_footer(inter.author, "random-d.uk"))
embed.set_image(file=image_file)
await inter.send(embed=embed)
@cooldowns.default_cooldown
@commands.slash_command(name="dadjoke", description=MessagesCZ.dadjoke_brief)
async def dadjoke(self, inter: disnake.ApplicationCommandInteraction, *, keyword=None):
"""Get random dad joke
Arguments
---------
keyword: search for a certain keyword in a joke
"""
await inter.response.defer()
if keyword is not None and ("&" in keyword or "?" in keyword):
await inter.send("I didn't find a joke like that.")
return
params: dict[str, str] = {"limit": "30"}
url: str = "https://icanhazdadjoke.com"
if keyword is not None:
params["term"] = keyword
url += "/search"
headers: dict[str, str] = {"Accept": "application/json"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status != 200:
raise ApiError(response.status)
fetched = await response.json()
if keyword is not None:
res = fetched["results"]
if len(res) == 0:
await inter.send("I didn't find a joke like that.")
return
result = random.choice(res)
result["joke"] = re.sub(
f"(\\b\\w*{keyword}\\w*\\b)",
r"**\1**",
result["joke"],
flags=re.IGNORECASE,
)
else:
result = fetched
embed = disnake.Embed(
title="Dadjoke",
description=result["joke"],
color=disnake.Color.blue(),
url="https://icanhazdadjoke.com/j/" + result["id"],
)
embed.set_footer(text=self.custom_footer(inter.author, "icanhazdadjoke.com"))
await inter.send(embed=embed)
@cooldowns.default_cooldown
@commands.slash_command(name="yo_mamajoke", description=MessagesCZ.yo_mamajoke_brief)
async def yo_mamajoke(self, inter: disnake.ApplicationCommandInteraction):
"""Get random Yo momma joke"""
await inter.response.defer()
async with aiohttp.ClientSession() as session:
async with session.get("https://www.yomama-jokes.com/api/v1/jokes/random/") as response:
if response.status != 200:
raise ApiError(response.status)
result = await response.json()
embed = disnake.Embed(
title="Yo mamajoke",
description=result["joke"],
color=disnake.Color.blue(),
url="https://www.yomama-jokes.com",
)
embed.set_footer(text=self.custom_footer(inter.author, "https://www.yomama-jokes.com/"))
await inter.send(embed=embed)
@cooldowns.default_cooldown
@commands.slash_command(name="fuchs", description=MessagesCZ.fuchs_brief)
async def fuchs(
self,
inter: disnake.ApplicationCommandInteraction,
hlaskaid: int = commands.Param(default=None, ge=1, le=len(fuchs_list)),
):
await inter.response.defer()
if len(fuchs_list) == 0:
inter.send(MessagesCZ.fuchs_no_reaction)
return
if hlaskaid is None:
index = randint(1, len(fuchs_list))
else:
index = hlaskaid
embed = disnake.Embed(
title="Fuchs reakce",
color=disnake.Color.blue(),
)
embed.set_image(url=f"attachment://{str(index)}.png")
utils.embed.add_author_footer(embed, inter.author, additional_text=[f" (hláškaid: #{str(index)})"])
with open(fuchs_path + str(index) + ".png", "rb") as fp:
await inter.send(embed=embed, file=disnake.File(fp=fp, filename=str(index) + ".png"))