mirror of
https://github.com/ChenXu233/nonebot_plugin_dialectlist.git
synced 2026-01-25 21:22:16 +00:00
Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b36e32fe19 | ||
|
|
bd195ac87a | ||
|
|
152128391c | ||
|
|
eee9ac2ab3 | ||
|
|
4970a47b83 | ||
|
|
383a3f602a | ||
|
|
b0e84c778b | ||
|
|
1cb2be770d | ||
|
|
d19d65f75e | ||
|
|
a7bdd6033e | ||
|
|
0d4f69356a | ||
|
|
0348a5d66c | ||
|
|
aff02f2666 | ||
|
|
2f725e0808 | ||
|
|
3434a5352f | ||
|
|
0954eb4f3e | ||
|
|
5b94bc0fff | ||
|
|
e1a20922c4 | ||
|
|
5e00605dfb | ||
|
|
833cdb4a75 | ||
|
|
29b4598e5f | ||
|
|
10cc5cf278 | ||
|
|
ed167a56b5 | ||
|
|
b40c7be1f9 | ||
|
|
07f85be527 | ||
|
|
f2cdfe7f8a | ||
|
|
e0ca7907c0 | ||
|
|
53b2a33923 | ||
|
|
4e339bcdb1 | ||
|
|
0b85f6fb34 | ||
|
|
83d9cda2eb | ||
|
|
dfde832dba | ||
|
|
987b34e282 | ||
|
|
49ce2ffb7c | ||
|
|
fcce94250c | ||
|
|
53e52eabb5 | ||
|
|
633ffbde9a | ||
|
|
d7baa9b04b | ||
|
|
df2cd495c0 | ||
|
|
d2e185c189 | ||
|
|
d42140cc95 | ||
|
|
a753305282 | ||
|
|
ad5f556229 | ||
|
|
3efaafe81c | ||
|
|
c6b87bf981 | ||
|
|
e62f2ed488 | ||
|
|
e5d107c520 | ||
|
|
bf577b5a31 | ||
|
|
d514d96db6 | ||
|
|
677ec56aeb | ||
|
|
4194097258 | ||
|
|
c94de918e9 | ||
|
|
a765267cf1 | ||
|
|
ea682ef18d | ||
|
|
ed7f1167f2 | ||
|
|
9944ece153 | ||
|
|
8d905cb647 | ||
|
|
65dc67c6ac | ||
|
|
7aaddb98f5 | ||
|
|
6d4d17075b | ||
|
|
d422560874 | ||
|
|
d4d3600f23 | ||
|
|
dc5293dbce | ||
|
|
c6c1ae2cc8 | ||
|
|
e42016378c | ||
|
|
fa2a23baca | ||
|
|
2394d3ac4e | ||
|
|
f1c8b700bd | ||
|
|
9474ff743a | ||
|
|
255db230e9 | ||
|
|
75dd80155b | ||
|
|
84d4096af1 |
5
.vscode/settings.json
vendored
5
.vscode/settings.json
vendored
@@ -11,10 +11,15 @@
|
||||
"dialectlist",
|
||||
"displayname",
|
||||
"htmlrender",
|
||||
"httpx",
|
||||
"localstore",
|
||||
"parameterless",
|
||||
"postprocessor",
|
||||
"pyecharts",
|
||||
"pygal",
|
||||
"sqlalchemy",
|
||||
"timecost",
|
||||
"uninfo",
|
||||
"userinfo",
|
||||
"whereclause",
|
||||
"xaxis",
|
||||
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 ChenXu233
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
222
README.md
222
README.md
@@ -6,14 +6,15 @@
|
||||
|
||||
<div align="center">
|
||||
|
||||
# 📃话痨排行榜
|
||||
# 📃 话痨排行榜
|
||||
|
||||
nonebot-plugin-dialectlist
|
||||
|
||||
<p align="center">
|
||||
<a href="https://pypi.python.org/pypi/nonebot-plugin-dialectlist">
|
||||
<img src="https://img.shields.io/pypi/v/nonebot-plugin-dialectlist.svg" alt="pypi">
|
||||
</a>
|
||||
|
||||
|
||||
<img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="python">
|
||||
|
||||
<a href="https://qm.qq.com/q/Yty2yc9Bee">
|
||||
@@ -21,106 +22,153 @@ nonebot-plugin-dialectlist
|
||||
</a>
|
||||
</p>
|
||||
|
||||
[](https://wakatime.com/badge/user/114aee90-a5f9-49aa-b441-9eca7eebfda3/project/68aaa2a1-fb8a-4b00-bb66-ee67e8a3f3b0)
|
||||
|
||||
\>💬**看看群友们这些天在群里水了多少话**💬<
|
||||
|
||||
</div>
|
||||
|
||||
## 💿 安装
|
||||
|
||||
通过`pip`或`nb`安装;
|
||||
通过`pip`或`nb`安装:
|
||||
|
||||
>**通过 pip **安装
|
||||
- 通过 pip 安装
|
||||
|
||||
`pip install nonebot-plugin-dialectlist`
|
||||
```bash
|
||||
pip install nonebot-plugin-dialectlist
|
||||
```
|
||||
|
||||
>**通过 nb **安装
|
||||
- 通过 nb-cli 安装
|
||||
|
||||
`nb plugin install nonebot-plugin-dialectlist`
|
||||
```bash
|
||||
nb plugin install nonebot-plugin-dialectlist
|
||||
```
|
||||
|
||||
### ✅ 插件依赖于
|
||||
|
||||
1. [nonebot-plugin-datastore](https://github.com/he0119/nonebot-plugin-datastore) ————储存历史的消息
|
||||
1. [nonebot-plugin-datastore](https://github.com/he0119/nonebot-plugin-datastore) ————本地化储存
|
||||
2. [nonebot-plugin-userinfo](https://github.com/noneplugin/nonebot-plugin-userinfo) ————获取用户信息
|
||||
3. [nonebot-plugin-apscheduler](https://github.com/nonebot/plugin-apscheduler) ————定时发送排行榜信息
|
||||
4. [nonebot-plugin-alconna](https://github.com/ArcletProject/nonebot-plugin-alconna) ————实现命令解析
|
||||
5. [nonebot-plugin-cesaa](https://github.com/MountainDash/nonebot-plugin-send-anything-anywhere) ————实现多平台
|
||||
|
||||
5. [nonebot-plugin-chatrecorder](https://github.com/noneplugin/nonebot-plugin-chatrecorder) ————实现消息储存
|
||||
6. [nonebot-plugin-cesaa](https://github.com/MountainDash/nonebot-plugin-send-anything-anywhere) ————实现多平台
|
||||
|
||||
**⚠ 注意** 若先前没有安装过`nonebot-plugin-chatrecorder`或者`nonebot-plugin-orm`,则会在启动时报错,请按报错的提示安装数据库!
|
||||
|
||||
## ⚙ 配置
|
||||
|
||||
需要**提前配置**本插件所**依赖的插件**!
|
||||
|
||||
在 .env 中,可以添加以下配置项
|
||||
```python
|
||||
dialectlist__string_format = '第{index}名:\n{nickname},{chatdatanum}条消息、n' #消息格式
|
||||
dialectlist__get_num = 10 #获取人数数量
|
||||
dialectlist__visualization = True #是否可视化
|
||||
# dialectlist__visualization_type = '圆环图' #可视化方案 (不再支持)
|
||||
dialectlist__font = 'SimHei' #字体格式
|
||||
dialectlist__excluded_people = [] #排除的人的 QQ 号(或频道号?(未经测试))
|
||||
dialectlist__excluded_self = True #是否排除机器人自己 QQ
|
||||
dialectlist__suffix: bool = False # 是否显示后缀
|
||||
dialectlist__string_suffix: str = "统计花费时间{timecost}" # 消息格式后缀
|
||||
```
|
||||
💭也可以不进行配置,这将会使插件按照默认配置运行
|
||||
|
||||
### ⚠ 注意!!
|
||||
```python
|
||||
dialectlist__get_num: int = 5 # 获取人数数量
|
||||
dialectlist__font: str = "SimHei" # 字体格式
|
||||
dialectlist__suffix: bool = True # 是否显示后缀
|
||||
dialectlist__excluded_self: bool = True # 是否排除自己
|
||||
dialectlist__visualization: bool = True # 是否可视化
|
||||
dialectlist__show_text_rank: bool = True # 是否显示文本排名
|
||||
dialectlist__excluded_people: List[str] = [] # 排除的人的 QQ 号
|
||||
dialectlist__use_user_info_cache: bool = False # 是否使用用户信息缓存
|
||||
dialectlist__aggregate_transmission: bool = False # 是否聚合转发消息
|
||||
dialectlist__timezone: Optional[str] = "Asia/Shanghai" # 时区,影响统计时间
|
||||
dialectlist__string_suffix: str = "统计花费时间:{timecost}秒" # 消息格式后缀
|
||||
dialectlist__template_path: str = "./template/rank_template.j2" # 模板路径
|
||||
dialectlist__string_format: str = "第{index}名:\n{nickname},{chatdatanum}条消息、n" # 消息格式
|
||||
```
|
||||
|
||||
💭 也可以不进行配置,这将会使插件按照默认配置运行
|
||||
|
||||
### ⚠ 注意!!
|
||||
|
||||
> 在旧版插件(2.0.0 以下)中,dialectlist 与后面的配置项只隔了一个下划线,若更新到新版本以后需要俩个下划线。
|
||||
|
||||
## 🗨命令
|
||||
__!!注意!!__
|
||||
> 由于插件依赖 chatrecord 多次引入爆炸性修改,建议在遇到问题后优先尝试降级 chatrecord 插件
|
||||
|
||||
## 🗨 命令
|
||||
|
||||
**!!注意!!**
|
||||
新版本指令调用方式改变,改为更易理解也更好打的 B 话榜。
|
||||
同时也可以用类似 `/今日废话榜` 的方式(只要改前面的就好了)(算是给 [盘古之白](https://github.com/vinta/pangu.js) 风格爱好者的福利吧?)
|
||||
|
||||
### 🎨一般用法
|
||||
### 🎨 一般用法
|
||||
|
||||
-`/B话榜` ————看看有史以来(机器人存在以来)群友们发了多少消息! (好像没写)
|
||||
#### B 话榜
|
||||
|
||||
-`/今日B话榜` ————看看今天的群友发了多少消息!
|
||||
-`/B 话榜` ————看看有史以来(机器人存在以来)群友们发了多少消息! (好像没写)
|
||||
|
||||
-`/昨日B话榜` ————看看昨天的群友发了多少消息!
|
||||
-`/今日 B 话榜` ————看看今天的群友发了多少消息!
|
||||
|
||||
-`/前日B话榜` ————看看前天的群友发了多少消息!
|
||||
-`/昨日 B 话榜` ————看看昨天的群友发了多少消息!
|
||||
|
||||
-`/本周B话榜` ————看看本周的群友发了多少消息!
|
||||
|
||||
-`/上周B话榜` ————看看上周的群友发了多少消息!
|
||||
-`/前日 B 话榜` ————看看前天的群友发了多少消息!
|
||||
|
||||
-`/本月B话榜` ————看看这个月的群友发了多少消息!
|
||||
-`/本周 B 话榜` ————看看本周的群友发了多少消息!
|
||||
|
||||
-`/年度B话榜` ————看看今年的群友发了多少消息!
|
||||
-`/上周 B 话榜` ————看看上周的群友发了多少消息!
|
||||
|
||||
-`/历史B话榜` ————看看历史上(机器人存在以来)的群友发了多少消息!
|
||||
-`/本月 B 话榜` ————看看这个月的群友发了多少消息!
|
||||
|
||||
### 🚀进阶用法
|
||||
-`/年度 B 话榜` ————看看今年的群友发了多少消息!
|
||||
|
||||
`/{时间类型(今日|年度)?}{B话榜|废话榜} {时间类型?} {ISO8601 格式时间} {群号}`
|
||||
-`/历史 B 话榜` ————看看历史上(机器人存在以来)的群友发了多少消息!
|
||||
|
||||
如:`/B话榜 历史 2024-01-01~2024-01-02 12345678`
|
||||
#### 看看 B 话(kkb)
|
||||
|
||||
-`/看看 B 话 [@某人|QQ 号]` ————看看这个 b 人在这个 b 群发了多少 b 话!
|
||||
|
||||
### 🚀 进阶用法
|
||||
|
||||
#### B 话榜
|
||||
|
||||
`/{时间类型(今日|年度)?}{B 话榜|废话榜} {时间类型?} {ISO8601 格式时间 ?} {群号} {关键词}`
|
||||
|
||||
如:`/B 话榜 历史 2024-01-01~2024-01-02 12345678 女装`
|
||||
|
||||
也可以 `/{时间类型(今日|年度)?}{B 话榜|废话榜} {时间类型?} {ISO8601 格式时间 ?} -g {群号} -k {关键词}`
|
||||
|
||||
以下调用方法均合法:
|
||||
|
||||
`/今日 B 话榜 -g 12345678 -k 女装`
|
||||
`/昨日 B 话榜 -k 女装`
|
||||
`/本周 B 话榜 -g 12345678`
|
||||
|
||||
#### 看看 B 话
|
||||
|
||||
`/看看 B 话 {@|QQ 号} {群号?} {关键词?}`
|
||||
|
||||
以下调用方法均合法:
|
||||
|
||||
`/kkb 114514 1919810 ♂`
|
||||
`/kkb @man -k ♂`
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 关键词支持正则表达式!
|
||||
|
||||
## 💪 目前支持的平台
|
||||
|
||||
| 平台 | 是否经过测试 | 是否能够正常工作 | 测试环境 |
|
||||
|:-----:|:----:|:----:| :----: |
|
||||
| Onebot | ✅ | ✅ | NapCat + Window11|
|
||||
| 飞书 | ❌ | ❓ | 🤔 |
|
||||
| Red | ❌ | ❓ | 🤔 |
|
||||
| DoDo | ❌ | ❓ | 🤔 |
|
||||
| Mirai | ❌ | ❓ | 🤔 |
|
||||
| 开黑啦 | ❌ | ❓ | 🤔 |
|
||||
| Kritor | ❌ | ❓ | 🤔 |
|
||||
| Ntchat | ❌ | ❓ | 🤔 |
|
||||
| Satori | ❌ | ❓ | 🤔 |
|
||||
| Telegram | ❌ | ❓ | 🤔 |
|
||||
| Discord | ❌ | ❓ | 🤔 |
|
||||
| Tailchat | ❌ | ❓ | 🤔 |
|
||||
| QQ 官方接口 | ❌ | ❓ | 🤔 |
|
||||
| Rocket.Chat | ❌ | ❓ | 🤔 |
|
||||
| 平台 | 是否经过测试 | 是否能够正常工作 | 测试环境 |
|
||||
| :---------: | :----------: | :--------------: | :---------------: |
|
||||
| Onebot | ✅ | ✅ | NapCat + Window11 |
|
||||
| 飞书 | ❌ | ❓ | 🤔 |
|
||||
| Red | ❌ | ❓ | 🤔 |
|
||||
| DoDo | ❌ | ❓ | 🤔 |
|
||||
| Mirai | ❌ | ❓ | 🤔 |
|
||||
| 开黑啦 | ❌ | ❓ | 🤔 |
|
||||
| Kritor | ❌ | ❓ | 🤔 |
|
||||
| Ntchat | ❌ | ❓ | 🤔 |
|
||||
| Satori | ❌ | ❓ | 🤔 |
|
||||
| Telegram | ❌ | ❓ | 🤔 |
|
||||
| Discord | ❌ | ❓ | 🤔 |
|
||||
| Tailchat | ❌ | ❓ | 🤔 |
|
||||
| QQ 官方接口 | ❌ | ❓ | 🤔 |
|
||||
| Rocket.Chat | ❌ | ❓ | 🤔 |
|
||||
|
||||
- 如果你测试过能够使用,请在 Issue 中指出
|
||||
|
||||
## 📦另外
|
||||
## 📦 另外
|
||||
|
||||
### 😳加入作者的 BUG 反馈群 ~~(🥵女装粉丝群)~~
|
||||
### 😳 加入作者的 BUG 反馈群 ~~(🥵 女装粉丝群)~~
|
||||
|
||||
[群连接](https://qm.qq.com/q/Yty2yc9Bee)
|
||||
|
||||
@@ -131,9 +179,11 @@ __!!注意!!__
|
||||
|
||||
</details>
|
||||
|
||||
### 💕感谢
|
||||

|
||||
|
||||
本插件的__init__.py 中的处理函数参考了词云中的方法 ~~(其实大部分都是 Ctrl+C Ctr+V)~~
|
||||
### 💕 感谢
|
||||
|
||||
本插件的**init**.py 中的处理函数参考了词云中的方法 ~~(其实大部分都是 Ctrl+C Ctr+V)~~
|
||||
|
||||
[nonebot-plugin-wordcloud](https://github.com/he0119/nonebot-plugin-wordcloud)
|
||||
|
||||
@@ -147,59 +197,21 @@ __!!注意!!__
|
||||
|
||||
- [x] 适配全平台
|
||||
|
||||
- [x] 更好看的图片渲染
|
||||
|
||||
- [x] 添加一些全新的可配置项
|
||||
- [x] 尝试利用 jinja2 模板引擎制作可视化图片
|
||||
|
||||
- [x] 私聊的查询(超级用户可以任意查询群聊的信息)一半完成
|
||||
|
||||
- [x] 添加一些全新的可配置项
|
||||
- [x] 特殊的储存方案优化消息统计
|
||||
|
||||
- [x] 更好看的图片渲染
|
||||
- [x] 查询带某关键词的消息量
|
||||
|
||||
- [ ] 提供多样化的渲染器配置(html 渲染,pillow 渲染,统计绘图软件渲染)
|
||||
- [ ] 为 pillow 渲染方式提供插件的加载方式(什么?插件里的插件???)
|
||||
- [x] 合并转发
|
||||
|
||||
- [ ] 查询带某关键词的消息量
|
||||
待补充。.....
|
||||
|
||||
- [ ] 使用管理员权限直接获取 QQ 官方统计的今日消息量以优化代码运行速度
|
||||
### 👾 题外话
|
||||
|
||||
- [ ] 特殊的储存方案优化消息统计
|
||||
|
||||
待补充。.....
|
||||
|
||||
## 📖版本
|
||||
|
||||
### V1.0
|
||||
|
||||
- 看看群里群友能有多话痨
|
||||
|
||||
### V1.1
|
||||
|
||||
- 支持频道咯!(*^_^*)
|
||||
|
||||
### V1.2
|
||||
|
||||
- 排行榜可视化
|
||||
|
||||
### V1.3
|
||||
|
||||
- 添加了一些可配置项
|
||||
|
||||
### V1.4
|
||||
|
||||
- 适配新版本的 chatrecorder, 暂时停止频道支持
|
||||
|
||||
### V2.0
|
||||
|
||||
- 理论支持全平台!暂停图片支持。
|
||||
|
||||
|
||||
### V2.1
|
||||
|
||||
- 恢复图片支持。
|
||||
|
||||
### V2.2
|
||||
|
||||
- 优化代码,添加一些新的可配置项。
|
||||
|
||||
### 👾题外话
|
||||
~~整个项目快被我写成屎山了~~
|
||||
|
||||
@@ -1,315 +1,352 @@
|
||||
from nonebot import require
|
||||
|
||||
require("nonebot_plugin_chatrecorder")
|
||||
require("nonebot_plugin_apscheduler")
|
||||
require("nonebot_plugin_htmlrender")
|
||||
require("nonebot_plugin_userinfo")
|
||||
require("nonebot_plugin_alconna")
|
||||
require("nonebot_plugin_cesaa")
|
||||
require('nonebot_plugin_chatrecorder')
|
||||
require('nonebot_plugin_apscheduler')
|
||||
require('nonebot_plugin_htmlrender')
|
||||
require('nonebot_plugin_userinfo')
|
||||
require('nonebot_plugin_alconna')
|
||||
require('nonebot_plugin_uninfo')
|
||||
require('nonebot_plugin_cesaa')
|
||||
|
||||
import re
|
||||
import os
|
||||
import cn2an
|
||||
import time as t
|
||||
import nonebot_plugin_saa as saa
|
||||
|
||||
from typing import Union, Optional, List
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Union
|
||||
|
||||
import nonebot_plugin_saa as saa
|
||||
from arclet.alconna import ArparmaBehavior
|
||||
from arclet.alconna.arparma import Arparma
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.log import logger
|
||||
from nonebot.params import Arg, Depends
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.compat import model_dump
|
||||
from nonebot.adapters import Bot, Event, Message
|
||||
from nonebot.params import Arg, Depends
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.plugin import PluginMetadata, inherit_supported_adapters
|
||||
from nonebot.typing import T_State
|
||||
from nonebot_plugin_alconna import (
|
||||
Alconna,
|
||||
AlconnaMatch,
|
||||
AlconnaMatcher,
|
||||
AlconnaQuery,
|
||||
Option,
|
||||
Args,
|
||||
Match,
|
||||
Option,
|
||||
Query,
|
||||
image_fetch,
|
||||
on_alconna,
|
||||
Alconna,
|
||||
Args,
|
||||
At,
|
||||
Field,
|
||||
Match,
|
||||
Option,
|
||||
on_alconna,
|
||||
)
|
||||
from nonebot_plugin_uninfo import Session, Uninfo, get_session
|
||||
|
||||
from nonebot_plugin_chatrecorder import get_message_records
|
||||
from nonebot_plugin_userinfo import get_user_info
|
||||
from nonebot_plugin_session import Session, SessionIdType, extract_session
|
||||
|
||||
# from . import migrations #抄词云的部分代码,还不知道这有什么用
|
||||
# from .function import *
|
||||
from .config import Config, plugin_config
|
||||
from .usage import __usage__
|
||||
|
||||
# from .storage import build_cache, get_cache
|
||||
from .time import (
|
||||
get_datetime_fromisoformat_with_timezone,
|
||||
get_datetime_now_with_timezone,
|
||||
parse_datetime,
|
||||
get_datetime_fromisoformat_with_timezone,
|
||||
get_datetime_now_with_timezone,
|
||||
parse_datetime,
|
||||
)
|
||||
from .model import UserRankInfo
|
||||
from .usage import __usage__
|
||||
from .utils import (
|
||||
got_rank,
|
||||
msg_counter,
|
||||
persist_id2user_id,
|
||||
user_id2persist_id,
|
||||
group_id2persist_id,
|
||||
get_rank_image,
|
||||
get_rank_image,
|
||||
get_user_infos,
|
||||
got_rank,
|
||||
persist_id2user_id,
|
||||
get_user_message_counts,
|
||||
)
|
||||
|
||||
__plugin_meta__ = PluginMetadata(
|
||||
name="B话排行榜",
|
||||
description="调查群U的B话数量,以一定的顺序排序后排序出来。",
|
||||
usage=__usage__,
|
||||
homepage="https://github.com/ChenXu233/nonebot_plugin_dialectlist",
|
||||
type="application",
|
||||
supported_adapters=inherit_supported_adapters(
|
||||
"nonebot_plugin_chatrecorder", "nonebot_plugin_saa", "nonebot_plugin_alconna"
|
||||
),
|
||||
config=Config,
|
||||
# extra={"orm_version_location": migrations},
|
||||
name='B话排行榜',
|
||||
description='调查群U的B话数量,以一定的顺序排序后排序出来。',
|
||||
usage=__usage__,
|
||||
homepage='https://github.com/ChenXu233/nonebot_plugin_dialectlist',
|
||||
type='application',
|
||||
supported_adapters=inherit_supported_adapters(
|
||||
'nonebot_plugin_chatrecorder',
|
||||
'nonebot_plugin_saa',
|
||||
'nonebot_plugin_alconna',
|
||||
),
|
||||
config=Config,
|
||||
)
|
||||
|
||||
|
||||
# 抄的词云,不过真的很适合B话榜。
|
||||
class SameTime(ArparmaBehavior):
|
||||
def operate(self, interface: Arparma):
|
||||
type = interface.query("type")
|
||||
time = interface.query("time")
|
||||
if type is None and time:
|
||||
interface.behave_fail()
|
||||
def operate(self, interface: Arparma):
|
||||
type = interface.query('type')
|
||||
time = interface.query('time')
|
||||
if type is None and time:
|
||||
interface.behave_fail()
|
||||
|
||||
|
||||
def wrapper(slot: Union[int, str], content: Optional[str], context) -> str:
|
||||
if slot == "type" and content:
|
||||
return content
|
||||
return "" # pragma: no cover
|
||||
if slot == 'type' and content:
|
||||
return content
|
||||
return '' # pragma: no cover
|
||||
|
||||
|
||||
b_cmd = on_alconna(
|
||||
Alconna(
|
||||
'看看B话',
|
||||
Args['at', [str, At], Field(completion=lambda: '请想要查询的人的QQ号')],
|
||||
Option('-g|--group_id', Args['group_id?', str]),
|
||||
Option('-k|--keyword', Args['keyword?', str]),
|
||||
),
|
||||
aliases={'kkb'},
|
||||
use_cmd_start=True,
|
||||
)
|
||||
|
||||
|
||||
@b_cmd.handle()
|
||||
async def handle_b_cmd(
|
||||
at: Match[str | At],
|
||||
group_id: Match[str],
|
||||
keyword: Match[str],
|
||||
uninfo: Uninfo,
|
||||
session: Session = Depends(get_session),
|
||||
):
|
||||
id = at.result
|
||||
if isinstance(id, At):
|
||||
id = id.target
|
||||
if group_id.available:
|
||||
gid = group_id.result
|
||||
else:
|
||||
gid = session.scene.id
|
||||
|
||||
if not gid:
|
||||
await b_cmd.finish('请指定群号。')
|
||||
|
||||
_keyword = keyword.result
|
||||
|
||||
d = await get_user_message_counts(
|
||||
keyword=_keyword,
|
||||
scene_ids=[gid],
|
||||
user_ids=[id],
|
||||
types=['message'], # 排除机器人自己发的消息
|
||||
exclude_user_ids=plugin_config.excluded_people,
|
||||
)
|
||||
|
||||
rank = got_rank(d)
|
||||
if not rank:
|
||||
await b_cmd.finish(
|
||||
f'该用户在群“{uninfo.scene.name}”关于“{keyword.result}”的B话数量为0。'
|
||||
)
|
||||
|
||||
await saa.Text(
|
||||
f'该用户在群“{uninfo.scene.name}”关于“{keyword.result}”的B话数量为{rank[0][1]}。'
|
||||
).send(reply=True)
|
||||
|
||||
|
||||
rank_cmd = on_alconna(
|
||||
Alconna(
|
||||
"B话榜",
|
||||
Args["type?", ["今日", "昨日", "本周", "上周", "本月", "上月", "年度", "历史"]][
|
||||
"time?",
|
||||
str,
|
||||
],
|
||||
Option("-g|--group_id", Args["group_id?", str]),
|
||||
behaviors=[SameTime()],
|
||||
),
|
||||
aliases={"废话榜"},
|
||||
use_cmd_start=True,
|
||||
block=True,
|
||||
Alconna(
|
||||
'B话榜',
|
||||
Args[
|
||||
'type?',
|
||||
['今日', '昨日', '本周', '上周', '本月', '上月', '年度', '历史'],
|
||||
][
|
||||
'time?',
|
||||
str,
|
||||
],
|
||||
Option('-g|--group_id', Args['group_id?', str]),
|
||||
Option('-k|--keyword', Args['keyword?', str]),
|
||||
behaviors=[SameTime()],
|
||||
),
|
||||
aliases={'废话榜'},
|
||||
use_cmd_start=True,
|
||||
block=True,
|
||||
)
|
||||
|
||||
|
||||
rank_cmd.shortcut(
|
||||
r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)B话榜",
|
||||
{
|
||||
"prefix": True,
|
||||
"command": "B话榜",
|
||||
"wrapper": wrapper,
|
||||
"args": ["{type}"],
|
||||
},
|
||||
r'(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)B话榜',
|
||||
{
|
||||
'prefix': True,
|
||||
'command': 'B话榜',
|
||||
'wrapper': wrapper,
|
||||
'args': ['{type}'],
|
||||
},
|
||||
)
|
||||
rank_cmd.shortcut(
|
||||
r"(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)废话榜",
|
||||
{
|
||||
"prefix": True,
|
||||
"command": "废话榜",
|
||||
"wrapper": wrapper,
|
||||
"args": ["{type}"],
|
||||
},
|
||||
r'(?P<type>今日|昨日|本周|上周|本月|上月|年度|历史)废话榜',
|
||||
{
|
||||
'prefix': True,
|
||||
'command': '废话榜',
|
||||
'wrapper': wrapper,
|
||||
'args': ['{type}'],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# 这段函数完全抄的词云
|
||||
@rank_cmd.handle()
|
||||
async def _group_message(
|
||||
state: T_State,
|
||||
session: Session = Depends(extract_session),
|
||||
type: Optional[str] = None,
|
||||
time: Optional[str] = None,
|
||||
group_id: Optional[str] = None,
|
||||
state: T_State,
|
||||
session: Session = Depends(get_session),
|
||||
type: Optional[str] = None,
|
||||
time: Optional[str] = None,
|
||||
group_id: Optional[str] = None,
|
||||
keyword: Optional[str] = None,
|
||||
):
|
||||
t1 = t.time()
|
||||
state["t1"] = t1
|
||||
dt = get_datetime_now_with_timezone()
|
||||
t1 = t.time()
|
||||
state['t1'] = t1
|
||||
dt = get_datetime_now_with_timezone()
|
||||
|
||||
if not group_id:
|
||||
group_id = session.id2
|
||||
logger.debug(f"session id2: {group_id}")
|
||||
if group_id:
|
||||
state["group_id"] = group_id
|
||||
if not group_id:
|
||||
group_id = session.scene.id
|
||||
logger.debug(f'session id2: {group_id}')
|
||||
if group_id:
|
||||
state['group_id'] = group_id
|
||||
|
||||
if not type:
|
||||
await rank_cmd.finish(__plugin_meta__.usage)
|
||||
state['keyword'] = keyword
|
||||
|
||||
dt = get_datetime_now_with_timezone()
|
||||
if not type:
|
||||
await rank_cmd.finish(__plugin_meta__.usage)
|
||||
|
||||
if type == "今日":
|
||||
state["start"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state["stop"] = dt
|
||||
elif type == "昨日":
|
||||
state["stop"] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state["start"] = state["stop"] - timedelta(days=1)
|
||||
elif type == "本周":
|
||||
state["start"] = dt.replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(days=dt.weekday())
|
||||
state["stop"] = dt
|
||||
elif type == "上周":
|
||||
state["stop"] = dt.replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(days=dt.weekday())
|
||||
state["start"] = state["stop"] - timedelta(days=7)
|
||||
elif type == "本月":
|
||||
state["start"] = dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
state["stop"] = dt
|
||||
elif type == "上月":
|
||||
state["stop"] = dt.replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(microseconds=1)
|
||||
state["start"] = state["stop"].replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
elif type == "年度":
|
||||
state["start"] = dt.replace(
|
||||
month=1, day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state["stop"] = dt
|
||||
elif type == "历史":
|
||||
if time:
|
||||
plaintext = time
|
||||
if match := re.match(r"^(.+?)(?:~(.+))?$", plaintext):
|
||||
start = match[1]
|
||||
stop = match[2]
|
||||
try:
|
||||
state["start"] = get_datetime_fromisoformat_with_timezone(start)
|
||||
if stop:
|
||||
state["stop"] = get_datetime_fromisoformat_with_timezone(stop)
|
||||
else:
|
||||
# 如果没有指定结束日期,则认为是所给日期的当天的词云
|
||||
state["start"] = state["start"].replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state["stop"] = state["start"] + timedelta(days=1)
|
||||
except ValueError:
|
||||
await rank_cmd.finish("请输入正确的日期,不然我没法理解呢!")
|
||||
dt = get_datetime_now_with_timezone()
|
||||
|
||||
if type == '今日':
|
||||
state['start'] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state['stop'] = dt
|
||||
elif type == '昨日':
|
||||
state['stop'] = dt.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
state['start'] = state['stop'] - timedelta(days=1)
|
||||
elif type == '本周':
|
||||
state['start'] = dt.replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(days=dt.weekday())
|
||||
state['stop'] = dt
|
||||
elif type == '上周':
|
||||
state['stop'] = dt.replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(days=dt.weekday())
|
||||
state['start'] = state['stop'] - timedelta(days=7)
|
||||
elif type == '本月':
|
||||
state['start'] = dt.replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state['stop'] = dt
|
||||
elif type == '上月':
|
||||
state['stop'] = dt.replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
) - timedelta(microseconds=1)
|
||||
state['start'] = state['stop'].replace(
|
||||
day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
elif type == '年度':
|
||||
state['start'] = dt.replace(
|
||||
month=1, day=1, hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state['stop'] = dt
|
||||
elif type == '历史':
|
||||
if time:
|
||||
plaintext = time
|
||||
if match := re.match(r'^(.+?)(?:~(.+))?$', plaintext):
|
||||
start = match[1]
|
||||
stop = match[2]
|
||||
try:
|
||||
state['start'] = get_datetime_fromisoformat_with_timezone(
|
||||
start
|
||||
)
|
||||
if stop:
|
||||
state['stop'] = (
|
||||
get_datetime_fromisoformat_with_timezone(stop)
|
||||
)
|
||||
else:
|
||||
# 如果没有指定结束日期,则认为是所给日期的当天的词云
|
||||
state['start'] = state['start'].replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
state['stop'] = state['start'] + timedelta(days=1)
|
||||
except ValueError:
|
||||
await rank_cmd.finish(
|
||||
'请输入正确的日期,不然我没法理解呢!'
|
||||
)
|
||||
|
||||
|
||||
@rank_cmd.got(
|
||||
"start",
|
||||
prompt="请输入你要查询的起始日期(如 2022-01-01)",
|
||||
parameterless=[Depends(parse_datetime("start"))],
|
||||
'start',
|
||||
prompt='请输入你要查询的起始日期(如 2022-01-01)',
|
||||
parameterless=[Depends(parse_datetime('start'))],
|
||||
)
|
||||
@rank_cmd.got(
|
||||
"stop",
|
||||
prompt="请输入你要查询的结束日期(如 2022-02-22)",
|
||||
parameterless=[Depends(parse_datetime("stop"))],
|
||||
'stop',
|
||||
prompt='请输入你要查询的结束日期(如 2022-02-22)',
|
||||
parameterless=[Depends(parse_datetime('stop'))],
|
||||
)
|
||||
@rank_cmd.got("group_id", prompt="请输入你要查询的群号。")
|
||||
@rank_cmd.got('group_id', prompt='请输入你要查询的群号。')
|
||||
async def handle_rank(
|
||||
state: T_State,
|
||||
bot: Bot,
|
||||
event: Event,
|
||||
session: Session = Depends(extract_session),
|
||||
start: datetime = Arg(),
|
||||
stop: datetime = Arg(),
|
||||
state: T_State,
|
||||
bot: Bot,
|
||||
event: Event,
|
||||
session: Session = Depends(get_session),
|
||||
start: datetime = Arg(),
|
||||
stop: datetime = Arg(),
|
||||
):
|
||||
if id := state["group_id"]:
|
||||
id = str(id)
|
||||
logger.debug(f"group_id: {id}")
|
||||
else:
|
||||
id = session.id2
|
||||
logger.debug(f"group_id: {id}")
|
||||
if id := state['group_id']:
|
||||
id = str(id)
|
||||
logger.debug(f'group_id: {id}')
|
||||
else:
|
||||
id = session.scene.id
|
||||
logger.debug(f'group_id: {id}')
|
||||
|
||||
if not id:
|
||||
await saa.Text("没有指定群哦").finish()
|
||||
if not id:
|
||||
await saa.Text('没有指定群哦').finish()
|
||||
|
||||
messages = await get_message_records(
|
||||
id2s=[id],
|
||||
id_type=SessionIdType.GROUP,
|
||||
include_bot_id=False,
|
||||
include_bot_type=False,
|
||||
types=["message"], # 排除机器人自己发的消息
|
||||
time_start=start,
|
||||
time_stop=stop,
|
||||
exclude_id1s=plugin_config.excluded_people,
|
||||
)
|
||||
keyword = state['keyword']
|
||||
|
||||
if not messages:
|
||||
await saa.Text("明明这个时间段都没有人说话怎么会有话痨榜呢?").finish()
|
||||
t1 = t.time()
|
||||
raw_rank = await get_user_message_counts(
|
||||
keyword=keyword,
|
||||
scene_ids=[id],
|
||||
types=['message'], # 排除机器人自己发的消息
|
||||
time_start=start,
|
||||
time_stop=stop,
|
||||
exclude_user_ids=plugin_config.excluded_people,
|
||||
)
|
||||
logger.debug(f'获取计数消息花费时间:{t.time() - t1}')
|
||||
|
||||
rank = got_rank(msg_counter(messages))
|
||||
logger.debug(rank)
|
||||
rank2: List[UserRankInfo] = []
|
||||
ids = await persist_id2user_id([int(i[0]) for i in rank])
|
||||
for i in range(len(rank)):
|
||||
rank[i][0] = str(ids[i])
|
||||
logger.debug(rank[i])
|
||||
if not raw_rank:
|
||||
await saa.Text(
|
||||
'没有获取到排行榜数据哦,请确认时间范围和群号是否正确或者关键词是否存在~'
|
||||
).finish()
|
||||
|
||||
total = sum([i[1] for i in rank])
|
||||
index = 1
|
||||
for i in rank:
|
||||
if user_info := await get_user_info(bot, event, user_id=str(i[0])):
|
||||
logger.debug(user_info)
|
||||
user_nickname = (
|
||||
user_info.user_displayname
|
||||
if user_info.user_displayname
|
||||
else user_info.user_name if user_info.user_name else user_info.user_id
|
||||
)
|
||||
user_avatar = (
|
||||
await user_info.user_avatar.get_image()
|
||||
if user_info.user_avatar
|
||||
else open(
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ "/template/avatar/default.jpg",
|
||||
"rb",
|
||||
).read()
|
||||
)
|
||||
user = UserRankInfo(
|
||||
**model_dump(user_info),
|
||||
user_bnum=i[1],
|
||||
user_proportion=round(i[1] / total * 100, 2),
|
||||
user_index=cn2an.an2cn(index),
|
||||
user_nickname=user_nickname,
|
||||
user_avatar_bytes=user_avatar,
|
||||
)
|
||||
user.user_gender = (
|
||||
"她"
|
||||
if user_info.user_gender == "female"
|
||||
else "他" if user_info.user_gender == "male" else "ta"
|
||||
)
|
||||
rank2.append(user)
|
||||
index += 1
|
||||
rank = got_rank(raw_rank)
|
||||
ids = await persist_id2user_id([int(i[0]) for i in rank])
|
||||
for i in range(len(rank)):
|
||||
rank[i][0] = str(ids[i])
|
||||
logger.debug(rank[i])
|
||||
|
||||
string: str = ""
|
||||
for i in rank2:
|
||||
logger.debug(i.user_name)
|
||||
for i in range(len(rank2)):
|
||||
str_example = plugin_config.string_format.format(
|
||||
index=rank2[i].user_index,
|
||||
nickname=rank2[i].user_nickname,
|
||||
chatdatanum=rank2[i].user_bnum,
|
||||
)
|
||||
string += str_example
|
||||
|
||||
msg = saa.Text(string)
|
||||
|
||||
if plugin_config.visualization:
|
||||
image = await get_rank_image(rank2)
|
||||
msg += saa.Image(image)
|
||||
|
||||
if plugin_config.suffix:
|
||||
timecost = t.time() - state["t1"]
|
||||
suffix = saa.Text(plugin_config.string_suffix.format(timecost=timecost))
|
||||
msg += suffix
|
||||
|
||||
await msg.finish(reply=True)
|
||||
t1 = t.time()
|
||||
rank2 = await get_user_infos(bot, event, rank)
|
||||
logger.debug(f'获取用户信息花费时间:{t.time() - t1}')
|
||||
|
||||
string: str = ''
|
||||
if plugin_config.show_text_rank:
|
||||
if keyword:
|
||||
string += f'关于{keyword}的话痨榜结果:\n'
|
||||
else:
|
||||
string += '话痨榜:\n'
|
||||
|
||||
for i in rank2:
|
||||
logger.debug(i.user_name)
|
||||
for i in range(len(rank2)):
|
||||
str_example = plugin_config.string_format.format(
|
||||
index=rank2[i].user_index,
|
||||
nickname=rank2[i].user_nickname,
|
||||
chatdatanum=rank2[i].user_bnum,
|
||||
)
|
||||
string += str_example
|
||||
|
||||
msg = saa.Text(string)
|
||||
|
||||
if plugin_config.visualization:
|
||||
t1 = t.time()
|
||||
image = await get_rank_image(rank2)
|
||||
msg += saa.Image(image)
|
||||
logger.debug(f'群聊消息渲染图片花费时间:{t.time() - t1}')
|
||||
|
||||
if plugin_config.suffix:
|
||||
timecost = t.time() - state['t1']
|
||||
suffix = saa.Text(plugin_config.string_suffix.format(timecost=timecost))
|
||||
msg += suffix
|
||||
if not msg:
|
||||
await saa.Text('你把可视化都关了哪来的排行榜?').finish()
|
||||
|
||||
if plugin_config.aggregate_transmission:
|
||||
await saa.AggregatedMessageFactory([msg]).finish()
|
||||
else:
|
||||
await msg.finish(reply=True)
|
||||
|
||||
@@ -1,23 +1,29 @@
|
||||
from typing import Optional, Literal, List
|
||||
from typing import List, Optional
|
||||
|
||||
from nonebot import get_driver, get_plugin_config
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ScopedConfig(BaseModel):
|
||||
font: str = "SimHei" # 字体格式
|
||||
get_num: int = 5 # 获取人数数量
|
||||
timezone: Optional[str] = "Asia/Shanghai"
|
||||
excluded_self: bool = True
|
||||
string_format: str = "第{index}名:\n{nickname},{chatdatanum}条消息\n" # 消息格式
|
||||
template_path: str = "./template/rank_template.j2" # 模板路径
|
||||
visualization: bool = True # 是否可视化
|
||||
excluded_people: List[str] = [] # 排除的人的QQ号
|
||||
suffix: bool = False # 是否显示后缀
|
||||
string_suffix: str = "统计花费时间:{timecost}秒" # 消息格式后缀
|
||||
get_num: int = 5 # 获取人数数量
|
||||
font: str = 'SimHei' # 字体格式
|
||||
suffix: bool = True # 是否显示后缀
|
||||
excluded_self: bool = True # 是否排除自己
|
||||
visualization: bool = True # 是否可视化
|
||||
show_text_rank: bool = True # 是否显示文本排名
|
||||
excluded_people: List[str] = [] # 排除的人的QQ号
|
||||
use_user_info_cache: bool = False # 是否使用用户信息缓存
|
||||
aggregate_transmission: bool = False # 是否聚合转发消息
|
||||
timezone: Optional[str] = 'Asia/Shanghai' # 时区,影响统计时间
|
||||
string_suffix: str = '统计花费时间:{timecost}秒' # 消息格式后缀
|
||||
template_path: str = './template/rank_template.j2' # 模板路径
|
||||
string_format: str = (
|
||||
'第{index}名:\n{nickname},{chatdatanum}条消息\n' # 消息格式
|
||||
)
|
||||
|
||||
|
||||
class Config(BaseModel):
|
||||
dialectlist: ScopedConfig = ScopedConfig()
|
||||
dialectlist: ScopedConfig = ScopedConfig()
|
||||
|
||||
|
||||
global_config = get_driver().config
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
from typing import Optional, Literal, List, Union
|
||||
from pydantic import BaseModel
|
||||
from nonebot_plugin_userinfo import get_user_info, UserInfo
|
||||
|
||||
|
||||
class UserRankInfo(UserInfo):
|
||||
user_bnum: int
|
||||
user_proportion: float
|
||||
user_nickname: str
|
||||
user_index: Union[int, str]
|
||||
user_avatar_bytes: bytes
|
||||
11
nonebot_plugin_dialectlist/schema.py
Normal file
11
nonebot_plugin_dialectlist/schema.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from typing import Union
|
||||
|
||||
from nonebot_plugin_userinfo import UserInfo
|
||||
|
||||
|
||||
class UserRankInfo(UserInfo):
|
||||
user_bnum: int
|
||||
user_proportion: float
|
||||
user_nickname: str
|
||||
user_index: Union[int, str]
|
||||
user_avatar_bytes: bytes
|
||||
@@ -1 +0,0 @@
|
||||
# TODO 使用计数缓存进行数据库查询优化,避免一次性查询过多消息导致内存爆炸。
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 38 KiB |
@@ -1,100 +1,114 @@
|
||||
body {
|
||||
background-image: url('https://image.anosu.top/pixiv/direct?size=regular');
|
||||
background-attachment: scroll;
|
||||
margin: 0;
|
||||
background-color: #1A1A1A;
|
||||
/* Dark gradient */
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
width: 1024;
|
||||
background-attachment: fixed;
|
||||
/* Ensure background stays fixed during scroll */
|
||||
margin: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
font-family: "text", sans-serif;
|
||||
color: #E0E0E0;
|
||||
/* Light gray text for better contrast */
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "text";
|
||||
src: url("../res/HarmonyOS_Sans_SC.woff2");
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 20px 40px;
|
||||
position: relative;
|
||||
flex-direction: column;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.card {
|
||||
border: 5px solid rgba(200, 200, 200, 1);
|
||||
text-align: center; /*设置文本水平居中*/
|
||||
.glow {
|
||||
border: 2px solid rgba(77, 228, 255, 0.8);
|
||||
box-shadow: 0 0 15px rgba(0, 255, 255, 0.3);
|
||||
/* Neon glow */
|
||||
}
|
||||
|
||||
.card,
|
||||
.card2 {
|
||||
text-align: center;
|
||||
align-content: center;
|
||||
margin: 1% 1% 1% 1%;
|
||||
border-radius: 2rem;
|
||||
background: rgba(255, 255, 255, .2);
|
||||
-webkit-backdrop-filter: blur(3px);
|
||||
backdrop-filter: blur(3px);
|
||||
margin: 1%;
|
||||
border-radius: 1rem;
|
||||
/* background: rgba(25, 25, 25, 0.9); Darker background */
|
||||
-webkit-backdrop-filter: blur(5px);
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.card2 {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
flex-direction: revert;
|
||||
display: flex;
|
||||
border: 5px solid rgba(200, 200, 200, 1);
|
||||
text-align: center; /*设置文本水平居中*/
|
||||
align-content: center;
|
||||
margin: 1% 1% 1% 1%;
|
||||
border-radius: 2rem;
|
||||
background: rgba(255, 255, 255, .2);
|
||||
-webkit-backdrop-filter: blur(3px);
|
||||
backdrop-filter: blur(3px);
|
||||
}
|
||||
|
||||
.center_text {
|
||||
text-align: center;
|
||||
font-size: 300%;
|
||||
font-weight: bolder;
|
||||
font-size: 3rem;
|
||||
font-weight: 900;
|
||||
color: #00FFFF;
|
||||
/* Cyan color for a techno vibe */
|
||||
}
|
||||
|
||||
.center_text2 {
|
||||
text-align: center;
|
||||
font-size: 150%;
|
||||
font-size: 1.5rem;
|
||||
color: #A0A0A0;
|
||||
/* Slightly lighter gray */
|
||||
}
|
||||
|
||||
.rank_container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
display: flex;
|
||||
border: 5px solid rgba(200, 200, 200, 1);
|
||||
border-radius: 2rem;
|
||||
padding: 10px 20px;
|
||||
margin: 1% 1% 1% 1%;
|
||||
display: flex;
|
||||
border-radius: 1rem;
|
||||
padding: 10px 10px;
|
||||
margin: 1%;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: rgba(243, 243, 240, 0.6);
|
||||
/* background: rgba(30, 30, 30, 0.9); Dark background */
|
||||
}
|
||||
|
||||
.rank_card {
|
||||
display: flex;
|
||||
width: 90%;
|
||||
width: 100%;
|
||||
flex-direction: row;
|
||||
border: 3px solid rgba(255, 255, 255, 0.61);
|
||||
margin: 20px 10px;
|
||||
border-radius: 2rem;
|
||||
/* padding: 20px 40px; */
|
||||
/* border: 2px solid rgba(100, 100, 100, 0.7); */
|
||||
margin: 10px 10px;
|
||||
border-radius: 1rem;
|
||||
align-content: center;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
/* background: rgba(40, 40, 40, 0.8); Slightly lighter for contrast */
|
||||
}
|
||||
|
||||
.profile{
|
||||
width: 20%;
|
||||
height: 20%;
|
||||
border: 3px solid rgba(255, 255, 255, 0.61);
|
||||
border-radius: 2000px;
|
||||
.profile,
|
||||
.profile2 {
|
||||
border: 2px solid rgba(100, 100, 100, 0.7);
|
||||
border-radius: 50%;
|
||||
background-size: cover;
|
||||
margin-right: 20px;
|
||||
}
|
||||
|
||||
.profile2{
|
||||
.avatar {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.profile {
|
||||
width: 12vw;
|
||||
height: 12vw;
|
||||
}
|
||||
|
||||
.profile2 {
|
||||
width: 8%;
|
||||
height: 8%;
|
||||
border: 3px solid rgba(255, 255, 255, 0.61);
|
||||
border-radius: 2000px;
|
||||
background-size: cover;
|
||||
margin-right: 20px;
|
||||
}
|
||||
|
||||
.rank_card_info {
|
||||
@@ -107,12 +121,50 @@ body {
|
||||
width: 90%;
|
||||
height: 25px;
|
||||
border-radius: 25px;
|
||||
background: #ffb2b25d;
|
||||
background: rgb(0 0 0 / 31%);
|
||||
}
|
||||
|
||||
.g-progress {
|
||||
width: 50%;
|
||||
height: inherit;
|
||||
border-radius: 25px 20px 20px 25px;
|
||||
background: linear-gradient(90deg,rgb(57, 230, 230), rgb(21, 161, 248));
|
||||
background: linear-gradient(90deg, rgb(0, 128, 255), rgb(255, 0, 174));
|
||||
/* Neon cyan to magenta gradient */
|
||||
}
|
||||
|
||||
.rank {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.rank_number {
|
||||
margin: 50px;
|
||||
font-size: 32px;
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
padding: 6px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.rank_number_1 {
|
||||
border-radius: 999px;
|
||||
background-color: gold;
|
||||
color: rgb(154, 105, 14);
|
||||
}
|
||||
|
||||
.rank_number_2 {
|
||||
border-radius: 999px;
|
||||
background-color: silver;
|
||||
color: rgb(80, 80, 80);
|
||||
}
|
||||
|
||||
.rank_number_3 {
|
||||
border-radius: 999px;
|
||||
background-color: #CD7F32;
|
||||
color: rgb(95 52 14);
|
||||
}
|
||||
@@ -9,29 +9,37 @@
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="card" >
|
||||
<div class="card glow" >
|
||||
<p class="center_text">话痨排行榜</p>
|
||||
</div>
|
||||
|
||||
<div class="rank_container">
|
||||
<div class="rank_container glow">
|
||||
|
||||
{% for i in users %}
|
||||
<div class="rank_card">
|
||||
<img class="profile" src="{{ cache_path }}/{{ i.user_id }}.jpg"/>
|
||||
<div class="rank">
|
||||
<div class="rank_number rank_number_{{ i.user_index }}">{{ i.user_index }}</div>
|
||||
</div>
|
||||
<div class="avatar">
|
||||
<img class="profile" src="{{ cache_path }}/{{ i.user_id }}.jpg"/>
|
||||
</div>
|
||||
<div class="rank_card_info">
|
||||
<h1>第{{ i.user_index }}名:{{ i.user_nickname }}</h1>
|
||||
<h1>{{ i.user_nickname }} {{ i.user_gender }}</h1>
|
||||
<div class="g-container">
|
||||
<div class="g-progress" style="width: {{ i.user_proportion }}%"></div>
|
||||
</div>
|
||||
<p>{{ i.user_gender }}一共废话了{{ i.user_bnum }}句,占比{{ i.user_proportion }}%</p>
|
||||
<p>{{ i.user_proportion }}%</p>
|
||||
</div>
|
||||
<div class="rank">
|
||||
<div class="rank_number">{{ i.user_bnum }}</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
|
||||
<div class="card2">
|
||||
<img class="profile2" src="{{ file_path }}/template/avatar/master.jpg"/>
|
||||
<div class="card2 glow">
|
||||
<img class="profile2" src="https://q2.qlogo.cn/headimg_dl?dst_uin=1964324406&spec=100"/>
|
||||
<p class="center_text2">Designed By ChenXu233</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
BIN
nonebot_plugin_dialectlist/template/res/HarmonyOS_Sans_SC.woff2
Normal file
BIN
nonebot_plugin_dialectlist/template/res/HarmonyOS_Sans_SC.woff2
Normal file
Binary file not shown.
@@ -1,15 +1,12 @@
|
||||
# TODO 时间处理模块,用于处理时间相关操作。
|
||||
from datetime import datetime, time, tzinfo
|
||||
from typing import Optional, Union
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.params import Arg
|
||||
from nonebot.adapters import Message
|
||||
|
||||
from nonebot_plugin_apscheduler import scheduler
|
||||
from nonebot.params import Arg
|
||||
from nonebot.typing import T_State
|
||||
from nonebot_plugin_alconna import AlconnaMatcher
|
||||
|
||||
from nonebot_plugin_apscheduler import scheduler
|
||||
|
||||
from .config import plugin_config
|
||||
|
||||
|
||||
@@ -1,9 +1,60 @@
|
||||
from inspect import cleandoc
|
||||
|
||||
__usage__ = cleandoc(
|
||||
"""
|
||||
/今日B话榜 查看今天群里谁B话最多。
|
||||
/昨日B话榜 顾名思义。
|
||||
以此类推,有本周,本月,上周,上月,年度排行榜。
|
||||
"""
|
||||
快速调用:
|
||||
/今日B话榜 ————看看今天群友发了多少消息。
|
||||
|
||||
### 🎨一般用法
|
||||
|
||||
#### B话榜
|
||||
|
||||
-`/B话榜` ————看看有史以来(机器人存在以来)群友们发了多少消息! (好像没写)
|
||||
|
||||
-`/今日B话榜` ————看看今天的群友发了多少消息!
|
||||
|
||||
-`/昨日B话榜` ————看看昨天的群友发了多少消息!
|
||||
|
||||
-`/前日B话榜` ————看看前天的群友发了多少消息!
|
||||
|
||||
-`/本周B话榜` ————看看本周的群友发了多少消息!
|
||||
|
||||
-`/上周B话榜` ————看看上周的群友发了多少消息!
|
||||
|
||||
-`/本月B话榜` ————看看这个月的群友发了多少消息!
|
||||
|
||||
-`/年度B话榜` ————看看今年的群友发了多少消息!
|
||||
|
||||
-`/历史B话榜` ————看看历史上(机器人存在以来)的群友发了多少消息!
|
||||
|
||||
#### 看看B话(kkb)
|
||||
|
||||
-`/看看B话 [@某人|QQ号]` ————看看这个b人在这个b群发了多少b话!
|
||||
|
||||
### 🚀进阶用法
|
||||
|
||||
#### B话榜
|
||||
|
||||
`/{时间类型(今日|年度)?}{B话榜|废话榜} {时间类型?} {ISO8601 格式时间 ?} {群号} {关键词}`
|
||||
|
||||
如:`/B话榜 历史 2024-01-01~2024-01-02 12345678 女装`
|
||||
|
||||
也可以 `/{时间类型(今日|年度)?}{B话榜|废话榜} {时间类型?} {ISO8601 格式时间 ?} -g {群号} -k {关键词}`
|
||||
|
||||
以下调用方法均合法:
|
||||
|
||||
`/今日B话榜 -g 12345678 -k 女装`
|
||||
`/昨日B话榜 -k 女装`
|
||||
`/本周B话榜 -g 12345678`
|
||||
|
||||
#### 看看B话
|
||||
|
||||
`/看看B话 {@|QQ号} {群号?} {关键词?}`
|
||||
|
||||
以下调用方法均合法:
|
||||
|
||||
`/kkb 114514 1919810 ♂`
|
||||
`/kkb @man -k ♂`
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -1,188 +1,269 @@
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Dict, List, Optional, Any
|
||||
|
||||
from typing import Optional, Dict, List, Union
|
||||
from pathlib import Path
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.sql import ColumnElement
|
||||
import httpx
|
||||
from sqlalchemy import select, func
|
||||
|
||||
from nonebot.adapters import Bot, Event
|
||||
from nonebot.compat import model_dump
|
||||
from nonebot.log import logger
|
||||
from nonebot.params import Arg, Depends
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.matcher import Matcher
|
||||
from nonebot.adapters import Message
|
||||
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_session import Session, SessionLevel, extract_session
|
||||
from nonebot_plugin_session_orm import SessionModel
|
||||
from nonebot_plugin_userinfo import EventUserInfo, UserInfo
|
||||
from nonebot_plugin_htmlrender import html_to_pic, template_to_pic
|
||||
from nonebot_plugin_apscheduler import scheduler
|
||||
from nonebot.params import Depends
|
||||
from nonebot_plugin_chatrecorder import MessageRecord
|
||||
from nonebot_plugin_htmlrender import template_to_pic
|
||||
from nonebot_plugin_localstore import get_cache_dir
|
||||
from nonebot_plugin_alconna import AlconnaMatcher
|
||||
from nonebot_plugin_orm import get_session
|
||||
from nonebot_plugin_userinfo import UserInfo, get_user_info
|
||||
from nonebot_plugin_uninfo import Session
|
||||
from nonebot_plugin_uninfo.model import SceneType
|
||||
from nonebot_plugin_uninfo.orm import SessionModel, UserModel
|
||||
from nonebot_plugin_uninfo import get_session as extract_session
|
||||
from nonebot_plugin_userinfo.exception import NetworkError
|
||||
from nonebot_plugin_chatrecorder.record import filter_statement
|
||||
|
||||
|
||||
from .config import plugin_config
|
||||
from .model import UserRankInfo
|
||||
from .schema import UserRankInfo
|
||||
|
||||
cache_path = get_cache_dir("nonebot_plugin_dialectlist")
|
||||
|
||||
# 暂时不做考虑
|
||||
# def admin_permission():
|
||||
# permission = SUPERUSER
|
||||
# with contextlib.suppress(ImportError):
|
||||
# from nonebot.adapters.onebot.v11.permission import GROUP_ADMIN, GROUP_OWNER
|
||||
|
||||
# permission = permission | GROUP_ADMIN | GROUP_OWNER
|
||||
|
||||
# return permission
|
||||
cache_path = get_cache_dir('nonebot_plugin_dialectlist')
|
||||
|
||||
|
||||
async def ensure_group(matcher: Matcher, session: Session = Depends(extract_session)):
|
||||
"""确保在群组中使用"""
|
||||
if session.level not in [SessionLevel.LEVEL2, SessionLevel.LEVEL3]:
|
||||
await matcher.finish("请在群组中使用!")
|
||||
async def ensure_group(
|
||||
matcher: Matcher, session: Session = Depends(extract_session)
|
||||
):
|
||||
"""确保在群组中使用"""
|
||||
if session.scene.type not in [SceneType.GROUP, SceneType.GUILD]:
|
||||
await matcher.finish('请在群组中使用!')
|
||||
|
||||
|
||||
async def persist_id2user_id(ids: List) -> List[str]:
|
||||
user_ids = []
|
||||
async with get_session() as db_session:
|
||||
for i in ids:
|
||||
user_id = (await db_session.scalar(select(SessionModel).where(or_(*[SessionModel.id == i])))).id1 # type: ignore
|
||||
user_ids.append(user_id)
|
||||
return user_ids
|
||||
user_ids = []
|
||||
if not ids:
|
||||
return user_ids
|
||||
|
||||
async with get_session() as db_session:
|
||||
statement = (
|
||||
select(UserModel.user_id)
|
||||
.join(SessionModel, UserModel.id == SessionModel.user_persist_id)
|
||||
.where(SessionModel.id.in_(ids))
|
||||
)
|
||||
result = await db_session.scalars(statement)
|
||||
user_ids = result.all()
|
||||
|
||||
return list(user_ids)
|
||||
|
||||
|
||||
async def user_id2persist_id(ids: List[str]) -> List[int]:
|
||||
whereclause: List[ColumnElement[bool]] = []
|
||||
whereclause.append(or_(*[SessionModel.id1 == id for id in ids]))
|
||||
statement = (
|
||||
select(SessionModel).where(*whereclause)
|
||||
# .join(SessionModel, SessionModel.id == MessageRecord.session_persist_id)
|
||||
)
|
||||
async with get_session() as db_session:
|
||||
records = (await db_session.scalars(statement)).all()
|
||||
return [i.id for i in records]
|
||||
def got_rank(msg_dict: Dict[int, int]) -> List[List[Any]]:
|
||||
"""### 获得排行榜
|
||||
|
||||
Args:
|
||||
msg_dict (Dict[int,int]): 要处理的字典
|
||||
|
||||
async def group_id2persist_id(ids: List[str]) -> List[int]:
|
||||
persist_ids = []
|
||||
async with get_session() as db_session:
|
||||
for i in ids:
|
||||
persist_id = (await db_session.scalar(select(SessionModel).where(or_(*[SessionModel.id2 == i])))).id # type: ignore
|
||||
persist_ids.append(persist_id)
|
||||
return persist_ids
|
||||
Returns:
|
||||
List[Tuple[int,int]]: 排行榜列表(已排序)
|
||||
"""
|
||||
rank = []
|
||||
while len(rank) < plugin_config.get_num:
|
||||
try:
|
||||
max_key = max(msg_dict.items(), key=lambda x: x[1])
|
||||
rank.append(list(max_key))
|
||||
msg_dict.pop(max_key[0])
|
||||
except ValueError:
|
||||
logger.error(
|
||||
'群内拥有聊天记录的人数不足,无法获取到长度为{}的排行榜,已将长度变化为:{}'.format(
|
||||
plugin_config.get_num, len(rank)
|
||||
)
|
||||
)
|
||||
break
|
||||
|
||||
|
||||
async def persist_id2group_id(ids: List[str]) -> List[str]:
|
||||
whereclause: List[ColumnElement[bool]] = []
|
||||
whereclause.append(or_(*[SessionModel.id == id for id in ids]))
|
||||
statement = (
|
||||
select(SessionModel).where(*whereclause)
|
||||
# .join(SessionModel, SessionModel.id == MessageRecord.session_persist_id)
|
||||
)
|
||||
async with get_session() as db_session:
|
||||
records = (await db_session.scalars(statement)).all()
|
||||
return [i.id2 for i in records]
|
||||
|
||||
|
||||
def msg_counter(msg_list: List[MessageRecord]) -> Dict[str, int]:
|
||||
"""### 计算每个人的消息量
|
||||
|
||||
Args:
|
||||
msg_list (list[MessageRecord]): 需要处理的消息列表
|
||||
|
||||
Returns:
|
||||
(dict[str,int]): 处理后的消息数量字典,键为用户,值为消息数量
|
||||
"""
|
||||
|
||||
lst: Dict[str, int] = {}
|
||||
msg_len = len(msg_list)
|
||||
logger.info("wow , there are {} msgs to count !!!".format(msg_len))
|
||||
|
||||
for i in msg_list:
|
||||
try:
|
||||
lst[str(i.session_persist_id)] += 1
|
||||
except KeyError:
|
||||
lst[str(i.session_persist_id)] = 1
|
||||
|
||||
logger.debug(f"finish counting, result is {lst}")
|
||||
|
||||
return lst
|
||||
|
||||
|
||||
def got_rank(msg_dict: Dict[str, int]) -> List:
|
||||
"""### 获得排行榜
|
||||
|
||||
Args:
|
||||
msg_dict (Dict[str,int]): 要处理的字典
|
||||
|
||||
Returns:
|
||||
List[Tuple[str,int]]: 排行榜列表(已排序)
|
||||
"""
|
||||
rank = []
|
||||
while len(rank) < plugin_config.get_num:
|
||||
try:
|
||||
max_key = max(msg_dict.items(), key=lambda x: x[1])
|
||||
rank.append(list(max_key))
|
||||
msg_dict.pop(max_key[0])
|
||||
except ValueError:
|
||||
logger.error(
|
||||
"群内拥有聊天记录的人数不足,无法获取到长度为{}的排行榜,已将长度变化为:{}".format(
|
||||
plugin_config.get_num, len(rank)
|
||||
)
|
||||
)
|
||||
break
|
||||
|
||||
return rank
|
||||
return rank
|
||||
|
||||
|
||||
def remove_control_characters(string: str) -> str:
|
||||
"""### 将字符串中的控制符去除
|
||||
"""### 将字符串中的控制符去除
|
||||
|
||||
Args:
|
||||
string (str): 需要去除的字符串
|
||||
Args:
|
||||
string (str): 需要去除的字符串
|
||||
|
||||
Returns:
|
||||
(str): 经过处理的字符串
|
||||
"""
|
||||
return "".join(ch for ch in string if unicodedata.category(ch)[0] != "C")
|
||||
Returns:
|
||||
(str): 经过处理的字符串
|
||||
"""
|
||||
return ''.join(ch for ch in string if unicodedata.category(ch)[0] != 'C')
|
||||
|
||||
|
||||
async def get_rank_image(rank: List[UserRankInfo]) -> bytes:
|
||||
for i in rank:
|
||||
if i.user_avatar:
|
||||
try:
|
||||
user_avatar = i.user_avatar_bytes
|
||||
except NotImplementedError:
|
||||
user_avatar = open(
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ "/template/avatar/default.jpg",
|
||||
"rb",
|
||||
).read()
|
||||
# if not os.path.exists(cache_path / str(i.user_id)):
|
||||
with open(cache_path / (str(i.user_id) + ".jpg"), "wb") as f:
|
||||
f.write(user_avatar)
|
||||
for i in rank:
|
||||
if i.user_avatar:
|
||||
try:
|
||||
user_avatar = i.user_avatar_bytes
|
||||
except NotImplementedError:
|
||||
user_avatar = open(
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ '/template/avatar/default.jpg',
|
||||
'rb',
|
||||
).read()
|
||||
# if not os.path.exists(cache_path / str(i.user_id)):
|
||||
with open(cache_path / (str(i.user_id) + '.jpg'), 'wb') as f:
|
||||
f.write(user_avatar)
|
||||
|
||||
if plugin_config.template_path[:2] == "./":
|
||||
path = (
|
||||
os.path.dirname(os.path.abspath(__file__)) + plugin_config.template_path[1:]
|
||||
)
|
||||
else:
|
||||
path = plugin_config.template_path
|
||||
if plugin_config.template_path[:2] == './':
|
||||
path = (
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ plugin_config.template_path[1:]
|
||||
)
|
||||
else:
|
||||
path = plugin_config.template_path
|
||||
|
||||
path_dir, filename = os.path.split(path)
|
||||
logger.debug(
|
||||
os.path.dirname(os.path.abspath(__file__)) + plugin_config.template_path[1:]
|
||||
)
|
||||
return await template_to_pic(
|
||||
path_dir,
|
||||
filename,
|
||||
{
|
||||
"users": rank,
|
||||
"cache_path": cache_path,
|
||||
"file_path": os.path.dirname(os.path.abspath(__file__)),
|
||||
},
|
||||
pages={"viewport": {"width": 1100, "height": 10}},
|
||||
)
|
||||
path_dir, filename = os.path.split(path)
|
||||
logger.debug(
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ plugin_config.template_path[1:]
|
||||
)
|
||||
return await template_to_pic(
|
||||
path_dir,
|
||||
filename,
|
||||
{
|
||||
'users': rank,
|
||||
'cache_path': cache_path,
|
||||
'file_path': os.path.dirname(os.path.abspath(__file__)),
|
||||
},
|
||||
pages={'viewport': {'width': 1000, 'height': 10}},
|
||||
)
|
||||
|
||||
|
||||
def _get_user_nickname(user_info: UserInfo) -> str:
|
||||
user_nickname = (
|
||||
user_info.user_displayname
|
||||
if user_info.user_displayname
|
||||
else user_info.user_name
|
||||
if user_info.user_name
|
||||
else user_info.user_id
|
||||
)
|
||||
return user_nickname
|
||||
|
||||
|
||||
async def _get_user_default_avatar() -> bytes:
|
||||
img = open(
|
||||
os.path.dirname(os.path.abspath(__file__))
|
||||
+ '/template/avatar/default.jpg',
|
||||
'rb',
|
||||
).read()
|
||||
return img
|
||||
|
||||
|
||||
async def _get_user_avatar(user: UserInfo, client: httpx.AsyncClient) -> bytes:
|
||||
if not user.user_avatar:
|
||||
return await _get_user_default_avatar()
|
||||
url = user.user_avatar.get_url()
|
||||
for i in range(3):
|
||||
try:
|
||||
resp = await client.get(url, timeout=10)
|
||||
resp.raise_for_status()
|
||||
return resp.content
|
||||
except Exception as e:
|
||||
logger.warning(f'Error downloading {url}, retry {i}/3: {e}')
|
||||
await asyncio.sleep(3)
|
||||
raise NetworkError(f'{url} 下载失败!')
|
||||
|
||||
|
||||
def get_default_user_info() -> UserInfo:
|
||||
user_info = UserInfo(
|
||||
user_id='114514',
|
||||
user_name='鬼知道这谁,bot获取不了',
|
||||
)
|
||||
return user_info
|
||||
|
||||
|
||||
async def get_user_infos(
|
||||
bot: Bot,
|
||||
event: Event,
|
||||
rank: List,
|
||||
use_cache: bool = plugin_config.use_user_info_cache,
|
||||
) -> List[UserRankInfo]:
|
||||
user_ids = [i[0] for i in rank]
|
||||
pool = [get_user_info(bot, event, id, use_cache) for id in user_ids]
|
||||
user_infos = await asyncio.gather(*pool)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
pool = []
|
||||
for i in user_infos:
|
||||
if not i:
|
||||
pool.append(_get_user_default_avatar())
|
||||
continue
|
||||
if i.user_avatar:
|
||||
pool.append(_get_user_avatar(i, client))
|
||||
user_avatars = await asyncio.gather(*pool)
|
||||
|
||||
for i in user_avatars:
|
||||
if not i:
|
||||
user_avatars[
|
||||
user_avatars.index(i)
|
||||
] = await _get_user_default_avatar()
|
||||
|
||||
total = sum([i[1] for i in rank])
|
||||
rank2 = []
|
||||
for i in range(len(rank)):
|
||||
user_info = user_infos[i]
|
||||
if not user_info:
|
||||
user_info = get_default_user_info()
|
||||
|
||||
user = UserRankInfo(
|
||||
**model_dump(user_info),
|
||||
user_bnum=rank[i][1],
|
||||
user_proportion=round(rank[i][1] / total * 100, 2),
|
||||
user_index=i + 1,
|
||||
user_nickname=_get_user_nickname(user_info),
|
||||
user_avatar_bytes=user_avatars[i],
|
||||
)
|
||||
print(user.user_gender)
|
||||
if user.user_gender == 'male':
|
||||
user.user_gender = '♂'
|
||||
elif user.user_gender == 'female':
|
||||
user.user_gender = '♀'
|
||||
else:
|
||||
user.user_gender = '🤔'
|
||||
rank2.append(user)
|
||||
|
||||
return rank2
|
||||
|
||||
|
||||
async def get_user_message_counts(
|
||||
keyword: Optional[str] = None, **kwargs
|
||||
) -> Dict[int, int]:
|
||||
"""获取每个用户的消息数量(直接在数据库层面统计)
|
||||
|
||||
参数:
|
||||
* ``keyword``: 可选,关键词,只统计包含该关键词的消息
|
||||
* ``**kwargs``: 筛选参数,具体查看 `filter_statement` 中的定义
|
||||
|
||||
返回值:
|
||||
* ``Dict[str, int]``: 键为user_persist_id,值为该用户的消息数量
|
||||
"""
|
||||
whereclause = filter_statement(**kwargs)
|
||||
|
||||
# 如果提供了关键词,添加关键词过滤条件
|
||||
if keyword:
|
||||
# 构造LIKE条件,类似于msg_counter函数中的正则匹配
|
||||
# 根据数据库类型不同,可能需要调整LIKE的语法
|
||||
keyword_condition = MessageRecord.plain_text.ilike(f'%{keyword}%')
|
||||
whereclause.append(keyword_condition)
|
||||
|
||||
# 使用SQL的GROUP BY和COUNT进行分组统计
|
||||
statement = (
|
||||
select(
|
||||
SessionModel.user_persist_id,
|
||||
func.count(MessageRecord.id).label('message_count'),
|
||||
)
|
||||
.select_from(MessageRecord)
|
||||
.join(SessionModel, SessionModel.id == MessageRecord.session_persist_id)
|
||||
.where(*whereclause)
|
||||
.group_by(SessionModel.user_persist_id)
|
||||
)
|
||||
|
||||
async with get_session() as db_session:
|
||||
result = await db_session.execute(statement)
|
||||
# 转换为字典格式返回
|
||||
return {user_id: count for user_id, count in result.all()}
|
||||
|
||||
@@ -1,57 +1,44 @@
|
||||
[project]
|
||||
name = "nonebot-plugin-dialectlist"
|
||||
version = "2.2.2"
|
||||
version = "3.0.1"
|
||||
description = "看看你群群友有多能说"
|
||||
authors = [
|
||||
{name = "Chen_Xu233", email = "woyerpa@outlook.com"},
|
||||
]
|
||||
authors = [{ name = "Chen_Xu233", email = "woyerpa@outlook.com" }]
|
||||
dependencies = [
|
||||
"nonebot-plugin-chatrecorder>=0.6.0",
|
||||
"requests>=2.32.3",
|
||||
"nonebot-plugin-chatrecorder>=0.7.0",
|
||||
"nonebot-plugin-orm[default]",
|
||||
"nonebot-plugin-apscheduler>=0.4.0",
|
||||
"nonebot-plugin-alconna>=0.50.2",
|
||||
"nonebot-plugin-cesaa>=0.4.0",
|
||||
"nonebot-plugin-userinfo>=0.2.4",
|
||||
"nonebot-plugin-userinfo>=0.2.6",
|
||||
"nonebot-plugin-htmlrender>=0.3.3",
|
||||
"nonebot2>=2.3.2",
|
||||
"cn2an>=0.5.22"
|
||||
"pillow>=11.3.0",
|
||||
"nonebot-plugin-uninfo>=0.1.1",
|
||||
]
|
||||
requires-python = ">=3.9,<4.0"
|
||||
readme = "README.md"
|
||||
license = {text = "MIT"}
|
||||
license = { text = "MIT" }
|
||||
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"ruff>=0.5.5",
|
||||
"setuptools>=71.1.0",
|
||||
"twine>=5.1.0",
|
||||
"nb-cli>=0.7.6"
|
||||
]
|
||||
Test = [
|
||||
"nonebot-adapter-onebot>=2.4.4",
|
||||
"setuptools>=80.9.0",
|
||||
"twine>=6.2.0",
|
||||
"nb-cli>=1.4.2",
|
||||
"py-spy>=0.3.14",
|
||||
]
|
||||
Test = ["nonebot-adapter-onebot>=2.4.4"]
|
||||
|
||||
[tool.pdm]
|
||||
distribution = true
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 80
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "single"
|
||||
indent-style = "tab"
|
||||
|
||||
[tool.pdm.scripts]
|
||||
|
||||
build = 'pdm run setup.py sdist'
|
||||
publish = 'pdm run python -m twine upload dist/*'
|
||||
|
||||
|
||||
# 以下为智普 AI 生成,还不知道这玩意有啥用。
|
||||
# [tool.pdm.dev-dependencies]
|
||||
# black = "^23.1.0"
|
||||
# isort = "^5.10.1"
|
||||
# pre-commit = "^2.20.0"
|
||||
|
||||
# [tool.pdm.global-options]
|
||||
# --no-pip-version-check = true
|
||||
[tool.ruff.lint]
|
||||
ignore = ["E402"]
|
||||
|
||||
Reference in New Issue
Block a user