This commit is contained in:
夜坂雅 2022-09-07 09:14:39 +08:00
parent 249f23af8b
commit 103d056f4f
5 changed files with 47 additions and 35 deletions

View file

@ -28,7 +28,7 @@ jobs:
- name: Check import statement sorting
run: |
isort -c --df my_project_name/ my-project-name tests
isort -c --df nyx_bot/ nyx-bot tests
- name: Python syntax errors, undefined names, etc.
run: |
@ -36,4 +36,4 @@ jobs:
- name: PEP8 formatting
run: |
black --check --diff my_project_name/ my-project-name tests
black --check --diff nyx_bot/ nyx-bot tests

View file

@ -1,6 +1,6 @@
from nio import AsyncClient, MatrixRoom, RoomMessageText
from nyx_bot.chat_functions import react_to_event, send_text_to_room
from nyx_bot.chat_functions import send_text_to_room
from nyx_bot.config import Config
from nyx_bot.storage import Storage
@ -14,6 +14,7 @@ class Command:
command: str,
room: MatrixRoom,
event: RoomMessageText,
reply_to: str,
):
"""A command made by a user.
@ -37,13 +38,14 @@ class Command:
self.room = room
self.event = event
self.args = self.command.split()[1:]
self.reply_to = reply_to
async def process(self):
"""Process the command"""
if self.command.startswith("echo"):
await self._echo()
elif self.command.startswith("react"):
await self._react()
elif self.command.startswith("quote"):
await self._quote()
elif self.command.startswith("help"):
await self._show_help()
else:
@ -54,25 +56,14 @@ class Command:
response = " ".join(self.args)
await send_text_to_room(self.client, self.room.room_id, response)
async def _react(self):
"""Make the bot react to the command message"""
# React with a start emoji
reaction = ""
await react_to_event(
self.client, self.room.room_id, self.event.event_id, reaction
)
# React with some generic text
reaction = "Some text"
await react_to_event(
self.client, self.room.room_id, self.event.event_id, reaction
)
async def _quote(self):
raise NotImplementedError("TBD !")
async def _show_help(self):
"""Show the help text"""
if not self.args:
text = (
"matrix-nio\nUse `help commands` to view "
"Nyx Bot via matrix-nio\n\nUse `help commands` to view "
"available commands."
)
await send_text_to_room(self.client, self.room.room_id, text)

View file

@ -1,6 +1,7 @@
import logging
import re
import time
import traceback
from nio import (
AsyncClient,
@ -11,8 +12,8 @@ from nio import (
UnknownEvent,
)
# from nyx_bot.bot_commands import Command
from nyx_bot.chat_functions import send_jerryxiao
from nyx_bot.bot_commands import Command
from nyx_bot.chat_functions import send_jerryxiao, send_text_to_room
from nyx_bot.config import Config
# from nyx_bot.message_responses import Message
@ -68,18 +69,23 @@ class Callbacks:
logger.debug(f"In-Reply-To: {reply_to}")
has_jerryxiao_prefix = False
has_command_prefix = False
for i in msg.splitlines():
if re.match("^(!!|\\\\|/|¡¡)", i):
has_jerryxiao_prefix = True
msg = i
break
elif msg.startswith(self.command_prefix):
has_command_prefix = True
msg = i
break
if has_jerryxiao_prefix and reply_to:
if msg.startswith("/"):
await send_jerryxiao(self.client, room, event, "/", reply_to, msg)
elif msg.startswith("!!"):
await send_jerryxiao(self.client, room, event, "!!", reply_to, msg)
if msg.startswith("\\"):
elif msg.startswith("\\"):
await send_jerryxiao(
self.client, room, event, "\\", reply_to, msg, True
)
@ -87,14 +93,26 @@ class Callbacks:
await send_jerryxiao(
self.client, room, event, "¡¡", reply_to, msg, True
)
return
# # Treat it as a command only if it has a prefix
# if has_command_prefix:
# # Remove the command prefix
# msg = msg[len(self.command_prefix) :]
# Treat it as a command only if it has a prefix
if has_command_prefix:
# Remove the command prefix
msg = msg[len(self.command_prefix) :]
# command = Command(self.client, self.store, self.config, msg, room, event)
# await command.process()
command = Command(
self.client, self.store, self.config, msg, room, event, reply_to
)
try:
await command.process()
except Exception as inst:
lines = ["An Exception occoured:\n"]
lines.extend(traceback.format_exception(inst, limit=1, chain=False))
string = "".join(lines).rstrip()
await send_text_to_room(
self.client, room.room_id, string, True, False, event.event_id, True
)
traceback.print_exception(inst)
async def unknown(self, room: MatrixRoom, event: UnknownEvent) -> None:
"""Callback for when an event with a type that is unknown to matrix-nio is received.

View file

@ -23,6 +23,7 @@ async def send_text_to_room(
notice: bool = True,
markdown_convert: bool = True,
reply_to_event_id: Optional[str] = None,
literal_text: Optional[bool] = False,
) -> Union[RoomSendResponse, ErrorResponse]:
"""Send text to a matrix room.
@ -50,10 +51,12 @@ async def send_text_to_room(
content = {
"msgtype": msgtype,
"format": "org.matrix.custom.html",
"body": message,
}
if not literal_text:
content["format"] = "org.matrix.custom.html"
if markdown_convert:
content["formatted_body"] = markdown(message)
@ -91,9 +94,7 @@ def make_pill(user_id: str, displayname: str = None) -> str:
return f'<a href="https://matrix.to/#/{user_id}">{displayname}</a>'
def make_jerryxiao_reply(
from_sender: str, to_sender: str, ref: str, room: MatrixRoom
):
def make_jerryxiao_reply(from_sender: str, to_sender: str, ref: str, room: MatrixRoom):
from_pill = make_pill(from_sender, room.user_name(from_sender))
to_pill = make_pill(to_sender, room.user_name(to_sender))
reply = ""
@ -109,8 +110,10 @@ def make_jerryxiao_reply(
reply = f"{room.user_name(from_sender)} {ref[0]}{ref[1:]} {room.user_name(to_sender)}"
reply_formatted = f"{from_pill} {ref[0]}{ref[1:]} {to_pill}"
elif ref.startswith("发动"):
effect = ref[len("发动"):]
reply = f"{room.user_name(from_sender)}{room.user_name(to_sender)} 发动了{effect}"
effect = ref[len("发动") :]
reply = (
f"{room.user_name(from_sender)}{room.user_name(to_sender)} 发动了{effect}"
)
reply_formatted = f"{from_pill}{to_pill} 发动了{effect}"
else:
reply = f"{room.user_name(from_sender)} {ref}{room.user_name(to_sender)}"

View file

@ -2,10 +2,10 @@
import asyncio
import logging
import sys
from asyncio.exceptions import TimeoutError
from time import sleep
from aiohttp import ClientConnectionError, ServerDisconnectedError
from asyncio.exceptions import TimeoutError
from nio import (
AsyncClient,
AsyncClientConfig,