nonebot-plugin-dialectlist 2.2.0__py3-none-any.whl → 2.2.2__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.
@@ -1,304 +1,315 @@
1
- from nonebot import require
2
-
3
- require("nonebot_plugin_chatrecorder")
4
- require("nonebot_plugin_apscheduler")
5
- require("nonebot_plugin_htmlrender")
6
- require("nonebot_plugin_userinfo")
7
- require("nonebot_plugin_alconna")
8
- require("nonebot_plugin_cesaa")
9
-
10
- import re
11
- import os
12
- import cn2an
13
- import nonebot_plugin_saa as saa
14
-
15
- from typing import Union, Optional, List
16
- from datetime import datetime, timedelta
17
- from arclet.alconna import ArparmaBehavior
18
- from arclet.alconna.arparma import Arparma
19
-
20
- from nonebot.log import logger
21
- from nonebot.params import Arg, Depends
22
- from nonebot.typing import T_State
23
- from nonebot.compat import model_dump
24
- from nonebot.adapters import Bot, Event, Message
25
- from nonebot.params import Arg, Depends
26
- from nonebot.permission import SUPERUSER
27
- from nonebot.plugin import PluginMetadata, inherit_supported_adapters
28
- from nonebot.typing import T_State
29
- from nonebot_plugin_alconna import (
30
- Alconna,
31
- AlconnaMatch,
32
- AlconnaMatcher,
33
- AlconnaQuery,
34
- Option,
35
- Args,
36
- Match,
37
- Option,
38
- Query,
39
- image_fetch,
40
- on_alconna,
41
- )
42
-
43
- from nonebot_plugin_chatrecorder import get_message_records
44
- from nonebot_plugin_userinfo import get_user_info
45
- from nonebot_plugin_session import Session, SessionIdType, extract_session
46
-
47
- # from . import migrations #抄词云的部分代码,还不知道这有什么用
48
- # from .function import *
49
- from .config import Config, plugin_config
50
- from .usage import __usage__
51
- from .time import (
52
- get_datetime_fromisoformat_with_timezone,
53
- get_datetime_now_with_timezone,
54
- parse_datetime,
55
- )
56
- from .model import UserRankInfo
57
- from .utils import (
58
- got_rank,
59
- msg_counter,
60
- persist_id2user_id,
61
- user_id2persist_id,
62
- group_id2persist_id,
63
- get_rank_image,
64
- )
65
-
66
- __plugin_meta__ = PluginMetadata(
67
- name="B话排行榜",
68
- description="调查群U的B话数量,以一定的顺序排序后排序出来。",
69
- usage=__usage__,
70
- homepage="https://github.com/ChenXu233/nonebot_plugin_dialectlist",
71
- type="application",
72
- supported_adapters=inherit_supported_adapters(
73
- "nonebot_plugin_chatrecorder", "nonebot_plugin_saa", "nonebot_plugin_alconna"
74
- ),
75
- config=Config,
76
- # extra={"orm_version_location": migrations},
77
- )
78
-
79
-
80
- # 抄的词云,不过真的很适合B话榜。
81
- class SameTime(ArparmaBehavior):
82
- def operate(self, interface: Arparma):
83
- type = interface.query("type")
84
- time = interface.query("time")
85
- if type is None and time:
86
- interface.behave_fail()
87
-
88
-
89
- def wrapper(slot: Union[int, str], content: Optional[str], context) -> str:
90
- if slot == "type" and content:
91
- return content
92
- return "" # pragma: no cover
93
-
94
-
95
- rank_cmd = on_alconna(
96
- Alconna(
97
- "B话榜",
98
- Args["type?", ["今日", "昨日", "本周", "上周", "本月", "上月", "年度", "历史"]][
99
- "time?",
100
- str,
101
- ],
102
- Option("-g|--group_id", Args["group_id?", str]),
103
- behaviors=[SameTime()],
104
- ),
105
- aliases={"废话榜"},
106
- use_cmd_start=True,
107
- block=True,
108
- )
109
-
110
-
111
- rank_cmd.shortcut(
112
- r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)B话榜",
113
- {
114
- "prefix": True,
115
- "command": "B话榜",
116
- "wrapper": wrapper,
117
- "args": ["{type}"],
118
- },
119
- )
120
- rank_cmd.shortcut(
121
- r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)废话榜",
122
- {
123
- "prefix": True,
124
- "command": "废话榜",
125
- "wrapper": wrapper,
126
- "args": ["{type}"],
127
- },
128
- )
129
-
130
-
131
- # 这段函数完全抄的词云
132
- @rank_cmd.handle()
133
- async def _group_message(
134
- state: T_State,
135
- session: Session = Depends(extract_session),
136
- type: Optional[str] = None,
137
- time: Optional[str] = None,
138
- group_id: Optional[str] = None,
139
- ):
140
-
141
- dt = get_datetime_now_with_timezone()
142
-
143
- if not group_id:
144
- group_id = session.id2
145
- logger.debug(f"session id2: {group_id}")
146
- if group_id:
147
- state["group_id"] = group_id
148
-
149
- if not type:
150
- await rank_cmd.finish(__plugin_meta__.usage)
151
-
152
- dt = get_datetime_now_with_timezone()
153
-
154
- if type == "今日":
155
- state["start"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
156
- state["stop"] = dt
157
- elif type == "昨日":
158
- state["stop"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
159
- state["start"] = state["stop"] - timedelta(days=1)
160
- elif type == "本周":
161
- state["start"] = dt.replace(
162
- hour=0, minute=0, second=0, microsecond=0
163
- ) - timedelta(days=dt.weekday())
164
- state["stop"] = dt
165
- elif type == "上周":
166
- state["stop"] = dt.replace(
167
- hour=0, minute=0, second=0, microsecond=0
168
- ) - timedelta(days=dt.weekday())
169
- state["start"] = state["stop"] - timedelta(days=7)
170
- elif type == "本月":
171
- state["start"] = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
172
- state["stop"] = dt
173
- elif type == "上月":
174
- state["stop"] = dt.replace(
175
- day=1, hour=0, minute=0, second=0, microsecond=0
176
- ) - timedelta(microseconds=1)
177
- state["start"] = state["stop"].replace(
178
- day=1, hour=0, minute=0, second=0, microsecond=0
179
- )
180
- elif type == "年度":
181
- state["start"] = dt.replace(
182
- month=1, day=1, hour=0, minute=0, second=0, microsecond=0
183
- )
184
- state["stop"] = dt
185
- elif type == "历史":
186
- if time:
187
- plaintext = time
188
- if match := re.match(r"^(.+?)(?:~(.+))?$", plaintext):
189
- start = match[1]
190
- stop = match[2]
191
- try:
192
- state["start"] = get_datetime_fromisoformat_with_timezone(start)
193
- if stop:
194
- state["stop"] = get_datetime_fromisoformat_with_timezone(stop)
195
- else:
196
- # 如果没有指定结束日期,则认为是所给日期的当天的词云
197
- state["start"] = state["start"].replace(
198
- hour=0, minute=0, second=0, microsecond=0
199
- )
200
- state["stop"] = state["start"] + timedelta(days=1)
201
- except ValueError:
202
- await rank_cmd.finish("请输入正确的日期,不然我没法理解呢!")
203
-
204
-
205
- @rank_cmd.got(
206
- "start",
207
- prompt="请输入你要查询的起始日期(如 2022-01-01)",
208
- parameterless=[Depends(parse_datetime("start"))],
209
- )
210
- @rank_cmd.got(
211
- "stop",
212
- prompt="请输入你要查询的结束日期(如 2022-02-22)",
213
- parameterless=[Depends(parse_datetime("stop"))],
214
- )
215
- @rank_cmd.got("group_id", prompt="请输入你要查询的群号。")
216
- async def handle_rank(
217
- state: T_State,
218
- bot: Bot,
219
- event: Event,
220
- session: Session = Depends(extract_session),
221
- start: datetime = Arg(),
222
- stop: datetime = Arg(),
223
- ):
224
- if id := state["group_id"]:
225
- id = str(id)
226
- logger.debug(f"group_id: {id}")
227
- else:
228
- id = session.id2
229
- logger.debug(f"group_id: {id}")
230
-
231
- if not id:
232
- await saa.Text("没有指定群哦").finish()
233
-
234
- messages = await get_message_records(
235
- id2s=[id],
236
- id_type=SessionIdType.GROUP,
237
- include_bot_id=False,
238
- include_bot_type=False,
239
- types=["message"], # 排除机器人自己发的消息
240
- time_start=start,
241
- time_stop=stop,
242
- exclude_id1s=plugin_config.excluded_people,
243
- )
244
-
245
- if not messages:
246
- await saa.Text("明明这个时间段都没有人说话怎么会有话痨榜呢?").finish()
247
-
248
- rank = got_rank(msg_counter(messages))
249
- logger.debug(rank)
250
- rank2: List[UserRankInfo] = []
251
- ids = await persist_id2user_id([int(i[0]) for i in rank])
252
- for i in range(len(rank)):
253
- rank[i][0] = str(ids[i])
254
- logger.debug(rank[i])
255
-
256
- total = sum([i[1] for i in rank])
257
- index = 1
258
- for i in rank:
259
- if user_info := await get_user_info(bot, event, user_id=str(i[0])):
260
- logger.debug(user_info)
261
- user_nickname = (
262
- user_info.user_displayname
263
- if user_info.user_displayname
264
- else user_info.user_name if user_info.user_name else user_info.user_id
265
- )
266
- user_avatar = (
267
- await user_info.user_avatar.get_image()
268
- if user_info.user_avatar
269
- else open(
270
- os.path.dirname(os.path.abspath(__file__))
271
- + "/template/avatar/default.jpg",
272
- "rb",
273
- ).read()
274
- )
275
- user = UserRankInfo(
276
- **model_dump(user_info),
277
- user_bnum=i[1],
278
- user_proportion=round(i[1] / total * 100, 2),
279
- user_index=cn2an.an2cn(index),
280
- user_nickname=user_nickname,
281
- user_avatar_bytes=user_avatar,
282
- )
283
- user.user_gender = (
284
- "她"
285
- if user_info.user_gender == "female"
286
- else "他" if user_info.user_gender == "male" else "ta"
287
- )
288
- rank2.append(user)
289
- index += 1
290
-
291
- string: str = ""
292
- for i in rank2:
293
- logger.debug(i.user_name)
294
- for i in range(len(rank2)):
295
- str_example = plugin_config.string_format.format(
296
- index=rank2[i].user_index,
297
- nickname=rank2[i].user_nickname,
298
- chatdatanum=rank2[i].user_bnum,
299
- )
300
- string += str_example
301
-
302
- image = await get_rank_image(rank2)
303
-
304
- await (saa.Text(string) + saa.Image(image)).finish(reply=True)
1
+ from nonebot import require
2
+
3
+ require("nonebot_plugin_chatrecorder")
4
+ require("nonebot_plugin_apscheduler")
5
+ require("nonebot_plugin_htmlrender")
6
+ require("nonebot_plugin_userinfo")
7
+ require("nonebot_plugin_alconna")
8
+ require("nonebot_plugin_cesaa")
9
+
10
+ import re
11
+ import os
12
+ import cn2an
13
+ import time as t
14
+ import nonebot_plugin_saa as saa
15
+
16
+ from typing import Union, Optional, List
17
+ from datetime import datetime, timedelta
18
+ from arclet.alconna import ArparmaBehavior
19
+ from arclet.alconna.arparma import Arparma
20
+
21
+ from nonebot.log import logger
22
+ from nonebot.params import Arg, Depends
23
+ from nonebot.typing import T_State
24
+ from nonebot.compat import model_dump
25
+ from nonebot.adapters import Bot, Event, Message
26
+ from nonebot.params import Arg, Depends
27
+ from nonebot.permission import SUPERUSER
28
+ from nonebot.plugin import PluginMetadata, inherit_supported_adapters
29
+ from nonebot.typing import T_State
30
+ from nonebot_plugin_alconna import (
31
+ Alconna,
32
+ AlconnaMatch,
33
+ AlconnaMatcher,
34
+ AlconnaQuery,
35
+ Option,
36
+ Args,
37
+ Match,
38
+ Option,
39
+ Query,
40
+ image_fetch,
41
+ on_alconna,
42
+ )
43
+
44
+ from nonebot_plugin_chatrecorder import get_message_records
45
+ from nonebot_plugin_userinfo import get_user_info
46
+ from nonebot_plugin_session import Session, SessionIdType, extract_session
47
+
48
+ # from . import migrations #抄词云的部分代码,还不知道这有什么用
49
+ # from .function import *
50
+ from .config import Config, plugin_config
51
+ from .usage import __usage__
52
+ from .time import (
53
+ get_datetime_fromisoformat_with_timezone,
54
+ get_datetime_now_with_timezone,
55
+ parse_datetime,
56
+ )
57
+ from .model import UserRankInfo
58
+ from .utils import (
59
+ got_rank,
60
+ msg_counter,
61
+ persist_id2user_id,
62
+ user_id2persist_id,
63
+ group_id2persist_id,
64
+ get_rank_image,
65
+ )
66
+
67
+ __plugin_meta__ = PluginMetadata(
68
+ name="B话排行榜",
69
+ description="调查群U的B话数量,以一定的顺序排序后排序出来。",
70
+ usage=__usage__,
71
+ homepage="https://github.com/ChenXu233/nonebot_plugin_dialectlist",
72
+ type="application",
73
+ supported_adapters=inherit_supported_adapters(
74
+ "nonebot_plugin_chatrecorder", "nonebot_plugin_saa", "nonebot_plugin_alconna"
75
+ ),
76
+ config=Config,
77
+ # extra={"orm_version_location": migrations},
78
+ )
79
+
80
+
81
+ # 抄的词云,不过真的很适合B话榜。
82
+ class SameTime(ArparmaBehavior):
83
+ def operate(self, interface: Arparma):
84
+ type = interface.query("type")
85
+ time = interface.query("time")
86
+ if type is None and time:
87
+ interface.behave_fail()
88
+
89
+
90
+ def wrapper(slot: Union[int, str], content: Optional[str], context) -> str:
91
+ if slot == "type" and content:
92
+ return content
93
+ return "" # pragma: no cover
94
+
95
+
96
+ rank_cmd = on_alconna(
97
+ Alconna(
98
+ "B话榜",
99
+ Args["type?", ["今日", "昨日", "本周", "上周", "本月", "上月", "年度", "历史"]][
100
+ "time?",
101
+ str,
102
+ ],
103
+ Option("-g|--group_id", Args["group_id?", str]),
104
+ behaviors=[SameTime()],
105
+ ),
106
+ aliases={"废话榜"},
107
+ use_cmd_start=True,
108
+ block=True,
109
+ )
110
+
111
+
112
+ rank_cmd.shortcut(
113
+ r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)B话榜",
114
+ {
115
+ "prefix": True,
116
+ "command": "B话榜",
117
+ "wrapper": wrapper,
118
+ "args": ["{type}"],
119
+ },
120
+ )
121
+ rank_cmd.shortcut(
122
+ r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)废话榜",
123
+ {
124
+ "prefix": True,
125
+ "command": "废话榜",
126
+ "wrapper": wrapper,
127
+ "args": ["{type}"],
128
+ },
129
+ )
130
+
131
+
132
+ # 这段函数完全抄的词云
133
+ @rank_cmd.handle()
134
+ async def _group_message(
135
+ state: T_State,
136
+ session: Session = Depends(extract_session),
137
+ type: Optional[str] = None,
138
+ time: Optional[str] = None,
139
+ group_id: Optional[str] = None,
140
+ ):
141
+ t1 = t.time()
142
+ state["t1"] = t1
143
+ dt = get_datetime_now_with_timezone()
144
+
145
+ if not group_id:
146
+ group_id = session.id2
147
+ logger.debug(f"session id2: {group_id}")
148
+ if group_id:
149
+ state["group_id"] = group_id
150
+
151
+ if not type:
152
+ await rank_cmd.finish(__plugin_meta__.usage)
153
+
154
+ dt = get_datetime_now_with_timezone()
155
+
156
+ if type == "今日":
157
+ state["start"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
158
+ state["stop"] = dt
159
+ elif type == "昨日":
160
+ state["stop"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
161
+ state["start"] = state["stop"] - timedelta(days=1)
162
+ elif type == "本周":
163
+ state["start"] = dt.replace(
164
+ hour=0, minute=0, second=0, microsecond=0
165
+ ) - timedelta(days=dt.weekday())
166
+ state["stop"] = dt
167
+ elif type == "上周":
168
+ state["stop"] = dt.replace(
169
+ hour=0, minute=0, second=0, microsecond=0
170
+ ) - timedelta(days=dt.weekday())
171
+ state["start"] = state["stop"] - timedelta(days=7)
172
+ elif type == "本月":
173
+ state["start"] = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
174
+ state["stop"] = dt
175
+ elif type == "上月":
176
+ state["stop"] = dt.replace(
177
+ day=1, hour=0, minute=0, second=0, microsecond=0
178
+ ) - timedelta(microseconds=1)
179
+ state["start"] = state["stop"].replace(
180
+ day=1, hour=0, minute=0, second=0, microsecond=0
181
+ )
182
+ elif type == "年度":
183
+ state["start"] = dt.replace(
184
+ month=1, day=1, hour=0, minute=0, second=0, microsecond=0
185
+ )
186
+ state["stop"] = dt
187
+ elif type == "历史":
188
+ if time:
189
+ plaintext = time
190
+ if match := re.match(r"^(.+?)(?:~(.+))?$", plaintext):
191
+ start = match[1]
192
+ stop = match[2]
193
+ try:
194
+ state["start"] = get_datetime_fromisoformat_with_timezone(start)
195
+ if stop:
196
+ state["stop"] = get_datetime_fromisoformat_with_timezone(stop)
197
+ else:
198
+ # 如果没有指定结束日期,则认为是所给日期的当天的词云
199
+ state["start"] = state["start"].replace(
200
+ hour=0, minute=0, second=0, microsecond=0
201
+ )
202
+ state["stop"] = state["start"] + timedelta(days=1)
203
+ except ValueError:
204
+ await rank_cmd.finish("请输入正确的日期,不然我没法理解呢!")
205
+
206
+
207
+ @rank_cmd.got(
208
+ "start",
209
+ prompt="请输入你要查询的起始日期(如 2022-01-01)",
210
+ parameterless=[Depends(parse_datetime("start"))],
211
+ )
212
+ @rank_cmd.got(
213
+ "stop",
214
+ prompt="请输入你要查询的结束日期(如 2022-02-22)",
215
+ parameterless=[Depends(parse_datetime("stop"))],
216
+ )
217
+ @rank_cmd.got("group_id", prompt="请输入你要查询的群号。")
218
+ async def handle_rank(
219
+ state: T_State,
220
+ bot: Bot,
221
+ event: Event,
222
+ session: Session = Depends(extract_session),
223
+ start: datetime = Arg(),
224
+ stop: datetime = Arg(),
225
+ ):
226
+ if id := state["group_id"]:
227
+ id = str(id)
228
+ logger.debug(f"group_id: {id}")
229
+ else:
230
+ id = session.id2
231
+ logger.debug(f"group_id: {id}")
232
+
233
+ if not id:
234
+ await saa.Text("没有指定群哦").finish()
235
+
236
+ messages = await get_message_records(
237
+ id2s=[id],
238
+ id_type=SessionIdType.GROUP,
239
+ include_bot_id=False,
240
+ include_bot_type=False,
241
+ types=["message"], # 排除机器人自己发的消息
242
+ time_start=start,
243
+ time_stop=stop,
244
+ exclude_id1s=plugin_config.excluded_people,
245
+ )
246
+
247
+ if not messages:
248
+ await saa.Text("明明这个时间段都没有人说话怎么会有话痨榜呢?").finish()
249
+
250
+ rank = got_rank(msg_counter(messages))
251
+ logger.debug(rank)
252
+ rank2: List[UserRankInfo] = []
253
+ ids = await persist_id2user_id([int(i[0]) for i in rank])
254
+ for i in range(len(rank)):
255
+ rank[i][0] = str(ids[i])
256
+ logger.debug(rank[i])
257
+
258
+ total = sum([i[1] for i in rank])
259
+ index = 1
260
+ for i in rank:
261
+ if user_info := await get_user_info(bot, event, user_id=str(i[0])):
262
+ logger.debug(user_info)
263
+ user_nickname = (
264
+ user_info.user_displayname
265
+ if user_info.user_displayname
266
+ else user_info.user_name if user_info.user_name else user_info.user_id
267
+ )
268
+ user_avatar = (
269
+ await user_info.user_avatar.get_image()
270
+ if user_info.user_avatar
271
+ else open(
272
+ os.path.dirname(os.path.abspath(__file__))
273
+ + "/template/avatar/default.jpg",
274
+ "rb",
275
+ ).read()
276
+ )
277
+ user = UserRankInfo(
278
+ **model_dump(user_info),
279
+ user_bnum=i[1],
280
+ user_proportion=round(i[1] / total * 100, 2),
281
+ user_index=cn2an.an2cn(index),
282
+ user_nickname=user_nickname,
283
+ user_avatar_bytes=user_avatar,
284
+ )
285
+ user.user_gender = (
286
+ "她"
287
+ if user_info.user_gender == "female"
288
+ else "他" if user_info.user_gender == "male" else "ta"
289
+ )
290
+ rank2.append(user)
291
+ index += 1
292
+
293
+ string: str = ""
294
+ for i in rank2:
295
+ logger.debug(i.user_name)
296
+ for i in range(len(rank2)):
297
+ str_example = plugin_config.string_format.format(
298
+ index=rank2[i].user_index,
299
+ nickname=rank2[i].user_nickname,
300
+ chatdatanum=rank2[i].user_bnum,
301
+ )
302
+ string += str_example
303
+
304
+ msg = saa.Text(string)
305
+
306
+ if plugin_config.visualization:
307
+ image = await get_rank_image(rank2)
308
+ msg += saa.Image(image)
309
+
310
+ if plugin_config.suffix:
311
+ timecost = t.time() - state["t1"]
312
+ suffix = saa.Text(plugin_config.string_suffix.format(timecost=timecost))
313
+ msg += suffix
314
+
315
+ await msg.finish(reply=True)