public inbox for [email protected]
 help / color / mirror / Atom feed
From: Muhammad Rizki <[email protected]>
To: Ammar Faizi <[email protected]>
Cc: Muhammad Rizki <[email protected]>,
	Alviro Iskandar Setiawan <[email protected]>,
	GNU/Weeb Mailing List <[email protected]>
Subject: [PATCH v1 11/16] telegram: Implement the log message for catching errors
Date: Sat,  5 Nov 2022 01:09:21 +0700	[thread overview]
Message-ID: <[email protected]> (raw)
In-Reply-To: <[email protected]>

After created the BotLogger() class and initialized it to the
DaemonClient() attribute, implement it in the
telegram/mailer/listener.py to log it into the file if catching errors.

v4:
  - Add logger

v3:
  - Simplify try and except statement (comment from Muhammad Rizki).

v2:
  * no changes *

Signed-off-by: Muhammad Rizki <[email protected]>
---
 daemon/telegram/mailer/listener.py            | 44 ++++++++++++-------
 daemon/telegram/packages/client.py            |  4 +-
 daemon/telegram/packages/decorator.py         | 15 +++----
 .../packages/plugins/commands/scrape.py       | 10 ++++-
 4 files changed, 45 insertions(+), 28 deletions(-)

diff --git a/daemon/telegram/mailer/listener.py b/daemon/telegram/mailer/listener.py
index 46ccf93..6fb2e44 100644
--- a/daemon/telegram/mailer/listener.py
+++ b/daemon/telegram/mailer/listener.py
@@ -13,7 +13,6 @@ from atom import utils
 from enums import Platform
 import asyncio
 import re
-import traceback
 
 
 class BotMutexes():
@@ -29,6 +28,7 @@ class Bot():
 		self.scraper = scraper
 		self.mutexes = mutexes
 		self.db = client.db
+		self.logger = client.logger
 		self.isRunnerFixed = False
 
 
@@ -49,8 +49,8 @@ class Bot():
 		# TODO(ammarfaizi2):
 		# Ideally, we also want to log and report this situation.
 		#
-		print(f"Database error: {str(e)}")
-		print("Reconnecting to the database...")
+		self.logger.error(f"Database error: {str(e)}")
+		self.logger.info("Reconnecting to the database...")
 
 		#
 		# Don't do this too often to avoid reconnect burst.
@@ -63,14 +63,17 @@ class Bot():
 
 
 	async def __run(self):
-		print("[__run]: Running...")
+		self.logger.info("Running...")
 		try:
 			for url in self.db.get_atom_urls():
 				await self.__handle_atom_url(url)
 		except (OperationalError, DatabaseError) as e:
 			await self.handle_db_error(e)
 		except:
-			print(traceback.format_exc())
+			exc_str = utils.catch_err()
+			self.logger.warning(exc_str)
+			capt = "Unkown raw lore URL, see full details in the log file."
+			await self.client.send_log_file(capt)
 
 		if not self.isRunnerFixed:
 			self.isRunnerFixed = True
@@ -86,8 +89,13 @@ class Bot():
 	async def __handle_atom_url(self, url):
 		urls = await self.scraper.get_new_threads_urls(url)
 		for url in urls:
-			mail = await self.scraper.get_email_from_url(url)
-			await self.__handle_mail(url, mail)
+			try:
+				mail = await self.scraper.get_email_from_url(url)
+				await self.__handle_mail(url, mail)
+			except:
+				exc_str = utils.catch_err()
+				self.logger.warning(exc_str)
+				await self.client.send_log_file(url)
 
 
 	async def __handle_mail(self, url, mail):
@@ -104,23 +112,27 @@ class Bot():
 	# @__must_hold(self.mutexes.send_to_tg)
 	async def __send_mail(self, url, mail, tg_chat_id):
 		email_msg_id = utils.get_email_msg_id(mail)
+
 		if not email_msg_id:
-			#
-			# It doesn't have a Message-Id.
-			# A malformed email. Skip!
-			#
+			md = "email_msg_id not detected, skipping malformed email"
+			self.logger.debug(md)
 			return False
 
 		email_id = self.__mail_id_from_db(email_msg_id,
 							tg_chat_id)
 		if not email_id:
-			#
-			# Email has already been sent to Telegram.
-			# Skip!
-			#
+			md = f"Skipping {email_id} because has already been sent to Telegram"
+			self.logger.debug(md)
 			return False
 
-		text, files, is_patch = utils.create_template(mail, Platform.TELEGRAM)
+		try:
+			text, files, is_patch = utils.create_template(mail, Platform.TELEGRAM)
+		except:
+			exc_str = utils.catch_err()
+			self.logger.warning(exc_str)
+			await self.client.send_log_file(url)
+			return
+
 		reply_to = self.get_reply(mail, tg_chat_id)
 		url = str(re.sub(r"/raw$", "", url))
 
diff --git a/daemon/telegram/packages/client.py b/daemon/telegram/packages/client.py
index 6c83a5a..58195b9 100644
--- a/daemon/telegram/packages/client.py
+++ b/daemon/telegram/packages/client.py
@@ -46,7 +46,7 @@ class DaemonClient(Client):
 		url: str = None,
 		parse_mode: ParseMode = ParseMode.HTML
 	) -> Message:
-		print("[send_text_email]")
+		self.logger.debug("[send_text_email]")
 		return await self.send_message(
 			chat_id=chat_id,
 			text=text,
@@ -71,7 +71,7 @@ class DaemonClient(Client):
 		url: str = None,
 		parse_mode: ParseMode = ParseMode.HTML
 	) -> Message:
