mirror of
https://github.com/zhenxun-org/zhenxun_bot.git
synced 2026-10-10 06:10:01 +08:00
refactor code
This commit is contained in:
+43
-38
@@ -1,41 +1,53 @@
|
||||
from .group_user_checkin import group_user_check_in, group_user_check, group_impression_rank, impression_rank
|
||||
from .group_user_checkin import (
|
||||
group_user_check_in,
|
||||
group_user_check,
|
||||
group_impression_rank,
|
||||
impression_rank,
|
||||
)
|
||||
from nonebot.typing import T_State
|
||||
from nonebot.adapters.cqhttp import Bot, GroupMessageEvent
|
||||
from nonebot.adapters.cqhttp.permission import GROUP
|
||||
from utils.init_result import image
|
||||
from utils.message_builder import image
|
||||
from nonebot import on_command
|
||||
from utils.utils import get_message_text
|
||||
from pathlib import Path
|
||||
from configs.path_config import DATA_PATH
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
except ModuleNotFoundError:
|
||||
import json
|
||||
|
||||
__plugin_name__ = '签到'
|
||||
__plugin_name__ = "签到"
|
||||
__plugin_usage__ = (
|
||||
'用法:\n'
|
||||
'对我说 “签到” 来签到\n'
|
||||
'“我的签到” 来获取历史签到信息\n'
|
||||
'“好感度排行” 来查看当前好感度前十的伙伴\n'
|
||||
'/ 签到时有 3% 概率 * 2 /'
|
||||
"用法:\n"
|
||||
"对我说 “签到” 来签到\n"
|
||||
"“我的签到” 来获取历史签到信息\n"
|
||||
"“好感度排行” 来查看当前好感度前十的伙伴\n"
|
||||
"/ 签到时有 3% 概率 * 2 /"
|
||||
)
|
||||
|
||||
_file = Path(f'{DATA_PATH}/not_show_sign_rank_user.json')
|
||||
_file = Path(f"{DATA_PATH}/not_show_sign_rank_user.json")
|
||||
try:
|
||||
data = json.load(open(_file, 'r', encoding='utf8'))
|
||||
data = json.load(open(_file, "r", encoding="utf8"))
|
||||
except (FileNotFoundError, ValueError, TypeError):
|
||||
data = {
|
||||
'0': []
|
||||
}
|
||||
data = {"0": []}
|
||||
|
||||
|
||||
sign = on_command("签到", priority=5, permission=GROUP, block=True)
|
||||
my_sign = on_command(cmd="我的签到", aliases={'好感度'}, priority=5, permission=GROUP, block=True)
|
||||
sign_rank = on_command(cmd="积分排行", aliases={'好感度排行', '签到排行', '积分排行', '好感排行',
|
||||
'好感度排名,签到排名,积分排名'},
|
||||
priority=5, permission=GROUP, block=True)
|
||||
total_sign_rank = on_command('签到总排行', aliases={'好感度总排行', '好感度总榜', '签到总榜'}, priority=5, block=True)
|
||||
my_sign = on_command(
|
||||
cmd="我的签到", aliases={"好感度"}, priority=5, permission=GROUP, block=True
|
||||
)
|
||||
sign_rank = on_command(
|
||||
cmd="积分排行",
|
||||
aliases={"好感度排行", "签到排行", "积分排行", "好感排行", "好感度排名,签到排名,积分排名"},
|
||||
priority=5,
|
||||
permission=GROUP,
|
||||
block=True,
|
||||
)
|
||||
total_sign_rank = on_command(
|
||||
"签到总排行", aliases={"好感度总排行", "好感度总榜", "签到总榜"}, priority=5, block=True
|
||||
)
|
||||
|
||||
|
||||
@sign.handle()
|
||||
@@ -56,31 +68,24 @@ async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
|
||||
@sign_rank.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
await sign_rank.send(
|
||||
await group_impression_rank(event.group_id)
|
||||
)
|
||||
await sign_rank.send(await group_impression_rank(event.group_id))
|
||||
|
||||
|
||||
@total_sign_rank.handle()
|
||||
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
|
||||
msg = get_message_text(event.json())
|
||||
if not msg:
|
||||
await total_sign_rank.send('请稍等..正在整理数据...')
|
||||
await total_sign_rank.send("请稍等..正在整理数据...")
|
||||
await total_sign_rank.send(image(b64=await impression_rank(0, data)))
|
||||
elif msg in ['屏蔽我']:
|
||||
if event.user_id in data['0']:
|
||||
await total_sign_rank.finish('您已经在屏蔽名单中了,请勿重复添加!', at_sender=True)
|
||||
data['0'].append(event.user_id)
|
||||
await total_sign_rank.send('设置成功,您不会出现在签到总榜中!', at_sender=True)
|
||||
elif msg in ['显示我']:
|
||||
if event.user_id not in data['0']:
|
||||
await total_sign_rank.finish('您不在屏蔽名单中!', at_sender=True)
|
||||
data['0'].remove(event.user_id)
|
||||
await total_sign_rank.send('设置成功,签到总榜将会显示您的头像名称以及好感度!', at_sender=True)
|
||||
with open(_file, 'w', encoding='utf8') as f:
|
||||
elif msg in ["屏蔽我"]:
|
||||
if event.user_id in data["0"]:
|
||||
await total_sign_rank.finish("您已经在屏蔽名单中了,请勿重复添加!", at_sender=True)
|
||||
data["0"].append(event.user_id)
|
||||
await total_sign_rank.send("设置成功,您不会出现在签到总榜中!", at_sender=True)
|
||||
elif msg in ["显示我"]:
|
||||
if event.user_id not in data["0"]:
|
||||
await total_sign_rank.finish("您不在屏蔽名单中!", at_sender=True)
|
||||
data["0"].remove(event.user_id)
|
||||
await total_sign_rank.send("设置成功,签到总榜将会显示您的头像名称以及好感度!", at_sender=True)
|
||||
with open(_file, "w", encoding="utf8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from models.sigin_group_user import SignGroupUser
|
||||
from models.group_member_info import GroupInfoUser
|
||||
from models.bag_user import BagUser
|
||||
from configs.config import MAX_SIGN_GOLD
|
||||
from utils.img_utils import CreateImg
|
||||
from utils.image_utils import CreateImg
|
||||
import aiohttp
|
||||
from asyncio.exceptions import TimeoutError
|
||||
import math
|
||||
@@ -15,7 +15,7 @@ import asyncio
|
||||
|
||||
|
||||
async def group_user_check_in(user_qq: int, group: int) -> str:
|
||||
'Returns string describing the result of checking in'
|
||||
"Returns string describing the result of checking in"
|
||||
present = datetime.now()
|
||||
async with db.transaction():
|
||||
# 取得相应用户
|
||||
@@ -23,11 +23,11 @@ async def group_user_check_in(user_qq: int, group: int) -> str:
|
||||
# 如果同一天签到过,特殊处理
|
||||
if user.checkin_time_last.date() == present.date():
|
||||
return _handle_already_checked_in(user)
|
||||
return await _handle_check_in(user_qq, group, present) # ok
|
||||
return await _handle_check_in(user_qq, group, present) # ok
|
||||
|
||||
|
||||
def _handle_already_checked_in(user: SignGroupUser) -> str:
|
||||
return f'已经签到过啦~ 好感度:{user.impression:.2f}'
|
||||
return f"已经签到过啦~ 好感度:{user.impression:.2f}"
|
||||
|
||||
|
||||
async def _handle_check_in(user_qq: int, group: int, present: datetime) -> str:
|
||||
@@ -42,10 +42,12 @@ async def _handle_check_in(user_qq: int, group: int, present: datetime) -> str:
|
||||
elif critx2 < specify_probability:
|
||||
impression_added *= 2
|
||||
new_impression = user.impression + impression_added
|
||||
message = random.choice((
|
||||
'谢谢,你是个好人!',
|
||||
'对了,来喝杯茶吗?',
|
||||
))
|
||||
message = random.choice(
|
||||
(
|
||||
"谢谢,你是个好人!",
|
||||
"对了,来喝杯茶吗?",
|
||||
)
|
||||
)
|
||||
await user.update(
|
||||
checkin_count=user.checkin_count + 1,
|
||||
checkin_time_last=present,
|
||||
@@ -64,30 +66,36 @@ async def _handle_check_in(user_qq: int, group: int, present: datetime) -> str:
|
||||
imgold = MAX_SIGN_GOLD
|
||||
await BagUser.add_gold(user_qq, group, gold + imgold)
|
||||
if critx2 + add_probability > 0.97 or critx2 < specify_probability:
|
||||
logger.info(f'(USER {user.user_qq}, GROUP {user.belonging_group})'
|
||||
f' CHECKED IN successfully. score: {new_impression:.2f} (+{impression_added * 2:.2f}).获取金币:{gold+imgold}')
|
||||
return f'{message} 好感度:{new_impression:.2f} (+{impression_added/2:.2f}×2)!!!\n获取金币:{gold} \n好感度额外获得金币:{imgold}'
|
||||
logger.info(
|
||||
f"(USER {user.user_qq}, GROUP {user.belonging_group})"
|
||||
f" CHECKED IN successfully. score: {new_impression:.2f} (+{impression_added * 2:.2f}).获取金币:{gold+imgold}"
|
||||
)
|
||||
return f"{message} 好感度:{new_impression:.2f} (+{impression_added/2:.2f}×2)!!!\n获取金币:{gold} \n好感度额外获得金币:{imgold}"
|
||||
else:
|
||||
logger.info(f'(USER {user.user_qq}, GROUP {user.belonging_group})'
|
||||
f' CHECKED IN successfully. score: {new_impression:.2f} (+{impression_added:.2f}).获取金币:{gold+imgold}')
|
||||
return f'{message} 好感度:{new_impression:.2f} (+{impression_added:.2f})\n获取金币:{gold} \n好感度额外获得金币:{imgold}'
|
||||
logger.info(
|
||||
f"(USER {user.user_qq}, GROUP {user.belonging_group})"
|
||||
f" CHECKED IN successfully. score: {new_impression:.2f} (+{impression_added:.2f}).获取金币:{gold+imgold}"
|
||||
)
|
||||
return f"{message} 好感度:{new_impression:.2f} (+{impression_added:.2f})\n获取金币:{gold} \n好感度额外获得金币:{imgold}"
|
||||
|
||||
|
||||
async def group_user_check(user_qq: int, group: int) -> str:
|
||||
# heuristic: if users find they have never checked in they are probable to check in
|
||||
user = await SignGroupUser.ensure(user_qq, group)
|
||||
gold = await BagUser.get_gold(user_qq, group)
|
||||
return '好感度:{:.2f}\n金币:{}\n历史签到数:{}\n上次签到日期:{}'.format(
|
||||
return "好感度:{:.2f}\n金币:{}\n历史签到数:{}\n上次签到日期:{}".format(
|
||||
user.impression,
|
||||
gold,
|
||||
user.checkin_count,
|
||||
user.checkin_time_last.date() if user.checkin_time_last != datetime.min else '从未',
|
||||
user.checkin_time_last.date()
|
||||
if user.checkin_time_last != datetime.min
|
||||
else "从未",
|
||||
)
|
||||
|
||||
|
||||
async def group_impression_rank(group: int) -> str:
|
||||
result = "\t好感度排行榜\t\n"
|
||||
user_qq_list, impression_list, _ = await SignGroupUser.query_impression_all(group)
|
||||
user_qq_list, impression_list, _ = await SignGroupUser.get_all_impression(group)
|
||||
_count = 11
|
||||
if user_qq_list and impression_list:
|
||||
for i in range(1, len(user_qq_list)):
|
||||
@@ -97,7 +105,9 @@ async def group_impression_rank(group: int) -> str:
|
||||
index = impression_list.index(impression)
|
||||
user_qq = user_qq_list[index]
|
||||
try:
|
||||
user_name = (await GroupInfoUser.select_member_info(user_qq, group)).user_name
|
||||
user_name = (
|
||||
await GroupInfoUser.get_member_info(user_qq, group)
|
||||
).user_name
|
||||
except Exception as e:
|
||||
logger.info(f"USER {user_qq}, GROUP {group} 不在群内")
|
||||
_count += 1
|
||||
@@ -120,8 +130,11 @@ async def random_gold(user_id, group_id, impression):
|
||||
return 0
|
||||
|
||||
|
||||
# 签到总榜
|
||||
async def impression_rank(group_id: int, data: dict):
|
||||
user_qq_list, impression_list, group_list = await SignGroupUser.query_impression_all(group_id)
|
||||
user_qq_list, impression_list, group_list = await SignGroupUser.get_all_impression(
|
||||
group_id
|
||||
)
|
||||
users, impressions, groups = [], [], []
|
||||
num = 0
|
||||
for i in range(105 if len(user_qq_list) > 105 else len(user_qq_list)):
|
||||
@@ -133,7 +146,7 @@ async def impression_rank(group_id: int, data: dict):
|
||||
impression_list.pop(index)
|
||||
group_list.pop(index)
|
||||
if user not in users and impression < 100000:
|
||||
if user not in data['0']:
|
||||
if user not in data["0"]:
|
||||
users.append(user)
|
||||
impressions.append(impression)
|
||||
groups.append(group)
|
||||
@@ -159,10 +172,10 @@ async def _pst(users: list, impressions: list, groups: list):
|
||||
count = math.ceil(lens / 33)
|
||||
width = 10
|
||||
idx = 0
|
||||
A = CreateImg(1740, 3300, color='#FFE4C4')
|
||||
A = CreateImg(1740, 3300, color="#FFE4C4")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
for _ in range(count):
|
||||
col_img = CreateImg(550, 3300, 550, 100, color='#FFE4C4')
|
||||
col_img = CreateImg(550, 3300, 550, 100, color="#FFE4C4")
|
||||
for _ in range(33 if int(lens / 33) >= 1 else lens % 33 - 1):
|
||||
idx += 1
|
||||
if idx > 100:
|
||||
@@ -175,29 +188,37 @@ async def _pst(users: list, impressions: list, groups: list):
|
||||
users.pop(index)
|
||||
groups.pop(index)
|
||||
try:
|
||||
user_name = (await GroupInfoUser.select_member_info(user, group)).user_name
|
||||
user_name = (
|
||||
await GroupInfoUser.get_member_info(user, group)
|
||||
).user_name
|
||||
except AttributeError:
|
||||
user_name = f'我名字呢?'
|
||||
user_name = user_name if len(user_name) < 11 else user_name[:10] + '...'
|
||||
impression = str(impression)[:4] if len(str(impression)) > 4 else impression
|
||||
user_name = f"我名字呢?"
|
||||
user_name = user_name if len(user_name) < 11 else user_name[:10] + "..."
|
||||
impression = (
|
||||
str(impression)[:4] if len(str(impression)) > 4 else impression
|
||||
)
|
||||
try:
|
||||
async with session.get(f'http://q1.qlogo.cn/g?b=qq&nk={user}&s=160', timeout=5) as response:
|
||||
ava = CreateImg(50, 50, background=BytesIO(await response.read()))
|
||||
async with session.get(
|
||||
f"http://q1.qlogo.cn/g?b=qq&nk={user}&s=160", timeout=5
|
||||
) as response:
|
||||
ava = CreateImg(
|
||||
50, 50, background=BytesIO(await response.read())
|
||||
)
|
||||
except TimeoutError:
|
||||
ava = CreateImg(50, 50, color='white')
|
||||
ava = CreateImg(50, 50, color="white")
|
||||
ava.circle()
|
||||
bk = CreateImg(550, 100, color='#FFE4C4', font_size=30)
|
||||
font_w, font_h = bk.getsize(f'{idx}')
|
||||
bk.text((5, int((100-font_h)/2)), f'{idx}.')
|
||||
bk.paste(ava, (55, int((100-50)/2)), True)
|
||||
bk.text((120, int((100-font_h)/2)), f'{user_name}')
|
||||
bk.text((460, int((100-font_h)/2)), f'[{impression}]')
|
||||
bk = CreateImg(550, 100, color="#FFE4C4", font_size=30)
|
||||
font_w, font_h = bk.getsize(f"{idx}")
|
||||
bk.text((5, int((100 - font_h) / 2)), f"{idx}.")
|
||||
bk.paste(ava, (55, int((100 - 50) / 2)), True)
|
||||
bk.text((120, int((100 - font_h) / 2)), f"{user_name}")
|
||||
bk.text((460, int((100 - font_h) / 2)), f"[{impression}]")
|
||||
col_img.paste(bk)
|
||||
A.paste(col_img, (width, 0))
|
||||
lens -= 33
|
||||
width += 580
|
||||
W = CreateImg(1740, 3700, color='#FFE4C4', font_size=130)
|
||||
W = CreateImg(1740, 3700, color="#FFE4C4", font_size=130)
|
||||
W.paste(A, (0, 260))
|
||||
font_w, font_h = W.getsize('真寻的好感度总榜')
|
||||
W.text((int((1740-font_w)/2), int((260-font_h)/2)), '真寻的好感度总榜')
|
||||
font_w, font_h = W.getsize("真寻的好感度总榜")
|
||||
W.text((int((1740 - font_w) / 2), int((260 - font_h) / 2)), "真寻的好感度总榜")
|
||||
return W.pic2bs4()
|
||||
|
||||
Reference in New Issue
Block a user