Skip to content

Commit 7ed3d5d

Browse files
solumathpeterdragun
authored andcommitted
add xkcd command
1 parent 1e220bf commit 7ed3d5d

File tree

4 files changed

+92
-12
lines changed

4 files changed

+92
-12
lines changed

cogs/README.md

+4
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ Cog containing commands that call random APIs for fun things.\
160160
- /dadjoke
161161
- /yo_mamajoke
162162
- /fuchs
163+
- /xkcd
164+
**Tasks:**
165+
166+
- xkcd_task_update
163167
---
164168

165169
### [Gif](gif/cog.py)

cogs/fun/cog.py

+54-12
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,21 @@
66
import os
77
import random
88
import re
9-
from datetime import datetime
9+
from datetime import datetime, time
1010
from io import BytesIO
1111
from random import randint
1212

1313
import aiohttp
1414
import disnake
15-
from disnake.ext import commands
15+
from disnake.ext import commands, tasks
1616

1717
import utils
1818
from cogs.base import Base
1919
from rubbergod import Rubbergod
2020
from utils import cooldowns
2121
from utils.errors import ApiError
2222

23+
from . import features
2324
from .messages_cz import MessagesCZ
2425

2526
fuchs_path = "cogs/fun/fuchs/"
@@ -30,9 +31,12 @@ class Fun(Base, commands.Cog):
3031
def __init__(self, bot: Rubbergod):
3132
super().__init__()
3233
self.bot = bot
34+
self.xkcd_url: str = "https://xkcd.com"
35+
self.total_xkcd_posts: int = 0
3336

34-
def custom_footer(self, author, url) -> str:
35-
return f"📩 {author} | {url}{datetime.now().strftime('%d.%m.%Y %H:%M')}"
37+
async def update_xkcd_posts(self):
38+
xkcd_post = await features.get_xkcd(self.bot.rubbergod_session, f"{self.xkcd_url}/info.0.json")
39+
self.total_xkcd_posts = xkcd_post["num"]
3640

3741
async def get_image(self, inter, url) -> tuple[BytesIO, str]:
3842
async with aiohttp.ClientSession() as session:
@@ -80,7 +84,7 @@ async def cat(self, inter: disnake.ApplicationCommandInteraction):
8084
fact_response = await self.get_fact("https://meowfacts.herokuapp.com/", "data")
8185

8286
image_embed = disnake.Embed(color=disnake.Color.blue())
83-
image_embed.set_footer(text=self.custom_footer(inter.author, "thecatapi.com"))
87+
image_embed.set_footer(text=features.custom_footer(inter.author, "thecatapi.com"))
8488
image_embed.set_image(file=image_file)
8589
embeds: list[disnake.Embed] = [image_embed]
8690

@@ -90,7 +94,7 @@ async def cat(self, inter: disnake.ApplicationCommandInteraction):
9094
description=fact_response,
9195
color=disnake.Color.blue(),
9296
)
93-
fact_embed.set_footer(text=self.custom_footer(inter.author, "thecatapi.com"))
97+
fact_embed.set_footer(text=features.custom_footer(inter.author, "thecatapi.com"))
9498
embeds.append(fact_embed)
9599

96100
await inter.send(embeds=embeds)
@@ -109,7 +113,7 @@ async def dog(self, inter: disnake.ApplicationCommandInteraction):
109113
fact_response = await self.get_fact("https://dogapi.dog/api/facts/", "facts")
110114

111115
image_embed = disnake.Embed(color=disnake.Color.blue())
112-
image_embed.set_footer(text=self.custom_footer(inter.author, "thedogapi.com"))
116+
image_embed.set_footer(text=features.custom_footer(inter.author, "thedogapi.com"))
113117
image_embed.set_image(file=image_file)
114118
embeds: list[disnake.Embed] = [image_embed]
115119

@@ -119,7 +123,7 @@ async def dog(self, inter: disnake.ApplicationCommandInteraction):
119123
description=fact_response,
120124
color=disnake.Color.blue(),
121125
)
122-
fact_embed.set_footer(text=self.custom_footer(inter.author, "thedogapi.com"))
126+
fact_embed.set_footer(text=features.custom_footer(inter.author, "thedogapi.com"))
123127
embeds.append(fact_embed)
124128

125129
await inter.send(embeds=embeds)
@@ -134,7 +138,7 @@ async def fox(self, inter: disnake.ApplicationCommandInteraction):
134138
image_file = disnake.File(image_bytes, filename=file_name)
135139

136140
embed = disnake.Embed(color=disnake.Color.blue())
137-
embed.set_footer(text=self.custom_footer(inter.author, "randomfox.ca"))
141+
embed.set_footer(text=features.custom_footer(inter.author, "randomfox.ca"))
138142
embed.set_image(file=image_file)
139143

140144
await inter.send(embed=embed)
@@ -149,7 +153,7 @@ async def duck(self, inter: disnake.ApplicationCommandInteraction):
149153
image_file = disnake.File(image_bytes, filename=file_name)
150154

