nonebot-plugin-l4d2-server 1.0.2__py3-none-any.whl → 1.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,7 +16,7 @@
16
16
  """
17
17
 
18
18
  from pathlib import Path
19
- from typing import TYPE_CHECKING, List, Optional
19
+ from typing import TYPE_CHECKING, List, Optional, Union
20
20
 
21
21
  import aiofiles
22
22
  import ujson as json
@@ -24,10 +24,11 @@ from nonebot.adapters import Message
24
24
  from nonebot.log import logger
25
25
  from nonebot.matcher import Matcher
26
26
  from nonebot.params import CommandArg, CommandStart, RawCommand
27
+ from nonebot.permission import SUPERUSER
27
28
  from nonebot.plugin import on_command
28
29
  from nonebot_plugin_alconna import UniMessage
29
30
 
30
- from .config import config
31
+ from .config import config, config_manager
31
32
  from .l4_help import get_l4d2_core_help
32
33
  from .l4_local import * # noqa: F403
33
34
  from .l4_request import (
@@ -45,7 +46,7 @@ if TYPE_CHECKING:
45
46
 
46
47
  reload_ip()
47
48
 
48
- l4_help = on_command("l4help", aliases={"l4帮助", "l4d2帮助"})
49
+ l4_help = on_command("l4help", aliases={"l4d2帮助"})
49
50
  l4_request = on_command("anne", aliases=COMMAND, priority=10)
50
51
  l4_reload = on_command("l4reload", aliases={"l4刷新,l4重载"})
51
52
  l4_all = on_command("l4all", aliases={"l4全服"})
@@ -59,13 +60,11 @@ config_path = Path(config.l4_path) / "config.json"
59
60
 
60
61
 
61
62
  @l4_help.handle()
62
- async def _(matcher: Matcher):
63
+ async def _():
63
64
  """帮助"""
64
65
  logger.info("开始执行[l4d2帮助]")
65
66
  im = await get_l4d2_core_help()
66
- if isinstance(im, str):
67
- await matcher.finish(im)
68
- await UniMessage.image(raw=im).send()
67
+ await out_msg_out(im)
69
68
 
70
69
 
71
70
  @l4_request.handle()
@@ -74,11 +73,31 @@ async def _(
74
73
  command: str = RawCommand(),
75
74
  args: Message = CommandArg(),
76
75
  ):
77
- """例:
78
- 指令: /橘5
79
- start: /(command开头指令)
80
- command: /橘(响应的全部指令)
81
- args: 5(响应的指令后的数字)
76
+ """
77
+ 异步函数,用于处理特定的指令。
78
+
79
+ Args:
80
+ start (str, optional): 指令的开头部分,默认为 CommandStart() 返回的值。
81
+ command (str, optional): 完整的指令字符串,默认为 RawCommand() 返回的值。
82
+ args (Message, optional): 指令后的参数,默认为 CommandArg() 返回的值。
83
+
84
+ Returns:
85
+ None
86
+
87
+ Examples:
88
+ 示例指令:"/橘5"
89
+ - start: "/" (指令的开头部分)
90
+ - command: "/橘" (完整的指令字符串)
91
+ - args: "5" (指令后的参数)
92
+
93
+ Notes:
94
+ 1. 如果 start 存在,会将 command 中的 start 部分替换为空字符串。
95
+ 2. 如果 command 等于 "anne",则将其替换为 "云"。
96
+ 3. 提取 args 中的纯文本内容,如果内容非空且不是数字,则返回。
97
+ 4. 如果 args 为空,则将其设置为 None。
98
+ 5. 使用 logger 记录处理过程中的信息。
99
+ 6. 调用 get_server_detail 函数获取服务器详情,并根据返回结果发送相应的消息。
100
+ 7. 如果 get_server_detail 返回 None,则发送 "服务器无响应" 的文本消息。
82
101
  """
83
102
 
84
103
  if start:
