Skip to content

Commit

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

Details: None

Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
  • Loading branch information
deepsource-autofix[bot] authored and DoroWolf committed Dec 15, 2024
1 parent 8c758ef commit 73f5540
Show file tree
Hide file tree
Showing 175 changed files with 12,673 additions and 9,178 deletions.
22 changes: 12 additions & 10 deletions bots/aiocqhttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@

from core.config import Config

access_token = Config('qq_access_token', cfg_type=str, secret=True, table_name='bot_aiocqhttp')
access_token = Config(
"qq_access_token", cfg_type=str, secret=True, table_name="bot_aiocqhttp"
)


class EventModded(Event):
@staticmethod
def from_payload(payload: Dict[str, Any]) -> 'Optional[Event]':
def from_payload(payload: Dict[str, Any]) -> "Optional[Event]":
"""
从 OneBot 事件数据构造 `Event` 对象。
"""
Expand All @@ -29,9 +31,9 @@ def detail_type(self) -> str:
事件具体类型,依 `type` 的不同而不同,以 ``message`` 类型为例,有
``private``、``group``、``discuss`` 等。
"""
if self.type == 'message_sent':
return self['message_type']
return self[f'{self.type}_type']
if self.type == "message_sent":
return self["message_type"]
return self[f"{self.type}_type"]


class CQHttpModded(CQHttp):
Expand All @@ -42,13 +44,13 @@ async def _handle_event(self, payload: Dict[str, Any]) -> Any:
return

event_name = ev.name
self.logger.info(f'received event: {event_name}')
self.logger.info(f"received event: {event_name}")

if self._message_class and 'message' in ev:
ev['message'] = self._message_class(ev['message'])
if self._message_class and "message" in ev:
ev["message"] = self._message_class(ev["message"])
results = list(
filter(lambda r: r is not None, await
self._bus.emit(event_name, ev)))
filter(lambda r: r is not None, await self._bus.emit(event_name, ev))
)
# return the first non-none result
return results[0] if results else None

Expand Down
34 changes: 19 additions & 15 deletions bots/aiogram/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,33 @@
from core.types import MsgInfo, Session
from core.utils.info import Info

PrivateAssets.set(os.path.join(assets_path, 'private', 'aiogram'))
PrivateAssets.set(os.path.join(assets_path, "private", "aiogram"))
ignored_sender = Config("ignored_sender", ignored_sender_default)


@dp.message()
async def msg_handler(message: types.Message):
target_from = f'{target_prefix}|{message.chat.type.title()}'
target_id = f'{target_from}|{message.chat.id}'
sender_id = f'{sender_prefix}|{message.from_user.id}'
target_from = f"{target_prefix}|{message.chat.type.title()}"
target_id = f"{target_from}|{message.chat.id}"
sender_id = f"{sender_prefix}|{message.from_user.id}"
if sender_id in ignored_sender:
return
reply_id = None
if message.reply_to_message:
reply_id = message.reply_to_message.message_id
msg = MessageSession(MsgInfo(target_id=target_id,
sender_id=sender_id,
target_from=target_from,
sender_from=sender_prefix,
sender_prefix=message.from_user.username,
client_name=client_name,
message_id=message.message_id,
reply_id=reply_id),
Session(message=message, target=message.chat.id, sender=message.from_user.id))
msg = MessageSession(
MsgInfo(
target_id=target_id,
sender_id=sender_id,
target_from=target_from,
sender_from=sender_prefix,
sender_prefix=message.from_user.username,
client_name=client_name,
message_id=message.message_id,
reply_id=reply_id,
),
Session(message=message, target=message.chat.id, sender=message.from_user.id),
)
await parser(msg)


Expand All @@ -47,9 +51,9 @@ async def on_startup():
await load_prompt(FetchTarget)


if Config("enable", False, table_name='bot_aiogram'):
if Config("enable", False, table_name="bot_aiogram"):
Info.client_name = client_name
if 'subprocess' in sys.argv:
if "subprocess" in sys.argv:
Info.subprocess = True

dp.startup.register(on_startup)
Expand Down
4 changes: 2 additions & 2 deletions bots/aiogram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

from core.config import Config

token = Config('telegram_token', cfg_type=str, secret=True, table_name='bot_aiogram')
token = Config("telegram_token", cfg_type=str, secret=True, table_name="bot_aiogram")

if token:
bot = Bot(token=token, proxy=Config('proxy', cfg_type=str, secret=True))
bot = Bot(token=token, proxy=Config("proxy", cfg_type=str, secret=True))
dp = Dispatcher()
else:
bot = dp = False
142 changes: 100 additions & 42 deletions bots/aiogram/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,17 @@

from bots.aiogram.client import bot, token
from bots.aiogram.info import *
from core.builtins import (Bot, Plain, Image, Voice, MessageSession as MessageSessionT, I18NContext, MessageTaskManager,
FetchTarget as FetchTargetT, FinishedSession as FinishedSessionT)
from core.builtins import (
Bot,
Plain,
Image,
Voice,
MessageSession as MessageSessionT,
I18NContext,
MessageTaskManager,
FetchTarget as FetchTargetT,
FinishedSession as FinishedSessionT,
)
from core.builtins.message.chain import MessageChain
from core.builtins.message.elements import PlainElement, ImageElement, VoiceElement
from core.config import Config
Expand All @@ -16,7 +25,7 @@
from core.utils.http import download
from core.utils.image import image_split

enable_analytics = Config('enable_analytics', False)
enable_analytics = Config("enable_analytics", False)


class FinishedSession(FinishedSessionT):
Expand All @@ -41,8 +50,15 @@ class Feature:
typing = False
wait = True

async def send_message(self, message_chain, quote=True, disable_secret_check=False,
enable_parse_message=True, enable_split_image=True, callback=None) -> FinishedSession:
async def send_message(
self,
message_chain,
quote=True,
disable_secret_check=False,
enable_parse_message=True,
enable_split_image=True,
callback=None,
) -> FinishedSession:
message_chain = MessageChain(message_chain)
if not message_chain.is_safe and not disable_secret_check:
return await self.send_message(I18NContext("error.message.chain.unsafe"))
Expand All @@ -51,38 +67,64 @@ async def send_message(self, message_chain, quote=True, disable_secret_check=Fal
send = []
for x in message_chain.as_sendable(self, embed=False):
if isinstance(x, PlainElement):
send_ = await bot.send_message(self.session.target, x.text,
reply_to_message_id=self.session.message.message_id if quote
and count == 0 and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: {x.text}')
send_ = await bot.send_message(
self.session.target,
x.text,
reply_to_message_id=(
self.session.message.message_id
if quote and count == 0 and self.session.message
else None
),
)
Logger.info(f"[Bot] -> [{self.target.target_id}]: {x.text}")
send.append(send_)
count += 1
elif isinstance(x, ImageElement):
if enable_split_image:
split = await image_split(x)
for xs in split:
send_ = await bot.send_photo(self.session.target, FSInputFile(await xs.get()),
reply_to_message_id=self.session.message.message_id
if quote
and count == 0
and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(xs.__dict__)}')
send_ = await bot.send_photo(
self.session.target,
FSInputFile(await xs.get()),
reply_to_message_id=(
self.session.message.message_id
if quote and count == 0 and self.session.message
else None
),
)
Logger.info(
f"[Bot] -> [{self.target.target_id}]: Image: {str(xs.__dict__)}"
)
send.append(send_)
count += 1
else:
send_ = await bot.send_photo(self.session.target, FSInputFile(await x.get()),
reply_to_message_id=self.session.message.message_id
if quote
and count == 0
and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Image: {str(x.__dict__)}')
send_ = await bot.send_photo(
self.session.target,
FSInputFile(await x.get()),
reply_to_message_id=(
self.session.message.message_id
if quote and count == 0 and self.session.message
else None
),
)
Logger.info(
f"[Bot] -> [{self.target.target_id}]: Image: {str(x.__dict__)}"
)
send.append(send_)
count += 1
elif isinstance(x, VoiceElement):
send_ = await bot.send_audio(self.session.target, FSInputFile(x.path),
reply_to_message_id=self.session.message.message_id if quote
and count == 0 and self.session.message else None)
Logger.info(f'[Bot] -> [{self.target.target_id}]: Voice: {str(x.__dict__)}')
send_ = await bot.send_audio(
self.session.target,
FSInputFile(x.path),
reply_to_message_id=(
self.session.message.message_id
if quote and count == 0 and self.session.message
else None
),
)
Logger.info(
f"[Bot] -> [{self.target.target_id}]: Voice: {str(x.__dict__)}"
)
send.append(send_)
count += 1

Expand All @@ -98,30 +140,38 @@ async def check_native_permission(self):
chat = await bot.get_chat(self.session.target)
else:
chat = self.session.message.chat
if chat.type == 'private':
if chat.type == "private":
return True
admins = [member.user.id for member in await bot.get_chat_administrators(chat.id)]
admins = [
member.user.id for member in await bot.get_chat_administrators(chat.id)
]
if self.session.sender in admins:
return True
return False

def as_display(self, text_only=False):
if self.session.message.text:
return self.session.message.text
return ''
return ""

async def to_message_chain(self):
lst = []
if self.session.message.audio:
file = await bot.get_file(self.session.message.audio.file_id)
d = await download(f'https://api.telegram.org/file/bot{token}/{file.file_path}')
d = await download(
f"https://api.telegram.org/file/bot{token}/{file.file_path}"
)
lst.append(Voice(d))
if self.session.message.photo:
file = await bot.get_file(self.session.message.photo[-1]['file_id'])
lst.append(Image(f'https://api.telegram.org/file/bot{token}/{file.file_path}'))
file = await bot.get_file(self.session.message.photo[-1]["file_id"])
lst.append(
Image(f"https://api.telegram.org/file/bot{token}/{file.file_path}")
)
if self.session.message.voice:
file = await bot.get_file(self.session.message.voice.file_id)
d = await download(f'https://api.telegram.org/file/bot{token}/{file.file_path}')
d = await download(
f"https://api.telegram.org/file/bot{token}/{file.file_path}"
)
lst.append(Voice(d))
if self.session.message.caption:
lst.append(Plain(self.session.message.caption))
Expand Down Expand Up @@ -160,15 +210,17 @@ class FetchTarget(FetchTargetT):

@staticmethod
async def fetch_target(target_id, sender_id=None) -> Union[Bot.FetchedSession]:
target_pattern = r'|'.join(re.escape(item) for item in target_prefix_list)
match_target = re.match(fr'^({target_pattern})\|(.*)', target_id)
target_pattern = r"|".join(re.escape(item) for item in target_prefix_list)
match_target = re.match(rf"^({target_pattern})\|(.*)", target_id)

if match_target:
target_from = sender_from = match_target.group(1)
target_id = match_target.group(2)
if sender_id:
sender_pattern = r'|'.join(re.escape(item) for item in sender_prefix_list)
match_sender = re.match(fr'^({sender_pattern})\|(.*)', sender_id)
sender_pattern = r"|".join(
re.escape(item) for item in sender_prefix_list
)
match_sender = re.match(rf"^({sender_pattern})\|(.*)", sender_id)
if match_sender:
sender_from = match_sender.group(1)
sender_id = match_sender.group(2)
Expand All @@ -188,24 +240,28 @@ async def fetch_target_list(target_list: list) -> List[Bot.FetchedSession]:

@staticmethod
async def post_message(module_name, message, user_list=None, i18n=False, **kwargs):
module_name = None if module_name == '*' else module_name
module_name = None if module_name == "*" else module_name
if user_list:
for x in user_list:
try:
msgchain = message
if isinstance(message, str):
if i18n:
msgchain = MessageChain([Plain(x.parent.locale.t(message, **kwargs))])
msgchain = MessageChain(
[Plain(x.parent.locale.t(message, **kwargs))]
)
else:
msgchain = MessageChain([Plain(message)])
msgchain = MessageChain(msgchain)
await x.send_direct_message(msgchain)
if enable_analytics and module_name:
BotDBUtil.Analytics(x).add('', module_name, 'schedule')
BotDBUtil.Analytics(x).add("", module_name, "schedule")
except Exception:
Logger.error(traceback.format_exc())
else:
get_target_id = BotDBUtil.TargetInfo.get_target_list(module_name, client_name)
get_target_id = BotDBUtil.TargetInfo.get_target_list(
module_name, client_name
)
for x in get_target_id:
fetch = await FetchTarget.fetch_target(x.targetId)
if fetch:
Expand All @@ -215,13 +271,15 @@ async def post_message(module_name, message, user_list=None, i18n=False, **kwarg
msgchain = message
if isinstance(message, str):
if i18n:
msgchain = MessageChain([Plain(fetch.parent.locale.t(message, **kwargs))])
msgchain = MessageChain(
[Plain(fetch.parent.locale.t(message, **kwargs))]
)
else:
msgchain = MessageChain([Plain(message)])
msgchain = MessageChain(msgchain)
await fetch.send_direct_message(msgchain)
if enable_analytics and module_name:
BotDBUtil.Analytics(fetch).add('', module_name, 'schedule')
BotDBUtil.Analytics(fetch).add("", module_name, "schedule")
except Exception:
Logger.error(traceback.format_exc())

Expand Down
Loading

0 comments on commit 73f5540

Please sign in to comment.