From f60bfdf0ca219c99140b02d2816f72f2330340f3 Mon Sep 17 00:00:00 2001 From: juacrumar Date: Wed, 1 Nov 2023 22:27:08 +0100 Subject: [PATCH] re-style the whole codebase --- src/pybliotecario/backend/__init__.py | 2 +- src/pybliotecario/backend/backend_test.py | 2 +- src/pybliotecario/backend/basic_backend.py | 6 ++-- src/pybliotecario/backend/facebook_util.py | 20 ++++------- src/pybliotecario/backend/telegram_util.py | 32 ++++++++--------- src/pybliotecario/components/arxiv_mod.py | 12 ++++--- .../components/component_core.py | 8 ++--- src/pybliotecario/components/dnd.py | 11 +++--- .../components/github_component.py | 24 +++++-------- src/pybliotecario/components/ip_lookup.py | 8 ++--- src/pybliotecario/components/photocol.py | 10 +++--- src/pybliotecario/components/pid.py | 25 ++++++------- src/pybliotecario/components/reactions.py | 5 +-- src/pybliotecario/components/repositories.py | 3 +- src/pybliotecario/components/scripts.py | 13 ++++--- src/pybliotecario/components/stocks.py | 10 ++---- src/pybliotecario/components/system.py | 1 + src/pybliotecario/components/weather.py | 5 ++- src/pybliotecario/components/wiki.py | 35 +++++++++---------- src/pybliotecario/core_loop.py | 3 +- src/pybliotecario/on_cmd_message.py | 2 +- src/pybliotecario/pybliotecario.py | 19 +++++----- 22 files changed, 121 insertions(+), 135 deletions(-) diff --git a/src/pybliotecario/backend/__init__.py b/src/pybliotecario/backend/__init__.py index 894a73e..2b20766 100644 --- a/src/pybliotecario/backend/__init__.py +++ b/src/pybliotecario/backend/__init__.py @@ -1,3 +1,3 @@ -from .telegram_util import TelegramUtil from .backend_test import TestUtil from .facebook_util import FacebookUtil +from .telegram_util import TelegramUtil diff --git a/src/pybliotecario/backend/backend_test.py b/src/pybliotecario/backend/backend_test.py index 4888411..af0d727 100644 --- a/src/pybliotecario/backend/backend_test.py +++ b/src/pybliotecario/backend/backend_test.py @@ -3,8 +3,8 @@ without communication with any service """ -import pathlib from datetime import datetime +import pathlib from pybliotecario.backend.telegram_util import TelegramMessage diff --git a/src/pybliotecario/backend/basic_backend.py b/src/pybliotecario/backend/basic_backend.py index 1e302b3..8bb001a 100644 --- a/src/pybliotecario/backend/basic_backend.py +++ b/src/pybliotecario/backend/basic_backend.py @@ -8,9 +8,9 @@ """ from abc import ABC, abstractmethod +import json import logging import urllib -import json logger = logging.getLogger(__name__) @@ -212,8 +212,8 @@ def send_file(self, filepath, chat): """Sends a file""" logger.error("This backend does not implement sending files") - def download_file(self, file_id, file_name): + def download_file(self, file_id, file_path): """Downloads a file using urllib. Understands file_id as the url """ - return urllib.request.urlretrieve(file_id, file_name) + return urllib.request.urlretrieve(file_id, file_path) diff --git a/src/pybliotecario/backend/facebook_util.py b/src/pybliotecario/backend/facebook_util.py index 04f3ff0..65c2f93 100644 --- a/src/pybliotecario/backend/facebook_util.py +++ b/src/pybliotecario/backend/facebook_util.py @@ -16,10 +16,12 @@ """ import json -import pathlib import logging +import pathlib + import requests -from pybliotecario.backend.basic_backend import Message, Backend + +from pybliotecario.backend.basic_backend import Backend, Message _HAS_FLASK = True try: @@ -162,12 +164,7 @@ def send_image(self, img_path, chat): payload = { "recipient": json.dumps({"id": chat}), "message": json.dumps( - { - "attachment": { - "type": "image", - "payload": {"is_reusable": True}, - } - } + {"attachment": {"type": "image", "payload": {"is_reusable": True}}} ), "filedata": (img.stem, img.read_bytes(), f"image/{img.suffix[1:]}"), } @@ -179,12 +176,7 @@ def send_file(self, filepath, chat): payload = { "recipient": json.dumps({"id": chat}), "message": json.dumps( - { - "attachment": { - "type": "file", - "payload": {"is_reusable": True}, - } - } + {"attachment": {"type": "file", "payload": {"is_reusable": True}}} ), "filedata": (fff.name, fff.read_bytes()), } diff --git a/src/pybliotecario/backend/telegram_util.py b/src/pybliotecario/backend/telegram_util.py index 9cb97d5..1843113 100644 --- a/src/pybliotecario/backend/telegram_util.py +++ b/src/pybliotecario/backend/telegram_util.py @@ -4,12 +4,13 @@ """ import json -import os.path -import urllib import logging -import requests from time import sleep -from pybliotecario.backend.basic_backend import Message, Backend +import urllib + +import requests + +from pybliotecario.backend.basic_backend import Backend, Message TELEGRAM_URL = "https://api.telegram.org/" @@ -21,7 +22,7 @@ def log_request(status_code, reason, content): """Log the status of the send requests""" - result = "Request sent, status code: {0} - {1}: {2}".format(status_code, reason, content) + result = f"Request sent, status code: {status_code} - {reason}: {content}" logger.info(result) @@ -56,7 +57,8 @@ def _parse_update(self, update): # Now get the chat data and id chat_data = message["chat"] self._chat_id = chat_data["id"] - # TODO test this part of the parser as this 'from' was a legacy thing at some point + # I believe from and chat_data are only different when using a group + # but the pybliotecario has not really been tested (or used) in groups... from_data = message.get("from", chat_data) # Populate the user (in the list, last has more priority) @@ -109,8 +111,8 @@ def __init__(self, TOKEN, debug=False, timeout=300): self.debug = debug self.timeout = timeout # Build app the API urls - base_URL = TELEGRAM_URL + "bot{}/".format(TOKEN) - self.base_fileURL = TELEGRAM_URL + "file/bot{}/".format(TOKEN) + base_URL = TELEGRAM_URL + f"bot{TOKEN}/" + self.base_fileURL = TELEGRAM_URL + f"file/bot{TOKEN}/" self.send_msg = base_URL + "sendMessage" self.send_img = base_URL + "sendPhoto" self.send_doc = base_URL + "sendDocument" @@ -205,26 +207,24 @@ def send_message(self, text, chat, markdown=False, **kwargs): text = urllib.parse.quote_plus(text) url = f"{self.send_msg}?text={text}&chat_id={chat}" if markdown: - url += f"&parse_mode=markdown" + url += "&parse_mode=markdown" content = self.__make_request(url) # Sometimes, when using markdown, the update might fail if markdown and not json.loads(content).get("ok"): # If that's the case, try to resend without md - return self.send_message(text, chat, **kwargs) + self.send_message(text, chat, **kwargs) def send_image(self, img_path, chat): """Send an image to a given chat""" data = {"chat_id": chat} - img = open(img_path, "rb") - files = {"photo": ("picture.jpg", img)} # Here, the "rb" thing + with open(img_path, "rb") as img: + files = {"photo": ("picture.jpg", img)} # Here, the "rb" thing blabla = requests.post(self.send_img, data=data, files=files) log_request(blabla.status_code, blabla.reason, blabla.content) def send_file(self, filepath, chat): data = {"chat_id": chat} - file_stream = open(filepath, "rb") - doc_name = os.path.basename(filepath) - files = {"document": (doc_name, file_stream)} + files = {"document": (filepath.name, filepath.open("rb"))} blabla = requests.post(self.send_doc, data=data, files=files) log_request(blabla.status_code, blabla.reason, blabla.content) @@ -243,8 +243,8 @@ def download_file(self, file_id, file_path): if not file_url: return None n = 0 + # If the file already exists, iterate it by adding a nX while file_path.exists(): - # If the file already exist, iterate it new_name = f"n{n}-{file_path.name}" file_path = file_path.parent / new_name n += 1 diff --git a/src/pybliotecario/components/arxiv_mod.py b/src/pybliotecario/components/arxiv_mod.py index ba02e36..7b3ad7d 100644 --- a/src/pybliotecario/components/arxiv_mod.py +++ b/src/pybliotecario/components/arxiv_mod.py @@ -3,10 +3,12 @@ update notifications and quick-querying from the Telegram app """ -import os -import logging from datetime import datetime, timedelta, timezone +import logging +import os + import arxiv + from pybliotecario.components.component_core import Component logger = logging.getLogger(__name__) @@ -117,7 +119,7 @@ def arxiv_recent_filtered(categories, filter_dict, abstract=False, max_authors=5 if n_int > 0: line += f"{n_int} interesting ones:\n" else: - line += f"(nothing to be highlighted)." + line += "(nothing to be highlighted)." for paper in results: paper_authors = paper.authors if len(paper_authors) > max_authors: @@ -137,7 +139,6 @@ def arxiv_query_info(arxiv_id_raw): """ arxiv_id = url_to_id(arxiv_id_raw) paper = next(arxiv.Search(id_list=[arxiv_id]).results()) - title = paper.title authors = [str(i) for i in paper.authors] abstract = paper.summary.replace("\n", " ") msg = f""" > {arxiv_id} @@ -224,9 +225,10 @@ def telegram_message(self, msg): if __name__ == "__main__": - from pybliotecario.pybliotecario import logger_setup import tempfile + from pybliotecario.pybliotecario import logger_setup + logger_setup(tempfile.TemporaryFile(), debug=True) logger.info("Testing the arxiv component") logger.info("Query a category") diff --git a/src/pybliotecario/components/component_core.py b/src/pybliotecario/components/component_core.py index 9be92f4..45b07b8 100644 --- a/src/pybliotecario/components/component_core.py +++ b/src/pybliotecario/components/component_core.py @@ -11,9 +11,9 @@ the class Component will just pass the text of the msg (or the command) to the `act_on_command` or `act_on_message` methods. """ +import logging import os import sys -import logging log = logging.getLogger(__name__) @@ -90,7 +90,7 @@ def help_msg(cls): return cls.help_text else: name = cls.whoamI() - help_str = "Help msg for {0} not implemented".format(name) + help_str = f"Help msg for {name} not implemented" return help_str @classmethod @@ -151,7 +151,7 @@ def send_img(self, imgpath, chat_id=None, delete=False): if chat_id is None: chat_id = self.interaction_chat if not os.path.isfile(imgpath): - self.send_msg("ERROR: failed to send {0}".format(imgpath), chat_id) + self.send_msg(f"ERROR: failed to send {imgpath}", chat_id) self.telegram.send_image(imgpath, chat_id) if delete: os.remove(imgpath) @@ -164,7 +164,7 @@ def send_file(self, filepath, chat_id=None, delete=False): if chat_id is None: chat_id = self.interaction_chat if not os.path.isfile(filepath): - self.send_msg("ERROR: failed to send {0}".format(filepath), chat_id) + self.send_msg(f"ERROR: failed to send {filepath}", chat_id) self.telegram.send_file(filepath, chat_id) if delete: os.remove(filepath) diff --git a/src/pybliotecario/components/dnd.py b/src/pybliotecario/components/dnd.py index 717d656..aaa3879 100644 --- a/src/pybliotecario/components/dnd.py +++ b/src/pybliotecario/components/dnd.py @@ -1,9 +1,10 @@ """ Module implementing some functions useful for playing DnD over the internet """ -import re import logging from random import randint +import re + from pybliotecario.components.component_core import Component log = logging.getLogger(__name__) @@ -27,7 +28,7 @@ def parse_roll(text): # Now get all the modifiers (if any) nindex = re_pm.search(modifiers) if nindex: - mod = modifiers[nindex.start():] + mod = modifiers[nindex.start() :] dice = text.partition(mod)[0] else: mod = "" @@ -71,7 +72,7 @@ def roll_dice(text): # Now sum everything together and add any possible modifiers final_result = sum(result) - final_str = " + ".join(["({0})".format(i) for i in result]) + final_str = " + ".join([f"({i})" for i in result]) # Evaluate the modifiers with ast if mod.strip(): @@ -80,7 +81,7 @@ def roll_dice(text): final_result += int(i) mod = " ".join(modifiers) # And now put all together - final_str += " {0} = {1}".format(mod, final_result) + final_str += f"{mod} = {final_result}" return final_str @@ -105,5 +106,5 @@ def telegram_message(self, msg): # Compute the result in the form of a string roll_result = roll_dice(roll_cmd) # Write the answer - answer = "{0} rolled{1}:\n{2}".format(username, roll_text, roll_result) + answer = f"{username} rolled{roll_text}:\n{roll_result}" self.send_msg(answer) diff --git a/src/pybliotecario/components/github_component.py b/src/pybliotecario/components/github_component.py index 03fa28b..7b301a9 100644 --- a/src/pybliotecario/components/github_component.py +++ b/src/pybliotecario/components/github_component.py @@ -6,10 +6,11 @@ and follow the instructions """ import datetime +import logging + import github as pygithub from pybliotecario.components.component_core import Component -import logging log = logging.getLogger(__name__) @@ -48,12 +49,7 @@ def configure_me(cls): hours = int(input(" > ")) except ValueError: print("Only integer numbers accepted") - dict_out = { - cls.key_name: { - "token": access_token, - "since_hours": hours, - } - } + dict_out = {cls.key_name: {"token": access_token, "since_hours": hours}} return dict_out def _check_issues(self, repo_name): @@ -72,8 +68,7 @@ def _check_issues(self, repo_name): titles.append(f" > {pr}#{issue.number}: [{issue.title}]({url})") if titles: self.send_msg( - f"New github issues/PR in {repo_name}: \n" + "\n".join(titles), - markdown=True, + f"New github issues/PR in {repo_name}: \n" + "\n".join(titles), markdown=True ) def cmdline_command(self, args): @@ -82,21 +77,18 @@ def cmdline_command(self, args): if __name__ == "__main__": + import configparser from pathlib import Path import tempfile - import configparser - from pybliotecario.pybliotecario import logger_setup, main + from pybliotecario.backend import TestUtil + from pybliotecario.pybliotecario import logger_setup, main tmpdir = Path(tempfile.mkdtemp()) tmptxt = tmpdir / "text.txt" config = configparser.ConfigParser() - config["DEFAULT"] = { - "main_folder": tmpdir, - "token": "AAAaaa123", - "chat_id": 453, - } + config["DEFAULT"] = {"main_folder": tmpdir, "token": "AAAaaa123", "chat_id": 453} config["GITHUB"] = {"token": "", "since_hours": 5} logger_setup(tmpdir / "log.txt", debug=True) diff --git a/src/pybliotecario/components/ip_lookup.py b/src/pybliotecario/components/ip_lookup.py index ad64576..0a45b30 100644 --- a/src/pybliotecario/components/ip_lookup.py +++ b/src/pybliotecario/components/ip_lookup.py @@ -1,8 +1,8 @@ """ Server-helper function to look up the current IP of the program """ +import logging import urllib.request -from pybliotecario.components.component_core import Component -import logging +from pybliotecario.components.component_core import Component log = logging.getLogger(__name__) @@ -36,8 +36,8 @@ def cmdline_command(self, args): my_ip = ip_lookup() # Then append it to the text and send it to Telegram message_text = " ".join(args.message) - message = "{0} {1}".format(message_text, my_ip) + message = f"{message_text} {my_ip}" self.telegram.send_message(message, self.chat_id) - log.info("IP: {0}".format(my_ip)) + log.info(f"IP: {my_ip}") # Finally, consume the text args.message = None diff --git a/src/pybliotecario/components/photocol.py b/src/pybliotecario/components/photocol.py index bb9200f..f7a871e 100644 --- a/src/pybliotecario/components/photocol.py +++ b/src/pybliotecario/components/photocol.py @@ -4,12 +4,14 @@ It's a companion to https://github.com/scarlehoff/websito/blob/master/views/foto.pug """ -from pathlib import Path from datetime import datetime -import uuid import json import logging +from pathlib import Path +import uuid + from PIL import Image + from pybliotecario.components.component_core import Component log = logging.getLogger(__name__) @@ -46,7 +48,7 @@ def _save_picture(self, file_id): aratio = image.width / image.height # Keep a resemblance of the original aspect ratio size = 240 - thumb_size = (size, int(size/aratio)) + thumb_size = (size, int(size / aratio)) image.thumbnail(thumb_size) image.save((self._photofol / "thumbnail" / unique_name).with_suffix(".jpg")) except IOError: @@ -86,7 +88,7 @@ def _remove_from_db(self, uuid): if success: # Create a removed folder to put the picture in removed_folder = self._photofol / "removed" - removed_folder.mkdir(exist_ok = True) + removed_folder.mkdir(exist_ok=True) # Move both picture and thumbnail to removed foto_path = self._photofol / test diff --git a/src/pybliotecario/components/pid.py b/src/pybliotecario/components/pid.py index 28c0336..32b92ca 100644 --- a/src/pybliotecario/components/pid.py +++ b/src/pybliotecario/components/pid.py @@ -5,10 +5,11 @@ an active process """ +import logging + import psutil -from pybliotecario.components.component_core import Component -import logging +from pybliotecario.components.component_core import Component logger = logging.getLogger(__name__) @@ -52,17 +53,17 @@ def is_it_alive(data): cmdline = proc.cmdline() for info in cmdline: if data in info: - matches.append("PID: {0}, {1}".format(proc.pid, " ".join(cmdline))) + command_str = " ".join(cmdline) + matches.append(f"PID: {proc.pid}, {command_str}") alive = True if alive: - msg = "{0} is alive".format(data) + msg = f"{data} is alive" if matches: - msg += "\nI found the following matching processes: \n > {0}".format( - "\n > ".join(matches) - ) + matching_processes = "\n > ".join(matches) + msg += f"\nI found the following matching processes: \n > {matching_processes}" else: - msg = "{0} not found among active processes".format(data) + msg = f"{data} not found among active processes" return msg @@ -71,13 +72,13 @@ def kill_pid(pid): process = get_process(pid) if process is not None: process.kill() - return "{0} killed".format(pid) + return f"{pid} killed" else: - return "No process with pid {0}".format(pid) + return f"No process with pid {pid}" class ControllerPID(Component): - """""" + """Check or kill pids""" help_text = """ > PID module /kill_pid pid: kills a given pid @@ -106,7 +107,7 @@ def telegram_message(self, msg): if pid_string.isdigit(): return_msg = self.kill(int(pid_string)) else: - return_msg = "{0} is not a PID?".format(pid_string) + return_msg = f"{pid_string} is not a PID?" elif msg.command == "is_pid_alive": return_msg = self.alive(pid_string) else: diff --git a/src/pybliotecario/components/reactions.py b/src/pybliotecario/components/reactions.py index 060d506..8d34689 100644 --- a/src/pybliotecario/components/reactions.py +++ b/src/pybliotecario/components/reactions.py @@ -5,10 +5,11 @@ # TODO: # Make sure you don't save img1.png img1.jpg -import os import glob -import pathlib import logging +import os +import pathlib + from pybliotecario.components.component_core import Component log = logging.getLogger(__name__) diff --git a/src/pybliotecario/components/repositories.py b/src/pybliotecario/components/repositories.py index 07baadd..d94a223 100644 --- a/src/pybliotecario/components/repositories.py +++ b/src/pybliotecario/components/repositories.py @@ -3,11 +3,12 @@ Useful for monitoring changes in a repository being able to apply custom filters """ +import logging import os import re import subprocess as sp + from pybliotecario.components.component_core import Component -import logging log = logging.getLogger(__name__) diff --git a/src/pybliotecario/components/scripts.py b/src/pybliotecario/components/scripts.py index be670cd..fa47269 100644 --- a/src/pybliotecario/components/scripts.py +++ b/src/pybliotecario/components/scripts.py @@ -3,10 +3,11 @@ For instant, good_morning will call the command defined in /script good_morning will call the command defined in [SCRIPTS] good_morning """ -import pathlib import logging -import subprocess as sp +import pathlib import shlex +import subprocess as sp + from pybliotecario.components.component_core import Component logger = logging.getLogger(__name__) @@ -113,9 +114,7 @@ def configure_me(cls): sc_cmd = script_command.strip() if not sc_cmd: break - script_file = input( - " Introduce the path of the command to run with '{0}': ".format(sc_cmd) - ) + script_file = input(f" Introduce the path of the command to run with '{sc_cmd}': ") dict_out[cls.section_name][sc_cmd] = script_file return dict_out @@ -134,7 +133,7 @@ def telegram_message(self, msg): if script_name == "list": self.available_commands() elif script_name not in self.script_names: - self.send_msg("Command {0} not defined".format(script_name)) + self.send_msg(f"Command {script_name} not defined") self.available_commands() else: command_path = pathlib.Path(self.scripts[script_name]) @@ -149,7 +148,7 @@ def telegram_message(self, msg): else: cmd_list = [f"./{command_path.name}"] + script_args sp.run(cmd_list, check=True, cwd=command_path.parent) - self.send_msg(f"Command ran") + self.send_msg("Command ran") except sp.CalledProcessError: self.send_msg("Command ran but failed") else: diff --git a/src/pybliotecario/components/stocks.py b/src/pybliotecario/components/stocks.py index a2bcdac..4e9745d 100644 --- a/src/pybliotecario/components/stocks.py +++ b/src/pybliotecario/components/stocks.py @@ -118,16 +118,10 @@ def telegram_message(self, msg): if __name__ == "__main__": - import tempfile import os + import tempfile - json_example = { - "AAPL": {"below": 140, "above": 110}, - "TSLA": { - "below": 1000, - "above": 200, - }, - } + json_example = {"AAPL": {"below": 140, "above": 110}, "TSLA": {"below": 1000, "above": 200}} fd, tmp = tempfile.mkstemp(suffix=".json", text=True) with os.fdopen(fd, "w") as f: json.dump(json_example, f) diff --git a/src/pybliotecario/components/system.py b/src/pybliotecario/components/system.py index ceae79d..0afed49 100644 --- a/src/pybliotecario/components/system.py +++ b/src/pybliotecario/components/system.py @@ -3,6 +3,7 @@ remotely """ import subprocess as sp + from pybliotecario.components.component_core import Component diff --git a/src/pybliotecario/components/weather.py b/src/pybliotecario/components/weather.py index 7e437a5..6a356f9 100644 --- a/src/pybliotecario/components/weather.py +++ b/src/pybliotecario/components/weather.py @@ -6,7 +6,9 @@ from datetime import datetime import logging + from pyowm import OWM + from pybliotecario.components.component_core import Component log = logging.getLogger(__name__) @@ -118,9 +120,10 @@ def cmdline_command(self, args): if __name__ == "__main__": - from pybliotecario.pybliotecario import logger_setup import tempfile + from pybliotecario.pybliotecario import logger_setup + logger_setup(tempfile.TemporaryFile(), debug=True) log.info("Testing weather") weather_api = "" diff --git a/src/pybliotecario/components/wiki.py b/src/pybliotecario/components/wiki.py index 3f4d4c6..b6c0a7b 100644 --- a/src/pybliotecario/components/wiki.py +++ b/src/pybliotecario/components/wiki.py @@ -5,7 +5,9 @@ # TODO use the selected language import re + import wikipedia + from pybliotecario.components.component_core import Component # log = logging.getLogger(__name__) @@ -33,30 +35,29 @@ def __init__(self, telegram_object, configuration=None, **kwargs): @classmethod def configure_me(cls): - print(f""" + print( + f""" # Wikipedia Module This is the configuration helper for the wikipedia module -Introduce the length of the msgs you want to obtain (max: {MAX_SIZE}):""") +Introduce the length of the msgs you want to obtain (max: {MAX_SIZE}):""" + ) summary_size = 0 while summary_size > MAX_SIZE or summary_size < 1: # The max msg in telegram is 4096 UTF char. try: - summary_size = int(input(f" > ".format(MAX_SIZE))) + summary_size = int(input(" > ")) except ValueError: print(f"Please, write a number between 0 and {MAX_SIZE}") possible_languages = ["EN", "ES", "IT"] language = None print("Introduce the default language for Wikipedia pages") while language not in possible_languages: - language = input(f" > Possible choices: {possible_languages} (default: {DEFAULT_LANGUAGE}) > ") + language = input( + f" > Possible choices: {possible_languages} (default: {DEFAULT_LANGUAGE}) > " + ) if language == "": language = DEFAULT_LANGUAGE - dict_out = { - WIKI_NAME: { - "msg_size": summary_size, - "language": language, - } - } + dict_out = {WIKI_NAME: {"msg_size": summary_size, "language": language}} return dict_out def get_page(self, term): @@ -71,7 +72,7 @@ def get_page(self, term): response = "Found disambiguation page, please try with one of these other terms: " response += ", ".join(other_terms) except wikipedia.exceptions.PageError: - response = "Sorry, no Wikipedia pages were found for this query: {0}".format(term) + response = f"Sorry, no Wikipedia pages were found for this query: {term}" self.send_msg(response) return None @@ -83,9 +84,7 @@ def read_summary(self, term): if wiki_page is not None: summary = wiki_page.summary[: self.summary_size] number_of_msg = int(len(wiki_page.content) / self.summary_size) - summary += "\n\n This page will need {0} msgs for the whole content".format( - number_of_msg - ) + summary += f"\n\n This page will need {number_of_msg} msgs for the whole content" self.send_msg(summary) def read_msg_fullpage(self, msg): @@ -94,10 +93,8 @@ def read_msg_fullpage(self, msg): """ reg_n = GET_N.search(msg) if reg_n is None: - error = """For a whole page, write the query in the form /wiki_full N search_term -where N is the number of msgs of size {0} you want to receive""".format( - self.summary_size - ) + error = f"""For a whole page, write the query in the form /wiki_full N search_term +where N is the number of msgs of size {self.summary_size} you want to receive""" self.send_msg(error) return 0, None n_str = reg_n[0] @@ -117,7 +114,7 @@ def read_whole_page(self, term, n_msg): total_length = len(whole_page) final_length = min(total_length, n_msg * self.summary_size) for char in range(0, final_length, self.summary_size): - response = whole_page[char: char + self.summary_size] + response = whole_page[char : char + self.summary_size] self.send_msg(response) def telegram_message(self, msg): diff --git a/src/pybliotecario/core_loop.py b/src/pybliotecario/core_loop.py index 91aac62..42076e1 100644 --- a/src/pybliotecario/core_loop.py +++ b/src/pybliotecario/core_loop.py @@ -3,9 +3,10 @@ when it is called with daemon mode -d """ from datetime import datetime +import logging from pathlib import Path + import pybliotecario.on_cmd_message as on_cmd_message -import logging logger = logging.getLogger(__name__) diff --git a/src/pybliotecario/on_cmd_message.py b/src/pybliotecario/on_cmd_message.py index 42cd777..5b2666b 100644 --- a/src/pybliotecario/on_cmd_message.py +++ b/src/pybliotecario/on_cmd_message.py @@ -6,8 +6,8 @@ This is a design choice as this way it is not necessary to have all dependencies if you want to run only some submodules of the pybliotecario. """ -import logging import importlib +import logging log = logging.getLogger(__name__) diff --git a/src/pybliotecario/pybliotecario.py b/src/pybliotecario/pybliotecario.py index cc04667..d722086 100755 --- a/src/pybliotecario/pybliotecario.py +++ b/src/pybliotecario/pybliotecario.py @@ -4,15 +4,14 @@ for command line invocation """ import logging -import sys from pathlib import Path - -from pybliotecario.backend import TelegramUtil, TestUtil, FacebookUtil -from pybliotecario.core_loop import main_loop -from pybliotecario.customconf import CustomConfigParser, default_config_path +import sys # Modify argument_parser.py to read new arguments from pybliotecario.argument_parser import parse_args +from pybliotecario.backend import FacebookUtil, TelegramUtil, TestUtil +from pybliotecario.core_loop import main_loop +from pybliotecario.customconf import CustomConfigParser, default_config_path import pybliotecario.on_cmdline as on_cmdline logger = logging.getLogger() @@ -27,7 +26,9 @@ def read_config(config_file=None): old_path = Path.home() / ".pybliotecario.ini" config_files = [old_path, default_file_path, default_file_path.name] if old_path.exists(): - logger.error(f"Deprecation notice: ~/.pybliotecario.ini is now deprecated, please move the configuration to {default_file_path}") + logger.error( + f"Deprecation notice: ~/.pybliotecario.ini is now deprecated, please move the configuration to {default_file_path}" + ) if config_file is not None: config_files.append(config_file) @@ -89,8 +90,7 @@ def main(cmdline_arg=None, tele_api=None, config=None): main_folder = defaults.get("main_folder") if not main_folder: logger.warning( - "No 'default:main_folder' option set in %s, using /tmp/", - args.config_file, + "No 'default:main_folder' option set in %s, using /tmp/", args.config_file ) main_folder = "/tmp/" logger_setup(main_folder + "/info.log", debug=args.debug) @@ -103,8 +103,7 @@ def main(cmdline_arg=None, tele_api=None, config=None): api_token = config.defaults().get("token") if not api_token: logger.error( - "No 'default:token' option set in %s, run --init option", - args.config_file, + "No 'default:token' option set in %s, run --init option", args.config_file ) sys.exit(-1)