@@ -93,49 +112,50 @@ async def _(
93
112
  logger.info(f"组:{command} ;数字:{_id}")
94
113
  msg = await get_server_detail(command, _id)
95
114
  if msg is not None:
96
- if isinstance(msg, str):
97
- await UniMessage.text(msg).finish()
98
- if isinstance(msg, bytes):
99
- await UniMessage.image(raw=msg).finish()
115
+ await out_msg_out(msg, is_connect=config.l4_image)
100
116
  else:
101
- await UniMessage.text("服务器无响应").finish()
117
+ await out_msg_out("服务器无响应")
102
118
 
103
119
 
104
120
  @l4_find_player.handle()
105
121
  async def _(
106
122
  args: Message = CommandArg(),
107
123
  ):
124
+ # 以后有时间补img格式
108
125
  msg: str = args.extract_plain_text().strip()
109
126
  tag_list: List[str] = msg.split(" ", maxsplit=1)
110
- if len(tag_list) < 2:
111
- return await UniMessage.text("格式错误,正确格式:/l4find 组名 玩家名").finish()
112
- group, name = tag_list
113
- out: List[OutServer] = await get_server_detail(group, is_img=False) # type: ignore
114
- out_msg = "未找到玩家"
115
- for one in out:
116
- for player in one["player"]:
117
- if name in player.name:
118
- out_msg = await get_ip_server(f"{one['host']}:{one['port']}")
119
-
120
- return await UniMessage.text(out_msg).finish()
127
+ if len(tag_list) == 1:
128
+ await UniMessage.text("未设置组,正在全服查找,时间较长").send()
129
+ name = tag_list[0]
130
+ out: List[OutServer] = await get_server_detail(is_img=False) # type: ignore
131
+ out_msg = "未找到玩家"
132
+ for one in out:
133
+ for player in one["player"]:
134
+ if name in player.name:
135
+ out_msg = await get_ip_server(f"{one['host']}:{one['port']}")
136
+ if len(tag_list) == 2:
137
+ group, name = tag_list
138
+ await UniMessage.text(f"正在查询{group}组").send()
139
+ out: List[OutServer] = await get_server_detail(group=group, is_img=False) # type: ignore
140
+ out_msg = "未找到玩家"
141
+ for one in out:
142
+ for player in one["player"]:
143
+ if name in player.name:
144
+ out_msg = await get_ip_server(f"{one['host']}:{one['port']}")
145
+
146
+ return await out_msg_out(out_msg)
121
147
 
122
148
 
123
149
  @l4_all.handle()
124
150
  async def _():
125
- await UniMessage.text(await get_all_server_detail()).finish()
151
+ await out_msg_out(await get_all_server_detail())
126
152
 
127
153
 
128
154
  @l4_connect.handle()
129
155
  async def _(args: Message = CommandArg()):
130
156
  ip: Optional[str] = args.extract_plain_text()
131
157
  if ip is not None:
132
- await UniMessage.text(await get_ip_server(ip)).finish()
133
-
134
-
135
- # anne部分
136
- if config.l4_anne:
137
- logger.info("加载anne功能")
138
- from .l4_anne import * # noqa: F403
158
+ await out_msg_out(await get_ip_server(ip), is_connect=config.l4_image)
139
159
 
140
160
 
141
161
  @l4_reload.handle()
@@ -151,7 +171,7 @@ async def _(args: Message = CommandArg()):
151
171
  for tag, url in ip_json.items():
152
172
  logger.info(f"重载{tag}的ip")
153
173
  await L4API.get_sourceban(tag, url)
154
- await UniMessage.text("重载ip完成").finish()
174
+ await out_msg_out("重载ip完成")
155
175
 
156
176
 
157
177
  l4_add_ban = on_command("l4addban", aliases={"l4添加ban"})
@@ -182,7 +202,7 @@ async def _(args: Message = CommandArg()):
182
202
  await UniMessage.text(f"文件写入失败: {e}").finish()
183
203
 
184
204
  await L4API.get_sourceban(arg[0], arg[1])
185
- await UniMessage.text(f"添加成功\n组名: {arg[0]}\n网址: {arg[1]}").finish()
205
+ await out_msg_out(f"添加成功\n组名: {arg[0]}\n网址: {arg[1]}")
186
206
 
187
207
 
188
208
  l4_del_ban = on_command("l4delban", aliases={"l4删除ban", "l4移除ban"})
@@ -209,7 +229,7 @@ async def _(args: Message = CommandArg()):
209
229
  del config_data[arg[0]]
210
230
  async with aiofiles.open(config_path, "w", encoding="utf-8") as f:
211
231
  json.dump(config_data, f, ensure_ascii=False, indent=4)
212
- await UniMessage.text(f"删除成功,组名:{arg[0]}").finish()
232
+ await out_msg_out(f"删除成功,组名:{arg[0]}")
213
233
  elif len(arg) == 2:
214
234
  if not Path(Path(config.l4_path) / "config.json").is_file():
215
235
  await UniMessage.text("没有添加过组名").finish()
@@ -226,7 +246,7 @@ async def _(args: Message = CommandArg()):
226
246
  config_datas[arg[0]] = arg[1]
227
247
  async with aiofiles.open(config_path, "w", encoding="utf-8") as f:
228
248
  json.dump(config_datas, f, ensure_ascii=False, indent=4)
229
- await UniMessage.text(f"修改成功,组名:{arg[0]},网址:{arg[1]}").finish()
249
+ await out_msg_out(f"修改成功,组名:{arg[0]},网址:{arg[1]}")
230
250
 
231
251
 
232
252
  @ld_tj.handle()
@@ -239,3 +259,39 @@ async def _(matcher: Matcher):
239
259
  async def _(matcher: Matcher):
240
260
  await matcher.send("正在寻找牢房信息")
241
261
  await matcher.finish(await tj_request("云", "zl"))
262
+
263
+
264
+ async def out_msg_out(
265
+ msg: Union[str, bytes, UniMessage],
266
+ is_connect: bool = False,
267
+ host: str = "",
268
+ port: str = "",
269
+ ):
270
+ if isinstance(msg, UniMessage):
271
+ return await msg.finish()
272
+ if isinstance(msg, str):
273
+ await UniMessage.text(msg).finish()
274
+ if is_connect:
275
+ out = UniMessage.image(raw=msg) + UniMessage.text(
276
+ f"连接到服务器: {host}:{port}",
277
+ )
278
+ return await out.finish()
279
+ return await UniMessage.image(raw=msg).finish()
280
+
281
+
282
+ ## 以下为配置修改
283
+
284
+ img_trung = on_command("l4img", aliases={"l4图片"}, permission=SUPERUSER)
285
+
286
+
287
+ @img_trung.handle()
288
+ async def _(args: Message = CommandArg()):
289
+ arg = args.extract_plain_text().strip().lower()
290
+ if arg == "开启":
291
+ config_manager.update_image_config(enabled=True)
292
+ await out_msg_out("[l4]已开启图片模式")
293
+ elif arg == "关闭":
294
+ config_manager.update_image_config(enabled=False)
295
+ await out_msg_out("[l4]已关闭图片模式")
296
+ else:
297
+ await UniMessage.text("请在参数后加上开启或关闭").finish()
@@ -1,10 +1,14 @@
1
1
  from pathlib import Path
2
2
 
3
3
  from nonebot import get_plugin_config
4
+ from nonebot.log import logger
4
5
  from pydantic import BaseModel
5
6
 
6
7
  DATAPATH = Path(__file__).parent.joinpath("data")
7
8
  DATAOUT = Path("data/L4D2")
9
+ if not Path(DATAOUT / "l4d2.json").exists():
10
+ logger.info("文件 l4d2.json 不存在,已创建并初始化为 {}")
11
+ Path(DATAOUT / "l4d2.json").write_text("{}", encoding="utf-8")
8
12
  print(DATAOUT.absolute())
9
13
  server_all_path = DATAOUT / "l4d2"
10
14
  server_all_path.mkdir(parents=True, exist_ok=True)
@@ -16,11 +20,9 @@ map_index = 0
16
20
 
17
21
 
18
22
  class ConfigModel(BaseModel):
19
- l4_anne: bool = False
20
- """是否启用anne电信服相关功能"""
21
23
  l4_enable: bool = True
22
24
  """是否全局启用求生功能"""
23
- l4_image: bool = False
25
+ l4_image: bool = True
24
26
  """是否启用图片"""
25
27
  l4_connect: bool = True
26
28
  """是否在查服命令后加入connect ip"""
@@ -39,3 +41,54 @@ class ConfigModel(BaseModel):
39
41
 
40
42
 
41
43
  config = get_plugin_config(ConfigModel)
44
+
45
+
46
+ class ConfigManager:
47
+ """配置项管理类,提供类型安全的配置更新方法"""
48
+
49
+ def __init__(self):
50
+ self._config = config
51
+
52
+ def update_image_config(self, enabled: bool) -> None:
53
+ """更新图片配置
54
+
55
+ Args:
56
+ enabled: 是否启用图片功能
57
+ """
58
+ self._config.l4_image = enabled
59
+
60
+ def update_style_config(self, style: str) -> None:
61
+ """更新图片风格配置
62
+
63
+ Args:
64
+ style: 图片风格名称
65
+ """
66
+ if not isinstance(style, str):
67
+ raise TypeError("style必须是字符串")
68
+ self._config.l4_style = style
69
+
70
+ def update_connect_config(self, enabled: bool) -> None:
71
+ """更新connect ip配置
72
+
73
+ Args:
74
+ enabled: 是否在查服命令后加入connect ip
75
+ """
76
+ self._config.l4_connect = enabled
77
+
78
+ def update(self, **kwargs) -> None:
79
+ """通用配置更新方法
80
+
81
+ Args:
82
+ **kwargs: 要更新的配置项键值对
83
+
84
+ Raises:
85
+ ValueError: 当传入无效的配置项时
86
+ """
87
+ for key, value in kwargs.items():
88
+ if hasattr(self._config, key):
89
+ setattr(self._config, key, value)
90
+ else:
91
+ raise ValueError(f"无效的配置项: {key}")
92
+
93
+
94
+ config_manager = ConfigManager()
@@ -10,7 +10,7 @@ from ..l4_image.convert import core_font
10
10
  from ..l4_image.model import PluginHelp
11
11
  from .draw import get_help
12
12
 
13
- __version__ = "1.0.2"
13
+ __version__ = "1.0.4"
14
14
  TEXT_PATH = Path(__file__).parent / "texture2d"
15
15
  HELP_DATA = Path(__file__).parent / "Help.json"
16
16