Skip to content

Commit

Permalink
feat: initial quick confirm
Browse files Browse the repository at this point in the history
Signed-off-by: xtex <xtexchooser@duck.com>
  • Loading branch information
xtexChooser committed Dec 10, 2023
1 parent 32846ab commit dae1c69
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 19 deletions.
34 changes: 22 additions & 12 deletions bots/matrix/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from bots.matrix import client
from bots.matrix.client import bot
from bots.matrix.info import client_name
from bots.matrix.message import MessageSession, FetchTarget
from bots.matrix.message import MessageSession, FetchTarget, ReactionMessageSession
from core.builtins import PrivateAssets, Url
from core.logger import Logger
from core.parser.message import parser
Expand Down Expand Up @@ -50,36 +50,45 @@ async def on_room_member(room: nio.MatrixRoom, event: nio.RoomMemberEvent):
Logger.info(f"Left empty room {room.room_id}")


async def on_message(room: nio.MatrixRoom, event: nio.RoomMessageFormatted):
async def on_message(room: nio.MatrixRoom, event: nio.Event):
if event.sender != bot.user_id and bot.olm:
for device_id, olm_device in bot.device_store[event.sender].items():
if bot.olm.is_device_verified(olm_device):
continue
bot.verify_device(olm_device)
Logger.info(f"trust olm device for device id {event.sender} -> {device_id}")
if event.source['content']['msgtype'] == 'm.notice':
if isinstance(event, nio.RoomMessageFormatted) and event.source['content']['msgtype'] == 'm.notice':
# https://spec.matrix.org/v1.7/client-server-api/#mnotice
return
is_room = room.member_count != 2 or room.join_rule != 'invite'
target_id = room.room_id if is_room else event.sender
reply_id = None
if 'm.relates_to' in event.source['content'] and 'm.in_reply_to' in event.source['content']['m.relates_to']:
reply_id = event.source['content']['m.relates_to']['m.in_reply_to']['event_id']

resp = await bot.get_displayname(event.sender)
if isinstance(resp, nio.ErrorResponse):
Logger.error(f"Failed to get display name for {event.sender}")
return
sender_name = resp.displayname

msg = MessageSession(MsgInfo(target_id=f'Matrix|{target_id}',
sender_id=f'Matrix|{event.sender}',
target_from=f'Matrix',
sender_from='Matrix',
sender_name=sender_name,
client_name=client_name,
message_id=event.event_id,
reply_id=reply_id),
Session(message=event.source, target=room.room_id, sender=event.sender))
target = MsgInfo(target_id=f'Matrix|{target_id}',
sender_id=f'Matrix|{event.sender}',
target_from=f'Matrix',
sender_from='Matrix',
sender_name=sender_name,
client_name=client_name,
message_id=event.event_id,
reply_id=reply_id)
session = Session(message=event.source, target=room.room_id, sender=event.sender)

msg = None
if isinstance(event, nio.RoomMessageFormatted):
msg = MessageSession(target, session)
elif isinstance(event, nio.ReactionEvent):
msg = ReactionMessageSession(target, session)
else:
raise NotImplemented
asyncio.create_task(parser(msg))


Expand Down Expand Up @@ -141,6 +150,7 @@ async def start():
bot.add_event_callback(on_invite, nio.InviteEvent)
bot.add_event_callback(on_room_member, nio.RoomMemberEvent)
bot.add_event_callback(on_message, nio.RoomMessageFormatted)
bot.add_event_callback(on_message, nio.ReactionEvent)
bot.add_to_device_callback(on_verify, nio.KeyVerificationEvent)
bot.add_event_callback(on_in_room_verify, nio.RoomMessageUnknown)

Expand Down
29 changes: 28 additions & 1 deletion bots/matrix/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ async def to_message_chain(self):

async def delete(self):
try:
await bot.room_redact(self.session.target, self.session.message['event_id'])
await bot.room_redact(self.session.target, self.target.message_id)
except Exception:
Logger.error(traceback.format_exc())

Expand All @@ -221,6 +221,33 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
pass


class ReactionMessageSession(MessageSession):
class Feature(MessageSession.Feature):
pass

class Typing(MessageSession.Typing):
pass

def as_display(self, text_only=False):
if text_only:
return ''
return self.session.message['content']['m.relates_to']['key']

async def to_message_chain(self):
return MessageChain([])

