idiomatic upload_image with raise

This commit is contained in:
Andrea Spacca 2021-05-15 18:34:06 +02:00 committed by xPMo
parent 4e42b14e50
commit d553750941
1 changed files with 11 additions and 7 deletions

16
bot.py
View File

@ -27,6 +27,9 @@ from nio import AsyncClient, InviteEvent, JoinError, RoomMessageText, MatrixRoom
# Couple of custom exceptions # Couple of custom exceptions
class UploadFailed(Exception):
pass
class CommandRequiresAdmin(Exception): class CommandRequiresAdmin(Exception):
pass pass
@ -92,12 +95,12 @@ class Bot:
try: try:
matrix_uri, mimetype, w, h, size = self.uri_cache[cache_key] matrix_uri, mimetype, w, h, size = self.uri_cache[cache_key]
except KeyError: except KeyError:
res = await self.upload_image(url, blob, blob_content_type) try:
matrix_uri, mimetype, w, h, size = res res = await self.upload_image(url, blob, blob_content_type)
if matrix_uri: matrix_uri, mimetype, w, h, size = res
self.uri_cache[cache_key] = list(res) self.uri_cache[cache_key] = list(res)
self.save_settings() self.save_settings()
else: except UploadFailed:
return await self.send_text(room, "sorry. something went wrong uploading the image to matrix server :(") return await self.send_text(room, "sorry. something went wrong uploading the image to matrix server :(")
if not text and not blob: if not text and not blob:
@ -105,6 +108,7 @@ class Bot:
return await self.send_image(room, matrix_uri, text, mimetype, w, h, size) return await self.send_image(room, matrix_uri, text, mimetype, w, h, size)
# Helper function to upload a image from URL to homeserver. Use send_image() to actually send it to room. # Helper function to upload a image from URL to homeserver. Use send_image() to actually send it to room.
# Throws exception if upload fails
async def upload_image(self, url, blob=False, blob_content_type="image/png"): async def upload_image(self, url, blob=False, blob_content_type="image/png"):
""" """
@ -137,7 +141,7 @@ class Bot:
else: else:
self.logger.error("unable to request url: %s", url_response) self.logger.error("unable to request url: %s", url_response)
return None, None, None, None raise UploadFailed
if isinstance(response, UploadResponse): if isinstance(response, UploadResponse):
self.logger.info("uploaded file to %s", response.content_uri) self.logger.info("uploaded file to %s", response.content_uri)
@ -146,7 +150,7 @@ class Bot:
response: UploadError response: UploadError
self.logger.error("unable to upload file. msg: %s", response.message) self.logger.error("unable to upload file. msg: %s", response.message)
return None, None, None, None raise UploadFailed
async def send_text(self, room, body, msgtype="m.notice", bot_ignore=False): async def send_text(self, room, body, msgtype="m.notice", bot_ignore=False):
""" """