Skip to content

Commit

Permalink
re-style the whole codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
scarlehoff committed Nov 1, 2023
1 parent fd9f73c commit f60bfdf
Show file tree
Hide file tree
Showing 22 changed files with 121 additions and 135 deletions.
2 changes: 1 addition & 1 deletion src/pybliotecario/backend/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .telegram_util import TelegramUtil
from .backend_test import TestUtil
from .facebook_util import FacebookUtil
from .telegram_util import TelegramUtil
2 changes: 1 addition & 1 deletion src/pybliotecario/backend/backend_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
without communication with any service
"""

import pathlib
from datetime import datetime
import pathlib

from pybliotecario.backend.telegram_util import TelegramMessage

Expand Down
6 changes: 3 additions & 3 deletions src/pybliotecario/backend/basic_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
"""

from abc import ABC, abstractmethod
import json
import logging
import urllib
import json

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -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)
20 changes: 6 additions & 14 deletions src/pybliotecario/backend/facebook_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:]}"),
}
Expand All @@ -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()),
}
Expand Down
32 changes: 16 additions & 16 deletions src/pybliotecario/backend/telegram_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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/"

Expand All @@ -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)


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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)

Expand All @@ -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
Expand Down
12 changes: 7 additions & 5 deletions src/pybliotecario/components/arxiv_mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand All @@ -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}
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions src/pybliotecario/components/component_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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)
11 changes: 6 additions & 5 deletions src/pybliotecario/components/dnd.py
Original file line number Diff line number Diff line change
@@ -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__)
Expand All @@ -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 = ""
Expand Down Expand Up @@ -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():
Expand All @@ -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


Expand All @@ -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)
24 changes: 8 additions & 16 deletions src/pybliotecario/components/github_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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": "<TOKEN GITHUB>", "since_hours": 5}

logger_setup(tmpdir / "log.txt", debug=True)
Expand Down
8 changes: 4 additions & 4 deletions src/pybliotecario/components/ip_lookup.py
Original file line number Diff line number Diff line change
@@ -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__)

Expand Down Expand Up @@ -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
Loading

0 comments on commit f60bfdf

Please sign in to comment.