Skip to content

Commit

Permalink
修复了qhpt找不到段位的bug,添加了三个新功能
Browse files Browse the repository at this point in the history
  • Loading branch information
NekoRabi committed Nov 6, 2022
1 parent a20514f commit 009da81
Show file tree
Hide file tree
Showing 107 changed files with 371 additions and 63 deletions.
60 changes: 57 additions & 3 deletions plugin/AlarmClock/bot_clock.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,72 @@
import datetime
import re

from core import bot, scheduler, config, bot_cfg
from mirai import GroupMessage, Plain, At, Startup

from core import bot, scheduler, config, bot_cfg, commandpre
from plugin.AlarmClock.file_init import *
from plugin.AlarmClock.clock_core import Clock
from utils.MessageChainBuilder import messagechain_builder
from utils.MessageChainSender import messagechain_sender
from utils.TimeCheckUtil import *
from utils.cfg_loader import read_file

__all__ = ['group_fixed_clock']

_alarmclockgroup: list = config['alarmclockgroup']

_botname = bot_cfg.get('nickname')


_clocksetting = read_file("./config/AlarmClock/config.yml")

if 0 in _alarmclockgroup:
_alarmclockgroup.remove(0)


@bot.on(GroupMessage)
async def addclock(event: GroupMessage):
"""添加闹钟"""
msg = "".join(map(str, event.message_chain[Plain]))
m = re.match(
fr"^{commandpre}添加提醒\s*(at|@[\d,,]+)?\s*(\d{{4}}-\d{{1,2}}-\d{{1,2}})\s*(\d{{1,2}}:\d{{1,2}}:\d{{1,2}})?\s*(\w+)$",
msg.strip())
if m:
if _clocksetting.get("enable", False):
at = m.group(1)
if at is None:
at = ""
else:
at = re.findall(r"\d+", at)
if At in event.message_chain:
msg = []
at = event.message_chain[At]
for _at in at:
msg.append(f"{_at.target}")
at = msg
date = m.group(2)
time = m.group(3)
description = m.group(4)
info = date_check(date)
if not info.get('effective'):
return await bot.send(event, await messagechain_builder(text=info.get('error')))
if m.group(3):
info = time_check(time)
if not info.get('effective'):
return await bot.send(event, await messagechain_builder(text=info.get('error')))
else:
time = '00:00:00'
groupid = event.group.id
msg = Clock.add_group_clock(group=groupid, creator=event.sender.id, scheduledtime=f'{date} {time}', at=at,
description=description)

return await messagechain_sender(event=event, msg=await messagechain_builder(text=msg))


# @bot.on(Startup)
# async def start_allclock():
# Clock.start_all_clock()


async def group_fixed_clock():
# 时分秒
hour_now = datetime.datetime.now().hour
Expand All @@ -26,7 +78,9 @@ async def group_fixed_clock():
rndimg=True))
if hour_now == 22:
await bot.send_group_message(groupid,
await messagechain_builder(text=f"晚上10点了,大家可以休息了,{_botname}也要休息了", rndimg=True))
await messagechain_builder(text=f"晚上10点了,大家可以休息了,{_botname}也要休息了",
rndimg=True))


