Skip to content

Commit

Permalink
Squashed commit of the following:
Browse files Browse the repository at this point in the history
commit 8bf52650bda60ca052c21ebdafc1769972137e40
Author: xtex <xtexchooser@duck.com>
Date:   Sun Dec 10 13:55:17 2023 +0800

    Revert "fix: quick confirm in ~wiki"

    This reverts commit cb9c9e0.

    Signed-off-by: xtex <xtexchooser@duck.com>

commit 054a3e7e803a9c3b67a80608bce3ca10fb85a52b
Author: xtex <xtexchooser@duck.com>
Date:   Sun Dec 10 13:54:35 2023 +0800

    Revert "fix: quick confirm in ~wiki"

    This reverts commit 618e823.

commit 4b35043e691d164fe82b65a73208dd60175ff1df
Author: xtex <xtexchooser@duck.com>
Date:   Sun Dec 10 13:54:05 2023 +0800

    Revert "feat: initial quick confirm"

    This reverts commit dae1c69.

commit 7fd4c17ec956519d75042f6f6f14fc126ff8840f
Author: xtex <xtexchooser@duck.com>
Date:   Sun Dec 10 13:53:40 2023 +0800

    Revert "build(deps): update matrix-nio"

    This reverts commit 6311fa9.

commit 3aececb6720c3245cacddffc6f8c9acec5c8119a
Author: xtex <xtexchooser@duck.com>
Date:   Sun Dec 10 13:53:35 2023 +0800

    Revert "feat: init quick confirm (Teahouse-Studios#1046)"

    This reverts commit 0f8b85c.

    Signed-off-by: xtex <xtexchooser@duck.com>

Signed-off-by: xtex <xtexchooser@duck.com>
  • Loading branch information
xtexChooser committed Dec 10, 2023
1 parent fc8d071 commit cbbb7f3
Show file tree
Hide file tree
Showing 15 changed files with 41 additions and 94 deletions.
34 changes: 12 additions & 22 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, ReactionMessageSession
from bots.matrix.message import MessageSession, FetchTarget
from core.builtins import PrivateAssets, Url
from core.logger import Logger
from core.parser.message import parser
Expand Down Expand Up @@ -50,45 +50,36 @@ 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.Event):
async def on_message(room: nio.MatrixRoom, event: nio.RoomMessageFormatted):
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 isinstance(event, nio.RoomMessageFormatted) and event.source['content']['msgtype'] == 'm.notice':
if 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

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
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))
asyncio.create_task(parser(msg))


Expand Down Expand Up @@ -150,7 +141,6 @@ 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
33 changes: 1 addition & 32 deletions 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.target.message_id)
await bot.room_redact(self.session.target, self.session.message['event_id'])
except Exception:
Logger.error(traceback.format_exc())

Expand All @@ -221,37 +221,6 @@ 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: Union[MessageSession, FinishedSession]) -> bool:
content = self.session.message['content']['m.relates_to']
if content['rel_type'] == 'm.annotation':
if content['key'] in ['👍️', '✔️', '🎉']: # todo: move to config
if target is None:
return True
else:
msg = [target.target.message_id] if isinstance(target, MessageSession) else target.message_id
if content['event_id'] in msg:
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: 0 additions & 1 deletion config/config.toml.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ 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
10 changes: 4 additions & 6 deletions core/builtins/message/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
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, quick_confirm
from core.builtins.utils import confirm_command
from core.exceptions import WaitCancelException
from core.types.message import MessageSession as MessageSessionT, FinishedSession, MsgInfo, Session
from core.types.message import MessageSession as MessageSessionT, MsgInfo, Session
from core.utils.i18n import Locale
from core.utils.text import parse_time_string
from database import BotDBUtil
Expand Down Expand Up @@ -52,14 +52,12 @@ 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(send):
return True
return False
else:
raise WaitCancelException