-		print("[send_patch_email]")
+		self.logger.debug("[send_patch_email]")
 		tmp, doc, caption, url = utils.prepare_patch(
 			mail, text, url, Platform.TELEGRAM
 		)
diff --git a/daemon/telegram/packages/decorator.py b/daemon/telegram/packages/decorator.py
index c7a5f02..153fa95 100644
--- a/daemon/telegram/packages/decorator.py
+++ b/daemon/telegram/packages/decorator.py
@@ -24,20 +24,19 @@ def handle_flood(func: Callable[[T], T]) -> Callable[[T], T]:
 			try:
 				return await func(*args)
 			except FloodWait as e:
-				#
-				# Aiee... we hit our limit.
-				# Let's slow down a bit.
-				#
-				_flood_exceptions(e)
-				print("[__handle_telegram_floodwait]: Woken up from flood wait...")
+				# Calling logger attr from the DaemonClient() class
+				logger = args[0].logger
+
+				_flood_exceptions(e, logger)
+				logger.info("Woken up from flood wait...")
 	return callback
 
 
-async def _flood_exceptions(e):
+async def _flood_exceptions(e, logger):
 	x = re.search(r"A wait of (\d+) seconds is required", str(e))
 	if not x:
 		raise e
 
 	n = int(x.group(1))
-	print(f"[____handle_telegram_floodwait]: Sleeping for {n} seconds due to Telegram limit")
+	logger.info(f"Sleeping for {n} seconds due to Telegram limit")
 	await asyncio.sleep(n)
diff --git a/daemon/telegram/packages/plugins/commands/scrape.py b/daemon/telegram/packages/plugins/commands/scrape.py
index 29cc8ad..f89727d 100644
--- a/daemon/telegram/packages/plugins/commands/scrape.py
+++ b/daemon/telegram/packages/plugins/commands/scrape.py
@@ -36,8 +36,14 @@ async def scrap_email(c: DaemonClient, m: Message):
 		return
 
 	s = Scraper()
-	mail = await s.get_email_from_url(url)
-	text, files, is_patch = utils.create_template(mail, Platform.TELEGRAM)
+
+	try:
+		mail = await s.get_email_from_url(url)
+		text, files, is_patch = utils.create_template(mail, Platform.TELEGRAM)
+	except:
+		exc_str = utils.catch_err()
+		c.logger.warning(exc_str)
+		await c.send_log_file(url)
 
 	if is_patch:
 		m = await c.send_patch_email(
-- 
Muhammad Rizki


  parent reply	other threads:[~2022-11-04 18:10 UTC|newest]

Thread overview: 45+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2022-11-04 18:09 [PATCH v1 00/16] Fix, improvement and implement a bot logger Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 01/16] discord: Fix typo on _flood_exception() Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 02/16] fix: utils: Fix the extract_list() utility function Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 03/16] utils: Change on max for TO/CC header list Muhammad Rizki
2022-11-07  0:55   ` Ammar Faizi
2022-11-07  1:08     ` Muhammad Rizki
2022-11-07  1:15       ` Ammar Faizi
2022-11-07  1:24         ` Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 04/16] utils: Back to use decode=True for the get_payload() Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 05/16] utils: Improve fix_utf8_char() Muhammad Rizki
2022-11-07  1:01   ` Ammar Faizi
2022-11-07  1:11     ` Muhammad Rizki
2022-11-07  1:26       ` Ammar Faizi
2022-11-07  1:27         ` Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 06/16] utils: Add catch_err() for the log message Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 07/16] logger: Initial work for the bot logger for future use Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 08/16] telegram: Use the created BotLogger() class Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 09/15] telegram: Add send_log_file() in the DaemonClient() Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 09/16] telegram: Add variable LOG_CHANNEL_ID declaration Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 10/16] telegram: Add send_log_file() in the DaemonClient() Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 10/15] telegram: Implement the log message for catching errors Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 11/15] discord: Add variable LOG_CHANNEL_ID declaration Muhammad Rizki
2022-11-04 18:09 ` Muhammad Rizki [this message]
2022-11-07  1:05   ` [PATCH v1 11/16] telegram: Implement the log message for catching errors Ammar Faizi
2022-11-07  1:13     ` Muhammad Rizki
2022-11-07  1:16       ` Ammar Faizi
2022-11-07  1:26         ` Muhammad Rizki
2022-11-07  1:31           ` Ammar Faizi
2022-11-07  1:34             ` Muhammad Rizki
2022-11-07  1:42               ` Ammar Faizi
2022-11-07  1:48                 ` Muhammad Rizki
2022-11-07  1:50                 ` Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 12/16] discord: Add variable LOG_CHANNEL_ID declaration Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 12/15] discord: Use the BotLogger() to the GWClient() Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 13/15] discord: Add send_log_file in " Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 13/16] discord: Use the BotLogger() to " Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 14/16] discord: Add send_log_file in " Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 14/15] discord: Implement the catch erros and logs Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 15/15] Remove some unused imports Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 15/16] discord: Implement the catch erros and logs Muhammad Rizki
2022-11-04 18:09 ` [PATCH v1 16/16] Remove some unused imports Muhammad Rizki
2022-11-07  1:10 ` [PATCH v1 00/16] Fix, improvement and implement a bot logger Ammar Faizi
2022-11-07  1:16   ` Muhammad Rizki
2022-11-07  1:28   ` Muhammad Rizki
2022-11-07  1:31     ` Ammar Faizi

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    [email protected] \
    [email protected] \
    [email protected] \
    [email protected] \
    [email protected] \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox