Skip to content

Commit

Permalink
style: format code with Autopep8 (#1499)
Browse files Browse the repository at this point in the history
This commit fixes the style issues introduced in 8124881 according to the output
from Autopep8.

Details: None

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
  • Loading branch information
deepsource-autofix[bot] authored Dec 19, 2024
1 parent 8124881 commit 8e7b557
Show file tree
Hide file tree
Showing 19 changed files with 104 additions and 110 deletions.
56 changes: 28 additions & 28 deletions bots/matrix/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,49 +74,49 @@ async def sendMsg(content):
# https://spec.matrix.org/v1.9/client-server-api/#fallbacks-for-rich-replies
# todo: standardize fallback for m.image, m.video, m.audio, and m.file
reply_to_type = self.session.message["content"]["msgtype"]
content["body"] = (f">{' *' if reply_to_type == 'm.emote' else ''} <{self.session.sender}> {
content["body"] = (f"> {' *' if reply_to_type == 'm.emote' else ''} < {self.session.sender} > {
self.session.message['content']['body']}\n\n{x.text}")
content["format"] = "org.matrix.custom.html"
html_text = x.text
html_text = html_text.replace("<", "&lt;").replace(">", "&gt;")
html_text = html_text.replace("\n", "<br />")
content["formatted_body"] = (
f"<mx-reply><blockquote><a href=\"https://matrix.to/#/{
self.session.target}/{reply_to}?via={homeserver_host}\">In reply to</a>{
' *' if reply_to_type == 'm.emote' else ''} <a href=\"https://matrix.to/#/{
self.session.sender}\">{
self.session.sender}</a><br/>{
self.session.message['content']['body']}</blockquote></mx-reply>{html_text}")
f"< mx - reply > <blockquote > <a href=\"https: // matrix.to / # /{
self.session.target} / {reply_to}?via = {homeserver_host}\"> In reply to < /a > {
' *' if reply_to_type == 'm.emote' else ''} < a href =\"https: // matrix.to/ # /{
self.session.sender}\"> {
self.session.sender} < /a > <br / >{
self.session.message['content']['body']} < /blockquote > < / mx - reply > {html_text}")