if len(_alarmclockgroup) > 0:
scheduler.add_job(group_fixed_clock, 'cron', hour='8-22')
Expand Down
101 changes: 101 additions & 0 deletions plugin/AlarmClock/clock_core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""
:Author: NekoRabi
:Create: 2022/10/16 20:31
:Update: /
:Describe: 时钟功能核心
:Version: 0.0.1
"""
import sqlite3
import time

from core import scheduler
from utils.MessageChainBuilder import messagechain_builder
from utils.MessageChainSender import messagechain_sender


class Clock:

@staticmethod
def add_group_clock(scheduledtime: str, group: int, creator: int, at: list[str], description: str):
"""
添加闹钟
Args:
scheduledtime: 计划时间
group: 群组
creator: 创建人
at: at的对象
description: 描述
Returns: 是否成功的消息
"""
ats = []
nowtime = time.time()
d_time = int(time.mktime(time.strptime(scheduledtime, '%Y-%m-%d %H:%M:%S'))) - nowtime
if d_time <= 0:
return f"添加失败,计划时间必须在将来"
elif d_time > 3600 * 24 * 14:
return f"添加失败,最多支持未来14天的安排"
for _at in at:
ats.append(int(_at))
if len(at) > 0:
at = f'{at}'.replace('"', '').replace("'", "")
else:
at = '[]'
cx = sqlite3.connect('./database/AlarmClock/clock.sqlite')
cursor = cx.cursor()
sql_select = f"select enable,scheduledtime from groupclock where creator = {creator} and description = '{description}'"
task = cursor.execute(sql_select).fetchall()
if len(task) > 0:
task = task[0]
task_time = task[1]
task_enable = task[0]
if int(time.mktime(time.strptime(task_time, '%Y-%m-%d %H:%M:%S'))) > time.time():
sql_update = f"update groupclock set scheduledtime = '{scheduledtime}' and enable = 1 where description = '{description}' and creator = {creator}"
scheduler.add_job(send_remind, 'date', run_date=scheduledtime, args=[group, description, ats])
cursor.execute(sql_update)
elif task_enable == 0:
sql_update = f"update groupclock set enable = 1 where description = '{description}' and creator = {creator}"
cursor.execute(sql_update)
scheduler.add_job(send_remind, 'date', run_date=scheduledtime, args=[group, description, ats])
else:
sql = f"insert into groupclock(creator,at,target,description,scheduledtime) values({creator},'{at[1:-1]}',{group},'{description}','{scheduledtime}')"
cursor.execute(sql)
scheduler.add_job(send_remind, 'date', run_date=scheduledtime, args=[group, description, ats])
cx.commit()
cursor.close()
cx.close()
return f"计划时间:{scheduledtime},创建人:{creator},{'目标:' if len(at) > 0 else ''}{ats if len(at) > 0 else ''},描述={description}"

@staticmethod
def start_all_clock():
"""启动所有闹钟"""
all_clock = get_all_active_clock()
for clock in all_clock:
ats = []
for at in clock[3].split(','):
ats.append(int(at))
scheduler.add_job(send_remind, 'date', run_date=clock[1], args=[clock[0], clock[2], ats])
print("已自动设置所有闹钟")


def get_all_active_clock() -> list[tuple[int, str, str, str]]:
"""
返回所有有效闹钟
Returns:
[(groupid, scheduledtime, description, at) , ......]
"""
cx = sqlite3.connect('./database/AlarmClock/clock.sqlite')
cursor = cx.cursor()
sql_select = f"select target,scheduledtime,description,at from groupclock where date(scheduledtime) > date('now') and enable = 1 "
all_clock = cursor.execute(sql_select).fetchall()
cursor.close()
cx.close()
return all_clock


async def send_remind(groupid: int, message: str, at: list or int = None):
return await messagechain_sender(grouptarget=groupid, msg=await messagechain_builder(text=message, at=at))
40 changes: 40 additions & 0 deletions plugin/AlarmClock/file_init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import os
import sqlite3

from core import add_help
from utils import write_file

if not os.path.exists("./database/AlarmClock"):
os.mkdir("./database/AlarmClock")

if not os.path.exists("./config/AlarmClock"):
os.mkdir("./config/AlarmClock")


def _db_init():
cx = sqlite3.connect('./database/AlarmClock/clock.sqlite')
cursor = cx.cursor()
cursor.execute("create table if not exists groupclock("
"id integer primary key,"
"type text not null default 'group',"
"creator integer not null,"
"at text not null default '',"
"target integer not null,"
"description text not null,"
"scheduledtime text not null,"
"enable integer not null default 1"
")")
cx.commit()
cursor.close()
cx.close()


def _cfg_init():
if not os.path.exists("./config/AlarmClock/config.yml"):
write_file(content=dict(enable=True), path="./config/AlarmClock/config.yml")


_db_init()
_cfg_init()

add_help('group', ["添加提醒 @xx YYYY-mm-DD HH:MM:ss 备注 : 设置一个闹钟"])
Loading

0 comments on commit 009da81

Please sign in to comment.