151155
embed = disnake.Embed(color=disnake.Color.blue())
152-
embed.set_footer(text=self.custom_footer(inter.author, "random-d.uk"))
156+
embed.set_footer(text=features.custom_footer(inter.author, "random-d.uk"))
153157
embed.set_image(file=image_file)
154158

155159
await inter.send(embed=embed)
@@ -202,7 +206,7 @@ async def dadjoke(self, inter: disnake.ApplicationCommandInteraction, *, keyword
202206
color=disnake.Color.blue(),
203207
url="https://icanhazdadjoke.com/j/" + result["id"],
204208
)
205-
embed.set_footer(text=self.custom_footer(inter.author, "icanhazdadjoke.com"))
209+
embed.set_footer(text=features.custom_footer(inter.author, "icanhazdadjoke.com"))
206210

207211
await inter.send(embed=embed)
208212

@@ -224,7 +228,7 @@ async def yo_mamajoke(self, inter: disnake.ApplicationCommandInteraction):
224228
color=disnake.Color.blue(),
225229
url="https://www.yomama-jokes.com",
226230
)
227-
embed.set_footer(text=self.custom_footer(inter.author, "https://www.yomama-jokes.com/"))
231+
embed.set_footer(text=features.custom_footer(inter.author, "https://www.yomama-jokes.com/"))
228232

229233
await inter.send(embed=embed)
230234

@@ -256,3 +260,41 @@ async def fuchs(
256260

257261
with open(fuchs_path + str(index) + ".png", "rb") as fp:
258262
await inter.send(embed=embed, file=disnake.File(fp=fp, filename=str(index) + ".png"))
263+
264+
@cooldowns.default_cooldown
265+
@commands.slash_command(name="xkcd", description=MessagesCZ.xkcd_brief)
266+
async def xkcd(
267+
self,
268+
inter: disnake.ApplicationCommandInteraction,
269+
number: int = commands.Param(default=None, ge=1),
270+
latest: bool = False,
271+
):
272+
"""Get random XKCD comic.
273+
If `latest` is specified, get the latest comic.
274+
If `number` is specified, get the comic with that number.
275+
If `number` and `latest` is specified, get comic with specified number.
276+
"""
277+
await inter.response.defer()
278+
if not self.total_xkcd_posts:
279+
await self.update_xkcd_posts()
280+
281+
if number:
282+
url = f"{self.xkcd_url}/{number}"
283+
elif latest:
284+
url = f"{self.xkcd_url}"
285+
else:
286+
number = random.randint(1, self.total_xkcd_posts)
287+
url = f"{self.xkcd_url}/{number}"
288+
289+
xkcd_post = await features.get_xkcd(self.bot.rubbergod_session, f"{url}/info.0.json")
290+
embed = await features.create_xkcd_embed(xkcd_post, inter.author, url)
291+
await inter.send(embed=embed)
292+
293+
@tasks.loop(time=time(12, 0, tzinfo=utils.general.get_local_zone()))
294+
async def xkcd_task_update(self):
295+
"""Update number of xkcd comics every sunday"""
296+
if datetime.today().isoweekday() != 7:
297+
# update only on sunday
298+
return
299+
300+
await self.update_xkcd_posts()

cogs/fun/features.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import asyncio
2+
from datetime import datetime
3+
4+
import aiohttp
5+
import disnake
6+
7+
from utils.errors import ApiError
8+
9+
10+
def custom_footer(author: disnake.User, url: str) -> str:
11+
return f"📩 {author} | {url}{datetime.now().strftime('%d.%m.%Y %H:%M')}"
12+
13+
14+
async def get_xkcd(rubbergod_session: aiohttp.ClientSession, url: str) -> dict:
15+
try:
16+
async with rubbergod_session.get(url) as resp:
17+
if resp.status != 200:
18+
raise ApiError(resp.status)
19+
res = await resp.json()
20+
return res
21+
except (aiohttp.ClientConnectorError, asyncio.TimeoutError) as error:
22+
raise ApiError(str(error))
23+
24+
25+
async def create_xkcd_embed(xkcd_post: dict, user: disnake.User, xkcd_url: str) -> disnake.Embed:
26+
embed = disnake.Embed(
27+
title=xkcd_post["title"],
28+
description=xkcd_post["alt"],
29+
url=xkcd_url,
30+
)
31+
embed.set_image(url=xkcd_post["img"])
32+
embed.set_footer(text=custom_footer(user, xkcd_url))
33+
return embed

cogs/fun/messages_cz.py

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ class MessagesCZ(GlobalMessages):
1010
yo_mamajoke_brief = "Pošle náhodný Yo momma joke"
1111
fuchs_brief = "Pošle náhodnou fuchs reakci"
1212
fuchs_no_reaction = "Žádná fuchs reakce není k dispozici"
13+
xkcd_brief = "Pošle náhodný XKCD komiks"

0 commit comments

Comments
 (0)