summaryrefslogtreecommitdiff
path: root/ATRI/plugins/essential.py
blob: 37c18a41ea199f1cf1eb25f3b13fc9e859acada4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import os
import json
import shutil
import asyncio
from time import sleep
from datetime import datetime
from pydantic.main import BaseModel
from random import choice, randint
from pathlib import Path

import nonebot
from nonebot.permission import SUPERUSER
from nonebot.message import run_preprocessor
from nonebot.exception import IgnoredException
from nonebot.adapters.onebot.v11 import (
    Bot,
    MessageEvent,
    GroupMessageEvent,
    FriendRequestEvent,
    GroupRequestEvent,
    GroupIncreaseNoticeEvent,
    GroupDecreaseNoticeEvent,
    GroupAdminNoticeEvent,
    GroupBanNoticeEvent,
    GroupRecallNoticeEvent,
    FriendRecallNoticeEvent,
    MessageSegment,
    Message,
)

import ATRI
from ATRI.service import Service
from ATRI.log import logger as log
from ATRI.config import BotSelfConfig
from ATRI.utils import MessageChecker
from ATRI.utils.apscheduler import scheduler
from ATRI.utils.check_update import CheckUpdate


driver = ATRI.driver()
bots = nonebot.get_bots()


ESSENTIAL_DIR = Path(".") / "data" / "database" / "essential"
MANEGE_DIR = Path(".") / "data" / "database" / "manege"
TEMP_PATH = Path(".") / "data" / "temp"
os.makedirs(ESSENTIAL_DIR, exist_ok=True)
os.makedirs(MANEGE_DIR, exist_ok=True)
os.makedirs(TEMP_PATH, exist_ok=True)


@driver.on_startup
async def startup():
    log.info(f"Now running: {ATRI.__version__}")

    try:
        log.info("Starting to check update...")
        log.info(await CheckUpdate.show_latest_commit_info())
        sleep(1)

        l_v, l_v_t = await CheckUpdate.show_latest_version()
        if l_v != ATRI.__version__:
            log.warning("New version has been released, please update.")
            log.warning(f"Latest version: {l_v} Update time: {l_v_t}")
            sleep(3)
    except Exception:
        log.error("检查 更新/最新推送 失败...")

    if not scheduler.running:
        scheduler.start()
        log.info("Scheduler Started.")

    log.info("アトリは、高性能ですから!")


@driver.on_shutdown
async def shutdown():
    log.info("Thanks for using.")


@run_preprocessor
async def _check_block(event: MessageEvent):
    user_file = "block_user.json"
    path = MANEGE_DIR / user_file
    if not path.is_file():
        with open(path, "w", encoding="utf-8") as w:
            w.write(json.dumps(dict()))

    try:
        data = json.loads(path.read_bytes())
    except BaseException:
        data = dict()

    user_id = event.get_user_id()
    if user_id in data:
        raise IgnoredException(f"Block user: {user_id}")

    if isinstance(event, GroupMessageEvent):
        group_file = "block_group.json"
        path = MANEGE_DIR / group_file
        if not path.is_file():
            with open(path, "w", encoding="utf-8") as w:
                w.write(json.dumps(dict()))

        try:
            data = json.loads(path.read_bytes())
        except BaseException:
            data = dict()

        group_id = str(event.group_id)
        if group_id in data:
            raise IgnoredException(f"Block group: {user_id}")


class FriendRequestInfo(BaseModel):
    user_id: str
    comment: str
    time: str
    is_approve: bool


class GroupRequestInfo(BaseModel):
    user_id: str
    comment: str
    time: str
    is_approve: bool


class Essential(Service):
    def __init__(self):
        Service.__init__(self, "基础部件", "对bot基础/必须请求进行处理")


friend_add_event = Essential().on_request("好友添加", "好友添加检测")


@friend_add_event.handle()
async def _friend_add(bot: Bot, event: FriendRequestEvent):
    """
    存储文件结构:
    {
        "Apply code": {
            "user_id": "User ID",
            "comment": "Comment content"
            "time": "Time",
            "is_approve": bool  # Default: False
        }
    }
    """
    file_name = "friend_add.json"
    path = ESSENTIAL_DIR / file_name
    if not path.is_file():
        with open(path, "w", encoding="utf-8") as w:
            w.write(json.dumps({}))
        data = dict()

    apply_code = event.flag
    apply_comment = event.comment
    user_id = event.get_user_id()
    now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    data = json.loads(path.read_bytes())
    data[apply_code] = FriendRequestInfo(
        user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
    ).dict()
    with open(path, "w", encoding="utf-8") as w:
        w.write(json.dumps(data, indent=4))

    repo = (
        "咱收到一条好友请求...\n"
        f"请求人:{user_id}\n"
        f"申请信息:{apply_comment}\n"
        f"申请码:{apply_code}\n"
        "Tip:好友申请 帮助"
    )
    for superuser in BotSelfConfig.superusers:
        await bot.send_private_msg(user_id=superuser, message=repo)


group_invite_event = Essential().on_request("邀请入群", "被邀请入群检测")


@group_invite_event.handle()
async def _group_invite(bot: Bot, event: GroupRequestEvent):
    """
    存储文件结构:
    {
        "Apply code": {
            "user_id": "User ID",
            "comment": "Comment content"
            "time": "Time",
            "is_approve": bool  # Default: False
        }
    }
    """
    file_name = "group_invite.json"
    path = ESSENTIAL_DIR / file_name
    if not path.is_file():
        with open(path, "w", encoding="utf-8") as w:
            w.write(json.dumps({}))
        data = dict()

    apply_code = event.flag
    apply_comment = event.comment
    user_id = event.get_user_id()
    now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    data = json.loads(path.read_bytes())
    data[apply_code] = GroupRequestInfo(
        user_id=user_id, comment=apply_comment, time=now_time, is_approve=False
    ).dict()
    with open(path, "w", encoding="utf-8") as w:
        w.write(json.dumps(data, indent=4))

    repo = (
        "咱收到一条群聊邀请请求...\n"
        f"请求人:{user_id}\n"
        f"申请信息:{apply_comment}\n"
        f"申请码:{apply_code}\n"
        "Tip:群聊邀请 帮助"
    )
    for superuser in BotSelfConfig.superusers:
        await bot.send_private_msg(user_id=superuser, message=repo)


