icalingua-python-bot/ica-rs/plugins/namerena.py

66 lines
2.0 KiB
Python
Raw Normal View History

2024-05-05 22:17:51 +08:00
import time
import traceback
import subprocess
2024-05-05 22:21:13 +08:00
from pathlib import Path
2024-05-05 22:17:51 +08:00
from typing import TYPE_CHECKING, TypeVar
if TYPE_CHECKING:
from ica_typing import IcaNewMessage, IcaClient, ConfigData
2024-05-05 22:27:41 +08:00
2024-05-05 22:17:51 +08:00
CONFIG_DATA: ConfigData
else:
2024-05-05 22:27:41 +08:00
CONFIG_DATA = None # type: ignore
2024-05-05 22:17:51 +08:00
IcaNewMessage = TypeVar("NewMessage")
IcaClient = TypeVar("IcaClient")
2024-05-10 23:03:44 +08:00
_version_ = "0.4.1"
2024-05-05 22:17:51 +08:00
COMMAND = "/namerena"
2024-05-05 22:27:41 +08:00
2024-05-05 22:17:51 +08:00
def on_ica_message(msg: IcaNewMessage, client: IcaClient) -> None:
2024-05-05 22:50:03 +08:00
if not msg.content.startswith("/namerena"):
2024-05-05 22:17:51 +08:00
return
if msg.content.find("\n") == -1:
2024-05-05 22:27:41 +08:00
client.send_message(
msg.reply_with(
f"请使用 {COMMAND} 命令,然后换行输入名字,例如:\n{COMMAND}\n张三\n李四\n王五\n"
2024-05-05 22:27:41 +08:00
)
)
2024-05-05 22:17:51 +08:00
return
# 去掉 /name
names = msg.content[len(COMMAND) :]
2024-05-05 22:34:09 +08:00
# 去掉第一个 \n
names = names[names.find("\n") + 1 :]
2024-05-05 22:17:51 +08:00
start_time = time.time()
# 开始 try
try:
# 内容写入到 ./md5/input.txt
2024-05-05 22:21:13 +08:00
# 路径是插件文件的相对路径
root_path = Path(__file__).parent
with open(root_path / "md5" / "input.txt", "w") as f:
2024-05-05 22:17:51 +08:00
f.write(names)
# 执行 node md5.js
2024-05-09 22:54:23 +08:00
runner_path = root_path / "md5" / "md5-api.js"
# input_path = root_path / "md5" / "input.txt"
2024-05-05 22:27:41 +08:00
result = subprocess.run(
2024-05-09 22:54:23 +08:00
["node", runner_path.absolute()],
2024-05-05 22:27:41 +08:00
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
2024-05-05 22:17:51 +08:00
# 获取结果
2024-05-05 22:27:07 +08:00
out_result = result.stdout.decode("utf-8")
err_result = result.stderr.decode("utf-8")
2024-05-05 22:17:51 +08:00
# 发送结果
end_time = time.time()
2024-05-05 22:27:41 +08:00
reply = msg.reply_with(
2024-05-10 23:03:44 +08:00
f"{out_result}{err_result}外部耗时:{end_time - start_time:.2f}s\n版本:{_version_}"
2024-05-05 22:27:41 +08:00
)
2024-05-05 22:17:51 +08:00
client.send_message(reply)
except Exception as e:
# 发送错误
reply = msg.reply_with(f"发生错误:{e}\n{traceback.format_exc()}")
2024-05-05 22:27:41 +08:00
client.send_message(reply)