Skip to content

Commit d159b49

Browse files
committed
style: format code with black
1 parent 6aee8e9 commit d159b49

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

89 files changed

+1452
-1203
lines changed

.pylintrc

+2-2
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ variable-naming-style=snake_case
243243
expected-line-ending-format=
244244

245245
# Regexp for a line that is allowed to be longer than the limit.
246-
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
246+
ignore-long-lines=^\s*(# |'|\")?<?https?://\S+>?$
247247

248248
# Number of spaces of indent required inside a hanging or continued line.
249249
indent-after-paren=4
@@ -253,7 +253,7 @@ indent-after-paren=4
253253
indent-string=' '
254254

255255
# Maximum number of characters on a single line.
256-
max-line-length=100
256+
max-line-length=88
257257

258258
# Maximum number of lines in a module.
259259
max-module-lines=1000

nazurin/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@
99
bot = NazurinBot(token=config.TOKEN, proxy=config.PROXY)
1010
dp = NazurinDispatcher(bot)
1111

12-
__all__ = ['bot', 'dp']
12+
__all__ = ["bot", "dp"]

nazurin/__main__.py

+19-12
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@
1515
from nazurin.utils.exceptions import NazurinError
1616
from nazurin.utils.helpers import format_error
1717

18-
@dp.message_handler(commands=['start', 'help'])
18+
19+
@dp.message_handler(commands=["start", "help"])
1920
@chat_action(ChatActions.TYPING)
2021
async def show_help(message: Message):
21-
await message.reply('''
22+
await message.reply(
23+
"""
2224
小さな小さな賢将, can help you collect images from various sites.
2325
Commands:
2426
/ping - pong
@@ -34,14 +36,17 @@ async def show_help(message: Message):
3436
/clear_cache - clear download cache
3537
/help - get this help text
3638
PS: Send Pixiv/Danbooru/Yandere/Konachan/Twitter URL to download image(s)
37-
''')
39+
"""
40+
)
41+
3842

39-
@dp.message_handler(commands=['ping'])
43+
@dp.message_handler(commands=["ping"])
4044
@chat_action(ChatActions.TYPING)
4145
async def ping(message: Message):
42-
await message.reply('pong!')
46+
await message.reply("pong!")
47+
4348

44-
@dp.message_handler(IDFilter(config.ADMIN_ID), commands=['clear_cache'])
49+
@dp.message_handler(IDFilter(config.ADMIN_ID), commands=["clear_cache"])
4550
async def clear_cache(message: Message):
4651
try:
4752
if os.path.exists(config.TEMP_DIR):
@@ -53,28 +58,30 @@ async def clear_cache(message: Message):
5358
except OSError as error:
5459
await message.reply(error.strerror)
5560

61+
5662
@dp.errors_handler()
5763
async def on_error(update: Update, exception: Exception):
5864
try:
5965
raise exception
6066
except ClientResponseError as error:
6167
traceback.print_exc()
62-
await update.message.reply(
63-
f'Response Error: {error.status} {error.message}')
68+
await update.message.reply(f"Response Error: {error.status} {error.message}")
6469
except NazurinError as error:
6570
await update.message.reply(error.msg)
6671
except asyncio.TimeoutError:
6772
traceback.print_exc()
68-
await update.message.reply('Error: Timeout, please try again.')
73+
await update.message.reply("Error: Timeout, please try again.")
6974
except Exception as error: # pylint: disable=broad-except
70-
logger.exception('Update {} caused {}: {}', update, type(error), error)
75+
logger.exception("Update {} caused {}: {}", update, type(error), error)
7176
if not isinstance(error, TelegramAPIError):
72-
await update.message.reply(f'Error: {format_error(error)}')
77+
await update.message.reply(f"Error: {format_error(error)}")
7378

7479
return True
7580

81+
7682
def main():
7783
dp.start()
7884

79-
if __name__ == '__main__':
85+
86+
if __name__ == "__main__":
8087
main()

nazurin/bot.py

+50-43
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from nazurin.utils.exceptions import NazurinError
1616
from nazurin.utils.helpers import handle_bad_request, sanitize_caption
1717

18+
1819
class NazurinBot(Bot):
1920
send_message = retry_after(Bot.send_message)
2021

@@ -28,29 +29,28 @@ def init(self):
2829
self.storage.load()
2930

3031
@retry_after
31-
async def send_single_group(self,
32-
imgs: List[Image],
33-
caption: str,
34-
chat_id: int,
35-
reply_to: Optional[int] = None):
32+
async def send_single_group(
33+
self,
34+
imgs: List[Image],
35+
caption: str,
36+
chat_id: int,
37+
reply_to: Optional[int] = None,
38+
):
3639
await self.send_chat_action(chat_id, ChatActions.UPLOAD_PHOTO)
3740
media = []
3841
for img in imgs:
3942
media.append(InputMediaPhoto(await img.display_url())) # TODO
4043
media[0].caption = caption
41-
await self.send_media_group(chat_id,
42-
media,
43-
reply_to_message_id=reply_to)
44-
45-
async def send_photos(self,
46-
illust: Illust,
47-
chat_id: int,
48-
reply_to: Optional[int] = None):
44+
await self.send_media_group(chat_id, media, reply_to_message_id=reply_to)
45+
46+
async def send_photos(
47+
self, illust: Illust, chat_id: int, reply_to: Optional[int] = None
48+
):
4949
caption = sanitize_caption(illust.caption)
5050
groups = []
5151
imgs = illust.images
5252
if len(imgs) == 0:
53-
raise NazurinError('No image to send, try download option.')
53+
raise NazurinError("No image to send, try download option.")
5454

5555
while imgs:
5656
groups.append(imgs[:10])
@@ -59,22 +59,25 @@ async def send_photos(self,
5959
for group in groups:
6060
await self.send_single_group(group, caption, chat_id, reply_to)
6161

62-
async def send_illust(self,
63-
illust: Illust,
64-
message: Optional[Message] = None,
65-
chat_id: Optional[int] = None):
62+
async def send_illust(
63+
self,
64+
illust: Illust,
65+
message: Optional[Message] = None,
66+
chat_id: Optional[int] = None,
67+
):
6668
reply_to = message.message_id if message else None
6769
if not chat_id:
6870
chat_id = message.chat.id
6971
elif chat_id != reply_to: # Sending to different chat, can't reply
7072
reply_to = None
7173
try:
7274
if isinstance(illust, Ugoira):
73-
await self.send_animation(chat_id,
74-
InputFile(illust.video.path),
75-
caption=sanitize_caption(
76-
illust.caption),
77-
reply_to_message_id=reply_to)
75+
await self.send_animation(
76+
chat_id,
77+
InputFile(illust.video.path),
78+
caption=sanitize_caption(illust.caption),
79+
reply_to_message_id=reply_to,
80+
)
7881
else:
7982
await self.send_photos(illust, chat_id, reply_to)
8083
except BadRequest as error:
@@ -83,14 +86,13 @@ async def send_illust(self,
8386
@retry_after
8487
async def send_doc(self, file: File, chat_id, message_id=None):
8588
await self.send_chat_action(chat_id, ChatActions.UPLOAD_DOCUMENT)
86-
await self.send_document(chat_id,
87-
InputFile(file.path),
88-
reply_to_message_id=message_id)
89-
90-
async def send_docs(self,
91-
illust: Illust,
92-
message: Optional[Message] = None,
93-
chat_id=None):
89+
await self.send_document(
90+
chat_id, InputFile(file.path), reply_to_message_id=message_id
91+
)
92+
93+
async def send_docs(
94+
self, illust: Illust, message: Optional[Message] = None, chat_id=None
95+
):
9496
if message:
9597
message_id = message.message_id
9698
if not chat_id:
@@ -100,32 +102,37 @@ async def send_docs(self,
100102
for file in illust.all_files:
101103
await self.send_doc(file, chat_id, message_id)
102104

103-
async def update_collection(self,
104-
urls: List[str],
105-
message: Optional[Message] = None):
105+
async def update_collection(
106+
self, urls: List[str], message: Optional[Message] = None
107+
):
106108
result = self.sites.match(urls)
107109
if not result:
108-
raise NazurinError('No source matched')
109-
logger.info('Collection update: site={}, match={}', result['site'],
110-
result['match'].groups())
110+
raise NazurinError("No source matched")
111+
logger.info(
112+
"Collection update: site={}, match={}",
113+
result["site"],
114+
result["match"].groups(),
115+
)
111116

112117
illust = await self.sites.handle_update(result)
113118

114119
# Send / Forward to gallery & Save to album
115120
download = asyncio.create_task(illust.download())
116121

117122
if config.GALLERY_ID:
118-
# If there're multiple images, then send a new message instead of
119-
# forwarding an existing one, since we currently can't forward albums correctly.
120-
if message and message.is_forward(
121-
) and not illust.has_multiple_images():
123+
# If there're multiple images,
124+
# then send a new message instead of forwarding an existing one,
125+
# since we currently can't forward albums correctly.
126+
if message and message.is_forward() and not illust.has_multiple_images():
122127
save = asyncio.create_task(message.forward(config.GALLERY_ID))
123128
elif not illust.has_image():
124129
save = asyncio.create_task(
125-
self.send_message(config.GALLERY_ID, '\n'.join(urls)))
130+
self.send_message(config.GALLERY_ID, "\n".join(urls))
131+
)
126132
else:
127133
save = asyncio.create_task(
128-
self.send_illust(illust, message, config.GALLERY_ID))
134+
self.send_illust(illust, message, config.GALLERY_ID)
135+
)
129136
await asyncio.gather(save, download)
130137
else:
131138
await download

nazurin/config.py

+21-21
Original file line numberDiff line numberDiff line change
@@ -6,42 +6,42 @@
66
# read config from .env file if exists
77
env.read_env()
88

9-
ENV = env.str('ENV', default='production')
10-
TOKEN = env.str('TOKEN')
9+
ENV = env.str("ENV", default="production")
10+
TOKEN = env.str("TOKEN")
1111

1212
# Webhook url, eg: https://xxx.fly.dev/, should end with '/'
13-
WEBHOOK_URL = env.str('WEBHOOK_URL', default=None)
14-
HOST = env.str('HOST', default='0.0.0.0')
13+
WEBHOOK_URL = env.str("WEBHOOK_URL", default=None)
14+
HOST = env.str("HOST", default="0.0.0.0")
1515
# Port is automatically set if on Heroku or fly.io
16-
PORT = env.int('PORT', default=80)
16+
PORT = env.int("PORT", default=80)
1717

18-
STORAGE = env.list('STORAGE', subcast=str, default=['Local'])
19-
STORAGE_DIR = env.str('STORAGE_DIR', default='Pictures')
18+
STORAGE = env.list("STORAGE", subcast=str, default=["Local"])
19+
STORAGE_DIR = env.str("STORAGE_DIR", default="Pictures")
2020

21-
DATABASE = env.str('DATABASE', default='Local')
21+
DATABASE = env.str("DATABASE", default="Local")
2222
# Nazurin data collection in database
23-
NAZURIN_DATA = 'nazurin'
23+
NAZURIN_DATA = "nazurin"
2424
# Ignored items in image caption
25-
CAPTION_IGNORE = env.list('CAPTION_IGNORE', subcast=str, default=[])
25+
CAPTION_IGNORE = env.list("CAPTION_IGNORE", subcast=str, default=[])
2626

27-
GALLERY_ID = env.int('GALLERY_ID', default=None)
27+
GALLERY_ID = env.int("GALLERY_ID", default=None)
2828

29-
ADMIN_ID = env.int('ADMIN_ID')
30-
IS_PUBLIC = env.bool('IS_PUBLIC', default=False)
29+
ADMIN_ID = env.int("ADMIN_ID")
30+
IS_PUBLIC = env.bool("IS_PUBLIC", default=False)
3131
# If IS_PUBLIC is True, the following items will be ignored
32-
ALLOW_ID = env.list('ALLOW_ID', subcast=int, default=[])
33-
ALLOW_USERNAME = env.list('ALLOW_USERNAME', default=[])
34-
ALLOW_GROUP = env.list('ALLOW_GROUP', subcast=int, default=[])
32+
ALLOW_ID = env.list("ALLOW_ID", subcast=int, default=[])
33+
ALLOW_USERNAME = env.list("ALLOW_USERNAME", default=[])
34+
ALLOW_GROUP = env.list("ALLOW_GROUP", subcast=int, default=[])
3535

36-
RETRIES = env.int('RETRIES', default=5)
37-
TIMEOUT = env.int('TIMEOUT', default=20)
38-
PROXY = env.str('HTTP_PROXY', default=None)
36+
RETRIES = env.int("RETRIES", default=5)
37+
TIMEOUT = env.int("TIMEOUT", default=20)
38+
PROXY = env.str("HTTP_PROXY", default=None)
3939
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
4040
AppleWebKit/537.36 (KHTML, like Gecko) \
4141
Chrome/90.0.4430.85 \
4242
Safari/537.36"
4343

4444
# Local directory to store database and temporary files
45-
DATA_DIR = 'data'
46-
TEMP_DIR = path.join(DATA_DIR, 'temp')
45+
DATA_DIR = "data"
46+
TEMP_DIR = path.join(DATA_DIR, "temp")
4747
ACCESS_LOG_FORMAT = '%a "%r" %s %b "%{Referer}i" "%{User-Agent}i"'

nazurin/database/__init__.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33

44
from nazurin.config import DATABASE
55

6+
67
class Database:
78
"""Nazurin database manager."""
9+
810
def __init__(self):
911
"""Dynamically load all database drivers."""
10-
module = importlib.import_module('nazurin.database.' +
11-
DATABASE.lower())
12+
module = importlib.import_module("nazurin.database." + DATABASE.lower())
1213
self.driver = getattr(module, DATABASE)

nazurin/database/cloudant.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,20 @@
44
from nazurin.config import RETRIES, env
55
from nazurin.utils.decorators import async_wrap
66

7-
with env.prefixed('CLOUDANT_'):
8-
USERNAME = env.str('USER')
9-
APIKEY = env.str('APIKEY')
10-
DATABASE = env.str('DB', default='nazurin')
7+
with env.prefixed("CLOUDANT_"):
8+
USERNAME = env.str("USER")
9+
APIKEY = env.str("APIKEY")
10+
DATABASE = env.str("DB", default="nazurin")
11+
1112

1213
class Cloudant:
1314
"""Cloudant driver of IBM Cloud."""
15+
1416
def __init__(self):
1517
"""Connect to database."""
16-
self.client = cloudant.iam(USERNAME,
17-
APIKEY,
18-
timeout=5,
19-
adapter=HTTPAdapter(max_retries=RETRIES))
18+
self.client = cloudant.iam(
19+
USERNAME, APIKEY, timeout=5, adapter=HTTPAdapter(max_retries=RETRIES)
20+
)
2021
self.client.connect()
2122
self.db = self.client[DATABASE]
2223
self._partition = None
@@ -44,7 +45,7 @@ def exists(self):
4445
@async_wrap
4546
def insert(self, key, data):
4647
self._document = str(key)
47-
data['_id'] = self._id()
48+
data["_id"] = self._id()
4849
return self.db.create_document(data)
4950

5051
@async_wrap
@@ -59,7 +60,7 @@ def delete(self):
5960
return doc.delete()
6061

6162
def _id(self):
62-
return ':'.join((self._partition, self._document))
63+
return ":".join((self._partition, self._document))
6364

6465
def __del__(self):
6566
"""Disconnect from database."""

nazurin/database/firebase.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,16 @@
66

77
from nazurin.config import env
88

9+
910
class Firebase:
1011
"""Firestore driver of Firebase."""
12+
1113
db: AsyncClient
1214

1315
def __init__(self):
1416
"""Load credentials and initialize Firebase app."""
15-
cert = env.str('GOOGLE_APPLICATION_CREDENTIALS')
16-
if cert.startswith('{'):
17+
cert = env.str("GOOGLE_APPLICATION_CREDENTIALS")
18+
if cert.startswith("{"):
1719
cert = json.loads(cert)
1820
cred = credentials.Certificate(cert)
1921
if len(firebase_admin._apps) == 0:

0 commit comments

Comments
 (0)