Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/bots/aiocqhttp/message.py

255 lines
11 KiB
Python
Raw Normal View History

2021-10-08 11:54:27 +00:00
import asyncio
2022-05-12 14:25:22 +00:00
import datetime
2021-11-12 14:25:53 +00:00
import html
2022-04-23 14:32:08 +00:00
import random
2021-10-08 11:54:27 +00:00
import re
import traceback
from pathlib import Path
2021-11-16 14:19:48 +00:00
from typing import List, Union
2021-10-08 11:54:27 +00:00
2022-02-02 05:16:49 +00:00
import aiocqhttp.exceptions
2021-10-09 13:32:54 +00:00
from aiocqhttp import MessageSegment
2021-11-12 14:25:53 +00:00
2022-06-12 07:07:53 +00:00
from bots.aiocqhttp.client import bot
from bots.aiocqhttp.message_guild import MessageSession as MessageSessionGuild
2022-07-14 13:23:15 +00:00
from config import Config
2022-06-27 17:00:00 +00:00
from core.builtins.message import MessageSession as MS
from core.elements import Plain, Image, MsgInfo, Session, Voice, FetchTarget as FT, \
2022-06-28 06:11:03 +00:00
FetchedSession as FS, FinishedSession as FinS
2021-12-31 14:44:34 +00:00
from core.elements.message.chain import MessageChain
2021-10-10 14:05:19 +00:00
from core.logger import Logger
2021-10-08 11:54:27 +00:00
from database import BotDBUtil
2022-07-14 13:23:15 +00:00
enable_analytics = Config('enable_analytics')
2022-01-15 14:28:35 +00:00
class FinishedSession(FinS):
async def delete(self):
"""
用于删除这条消息
"""
try:
2022-06-28 08:47:00 +00:00
for x in self.messageId:
await bot.call_action('delete_msg', message_id=x)
2022-01-15 14:28:35 +00:00
except Exception:
2022-01-20 13:31:50 +00:00
Logger.error(traceback.format_exc())
2021-10-08 11:54:27 +00:00
2022-05-12 14:25:22 +00:00
last_send_typing_time = {}
2021-10-08 11:54:27 +00:00
class MessageSession(MS):
class Feature:
image = True
voice = True
2022-01-16 13:24:15 +00:00
embed = False
2021-10-11 14:45:28 +00:00
forward = True
2021-11-16 14:19:48 +00:00
delete = True
2022-01-16 13:24:15 +00:00
wait = True
quote = True
2022-01-15 14:28:35 +00:00
async def sendMessage(self, msgchain, quote=True, disable_secret_check=False) -> FinishedSession:
2021-10-08 11:54:27 +00:00
msg = MessageSegment.text('')
if quote and self.target.targetFrom == 'QQ|Group' and self.session.message:
2021-10-08 11:54:27 +00:00
msg = MessageSegment.reply(self.session.message.message_id)
2021-12-31 14:44:34 +00:00
msgchain = MessageChain(msgchain)
2022-01-08 08:08:25 +00:00
if not msgchain.is_safe and not disable_secret_check:
2021-11-17 14:14:57 +00:00
return await self.sendMessage('https://wdf.ink/6Oup')
2022-06-26 06:06:26 +00:00
self.sent.append(msgchain)
2021-12-31 14:44:34 +00:00
count = 0
for x in msgchain.asSendable(embed=False):
if isinstance(x, Plain):
msg = msg + MessageSegment.text(('\n' if count != 0 else '') + x.text)
elif isinstance(x, Image):
msg = msg + MessageSegment.image(Path(await x.get()).as_uri())
elif isinstance(x, Voice):
2022-03-05 13:34:08 +00:00
msg = msg + MessageSegment.record(file=Path(x.path).as_uri())
2021-12-31 14:44:34 +00:00
count += 1
2021-10-10 14:05:19 +00:00
Logger.info(f'[Bot] -> [{self.target.targetId}]: {msg}')
2021-10-08 11:54:27 +00:00
if self.target.targetFrom == 'QQ|Group':
2022-02-02 05:16:49 +00:00
try:
send = await bot.send_group_msg(group_id=self.session.target, message=msg)
except aiocqhttp.exceptions.ActionFailed:
2022-04-23 14:32:08 +00:00
anti_autofilter_word_list = ['ffk', '(阻止风向控制)', '(房蜂控)']
msg = msg + MessageSegment.text(random.choice(anti_autofilter_word_list))
2022-02-02 05:16:49 +00:00
send = await bot.send_group_msg(group_id=self.session.target, message=msg)
2021-10-08 11:54:27 +00:00
else:
send = await bot.send_private_msg(user_id=self.session.target, message=msg)
2022-06-28 06:11:03 +00:00
return FinishedSession(send['message_id'], [send])
2021-10-08 11:54:27 +00:00
async def checkPermission(self):
if self.target.targetFrom == 'QQ' \
or self.target.senderInfo.check_TargetAdmin(self.target.targetId) \
2022-07-31 08:33:20 +00:00
or self.target.senderInfo.query.isSuperUser:
2021-10-08 11:54:27 +00:00
return True
2021-11-12 14:25:53 +00:00
get_member_info = await bot.call_action('get_group_member_info', group_id=self.session.target,
user_id=self.session.sender)
2021-10-08 11:54:27 +00:00
if get_member_info['role'] in ['owner', 'admin']:
return True
return False
async def checkNativePermission(self):
if self.target.targetFrom == 'QQ':
return True
get_member_info = await bot.call_action('get_group_member_info', group_id=self.session.target,
user_id=self.session.sender)
if get_member_info['role'] in ['owner', 'admin']:
return True
return False
def asDisplay(self, message=None):
2022-01-20 12:13:03 +00:00
return ''.join(
2022-06-28 06:11:03 +00:00
re.split(r'\[CQ:.*?]', html.unescape(self.session.message.message if message is None else message))).strip()
2021-10-08 11:54:27 +00:00
2021-10-11 14:45:28 +00:00
async def fake_forward_msg(self, nodelist):
if self.target.targetFrom == 'QQ|Group':
2021-11-17 16:17:41 +00:00
await bot.call_action('send_group_forward_msg', group_id=int(self.session.target), messages=nodelist)
2021-10-11 14:45:28 +00:00
2021-10-08 11:54:27 +00:00
async def delete(self):
try:
if isinstance(self.session.message, list):
for x in self.session.message:
await bot.call_action('delete_msg', message_id=x['message_id'])
else:
await bot.call_action('delete_msg', message_id=self.session.message['message_id'])
except Exception:
2022-01-20 13:31:50 +00:00
Logger.error(traceback.format_exc())
2021-10-08 11:54:27 +00:00
2022-03-05 13:34:08 +00:00
async def call_api(self, action, **params):
return await bot.call_action(action, **params)
2021-10-08 11:54:27 +00:00
class Typing:
def __init__(self, msg: MS):
self.msg = msg
async def __aenter__(self):
2022-05-12 14:25:22 +00:00
if self.msg.target.targetFrom == 'QQ|Group':
if self.msg.session.sender in last_send_typing_time:
2022-05-15 15:55:04 +00:00
if datetime.datetime.now().timestamp() - last_send_typing_time[self.msg.session.sender] <= 3600:
2022-05-12 14:25:22 +00:00
return
last_send_typing_time[self.msg.session.sender] = datetime.datetime.now().timestamp()
2021-11-12 14:25:53 +00:00
await bot.send_group_msg(group_id=self.msg.session.target,
2022-05-12 14:25:22 +00:00
message=f'[CQ:poke,qq={self.msg.session.sender}]')
2021-10-08 11:54:27 +00:00
async def __aexit__(self, exc_type, exc_val, exc_tb):
pass
2022-01-15 13:46:23 +00:00
class FetchedSession(FS):
def __init__(self, targetFrom, targetId):
self.target = MsgInfo(targetId=f'{targetFrom}|{targetId}',
senderId=f'{targetFrom}|{targetId}',
targetFrom=targetFrom,
senderFrom=targetFrom,
2022-06-12 14:30:02 +00:00
senderName='',
2022-06-28 06:11:03 +00:00
clientName='QQ',
messageId=0,
replyId=None)
2022-01-15 13:46:23 +00:00
self.session = Session(message=False, target=targetId, sender=targetId)
if targetFrom == 'QQ|Guild':
self.parent = MessageSessionGuild(self.target, self.session)
else:
self.parent = MessageSession(self.target, self.session)
2021-10-08 11:54:27 +00:00
class FetchTarget(FT):
2022-01-05 11:14:45 +00:00
name = 'QQ'
2021-10-08 11:54:27 +00:00
@staticmethod
2022-01-15 13:46:23 +00:00
async def fetch_target(targetId) -> Union[FetchedSession, bool]:
2021-11-16 14:19:48 +00:00
matchTarget = re.match(r'^(QQ\|Group|QQ\|Guild|QQ)\|(.*)', targetId)
2021-10-08 11:54:27 +00:00
if matchTarget:
2022-01-15 13:46:23 +00:00
return FetchedSession(matchTarget.group(1), matchTarget.group(2))
2021-11-16 14:19:48 +00:00
return False
2021-10-08 11:54:27 +00:00
@staticmethod
2022-01-15 13:46:23 +00:00
async def fetch_target_list(targetList: list) -> List[FetchedSession]:
2021-10-08 11:54:27 +00:00
lst = []
group_list_raw = await bot.call_action('get_group_list')
group_list = []
for g in group_list_raw:
group_list.append(g['group_id'])
friend_list_raw = await bot.call_action('get_friend_list')
friend_list = []
2021-11-16 14:19:48 +00:00
guild_list_raw = await bot.call_action('get_guild_list')
guild_list = []
for g in guild_list_raw:
get_channel_list = await bot.call_action('get_guild_channel_list', guild_id=g['guild_id'])
for channel in get_channel_list:
if channel['channel_type'] == 1:
guild_list.append(f"{str(g['guild_id'])}|{str(channel['channel_id'])}")
2021-10-08 11:54:27 +00:00
for f in friend_list_raw:
friend_list.append(f)
for x in targetList:
fet = await FetchTarget.fetch_target(x)
if fet:
if fet.target.targetFrom == 'QQ|Group':
if fet.session.target not in group_list:
continue
if fet.target.targetFrom == 'QQ':
if fet.session.target not in friend_list:
continue
2021-11-16 14:19:48 +00:00
if fet.target.targetFrom == 'QQ|Guild':
if fet.session.target not in guild_list:
continue
2021-10-08 11:54:27 +00:00
lst.append(fet)
return lst
@staticmethod
2022-01-15 13:46:23 +00:00
async def post_message(module_name, message, user_list: List[FetchedSession] = None):
2021-10-08 11:54:27 +00:00
send_list = []
if user_list is not None:
for x in user_list:
try:
send = await x.sendDirectMessage(message)
2021-10-08 11:54:27 +00:00
send_list.append(send)
2022-07-14 13:23:15 +00:00
if enable_analytics:
BotDBUtil.Analytics(x).add('', module_name, 'schedule')
2021-10-08 11:54:27 +00:00
except Exception:
2022-01-20 13:31:50 +00:00
Logger.error(traceback.format_exc())
2021-10-08 11:54:27 +00:00
else:
get_target_id = BotDBUtil.Module.get_enabled_this(module_name)
group_list_raw = await bot.call_action('get_group_list')
group_list = []
for g in group_list_raw:
group_list.append(g['group_id'])
friend_list_raw = await bot.call_action('get_friend_list')
friend_list = []
for f in friend_list_raw:
2022-01-15 13:46:23 +00:00
friend_list.append(f['user_id'])
2021-11-16 14:19:48 +00:00
guild_list_raw = await bot.call_action('get_guild_list')
guild_list = []
for g in guild_list_raw:
2022-06-17 06:02:13 +00:00
try:
get_channel_list = await bot.call_action('get_guild_channel_list', guild_id=g['guild_id'],
no_cache=True)
for channel in get_channel_list:
if channel['channel_type'] == 1:
guild_list.append(f"{str(g['guild_id'])}|{str(channel['channel_id'])}")
except Exception:
traceback.print_exc()
continue
2021-10-08 11:54:27 +00:00
for x in get_target_id:
fetch = await FetchTarget.fetch_target(x)
2021-11-16 23:08:09 +00:00
Logger.info(fetch)
2021-10-08 11:54:27 +00:00
if fetch:
if fetch.target.targetFrom == 'QQ|Group':
2022-01-15 13:46:23 +00:00
if int(fetch.session.target) not in group_list:
2021-10-08 11:54:27 +00:00
continue
if fetch.target.targetFrom == 'QQ':
2022-01-15 13:46:23 +00:00
if int(fetch.session.target) not in friend_list:
2021-10-08 11:54:27 +00:00
continue
2021-11-16 14:19:48 +00:00
if fetch.target.targetFrom == 'QQ|Guild':
if fetch.session.target not in guild_list:
continue
2021-10-08 11:54:27 +00:00
try:
2021-11-16 14:19:48 +00:00
print(fetch)
send = await fetch.sendDirectMessage(message)
2022-07-14 13:23:15 +00:00
if enable_analytics:
BotDBUtil.Analytics(fetch).add('', module_name, 'schedule')
2021-10-08 11:54:27 +00:00
send_list.append(send)
await asyncio.sleep(0.5)
except Exception:
2022-01-20 13:31:50 +00:00
Logger.error(traceback.format_exc())
2021-10-08 11:54:27 +00:00
return send_list