group_member_event = Essential().on_notice("群成员变动", "群成员变动检测")


@group_member_event.handle()
async def _group_member_join(bot: Bot, event: GroupIncreaseNoticeEvent):
    await asyncio.sleep(randint(1, 6))
    msg = "好欸!事新人!\n" f"在下 {choice(list(BotSelfConfig.nickname))} 哒!w!"
    await group_member_event.finish(msg)


@group_member_event.handle()
async def _group_member_left(bot: Bot, event: GroupDecreaseNoticeEvent):
    await asyncio.sleep(randint(1, 6))
    await group_member_event.finish("呜——有人跑了...")


group_admin_event = Essential().on_notice("群管理变动", "群管理变动检测")


@group_admin_event.handle()
async def _group_admin_event(bot: Bot, event: GroupAdminNoticeEvent):
    if not event.is_tome():
        return

    for superuser in BotSelfConfig.superusers:
        await bot.send_private_msg(
            user_id=int(superuser), message=f"好欸!主人!我在群 {event.group_id} 成为了管理!!"
        )


group_ban_event = Essential().on_notice("群禁言变动", "群禁言变动检测")


@group_ban_event.handle()
async def _group_ban_event(bot: Bot, event: GroupBanNoticeEvent):
    if not event.is_tome():
        return

    if event.duration:
        msg = (
            "那个..。,主人\n"
            f"咱在群 {event.group_id}{event.operator_id} 塞上了口球...\n"
            f"时长...是 {event.duration} 秒"
        )
        for superuser in BotSelfConfig.superusers:
            await bot.send_private_msg(user_id=int(superuser), message=msg)
    else:
        msg = "好欸!主人\n" f"咱在群 {event.group_id} 的口球被 {event.operator_id} 解除了!"
        for superuser in BotSelfConfig.superusers:
            await bot.send_private_msg(user_id=int(superuser), message=msg)


_acc_recall = True


recall_event = Essential().on_notice("撤回事件", "撤回事件检测")


@recall_event.handle()
async def _recall_group_event(bot: Bot, event: GroupRecallNoticeEvent):
    if event.is_tome():
        return

    if not _acc_recall:
        return

    try:
        repo = await bot.get_msg(message_id=event.message_id)
    except BaseException:
        return

    log.debug(f"Recall raw msg:\n{repo}")
    user = event.user_id
    group = event.group_id
    repo = repo["message"]

    try:
        m = recall_msg_dealer(repo)
    except:
        check = MessageChecker(repo).check_cq_code
        if not check:
            m = repo
        else:
            return

    msg = f"主人,咱拿到了一条撤回信息!\n{user}@[群:{group}]\n撤回了\n{m}"
    for superuser in BotSelfConfig.superusers:
        await bot.send_private_msg(user_id=int(superuser), message=Message(msg))


@recall_event.handle()
async def _recall_private_event(bot: Bot, event: FriendRecallNoticeEvent):
    if event.is_tome():
        return

    if not _acc_recall:
        return

    try:
        repo = await bot.get_msg(message_id=event.message_id)
    except BaseException:
        return

    log.debug(f"Recall raw msg:\n{repo}")
    user = event.user_id
    repo = repo["message"]

    try:
        m = recall_msg_dealer(repo)
    except:
        check = MessageChecker(repo).check_cq_code
        if not check:
            m = repo
        else:
            return

    msg = f"主人,咱拿到了一条撤回信息!\n{user}@[私聊]撤回了\n{m}"
    for superuser in BotSelfConfig.superusers:
        await bot.send_private_msg(user_id=int(superuser), message=Message(msg))


rej_recall = Essential().on_command("拒绝撤回", "拒绝撤回信息", permission=SUPERUSER)


@rej_recall.handle()
async def _():
    global _acc_recall
    _acc_recall = False
    await rej_recall.finish("已拒绝撤回信息...")


acc_recall = Essential().on_command("接受撤回", "接受撤回信息", permission=SUPERUSER)


@acc_recall.handle()
async def _():
    global _acc_recall
    _acc_recall = True
    await acc_recall.finish("现在可以接受撤回信息啦!")


@scheduler.scheduled_job("interval", name="清除缓存", minutes=30, misfire_grace_time=5)  # type: ignore
async def _clear_cache():
    try:
        shutil.rmtree(TEMP_PATH)
        os.makedirs(TEMP_PATH, exist_ok=True)
    except Exception:
        log.warning("清除缓存失败,请手动清除:data/temp")


def recall_msg_dealer(msg: dict) -> str:
    temp_m = list()

    for i in msg:
        _type = i.get("type", "idk")
        _data = i.get("data", "idk")
        if _type == "text":
            temp_m.append(_data["text"])
        elif _type == "image":
            url = _data["url"]
            check = MessageChecker(url).check_image_url
            if check:
                temp_m.append(MessageSegment.image(url))
            else:
                temp_m.append(f"[该图片可能包含非法内容,源url:{url}]")
        elif _type == "face":
            temp_m.append(MessageSegment.face(_data["id"]))
        else:
            temp_m.append(f"[未知类型信息:{_data}]")

    repo = str().join(map(str, temp_m))
    return repo