Skip to content

Commit d210280

Browse files
nekealNMertsch
andauthored
Add animality API for for animals and as a fallback for existing ones (#368)
* Add animality API for for animals and as a fallback for existing ones * Improve typing and error handling --------- Co-authored-by: Niklas Mertsch <49114330+NMertsch@users.noreply.github.com>
1 parent 27c69ae commit d210280

5 files changed

Lines changed: 204 additions & 54 deletions

File tree

‎src/europython_discord/animals/clients.py‎

Lines changed: 44 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,50 @@
22

33
import logging
44
import time
5+
from dataclasses import dataclass
56

67
import aiohttp
78

89
_logger = logging.getLogger(__name__)
910

11+
12+
@dataclass
13+
class ImageResult:
14+
url: str
15+
source: str
16+
17+
1018
# APIs to fetch animals
1119
DOG_API_URL = "https://dog.ceo/api/breeds/image/random"
20+
DOG_SOURCE = "https://dog.ceo"
1221
CAT_API_URL = "https://cataas.com/cat/says/I%20love%20EuroPython"
22+
CAT_SOURCE = "https://cataas.com"
1323
DUCK_API_URL = "https://random-d.uk/api/randomimg"
24+
DUCK_SOURCE = "https://random-d.uk"
1425
FOX_API_URL = "https://randomfox.ca/floof/"
26+
FOX_SOURCE = "https://randomfox.ca/floof/"
27+
ANIMALITY_API_URL = "https://api.animality.xyz/img"
28+
ANIMALITY_SOURCE = "https://animality.xyz"
1529

1630

1731
class AnimalClient:
1832
def __init__(self) -> None:
1933
self._session = aiohttp.ClientSession()
2034

21-
async def fetch_image(self, animal: str) -> str | None:
35+
async def fetch_image(self, animal: str) -> ImageResult | None:
2236
"""Fetch a random image for the given animal."""
2337
if animal == "dog":
24-
return await self._fetch_dog()
38+
return await self._fetch_dog() or await self._fetch_animality(animal)
2539
if animal == "cat":
26-
return await self._fetch_cat()
40+
return await self._fetch_cat() or await self._fetch_animality(animal)
2741
if animal == "duck":
28-
return await self._fetch_duck()
42+
return await self._fetch_duck() or await self._fetch_animality(animal)
2943
if animal == "fox":
30-
return await self._fetch_fox()
31-
_logger.warning(f"Sadly we don't have {animal} pics yet :(")
32-
return None
44+
return await self._fetch_fox() or await self._fetch_animality(animal)
45+
46+
return await self._fetch_animality(animal)
3347

34-
async def _fetch_dog(self) -> str | None:
48+
async def _fetch_dog(self) -> ImageResult | None:
3549
try:
3650
async with self._session.get(DOG_API_URL) as response:
3751
response.raise_for_status()
@@ -40,9 +54,10 @@ async def _fetch_dog(self) -> str | None:
4054
_logger.exception("Failed to fetch dog image")
4155
return None
4256

43-
return data.get("message")
57+
url = data.get("message")
58+
return ImageResult(url, DOG_SOURCE) if url else None
4459

45-
async def _fetch_fox(self) -> str | None:
60+
async def _fetch_fox(self) -> ImageResult | None:
4661
try:
4762
async with self._session.get(FOX_API_URL) as response:
4863
response.raise_for_status()
@@ -51,13 +66,14 @@ async def _fetch_fox(self) -> str | None:
5166
_logger.exception("Failed to fetch fox image")
5267
return None
5368

54-
return data.get("image")
69+
url = data.get("image")
70+
return ImageResult(url, FOX_SOURCE) if url else None
5571

56-
async def _fetch_duck(self) -> str | None:
72+
async def _fetch_duck(self) -> ImageResult | None:
5773
timestamp = int(time.time() * 1000)
58-
return f"{DUCK_API_URL}?t={timestamp}"
74+
return ImageResult(f"{DUCK_API_URL}?t={timestamp}", DUCK_SOURCE)
5975

60-
async def _fetch_cat(self) -> str | None:
76+
async def _fetch_cat(self) -> ImageResult | None:
6177
params = {
6278
"position": "center",
6379
"font": "Impact",
@@ -77,7 +93,19 @@ async def _fetch_cat(self) -> str | None:
7793
url = data.get("url")
7894
if url:
7995
if url.startswith("http"):
80-
return url
81-
return f"https://cataas.com{url}"
96+
return ImageResult(url, CAT_SOURCE)
97+
return ImageResult(f"https://cataas.com{url}", CAT_SOURCE)
8298

8399
return None
100+
101+
async def _fetch_animality(self, animal: str) -> ImageResult | None:
102+
try:
103+
async with self._session.get(f"{ANIMALITY_API_URL}/{animal}") as response:
104+
response.raise_for_status()
105+
data = await response.json()
106+
except Exception:
107+
_logger.exception("Failed to fetch animality image for %s", animal)
108+
return None
109+
110+
url = data.get("image")
111+
return ImageResult(url, ANIMALITY_SOURCE) if url else None

‎src/europython_discord/animals/cog.py‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from discord.ext import commands
1010

1111
from europython_discord.animals.clients import AnimalClient
12-
from europython_discord.animals.config import AnimalsConfig
12+
from europython_discord.animals.config import AnimalKind, AnimalsConfig
1313

1414
_logger = logging.getLogger(__name__)
1515

@@ -29,45 +29,58 @@ def __init__(
2929
self._last_usage_timestamp_by_user_id: OrderedDict[int, float] = OrderedDict()
3030
_logger.info("Cog 'Animals' has been initialized")
3131

32-
async def _handle_animal_command(
33-
self, ctx: commands.Context, animal: str, source_url: str
34-
) -> None:
32+
async def handle_animal_command(self, ctx: commands.Context, animal: AnimalKind) -> None:
3533
if ctx.channel.name != self.config.channel_name:
3634
return
3735

3836
if self._is_rate_limited(ctx.author.id):
3937
return
4038

41-
image_url = await self._client.fetch_image(animal)
42-
if image_url is None:
43-
# Get the error messages for this specific animal
44-
animal_config = getattr(self.config, animal)
45-
message = random.choice(animal_config.error_messages) # noqa: S311
46-
await ctx.send(message)
39+
result = await self._client.fetch_image(animal)
40+
if result is not None:
41+
embed = discord.Embed()
42+
embed.description = f"Behold! A friendly {animal} appeared from {result.source}"
43+
embed.set_image(url=result.url)
44+
self._update_rate_limit_cache(ctx.author.id)
45+
await ctx.send(embed=embed)
4746
return
4847

49-
embed = discord.Embed()
50-
embed.description = f"Behold! A friendly {animal} appeared from {source_url}"
51-
embed.set_image(url=image_url)
52-
53-
self._update_rate_limit_cache(ctx.author.id)
54-
await ctx.send(embed=embed)
48+
await ctx.send(self._error_message_for(animal))
5549

5650
@commands.hybrid_command(name="dog", description="Get a random dog picture")
5751
async def dog_command(self, ctx: commands.Context) -> None:
58-
await self._handle_animal_command(ctx, "dog", "https://dog.ceo")
52+
await self.handle_animal_command(ctx, AnimalKind.DOG)
5953

6054
@commands.hybrid_command(name="cat", description="Get a random cat picture")
6155
async def cat_command(self, ctx: commands.Context) -> None:
62-
await self._handle_animal_command(ctx, "cat", "https://cataas.com")
56+
await self.handle_animal_command(ctx, AnimalKind.CAT)
6357

6458
@commands.hybrid_command(name="duck", description="Get a random duck picture")
6559
async def duck_command(self, ctx: commands.Context) -> None:
66-
await self._handle_animal_command(ctx, "duck", "https://random-d.uk")
60+
await self.handle_animal_command(ctx, AnimalKind.DUCK)
6761

6862
@commands.hybrid_command(name="fox", description="Get a random fox picture")
6963
async def fox_command(self, ctx: commands.Context) -> None:
70-
await self._handle_animal_command(ctx, "fox", "https://randomfox.ca/floof/")
64+
await self.handle_animal_command(ctx, AnimalKind.FOX)
65+
66+
async def cog_load(self) -> None:
67+
existing = {"dog", "cat", "duck", "fox"}
68+
for animal in AnimalKind:
69+
if animal in existing:
70+
continue
71+
cmd = _make_animality_command(animal, self)
72+
self.bot.add_command(cmd)
73+
74+
def _error_message_for(self, animal: AnimalKind) -> str:
75+
if animal_config := self.config.config_by_kind.get(animal):
76+
return random.choice(animal_config.error_messages) # noqa: S311
77+
78+
if not self.config.animality_error_messages:
79+
return f"Couldn't find a {animal} picture right now."
80+
plural = f"{animal}s" if animal != "fish" else "fish"
81+
return random.choice(self.config.animality_error_messages).format( # noqa: S311
82+
animal=animal, plural=plural
83+
)
7184

7285
def _is_rate_limited(self, user_id: int) -> bool:
7386
last_usage_timestamp = self._last_usage_timestamp_by_user_id.get(user_id, 0)
@@ -81,3 +94,11 @@ def _update_rate_limit_cache(self, user_id: int) -> None:
8194
self._last_usage_timestamp_by_user_id.move_to_end(user_id)
8295
if len(self._last_usage_timestamp_by_user_id) > _MAX_COOLDOWN_TRACKING:
8396
self._last_usage_timestamp_by_user_id.popitem(last=False)
97+
98+
99+
def _make_animality_command(name: AnimalKind, cog: AnimalsCog) -> commands.HybridCommand:
100+
@commands.hybrid_command(name=name, description=f"Get a random {name} picture")
101+
async def callback(ctx: commands.Context) -> None:
102+
await cog.handle_animal_command(ctx, name)
103+
104+
return callback

‎src/europython_discord/animals/config.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,37 @@
11
from __future__ import annotations
22

3+
from enum import StrEnum
4+
35
from pydantic import BaseModel
46

57

8+
class AnimalKind(StrEnum):
9+
CAT = "cat"
10+
DOG = "dog"
11+
BIRD = "bird"
12+
PANDA = "panda"
13+
REDPANDA = "redpanda"
14+
KOALA = "koala"
15+
FOX = "fox"
16+
WHALE = "whale"
17+
DOLPHIN = "dolphin"
18+
KANGAROO = "kangaroo"
19+
RABBIT = "rabbit"
20+
LION = "lion"
21+
BEAR = "bear"
22+
FROG = "frog"
23+
DUCK = "duck"
24+
PENGUIN = "penguin"
25+
AXOLOTL = "axolotl"
26+
CAPYBARA = "capybara"
27+
HEDGEHOG = "hedgehog"
28+
TURTLE = "turtle"
29+
NARWHAL = "narwhal"
30+
SQUIRREL = "squirrel"
31+
FISH = "fish"
32+
HORSE = "horse"
33+
34+
635
class AnimalSpecificConfig(BaseModel):
736
error_messages: list[str]
837

@@ -14,3 +43,18 @@ class AnimalsConfig(BaseModel):
1443
cat: AnimalSpecificConfig
1544
duck: AnimalSpecificConfig
1645
fox: AnimalSpecificConfig
46+
animality_error_messages: list[str] = [
47+
"The {plural} are on strike today! Try again later.",
48+
"A wild error appeared! The {animal} got away...",
49+
"The {animal} API is fetching a treat. Try again!",
50+
"404: {plural} not found. Have you checked the nearest zoo?",
51+
]
52+
53+
@property
54+
def config_by_kind(self) -> dict[AnimalKind, AnimalSpecificConfig]:
55+
return {
56+
AnimalKind.DOG: self.dog,
57+
AnimalKind.CAT: self.cat,
58+
AnimalKind.DUCK: self.duck,
59+
AnimalKind.FOX: self.fox,
60+
}

‎tests/animals/test_clients.py‎

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import pytest
44
from aiohttp import ClientSession
55

6-
from europython_discord.animals.clients import AnimalClient
6+
from europython_discord.animals.clients import AnimalClient, ImageResult
77

88

99
@pytest.fixture
@@ -24,9 +24,9 @@ async def test_fetch_dog(client: AnimalClient) -> None:
2424
mock_get.return_value.__aenter__.return_value = mock_response
2525

2626
with patch.object(ClientSession, "get", mock_get):
27-
url = await client.fetch_image("dog")
27+
result = await client.fetch_image("dog")
2828

29-
assert url == "https://images.dog.ceo/dog.jpg"
29+
assert result == ImageResult("https://images.dog.ceo/dog.jpg", "https://dog.ceo")
3030
mock_get.assert_called_once()
3131

3232

@@ -39,25 +39,27 @@ async def test_fetch_cat(client: AnimalClient) -> None:
3939
mock_get.return_value.__aenter__.return_value = mock_response
4040

4141
with patch.object(ClientSession, "get", mock_get):
42-
url = await client.fetch_image("cat")
42+
result = await client.fetch_image("cat")
4343

44-
assert url == "https://cataas.com/cat/mockid"
44+
assert result == ImageResult("https://cataas.com/cat/mockid", "https://cataas.com")
4545
mock_get.assert_called_once()
4646

4747
# Test absolute url
4848
mock_response.json = AsyncMock(return_value={"url": "https://example.com/cat.jpg"})
4949
with patch.object(ClientSession, "get", mock_get):
50-
url = await client.fetch_image("cat")
50+
result = await client.fetch_image("cat")
5151

52-
assert url == "https://example.com/cat.jpg"
52+
assert result == ImageResult("https://example.com/cat.jpg", "https://cataas.com")
5353

5454

5555
async def test_fetch_duck(client: AnimalClient) -> None:
5656
# Duck API just returns a formatted URL without HTTP requests in the client
5757
with patch("time.time", return_value=12345.0):
58-
url = await client.fetch_image("duck")
58+
result = await client.fetch_image("duck")
5959

60-
assert url == "https://random-d.uk/api/randomimg?t=12345000"
60+
assert result == ImageResult(
61+
"https://random-d.uk/api/randomimg?t=12345000", "https://random-d.uk"
62+
)
6163

6264

6365
async def test_fetch_fox(client: AnimalClient) -> None:
@@ -71,22 +73,49 @@ async def test_fetch_fox(client: AnimalClient) -> None:
7173
mock_get.return_value.__aenter__.return_value = mock_response
7274

7375
with patch.object(ClientSession, "get", mock_get):
74-
url = await client.fetch_image("fox")
76+
result = await client.fetch_image("fox")
7577

76-
assert url == "https://randomfox.ca/images/123.jpg"
78+
assert result == ImageResult(
79+
"https://randomfox.ca/images/123.jpg", "https://randomfox.ca/floof/"
80+
)
7781
mock_get.assert_called_once()
7882

7983

8084
async def test_fetch_unknown(client: AnimalClient) -> None:
81-
url = await client.fetch_image("unknown_animal")
82-
assert url is None
85+
with patch.object(client, "_fetch_animality", AsyncMock(return_value=None)):
86+
result = await client.fetch_image("unknown_animal")
87+
assert result is None
88+
89+
90+
async def test_fetch_animality_success(client: AnimalClient) -> None:
91+
mock_response = AsyncMock()
92+
mock_response.json = AsyncMock(return_value={"image": "https://cdn.animality.xyz/panda/1.png"})
93+
mock_response.raise_for_status = MagicMock()
94+
95+
mock_get = MagicMock()
96+
mock_get.return_value.__aenter__.return_value = mock_response
97+
98+
with patch.object(ClientSession, "get", mock_get):
99+
result = await client.fetch_image("panda")
100+
101+
assert result == ImageResult("https://cdn.animality.xyz/panda/1.png", "https://animality.xyz")
102+
103+
104+
async def test_fetch_animality_error(client: AnimalClient) -> None:
105+
mock_get = MagicMock()
106+
mock_get.return_value.__aenter__.side_effect = Exception("Animality Error")
107+
108+
with patch.object(ClientSession, "get", mock_get):
109+
result = await client.fetch_image("panda")
110+
111+
assert result is None
83112

84113

85114
async def test_fetch_error(client: AnimalClient) -> None:
86115
mock_get = MagicMock()
87116
mock_get.return_value.__aenter__.side_effect = Exception("API Error")
88117

89118
with patch.object(ClientSession, "get", mock_get):
90-
url = await client.fetch_image("dog")
119+
result = await client.fetch_image("dog")
91120

92-
assert url is None
121+
assert result is None

0 commit comments

Comments
 (0)