From 20e4480d22dd6bee2a63310820eff12516aafc00 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:46:58 +0800 Subject: [PATCH 1/8] style: format code with Autopep8 (#30) This commit fixes the style issues introduced in 0ead071 according to the output from Autopep8. Details: None Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/ncm/__init__.py | 39 ++++++++++++++++++++++------------ src/plugins/ncm/data_source.py | 38 +++++++++++++++++++++------------ 2 files changed, 51 insertions(+), 26 deletions(-) diff --git a/src/plugins/ncm/__init__.py b/src/plugins/ncm/__init__.py index 164a893..e9701af 100644 --- a/src/plugins/ncm/__init__.py +++ b/src/plugins/ncm/__init__.py @@ -40,7 +40,8 @@ async def song_is_open(event: Union[GroupMessageEvent, PrivateMessageEvent]) -> if isinstance(event, GroupMessageEvent): if info := setting.search(Q["group_id"] == event.group_id): return info[0]["song"] - setting.insert({"group_id": event.group_id, "song": False, "list": False}) + setting.insert({"group_id": event.group_id, + "song": False, "list": False}) return False elif isinstance(event, PrivateMessageEvent): if info := setting.search(Q["user_id"] == event.user_id): @@ -57,14 +58,16 @@ async def playlist_is_open( if info: return info[0]["list"] else: - setting.insert({"group_id": event.group_id, "song": False, "list": False}) + setting.insert({"group_id": event.group_id, + "song": False, "list": False}) return False elif isinstance(event, PrivateMessageEvent): info = setting.search(Q["user_id"] == event.user_id) if info: return info[0]["list"] else: - setting.insert({"user_id": event.user_id, "song": True, "list": True}) + setting.insert({"user_id": event.user_id, + "song": True, "list": True}) return True @@ -95,7 +98,8 @@ async def music_reply_rule(event: Union[GroupMessageEvent, PrivateMessageEvent]) """功能设置""" music_regex = on_regex(r"(song|url)\?id=([0-9]+)(|&)", priority=2, block=False) """歌曲id识别""" -playlist_regex = on_regex(r"playlist\?id=([0-9]+)(|&)", priority=2, block=False) +playlist_regex = on_regex( + r"playlist\?id=([0-9]+)(|&)", priority=2, block=False) """歌单识别""" music_reply = on_message(priority=2, rule=Rule(music_reply_rule), block=False) """回复下载""" @@ -117,7 +121,8 @@ async def receive_song( ): _id = await nncm.search_song(keyword=song.extract_plain_text(), limit=1) message_id = await bot.send( - event=event, message=Message(MessageSegment.music(type_="163", id_=_id)) + event=event, message=Message( + MessageSegment.music(type_="163", id_=_id)) ) nncm.get_song(message_id=message_id["message_id"], nid=_id) # try: @@ -185,28 +190,34 @@ async def set_receive( if mold in TRUE: info[0]["song"] = True info[0]["list"] = True - setting.update(info[0], Q["group_id"] == event.group_id) + setting.update( + info[0], Q["group_id"] == event.group_id) msg = "已开启自动下载功能" await bot.send( - event=event, message=Message(MessageSegment.text(msg)) + event=event, message=Message( + MessageSegment.text(msg)) ) elif mold in FALSE: info[0]["song"] = False info[0]["list"] = False - setting.update(info[0], Q["group_id"] == event.group_id) + setting.update( + info[0], Q["group_id"] == event.group_id) msg = "已关闭自动下载功能" await bot.send( - event=event, message=Message(MessageSegment.text(msg)) + event=event, message=Message( + MessageSegment.text(msg)) ) logger.debug(f"用户<{event.sender.nickname}>执行操作成功") else: if mold in TRUE: setting.insert( - {"group_id": event.group_id, "song": True, "list": True} + {"group_id": event.group_id, + "song": True, "list": True} ) elif mold in FALSE: setting.insert( - {"group_id": event.group_id, "song": False, "list": False} + {"group_id": event.group_id, + "song": False, "list": False} ) elif isinstance(event, PrivateMessageEvent): info = setting.search(Q["user_id"] == event.user_id) @@ -218,7 +229,8 @@ async def set_receive( setting.update(info[0], Q["user_id"] == event.user_id) msg = "已开启下载功能" await bot.send( - event=event, message=Message(MessageSegment.text(msg)) + event=event, message=Message( + MessageSegment.text(msg)) ) elif mold in FALSE: info[0]["song"] = False @@ -226,7 +238,8 @@ async def set_receive( setting.update(info[0], Q["user_id"] == event.user_id) msg = "已关闭下载功能" await bot.send( - event=event, message=Message(MessageSegment.text(msg)) + event=event, message=Message( + MessageSegment.text(msg)) ) logger.debug(f"用户<{event.sender.nickname}>执行操作成功") else: diff --git a/src/plugins/ncm/data_source.py b/src/plugins/ncm/data_source.py index 8790902..3088d0e 100644 --- a/src/plugins/ncm/data_source.py +++ b/src/plugins/ncm/data_source.py @@ -38,7 +38,8 @@ cmd = list(nonebot.get_driver().config.command_start)[0] -class NcmLoginFailedException(Exception): pass +class NcmLoginFailedException(Exception): + pass # ============主类============= @@ -61,7 +62,8 @@ def load_user(session: str): def login(self) -> bool: try: - self.api.login.LoginViaCellphone(phone=ncm_config.ncm_phone, password=ncm_config.ncm_password) + self.api.login.LoginViaCellphone( + phone=ncm_config.ncm_phone, password=ncm_config.ncm_password) self.get_user_info() return True except Exception as e: @@ -74,7 +76,7 @@ def login(self) -> bool: return False def get_user_info(self) -> str: - message: str = f"欢迎您网易云用户:{GetCurrentSession().nickname} [{GetCurrentSession().uid}]"; + message: str = f"欢迎您网易云用户:{GetCurrentSession().nickname} [{GetCurrentSession().uid}]" logger.success(message) self.save_user(DumpSessionAsString(GetCurrentSession())) return message @@ -82,17 +84,20 @@ def get_user_info(self) -> str: def get_phone_login(self): phone = ncm_config.ncm_phone ctcode = int(ncm_config.ncm_ctcode) - result = self.api.login.SetSendRegisterVerifcationCodeViaCellphone(cell=phone, ctcode=ctcode) + result = self.api.login.SetSendRegisterVerifcationCodeViaCellphone( + cell=phone, ctcode=ctcode) if not result.get('code', 0) == 200: logger.error(result) else: logger.success('已发送验证码,输入验证码:') while True: captcha = int(input()) - verified = self.api.login.GetRegisterVerifcationStatusViaCellphone(phone, captcha, ctcode) + verified = self.api.login.GetRegisterVerifcationStatusViaCellphone( + phone, captcha, ctcode) if verified.get('code', 0) == 200: break - result = self.api.login.LoginViaCellphone(phone, captcha=captcha, ctcode=ctcode) + result = self.api.login.LoginViaCellphone( + phone, captcha=captcha, ctcode=ctcode) self.get_user_info() def get_qrcode(self): @@ -122,12 +127,14 @@ def get_qrcode(self): def detail_names(self, ids: List[int]) -> List[str]: songs: list = self.api.track.GetTrackDetail(song_ids=ids)["songs"] - detail = [(data["name"] + "-" + ",".join([names["name"] for names in data["ar"]])) for data in songs] + detail = [(data["name"] + "-" + ",".join([names["name"] + for names in data["ar"]])) for data in songs] return detail @logger.catch() def get_detail(self, ids: List[int]): - data: list = self.api.track.GetTrackAudio(song_ids=ids, bitrate=ncm_config.ncm_bitrate * 1000)["data"] + data: list = self.api.track.GetTrackAudio( + song_ids=ids, bitrate=ncm_config.ncm_bitrate * 1000)["data"] names: list = self.detail_names(ids) for i in range(len(ids)): data[i]['ncm_name'] = names[i] @@ -143,7 +150,8 @@ async def music_check(self, nid: Union[int, List[int]], event: Union[GroupMessag info = music.search(Q["id"] == i) if info: try: - tasks.append(asyncio.create_task(self.upload_data_file(event=event, data=info[0]))) + tasks.append(asyncio.create_task( + self.upload_data_file(event=event, data=info[0]))) del_nid.append(i) except Exception: continue @@ -154,7 +162,8 @@ async def music_check(self, nid: Union[int, List[int]], event: Union[GroupMessag info = music.search(Q["id"] == nid) if info: try: - tasks.append(asyncio.create_task(self.upload_data_file(event=event, data=info[0]))) + tasks.append(asyncio.create_task( + self.upload_data_file(event=event, data=info[0]))) return except Exception as e: if isinstance(e, ActionFailed) and e.info.get("retcode") != 10003: @@ -168,7 +177,8 @@ async def music_check(self, nid: Union[int, List[int]], event: Union[GroupMessag await self.start_upload(ids=nid, event=event) async def search_song(self, keyword: str, limit: int = 1) -> int: # 搜索歌曲 - res = self.api.cloudsearch.GetSearchResult(keyword=keyword, stype=SONG, limit=limit) + res = self.api.cloudsearch.GetSearchResult( + keyword=keyword, stype=SONG, limit=limit) logger.debug(f"搜索歌曲{keyword},返回结果:{res}") if "result" in res.keys(): data = res["result"]["songs"] @@ -178,10 +188,12 @@ async def search_song(self, keyword: str, limit: int = 1) -> int: # 搜索歌 return data[0]["id"] async def search_user(self, keyword: str, limit: int = 1): # 搜索用户 - self.api.cloudsearch.GetSearchResult(keyword=keyword, stype=USER, limit=limit) + self.api.cloudsearch.GetSearchResult( + keyword=keyword, stype=USER, limit=limit) async def search_playlist(self, keyword: str, limit: int = 1): # 搜索歌单 - self.api.cloudsearch.GetSearchResult(keyword=keyword, stype=PLAYLIST, limit=limit) + self.api.cloudsearch.GetSearchResult( + keyword=keyword, stype=PLAYLIST, limit=limit) @staticmethod def check_message(message_id: int): From d851d5a87b5f044edd60c5ee85301db60ca7f325 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:51:48 +0800 Subject: [PATCH 2/8] refactor: convert string with anomalous backslash into a raw string (#32) Backslash is present in the literal string but is not a valid escape sequence. If it is intended to be an escape sequence, use the correct escape characters. If it is intended to be a literal backslash, it can either be replaced with with an escaped backslash `\\`, or you can add an `r` prefix to make it a "raw" string. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/today_in_history/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/today_in_history/__init__.py b/src/plugins/today_in_history/__init__.py index 76c2c92..eb8944c 100644 --- a/src/plugins/today_in_history/__init__.py +++ b/src/plugins/today_in_history/__init__.py @@ -50,7 +50,7 @@ async def _(event: MessageEvent): # api处理->json def text_handle(text: str) -> json: - text = text.replace("<\/a>", "") + text = text.replace(r"<\/a>", "") text = text.replace("\n", "") # 去除html标签 From 3d8f3677422136ace49c268a6ed1e6b86e24361b Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:52:48 +0800 Subject: [PATCH 3/8] refactor: remove commented out code (#33) It is recommended to remove any commented code in your codebase. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/ncm/__init__.py | 4 ---- src/plugins/ncm/data_source.py | 9 --------- 2 files changed, 13 deletions(-) diff --git a/src/plugins/ncm/__init__.py b/src/plugins/ncm/__init__.py index e9701af..e92d535 100644 --- a/src/plugins/ncm/__init__.py +++ b/src/plugins/ncm/__init__.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- from typing import Tuple, Any, Union from nonebot import on_regex, on_command, on_message @@ -89,7 +87,6 @@ async def music_set_rule(event: Union[GroupMessageEvent, PrivateMessageEvent]) - async def music_reply_rule(event: Union[GroupMessageEvent, PrivateMessageEvent]): - # logger.info(event.get_plaintext()) return event.reply and event.get_plaintext().strip() == "下载" @@ -125,7 +122,6 @@ async def receive_song( MessageSegment.music(type_="163", id_=_id)) ) nncm.get_song(message_id=message_id["message_id"], nid=_id) - # try: # except ActionFailed as e: # logger.error(e.info) diff --git a/src/plugins/ncm/data_source.py b/src/plugins/ncm/data_source.py index 3088d0e..99dc65a 100644 --- a/src/plugins/ncm/data_source.py +++ b/src/plugins/ncm/data_source.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- import asyncio import re import time @@ -273,13 +271,6 @@ async def upload_private_file(user_id: int, file: str, name: str): await bot.send_private_msg(user_id=user_id, message=Message(MessageSegment.text( "[ERROR] 文件上传失败\r\n[原因] 上传超时(一般来说还在传,建议等待五分钟)"))) - # @run_sync - # def get_zip(self, lid: int, filenames: list): - # zip_file_new = f'{lid}.zip' - # with zipfile.ZipFile(str(Path.cwd().joinpath("music").joinpath(zip_file_new)), 'w', zipfile.ZIP_DEFLATED) as z: - # for f in filenames: - # z.write(str(f), f.name) - # return zip_file_new async def upload(self, data: dict, fr: str, event: Union[GroupMessageEvent, PrivateMessageEvent]): if data["code"] == 404: logger.error("未从网易云读取到下载地址") From b66f389bc5172e9d184c9bee5ec7b6ade587543a Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:53:39 +0800 Subject: [PATCH 4/8] refactor: remove module level global statement (#34) The global statement is used to specify that the assignment to that name is an assignment to the variable in the global (module) scope, rather than in the local scope. At the module level, this statement is redundant because the local scope and global scope are the same. It is recommended to remove the `global` statement. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/waifu/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/plugins/waifu/__init__.py b/src/plugins/waifu/__init__.py index 2528ff0..0d41e22 100644 --- a/src/plugins/waifu/__init__.py +++ b/src/plugins/waifu/__init__.py @@ -260,7 +260,6 @@ async def check_divorce_rule(event): # 分手 if waifu_cd_bye > -1: - global cd_bye cd_bye = {} bye = on_command( "离婚", From 0e75ecfa453afc3136bd74de80cb09bf91d9ef67 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:55:39 +0800 Subject: [PATCH 5/8] refactor: refactor unnecessary `else` / `elif` when `if` block has a `return` statement (#35) The use of `else` or `elif` becomes redundant and can be dropped if the last statement under the leading `if` / `elif` block is a `return` statement. In the case of an `elif` after `return`, it can be written as a separate `if` block. For `else` blocks after `return`, the statements can be shifted out of `else`. Please refer to the examples below for reference. Refactoring the code this way can improve code-readability and make it easier to maintain. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/ncm/__init__.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/plugins/ncm/__init__.py b/src/plugins/ncm/__init__.py index e92d535..f004b2e 100644 --- a/src/plugins/ncm/__init__.py +++ b/src/plugins/ncm/__init__.py @@ -41,7 +41,7 @@ async def song_is_open(event: Union[GroupMessageEvent, PrivateMessageEvent]) -> setting.insert({"group_id": event.group_id, "song": False, "list": False}) return False - elif isinstance(event, PrivateMessageEvent): + if isinstance(event, PrivateMessageEvent): if info := setting.search(Q["user_id"] == event.user_id): return info[0]["song"] setting.insert({"user_id": event.user_id, "song": True, "list": True}) @@ -55,27 +55,24 @@ async def playlist_is_open( info = setting.search(Q["group_id"] == event.group_id) if info: return info[0]["list"] - else: - setting.insert({"group_id": event.group_id, - "song": False, "list": False}) - return False + setting.insert({"group_id": event.group_id, + "song": False, "list": False}) + return False elif isinstance(event, PrivateMessageEvent): info = setting.search(Q["user_id"] == event.user_id) if info: return info[0]["list"] - else: - setting.insert({"user_id": event.user_id, - "song": True, "list": True}) - return True + setting.insert({"user_id": event.user_id, + "song": True, "list": True}) + return True async def check_search() -> bool: info = setting.search(Q["global"] == "search") if info: return info[0]["value"] - else: - setting.insert({"global": "search", "value": True}) - return True + setting.insert({"global": "search", "value": True}) + return True async def music_set_rule(event: Union[GroupMessageEvent, PrivateMessageEvent]) -> bool: From 964798e9efbf59f4b7ff3be6b5d1610cb5c774b5 Mon Sep 17 00:00:00 2001 From: wling <90316914+wling-art@users.noreply.github.com> Date: Wed, 10 Jan 2024 04:58:39 +0800 Subject: [PATCH 6/8] Update __init__.py --- src/plugins/ncm/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/ncm/__init__.py b/src/plugins/ncm/__init__.py index f004b2e..e2e6eb3 100644 --- a/src/plugins/ncm/__init__.py +++ b/src/plugins/ncm/__init__.py @@ -58,7 +58,7 @@ async def playlist_is_open( setting.insert({"group_id": event.group_id, "song": False, "list": False}) return False - elif isinstance(event, PrivateMessageEvent): + if isinstance(event, PrivateMessageEvent): info = setting.search(Q["user_id"] == event.user_id) if info: return info[0]["list"] From eecbb5ea25725665504c5f6c8f7da657dda1396d Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 05:04:50 +0800 Subject: [PATCH 7/8] refactor: use `is` to compare type of objects (#36) It is recommended to use `identity test` ( `is` ) instead of equality test ( `==` ) when you need to compare types of two objects. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/nonebot_plugin_addFriend/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/nonebot_plugin_addFriend/utils.py b/src/plugins/nonebot_plugin_addFriend/utils.py index b18e230..92e8612 100644 --- a/src/plugins/nonebot_plugin_addFriend/utils.py +++ b/src/plugins/nonebot_plugin_addFriend/utils.py @@ -13,7 +13,7 @@ def filterFriend(comment, type, allowTextList): async def parseMsg(commandText, resMsg, font_size=32, isText=1): - if type(resMsg) == list: + if type(resMsg) is list: temp = ''.join(str(item)+'\n' for item in resMsg) temp = temp.replace("'", "").replace('"', '') resMsg = temp From 0208cdc22de75e9c37be755234dd1cb4deac0c3b Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 10 Jan 2024 05:06:11 +0800 Subject: [PATCH 8/8] refactor: refactor unnecessary `else` / `elif` when `if` block has a `raise` statement (#37) `raise` causes control flow to be disrupted, as it will exit the block. It is recommended to check other conditions using another `if` statement, and get rid of `else` statements as they are unnecessary. Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com> --- src/plugins/nonebot_plugin_heweather/weather_data.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/plugins/nonebot_plugin_heweather/weather_data.py b/src/plugins/nonebot_plugin_heweather/weather_data.py index 01c0c18..9572fc6 100644 --- a/src/plugins/nonebot_plugin_heweather/weather_data.py +++ b/src/plugins/nonebot_plugin_heweather/weather_data.py @@ -84,11 +84,10 @@ async def _get_city_id(self, api_type: str = "lookup"): logger.debug(res) if res["code"] == "404": raise CityNotFoundError() - elif res["code"] != "200": + if res["code"] != "200": raise APIError(f'错误! 错误代码: {res["code"]}{self.__reference}') - else: - self.city_name = res["location"][0]["name"] - return res["location"][0]["id"] + self.city_name = res["location"][0]["name"] + return res["location"][0]["id"] def _data_validate(self): if self.now.code != "200" or self.daily.code != "200":