Skip to content

Commit 32f84d2

Browse files
committed
Improve get avatar from url method
1 parent 0915767 commit 32f84d2

1 file changed

Lines changed: 18 additions & 22 deletions

File tree

bot/controller.py

Lines changed: 18 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -221,20 +221,6 @@ def switch_account(self, token):
221221
def get_user_from_id(self, user_id):
222222
return self.bot.get_user(user_id)
223223

224-
def _download_avatar_async(self, url):
225-
def worker():
226-
try:
227-
response = requests.get(url, timeout=5)
228-
response.raise_for_status()
229-
230-
with self._avatar_lock:
231-
self._avatar_bytes_cache[url] = response.content
232-
233-
except Exception:
234-
pass
235-
236-
threading.Thread(target=worker, daemon=True).start()
237-
238224
def get_avatar_from_url(self, url, size=50, radius=5):
239225
try:
240226
if not url:
@@ -247,19 +233,25 @@ def get_avatar_from_url(self, url, size=50, radius=5):
247233
if cache_key in self._avatar_cache:
248234
return self._avatar_cache[cache_key]
249235

250-
content = self._avatar_bytes_cache.get(url)
251-
252-
# If bytes not cached → trigger async download and return
253-
if content is None:
254-
self._download_avatar_async(url)
255-
return None
236+
# Download or reuse bytes
237+
with self._avatar_lock:
238+
if url in self._avatar_bytes_cache:
239+
content = self._avatar_bytes_cache[url]
240+
else:
241+
response = requests.get(url, timeout=5)
242+
response.raise_for_status()
243+
content = response.content
244+
self._avatar_bytes_cache[url] = content
256245

257246
image = Image.open(BytesIO(content))
258247

248+
# --- HANDLE GIFS PROPERLY ---
259249
if getattr(image, "is_animated", False):
260-
image.seek(0)
250+
image.seek(0) # first frame only
251+
image = image.convert("RGBA")
252+
else:
253+
image = image.convert("RGBA")
261254

262-
image = image.convert("RGBA")
263255
image = resize_and_sharpen(image, (size, size))
264256

265257
if radius > 0:
@@ -276,6 +268,10 @@ def get_avatar_from_url(self, url, size=50, radius=5):
276268
print(f"Error processing avatar from URL {url}: {e}")
277269
return None
278270

271+
except Exception as e:
272+
print(f"Error processing avatar from URL {url}: {e}")
273+
return None
274+
279275
def get_avatar(self, size=50, radius=5):
280276
try:
281277
url = self.get_user().avatar.url if self.get_user() else None

0 commit comments

Comments
 (0)