Skip to content

Commit

Permalink
✅ Handle cases efficiently when user avatar hash is None. Add method …
Browse files Browse the repository at this point in the history
…to return Discord default avatar url equivalent.
  • Loading branch information
weibeu committed Jun 2, 2020
1 parent f5be182 commit 1fc91d2
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion flask_discord/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@
]


__version__ = "0.1.51"
__version__ = "0.1.52"
2 changes: 2 additions & 0 deletions flask_discord/configs.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@


DISCORD_IMAGE_BASE_URL = "https://cdn.discordapp.com/"
DISCORD_EMBED_BASE_BASE_URL = "https://cdn.discordapp.com/"
DISCORD_IMAGE_FORMAT = "png"
DISCORD_ANIMATED_IMAGE_FORMAT = "gif"
DISCORD_USER_AVATAR_BASE_URL = DISCORD_IMAGE_BASE_URL + "avatars/{user_id}/{avatar_hash}.{format}"
DISCORD_DEFAULT_USER_AVATAR_BASE_URL = DISCORD_EMBED_BASE_BASE_URL + "embed/avatars/{modulo5}.png"
DISCORD_GUILD_ICON_BASE_URL = DISCORD_IMAGE_BASE_URL + "icons/{guild_id}/{icon_hash}.png"

DISCORD_USERS_CACHE_DEFAULT_MAX_LIMIT = 100
12 changes: 11 additions & 1 deletion flask_discord/models/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,25 @@ def name(self):
@property
def avatar_url(self):
"""A property returning direct URL to user's avatar."""
if not self.avatar_hash:
return
image_format = configs.DISCORD_ANIMATED_IMAGE_FORMAT \
if self.is_avatar_animated else configs.DISCORD_IMAGE_FORMAT
return configs.DISCORD_USER_AVATAR_BASE_URL.format(
user_id=self.id, avatar_hash=self.avatar_hash, format=image_format)

@property
def default_avatar_url(self):
"""A property which returns the default avatar URL as when user doesn't has any avatar set."""
return configs.DISCORD_DEFAULT_USER_AVATAR_BASE_URL.format(modulo5=int(self.discriminator) % 5)

@property
def is_avatar_animated(self):
"""A boolean representing if avatar of user is animated. Meaning user has GIF avatar."""
return self.avatar_hash.startswith("a_")
try:
return self.avatar_hash.startswith("a_")
except AttributeError:
return False

@classmethod
def fetch_from_api(cls, guilds=False, connections=False):
Expand Down
3 changes: 2 additions & 1 deletion tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ def me():
<head>
<title>{user.name}</title>
</head>
<body><img src='{user.avatar_url}' />
<body><img src='{user.avatar_url or user.default_avatar_url}' />
<p>Is avatar animated: {str(user.is_avatar_animated)}</p>
<a href={url_for("my_connections")}>Connections</a>
<br />
</body>
Expand Down

0 comments on commit 1fc91d2

Please sign in to comment.