Skip to content
Open

Dadjoke #1693

Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions bot/exts/fun/fun.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path
from typing import Literal

import aiohttp
import pyjokes
from discord import Embed
from discord.ext import commands
Expand Down Expand Up @@ -153,10 +154,28 @@ async def caesarcipher_decrypt(self, ctx: Context, offset: int, *, msg: str) ->
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)
async def joke(self, ctx: commands.Context, category: Literal["dad", "neutral", "chuck", "all"] = "all") -> None:
"""
Retrieves a joke of the specified `category` from the pyjokes api.

- dad uses icanhazdadjoke.
- others use pyjokes.
"""
if category == "dad":
async with aiohttp.ClientSession() as session, session.get(
"https://icanhazdadjoke.com",
headers={
"Accept":"application/json",
"User-Agent": "Sir-lancebot"
}) as res:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Reusing the bot's internal http_session is more efficient than creating a new one.
  • Including a contact method (e.g. the URL to the project) in the user agent is good practice.
Suggested change
async with aiohttp.ClientSession() as session, session.get(
"https://icanhazdadjoke.com",
headers={
"Accept":"application/json",
"User-Agent": "Sir-lancebot"
}) as res:
async with self.bot.http_session.get(
"https://icanhazdadjoke.com",
headers={
"Accept": "application/json",
"User-Agent": "Sir-Lancebot (https://github.com/python-discord/sir-lancebot)",
}
) as res:

if res.status == 200:
data = await res.json()
await ctx.send(data["joke"])
else:
await ctx.send("There is no dad joke now")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This path indicates something is wrong, it's probably a good idea to raise an error so it will be logged and we can look into it. res.raise_for_status() can be used to do this.

else:
joke = pyjokes.get_joke(category=category)
await ctx.send(joke)


async def setup(bot: Bot) -> None:
Expand Down