async def wait_next_message(self, message_chain=None, quote=True, delete=False,
append_instruction=True) -> (MessageSessionT, FinishedSession):
append_instruction=True) -> MessageSessionT:
sent = None
ExecutionLockList.remove(self)
if message_chain is not None:
Expand All @@ -74,7 +72,7 @@ async def wait_next_message(self, message_chain=None, quote=True, delete=False,
if delete and sent is not None:
await sent.delete()
if result is not None:
return (result, sent)
return result
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) -> MessageSession:
def get_result(cls, session: 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: 1 addition & 2 deletions core/builtins/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@


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", "quick_confirm", "command_prefix", "EnableDirtyWordCheck", "PrivateAssets", "Secret"]
__all__ = ["confirm_command", "command_prefix", "EnableDirtyWordCheck", "PrivateAssets", "Secret"]
13 changes: 3 additions & 10 deletions 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, Self, Union, Dict
from typing import List, Union, Dict

from core.exceptions import FinishedException
from .chain import MessageChain
Expand Down Expand Up @@ -141,13 +141,13 @@ async def wait_confirm(self, message_chain=None, quote=True, delete=True):
"""
raise NotImplementedError

async def wait_next_message(self, message_chain=None, quote=True, delete=False, append_instruction=True) -> (Self, FinishedSession):
async def wait_next_message(self, message_chain=None, quote=True, delete=False, append_instruction=True):
"""
一次性模板,用于等待对象的下一条消息。
:param message_chain: 需要发送的确认消息,可不填
:param quote: 是否引用传入dict中的消息(默认为True)
:param delete: 是否在触发后删除消息
:return: 下一条消息的MessageChain对象和发出的提示消息
:return: 下一条消息的MessageChain对象
"""
raise NotImplementedError

Expand Down Expand Up @@ -201,13 +201,6 @@ async def check_native_permission(self):
"""
raise NotImplementedError

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

async def fake_forward_msg(self, nodelist):
"""
用于发送假转发消息(QQ)。
Expand Down
6 changes: 3 additions & 3 deletions modules/chemical_code/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,9 @@ async def timer(start):

await asyncio.gather(ans(msg, csr['name'], random_mode), timer(time_start))
else:
result, _ = await msg.wait_next_message([Plain(msg.locale.t('chemical_code.message.showid', id=csr["id"])),
Image(newpath), Plain(msg.locale.t('chemical_code.message.captcha',
times=set_timeout))], append_instruction=False)
result = await msg.wait_next_message([Plain(msg.locale.t('chemical_code.message.showid', id=csr["id"])),
Image(newpath), Plain(msg.locale.t('chemical_code.message.captcha',
times=set_timeout))], append_instruction=False)
if play_state[msg.target.target_id]['active']:
if result.as_display(text_only=True) == csr['name']:
send_ = msg.locale.t('chemical_code.message.correct')
Expand Down
4 changes: 2 additions & 2 deletions modules/ncmusic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async def search(msg: Bot.MessageSession, keyword: str):
if len(result['result']['songs']) > 10:
send_msg.append(Plain(msg.locale.t('ncmusic.message.search.collapse')))
send_msg.append(Plain(msg.locale.t('ncmusic.message.search.prompt')))
query, _ = await msg.wait_next_message(send_msg)
query = await msg.wait_next_message(send_msg)
query = query.as_display(text_only=True)
try:
query = int(query)
Expand Down Expand Up @@ -87,7 +87,7 @@ async def search(msg: Bot.MessageSession, keyword: str):
send_msg += msg.locale.t('ncmusic.message.search.collapse')
send_msg += '\n'
send_msg += msg.locale.t('ncmusic.message.search.prompt')
query, _ = await msg.wait_next_message(send_msg)
query = await msg.wait_next_message(send_msg)
query = query.as_display(text_only=True)
try:
query = int(query)
Expand Down
2 changes: 1 addition & 1 deletion modules/summary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def _(msg: Bot.MessageSession):
qc = CoolDown('call_openai', msg)
c = qc.check(60)
if c == 0 or msg.target.target_from == 'TEST|Console' or is_superuser:
f_msg, _ = await msg.wait_next_message(msg.locale.t('summary.message'), append_instruction=False)
f_msg = await msg.wait_next_message(msg.locale.t('summary.message'), append_instruction=False)
try:
f = re.search(r'\[Ke:forward,id=(.*?)\]', f_msg.as_display()).group(1)
except AttributeError:
Expand Down
2 changes: 1 addition & 1 deletion modules/twenty_four/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ async def _(msg: Bot.MessageSession):
numbers = [random.randint(1, 13) for _ in range(4)]
has_solution_flag = await has_solution(numbers)

answer, _ = await msg.wait_next_message(msg.locale.t('twenty_four.message', numbers=numbers), append_instruction=False)
answer = await msg.wait_next_message(msg.locale.t('twenty_four.message', numbers=numbers), append_instruction=False)
expression = answer.as_display(text_only=True)
if play_state[msg.target.target_id]['active']:
if expression.lower() in no_solution:
Expand Down
6 changes: 2 additions & 4 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, quick_confirm
from core.builtins import Bot, Plain, Image, Voice, Url, confirm_command
from core.component import module
from core.exceptions import AbuseWarning
from core.logger import Logger
Expand Down Expand Up @@ -346,13 +346,11 @@ async def image_and_voice():

async def wait_confirm():
if wait_msg_list and session.Feature.wait:
confirm, sent = await session.wait_next_message(wait_msg_list, delete=True, append_instruction=False)
confirm = await session.wait_next_message(wait_msg_list, delete=True, append_instruction=False)
auto_index = False
index = 0
if confirm.as_display(text_only=True) in confirm_command:
auto_index = True
elif quick_confirm and confirm.is_quick_confirm(sent):
auto_index = True
elif confirm.as_display(text_only=True).isdigit():
index = int(confirm.as_display()) - 1
else:
Expand Down
11 changes: 6 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ pycryptodome = "^3.18.0"
langconv = "^0.2.0"
toml = "^0.10.2"
khl-py = "^0.3.16"
matrix-nio = "^0.22.0"
matrix-nio = "^0.21.2"
attrs = "^23.1.0"
uvicorn = {extras = ["standard"], version = "^0.23.2"}
pyjwt = {extras = ["crypto"], version = "^2.8.0"}
Expand Down
6 changes: 3 additions & 3 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1145,9 +1145,9 @@ matplotlib==3.7.2 ; python_full_version >= "3.8.1" and python_full_version < "4.
--hash=sha256:f081c03f413f59390a80b3e351cc2b2ea0205839714dbc364519bcf51f4b56ca \
--hash=sha256:fdbb46fad4fb47443b5b8ac76904b2e7a66556844f33370861b4788db0f8816a \
--hash=sha256:fdcd28360dbb6203fb5219b1a5658df226ac9bebc2542a9e8f457de959d713d0
matrix-nio==0.22.1 ; python_full_version >= "3.8.1" and python_full_version < "4.0.0" \
--hash=sha256:36a7175a41b145026db7f3bf004577aa8906d09ed8c53f276452ac06ed8635e4 \
--hash=sha256:65956252c516f0b42b359d5816fbb66e2617a1f2c02ae45f2730257b815656d8
matrix-nio==0.21.2 ; python_full_version >= "3.8.1" and python_full_version < "4.0.0" \
--hash=sha256:414301fc25662af3e3436de5b955980474c03b0f3001f1b041c49743ede73232 \
--hash=sha256:95bec84dd0d4eca4f0ce252d2f630d435edbc41bb405448d88916a3783479237
monotonic==1.6 ; python_full_version >= "3.8.1" and python_full_version < "4.0.0" \
--hash=sha256:3a55207bcfed53ddd5c5bae174524062935efed17792e9de2ad0205ce9ad63f7 \
--hash=sha256:68687e19a14f11f26d140dd5c86f3dba4bf5df58003000ed467e0e2a69bca96c
Expand Down

0 comments on commit cbbb7f3

Please sign in to comment.