def is_quick_confirm(self, target: MessageSession) -> bool:
content = self.session.message['content']['m.relates_to']
if content['rel_type'] == 'm.annotation':
if target is None or content['event_id'] == target.target.message_id:
if content['key'] in ['👍️', '✔️', '🎉']: # todo: move to config
return True
return False

asDisplay = as_display
toMessageChain = to_message_chain


class FetchedSession(Bot.FetchedSession):

async def _resolve_matrix_room_(self):
Expand Down
1 change: 1 addition & 0 deletions config/config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ debug = false
cache_path = "./cache/"
command_prefix = ["~", "~",]
confirm_command = ["是", "对", "對", "yes", "Yes", "YES", "y", "Y",]
quick_confirm = true
disabled_bots =
locale = "zh_cn"
timezone_offset = "+8"
Expand Down
4 changes: 3 additions & 1 deletion core/builtins/message/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from core.builtins.message.internal import *
from core.builtins.tasks import MessageTaskManager
from core.builtins.temp import ExecutionLockList
from core.builtins.utils import confirm_command
from core.builtins.utils import confirm_command, quick_confirm
from core.exceptions import WaitCancelException
from core.types.message import MessageSession as MessageSessionT, MsgInfo, Session
from core.utils.i18n import Locale
Expand Down Expand Up @@ -52,6 +52,8 @@ async def wait_confirm(self, message_chain=None, quote=True, delete=True, append
await send.delete()
if result.as_display(text_only=True) in confirm_command:
return True
if quick_confirm and result.is_quick_confirm(self):
return True
return False
else:
raise WaitCancelException
Expand Down
2 changes: 1 addition & 1 deletion core/builtins/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def add_task(cls, session: MessageSession, flag, all_=False, reply=None):
Logger.debug(cls._list)

@classmethod
def get_result(cls, session: MessageSession):
def get_result(cls, session: MessageSession) -> MessageSession:
if 'result' in cls._list[session.target.target_id][session.target.sender_id][session]:
return cls._list[session.target.target_id][session.target.sender_id][session]['result']
else:
Expand Down
3 changes: 2 additions & 1 deletion core/builtins/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@


confirm_command = Config('confirm_command', default=["是", "对", "對", "yes", "Yes", "YES", "y", "Y"])
quick_confirm = Config('quick_confirm', default=True)
command_prefix = Config('command_prefix', default=['~', '~']) # 消息前缀


class EnableDirtyWordCheck:
status = False


__all__ = ["confirm_command", "command_prefix", "EnableDirtyWordCheck", "PrivateAssets", "Secret"]
__all__ = ["confirm_command", "quick_confirm", "command_prefix", "EnableDirtyWordCheck", "PrivateAssets", "Secret"]
9 changes: 8 additions & 1 deletion core/types/message/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from typing import List, Union, Dict
from typing import List, Self, Union, Dict

from core.exceptions import FinishedException
from .chain import MessageChain
Expand Down Expand Up @@ -201,6 +201,13 @@ async def check_native_permission(self):
"""
raise NotImplementedError

def is_quick_confirm(self, target: Self = None) -> bool:
"""
用于检查消息是否可用作快速确认事件。
:param target: 确认的目标消息
"""
return False

async def fake_forward_msg(self, nodelist):
"""
用于发送假转发消息(QQ)。
Expand Down
6 changes: 4 additions & 2 deletions modules/wiki/wiki.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import filetype

from core.builtins import Bot, Plain, Image, Voice, Url, confirm_command
from core.builtins import Bot, Plain, Image, Voice, Url, confirm_command, quick_confirm
from core.component import module
from core.exceptions import AbuseWarning
from core.logger import Logger
Expand All @@ -25,7 +25,7 @@


@wiki.command('<PageName> [-l <lang>] {{wiki.help}}',
options_desc={'-l': '{wiki.help.option.l}'})
options_desc={'-l': '{wiki.help.option.l}'})
async def _(msg: Bot.MessageSession):
get_lang = msg.parsed_msg.get('-l', False)
if get_lang:
Expand Down Expand Up @@ -351,6 +351,8 @@ async def wait_confirm():
index = 0
if confirm.as_display(text_only=True) in confirm_command:
auto_index = True
if quick_confirm and confirm.is_quick_confirm(session):
auto_index = True
elif confirm.as_display(text_only=True).isdigit():
index = int(confirm.as_display()) - 1
else:
Expand Down

0 comments on commit dae1c69

Please sign in to comment.