if (
self.session.message
and "m.relates_to" in self.session.message["content"]
):
relates_to = self.session.message["content"]["m.relates_to"]
relates_to= self.session.message["content"]["m.relates_to"]
if (
"rel_type" in relates_to
and relates_to["rel_type"] == "m.thread"
):
# replying in thread
thread_root = relates_to["event_id"]
thread_root= relates_to["event_id"]
if reply_to:
# reply to msg replying in thread
content["m.relates_to"] = {
content["m.relates_to"]= {
"rel_type": "m.thread",
"event_id": thread_root,
"is_falling_back": False,
"m.in_reply_to": {"event_id": reply_to},
}
else:
# reply in thread
content["m.relates_to"] = {
content["m.relates_to"]= {
"rel_type": "m.thread",
"event_id": thread_root,
"is_falling_back": True,
"m.in_reply_to": {"event_id": self.target.message_id},
}

resp = await bot.room_send(
resp= await bot.room_send(
self.session.target,
"m.room.message",
content,
Expand All @@ -126,31 +126,31 @@ async def sendMsg(content):
Logger.error(f"Error while sending message: {str(resp)}")
else:
sentMessages.append(resp)
reply_to = None
reply_to_user = None
reply_to= None
reply_to_user= None

if isinstance(x, PlainElement):
content = {"msgtype": "m.notice", "body": x.text}
content= {"msgtype": "m.notice", "body": x.text}
Logger.info(f"[Bot] -> [{self.target.target_id}]: {x.text}")
await sendMsg(content)
elif isinstance(x, ImageElement):
split = [x]
split= [x]
if enable_split_image:
Logger.info(f"Split image: {str(x.__dict__)}")
split = await image_split(x)
split= await image_split(x)
for xs in split:
path = await xs.get()
path= await xs.get()
with open(path, "rb") as image:
filename = os.path.basename(path)
filesize = os.path.getsize(path)
(content_type, content_encoding) = mimetypes.guess_type(path)
filename= os.path.basename(path)
filesize= os.path.getsize(path)
(content_type, content_encoding)= mimetypes.guess_type(path)
if not content_type or not content_encoding:
content_type = "image"
content_encoding = "png"
mimetype = f"{content_type}/{content_encoding}"
content_type= "image"
content_encoding= "png"
mimetype= f"{content_type}/{content_encoding}"

encrypted = self.session.target in bot.encrypted_rooms
(upload, upload_encryption) = await bot.upload(
encrypted= self.session.target in bot.encrypted_rooms
(upload, upload_encryption)= await bot.upload(
image,
content_type=mimetype,
filename=filename,
Expand All @@ -162,7 +162,7 @@ async def sendMsg(content):
upload.content_uri}, mime: {mimetype}, encrypted: {encrypted}")
# todo: provide more image info
if not encrypted:
content = {
content= {
"msgtype": "m.image",
"url": upload.content_uri,
"body": filename,
Expand Down Expand Up @@ -209,7 +209,7 @@ async def sendMsg(content):
upload.content_uri}, mime: {mimetype}, encrypted: {encrypted}")
# todo: provide audio duration info
if not encrypted:
content = {
content= {
"msgtype": "m.audio",
"url": upload.content_uri,
"body": filename,
Expand Down
2 changes: 1 addition & 1 deletion core/dirty_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def parse_data(
content = (
content[: pos["startPos"] + _offset]
+ reason
+ content[pos["endPos"] + _offset :]
+ content[pos["endPos"] + _offset:]
)
if additional_text:
content += "\n" + additional_text + "\n"
Expand Down
4 changes: 2 additions & 2 deletions core/parser/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,13 +236,13 @@ def parse_argv(argv: List[str], templates: List["Template"]) -> MatchedResult:
if len(argv_copy[index_flag:]) >= len_t_args:

sub_argv = argv_copy[
index_flag + 1 : index_flag + len_t_args + 1
index_flag + 1: index_flag + len_t_args + 1
]

parsed_argv[a.flag] = Optional(
parse_argv(sub_argv, a.args).args, flagged=True
)
del argv_copy[index_flag : index_flag + len_t_args + 1]
del argv_copy[index_flag: index_flag + len_t_args + 1]
for a in args:
if isinstance(a, ArgumentPattern):
if a.name.startswith("<"):
Expand Down
5 changes: 3 additions & 2 deletions core/parser/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,9 @@ async def execute_submodule(msg: Bot.MessageSession, command_first_word):
else:
kwargs[param_name_] = None
if no_message_session:
Logger.warning(f'{submodule.function.__name__} has no Bot.MessageSession parameter, did you forgot to add it?\n'
'Remember: MessageSession IS NOT Bot.MessageSession')
Logger.warning(
f'{submodule.function.__name__} has no Bot.MessageSession parameter, did you forgot to add it?\n'
'Remember: MessageSession IS NOT Bot.MessageSession')
else:
kwargs[func_params[list(func_params.keys())[0]].name] = msg

Expand Down
64 changes: 32 additions & 32 deletions core/scripts/config_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ def generate_config(dir_path, language):
f.write(f"# {locale.t('config.header.line.3', fallback_failed_prompt=False)}\n")
f.write('\n')
f.write(
f'default_locale = "{language}" # {
f'default_locale="{language}" # {
locale.t(
'config.comments.default_locale',
fallback_failed_prompt=False)}\n')
f.write(
f'config_version = {
str(config_version)} # {
str(config_version)} # {
locale.t(
'config.comments.config_version',
fallback_failed_prompt=False)}\n')
Expand All @@ -54,23 +54,23 @@ def generate_config(dir_path, language):
continue
for file in _files:
if file.endswith('.py'):
file_path = os.path.join(root, file)
file_path= os.path.join(root, file)
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
code= f.read()
if f := match_code.finditer(code): # Find all Config() functions in the code
for m in f:
left_brackets_count = 0
param_text = ''
left_brackets_count= 0
param_text= ''
for param in code[m.end(
):]: # Get the parameters text inside the Config() function by counting brackets
): ]: # Get the parameters text inside the Config() function by counting brackets
if param == '(':
left_brackets_count += 1
elif param == ')':
left_brackets_count -= 1
if left_brackets_count == -1:
break
param_text += param
config_code_list[param_text] = file_path
config_code_list[param_text]= file_path
# filtered_config_code_map = {}
# for c in config_code_list:
# opt = c.split(',')[0]
Expand All @@ -82,13 +82,13 @@ def generate_config(dir_path, language):
# filtered_config_code_map[opt] = c
# config_code_list = [filtered_config_code_map[c] for c in filtered_config_code_map]
for c in config_code_list:
spl = c.split(',') + ['_generate=True'] # Add _generate=True param to the end of the config function
spl= c.split(',') + ['_generate=True'] # Add _generate=True param to the end of the config function
for s in spl:
if s.strip() == '':
spl.remove(s)
try:
# Execute the code to generate the config file, yeah, just stupid but works
eval(f'Config({','.join(spl)})')
eval(f'Config({', '.join(spl)})')
except (NameError, TypeError):
# traceback.print_exc()
...
Expand All @@ -98,15 +98,15 @@ def generate_config(dir_path, language):

if not os.path.exists(os.path.join(config_path, config_filename)) and __name__ != '__main__':
while True:
i = 1
lang = input(
i= 1
lang= input(
f"""Hi, it seems you are first time to run AkariBot, what language do you want to use by default?
{''.join([f"{i}. {lang_list[list(lang_list.keys())[i - 1]]}\n" for i in range(1, len(lang_list) + 1)])}
Please input the number of the language you want to use: """)
if lang.strip() == '':
sys.exit(0)
if isint(lang) and (langI := (int(lang) - 1)) in range(len(lang_list)):
lang = list(lang_list.keys())[langI]
lang= list(lang_list.keys())[langI]
break
print('Invalid input, please try again.')

Expand All @@ -127,54 +127,54 @@ def generate_config(dir_path, language):

def zip_language_folders(config_store_path, config_store_packed_path):
for lang in os.listdir(config_store_path):
lang_path = os.path.join(config_store_path, lang)
lang_path= os.path.join(config_store_path, lang)
if os.path.isdir(lang_path):
zip_path = os.path.join(config_store_packed_path, f'{lang}.zip')
zip_path= os.path.join(config_store_packed_path, f'{lang}.zip')
with zipfile.ZipFile(zip_path, 'w') as zipf:
for root, _, files in os.walk(lang_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, lang_path)
file_path= os.path.join(root, file)
arcname= os.path.relpath(file_path, lang_path)
zipf.write(file_path, arcname)

config_store_path = os.path.join(assets_path, 'config_store')
config_store_packed_path = os.path.join(assets_path, 'config_store_packed')
config_store_path_bak = config_store_path + '_bak'
config_store_path= os.path.join(assets_path, 'config_store')
config_store_packed_path= os.path.join(assets_path, 'config_store_packed')
config_store_path_bak= config_store_path + '_bak'
if os.path.exists(config_store_path_bak):
shutil.rmtree(config_store_path_bak)
if os.path.exists(config_store_path):
shutil.move(config_store_path, config_store_path_bak)
os.makedirs(config_store_path, exist_ok=True)
os.makedirs(config_store_packed_path, exist_ok=True)
for lang in lang_list:
config_store_path_ = os.path.join(config_store_path, lang)
config_store_path_= os.path.join(config_store_path, lang)
os.makedirs(config_store_path_, exist_ok=True)
generate_config(config_store_path_, lang)
# compare old and new config files
repack = False
repack= False
for lang in lang_list:
config_store_path_ = os.path.join(config_store_path, lang)
config_store_path_bak = config_store_path + '_bak'
config_store_path_= os.path.join(config_store_path, lang)
config_store_path_bak= config_store_path + '_bak'
if not os.path.exists(config_store_path_bak):
repack = True
repack= True
break
for root, _, files_ in os.walk(config_store_path_):
for file in files_:
file_path = os.path.join(root, file)
file_path_bak = file_path.replace(config_store_path, config_store_path_bak)
file_path= os.path.join(root, file)
file_path_bak= file_path.replace(config_store_path, config_store_path_bak)
if not os.path.exists(file_path_bak):
repack = True
repack= True
break
with open(file_path, 'r', encoding='utf-8') as f:
new = f.readlines()
new= f.readlines()
with open(file_path_bak, 'r', encoding='utf-8') as f:
old = f.readlines()
diff = difflib.unified_diff(old, new, fromfile=file_path_bak, tofile=file_path)
old= f.readlines()
diff= difflib.unified_diff(old, new, fromfile=file_path_bak, tofile=file_path)
for d in diff:

if d:
print(d)
repack = True
repack= True
break
if repack:
break
Expand Down
2 changes: 1 addition & 1 deletion core/utils/decrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def decrypt_string(text):
)
d = []
for i in range(0, len(text), 28):
d.append(text[i : i + 28])
d.append(text[i: i + 28])
dec_text = "".join([c.decrypt(i) for i in d])
if m := re.match(r"^.{2}:(.*?):.{2}.*?$", dec_text):
return m.group(1)
Expand Down
4 changes: 2 additions & 2 deletions core/utils/html2text/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def dumb_css_parser(data: str) -> Dict[str, Dict[str, str]]:
data += ";"
importIndex = data.find("@import")
while importIndex != -1:
data = data[0:importIndex] + data[data.find(";", importIndex) + 1 :]
data = data[0:importIndex] + data[data.find(";", importIndex) + 1:]
importIndex = data.find("@import")

# parse the css. reverted from dictionary comprehension in order to
Expand Down Expand Up @@ -227,7 +227,7 @@ def reformat_table(lines: List[str], right_margin: int) -> List[str]:
if num_cols < max_cols:
cols += [""] * (max_cols - num_cols)
elif max_cols < num_cols:
max_width += [len(x) + right_margin for x in cols[-(num_cols - max_cols) :]]
max_width += [len(x) + right_margin for x in cols[-(num_cols - max_cols):]]
max_cols = num_cols

max_width = [
Expand Down
5 changes: 3 additions & 2 deletions core/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,9 @@ async def msgchain2image(message_chain: Union[List, MessageChain],
data = await fi.read()
try:
ftt = ft.match(data)
lst.append(f'<img src="data:{ftt.mime};base64,{
(base64.encodebytes(data)).decode("utf-8")}" width="720" />')
lst.append(f'< img src="data: {ftt.mime}
base64, {
(base64.encodebytes(data)).decode("utf-8")}" width="720" / >')
except Exception:
Logger.error(traceback.format_exc())
elif isinstance(m, VoiceElement):
Expand Down
Loading

0 comments on commit 8e7b557

Please sign in to comment.