code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
from io import BytesIO
from random import choice
from nonebot import on_regex
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message
from utils.utils import get_message_at, get_user_avatar, get_message_text
from utils.message_builder import image
from utils.image_utils import BuildImage
from nonebot.params import RegexGroup
from typing import Tuple, Any
__zx_plugin_name__ = "我有一个朋友"
__plugin_usage__ = """
usage:
我有一个朋友他...,不知道是不是你
指令:
我有一个朋友想问问 [文本] ?[at]: 当at时你的朋友就是艾特对象
""".strip()
__plugin_des__ = "我有一个朋友想问问..."
__plugin_cmd__ = ["我有一个朋友想问问[文本] ?[at]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["我有一个朋友想问问", "我有一个朋友"],
}
one_friend = on_regex(
"^我.*?朋友.*?[想问问|说|让我问问|想问|让我问|想知道|让我帮他问问|让我帮他问|让我帮忙问|让我帮忙问问|问](.*)",
priority=4,
block=True,
)
@one_friend.handle()
async def _(bot: Bot, event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
qq = get_message_at(event.json())
if not qq:
qq = choice(
[
x["user_id"]
for x in await bot.get_group_member_list(
group_id=event.group_id
)
]
)
user_name = "朋友"
else:
qq = qq[0]
at_user = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
user_name = at_user["card"] or at_user["nickname"]
msg = get_message_text(Message(reg_group[0])).strip()
if not msg:
msg = "都不知道问什么"
msg = msg.replace("他", "我").replace("她", "我").replace("它", "我")
x = await get_user_avatar(qq)
if x:
ava = BuildImage(200, 100, background=BytesIO(x))
else:
ava = BuildImage(200, 100, color=(0, 0, 0))
ava.circle()
text = BuildImage(400, 30, font_size=30)
text.text((0, 0), user_name)
A = BuildImage(700, 150, font_size=25, color="white")
await A.apaste(ava, (30, 25), True)
await A.apaste(text, (150, 38))
await A.atext((150, 85), msg, (125, 125, 125))
await one_friend.send(image(b64=A.pic2bs4())) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/one_friend/__init__.py | __init__.py |
from services.db_context import db
from typing import List
class RussianUser(db.Model):
__tablename__ = "russian_users"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger(), nullable=False)
win_count = db.Column(db.Integer(), default=0)
fail_count = db.Column(db.Integer(), default=0)
make_money = db.Column(db.Integer(), default=0)
lose_money = db.Column(db.Integer(), default=0)
winning_streak = db.Column(db.Integer(), default=0)
losing_streak = db.Column(db.Integer(), default=0)
max_winning_streak = db.Column(db.Integer(), default=0)
max_losing_streak = db.Column(db.Integer(), default=0)
_idx1 = db.Index("russian_group_users_idx1", "user_qq", "group_id", unique=True)
@classmethod
async def ensure(cls, user_qq: int, group_id: int) -> "RussianUser":
"""
说明:
获取用户对象
参数:
:param user_qq: qq号
:param group_id: 群号
"""
user = (
await cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
.with_for_update()
.gino.first()
)
return user or await cls.create(user_qq=user_qq, group_id=group_id)
@classmethod
async def add_count(cls, user_qq: int, group_id: int, itype: str) -> bool:
"""
说明:
添加用户输赢次数
说明:
:param user_qq: qq号
:param group_id: 群号
:param itype: 输或赢 'win' or 'lose'
"""
try:
user = (
await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
.with_for_update()
.gino.first()
)
if not user:
user = await cls.create(user_qq=user_qq, group_id=group_id)
if itype == "win":
_max = (
user.max_winning_streak
if user.max_winning_streak > user.winning_streak + 1
else user.winning_streak + 1
)
await user.update(
win_count=user.win_count + 1,
winning_streak=user.winning_streak + 1,
losing_streak=0,
max_winning_streak=_max
).apply()
elif itype == "lose":
_max = (
user.max_losing_streak
if user.max_losing_streak > user.losing_streak + 1
else user.losing_streak + 1
)
await user.update(
fail_count=user.fail_count + 1,
losing_streak=user.losing_streak + 1,
winning_streak=0,
max_losing_streak=_max,
).apply()
return True
except Exception:
return False
@classmethod
async def money(cls, user_qq: int, group_id: int, itype: str, count: int) -> bool:
"""
说明:
添加用户输赢金钱
参数:
:param user_qq: qq号
:param group_id: 群号
:param itype: 输或赢 'win' or 'lose'
:param count: 金钱数量
"""
try:
user = (
await cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
.with_for_update()
.gino.first()
)
if not user:
user = await cls.create(user_qq=user_qq, group_id=group_id)
if itype == "win":
await user.update(
make_money=user.make_money + count,
).apply()
elif itype == "lose":
await user.update(
lose_money=user.lose_money + count,
).apply()
return True
except Exception:
return False
@classmethod
async def get_all_user(cls, group_id: int) -> List["RussianUser"]:
"""
说明:
获取该群所有用户对象
参数:
:param group_id: 群号
"""
users = await cls.query.where((cls.group_id == group_id)).gino.all()
return users | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/russian/model.py | model.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GROUP, Bot, GroupMessageEvent, Message
from nonebot.typing import T_State
from utils.utils import is_number, get_message_at
from nonebot.params import CommandArg, Command, ArgStr
from models.group_member_info import GroupInfoUser
from utils.message_builder import at, image
from .model import RussianUser
from models.bag_user import BagUser
from services.log import logger
from .data_source import rank
from configs.config import NICKNAME, Config
from typing import Tuple
import random
import asyncio
import time
__zx_plugin_name__ = "俄罗斯轮盘"
__plugin_usage__ = """
usage:
又到了决斗时刻
指令:
装弹 [子弹数] ?[金额=200] ?[at]: 开启游戏,装填子弹,可选自定义金额,或邀请决斗对象
接受对决: 接受当前存在的对决
拒绝对决: 拒绝邀请的对决
开枪: 开出未知的一枪
结算: 强行结束当前比赛 (仅当一方未开枪超过30秒时可使用)
我的战绩: 对,你的战绩
胜场排行/败场排行/欧洲人排行/慈善家排行/最高连胜排行/最高连败排行: 各种排行榜
示例:装弹 3 100 @sdd
* 注:同一时间群内只能有一场对决 *
""".strip()
__plugin_des__ = "虽然是运气游戏,但这可是战场啊少年"
__plugin_cmd__ = [
"装弹 [子弹数] ?[金额=200] ?[at]",
"接受对决",
"拒绝对决",
"开枪",
"结算",
"我的战绩",
"胜场排行/败场排行/欧洲人排行/慈善家排行/最高连胜排行/最高连败排行",
]
__plugin_type__ = ("群内小游戏", 1)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["俄罗斯轮盘", "装弹"],
}
__plugin_configs__ = {
"MAX_RUSSIAN_BET_GOLD": {
"value": 1000,
"help": "俄罗斯轮盘最大赌注金额",
"default_value": 1000,
}
}
rs_player = {}
russian = on_command(
"俄罗斯轮盘", aliases={"装弹", "俄罗斯转盘"}, permission=GROUP, priority=5, block=True
)
accept = on_command(
"接受对决", aliases={"接受决斗", "接受挑战"}, permission=GROUP, priority=5, block=True
)
refuse = on_command(
"拒绝对决", aliases={"拒绝决斗", "拒绝挑战"}, permission=GROUP, priority=5, block=True
)
shot = on_command(
"开枪", aliases={"咔", "嘭", "嘣"}, permission=GROUP, priority=5, block=True
)
settlement = on_command("结算", permission=GROUP, priority=5, block=True)
record = on_command("我的战绩", permission=GROUP, priority=5, block=True)
russian_rank = on_command(
"胜场排行",
aliases={"胜利排行", "败场排行", "失败排行", "欧洲人排行", "慈善家排行", "最高连胜排行", "最高连败排行"},
permission=GROUP,
priority=5,
block=True,
)
@accept.handle()
async def _(event: GroupMessageEvent):
global rs_player
try:
if rs_player[event.group_id][1] == 0:
await accept.finish("目前没有发起对决,你接受个啥?速速装弹!", at_sender=True)
except KeyError:
await accept.finish("目前没有进行的决斗,请发送 装弹 开启决斗吧!", at_sender=True)
if rs_player[event.group_id][2] != 0:
if (
rs_player[event.group_id][1] == event.user_id
or rs_player[event.group_id][2] == event.user_id
):
await accept.finish(f"你已经身处决斗之中了啊,给我认真一点啊!", at_sender=True)
else:
await accept.finish("已经有人接受对决了,你还是乖乖等待下一场吧!", at_sender=True)
if rs_player[event.group_id][1] == event.user_id:
await accept.finish("请不要自己枪毙自己!换人来接受对决...", at_sender=True)
if (
rs_player[event.group_id]["at"] != 0
and rs_player[event.group_id]["at"] != event.user_id
):
await accept.finish(
Message(f'这场对决是邀请 {at(rs_player[event.group_id]["at"])}的,不要捣乱!'),
at_sender=True,
)
if time.time() - rs_player[event.group_id]["time"] > 30:
rs_player[event.group_id] = {}
await accept.finish("这场对决邀请已经过时了,请重新发起决斗...", at_sender=True)
user_money = await BagUser.get_gold(event.user_id, event.group_id)
if user_money < rs_player[event.group_id]["money"]:
if (
rs_player[event.group_id]["at"] != 0
and rs_player[event.group_id]["at"] == event.user_id
):
rs_player[event.group_id] = {}
await accept.finish("你的金币不足以接受这场对决!对决还未开始便结束了,请重新装弹!", at_sender=True)
else:
await accept.finish("你的金币不足以接受这场对决!", at_sender=True)
player2_name = event.sender.card or event.sender.nickname
rs_player[event.group_id][2] = event.user_id
rs_player[event.group_id]["player2"] = player2_name
rs_player[event.group_id]["time"] = time.time()
await accept.send(
Message(f"{player2_name}接受了对决!\n" f"请{at(rs_player[event.group_id][1])}先开枪!")
)
@refuse.handle()
async def _(event: GroupMessageEvent):
global rs_player
try:
if rs_player[event.group_id][1] == 0:
await accept.finish("你要拒绝啥?明明都没有人发起对决的说!", at_sender=True)
except KeyError:
await refuse.finish("目前没有进行的决斗,请发送 装弹 开启决斗吧!", at_sender=True)
if (
rs_player[event.group_id]["at"] != 0
and event.user_id != rs_player[event.group_id]["at"]
):
await accept.finish("又不是找你决斗,你拒绝什么啊!气!", at_sender=True)
if rs_player[event.group_id]["at"] == event.user_id:
at_player_name = (
await GroupInfoUser.get_member_info(event.user_id, event.group_id)
).user_name
await accept.send(
Message(f"{at(rs_player[event.group_id][1])}\n" f"{at_player_name}拒绝了你的对决!")
)
rs_player[event.group_id] = {}
@settlement.handle()
async def _(bot: Bot, event: GroupMessageEvent):
global rs_player
if (
not rs_player.get(event.group_id)
or rs_player[event.group_id][1] == 0
or rs_player[event.group_id][2] == 0
):
await settlement.finish("比赛并没有开始...无法结算...", at_sender=True)
if (
event.user_id != rs_player[event.group_id][1]
and event.user_id != rs_player[event.group_id][2]
):
await settlement.finish("吃瓜群众不要捣乱!黄牌警告!", at_sender=True)
if time.time() - rs_player[event.group_id]["time"] <= 30:
await settlement.finish(
f'{rs_player[event.group_id]["player1"]} 和'
f' {rs_player[event.group_id]["player2"]} 比赛并未超时,请继续比赛...'
)
win_name = (
rs_player[event.group_id]["player1"]
if rs_player[event.group_id][2] == rs_player[event.group_id]["next"]
else rs_player[event.group_id]["player2"]
)
await settlement.send(f"这场对决是 {win_name} 胜利了")
await end_game(bot, event)
@russian.handle()
async def _(
bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = CommandArg()
):
global rs_player
msg = arg.extract_plain_text().strip()
try:
if (
rs_player[event.group_id][1]
and not rs_player[event.group_id][2]
and time.time() - rs_player[event.group_id]["time"] <= 30
):
await russian.finish(
f'现在是 {rs_player[event.group_id]["player1"]} 发起的对决\n请等待比赛结束后再开始下一轮...'
)
if (
rs_player[event.group_id][1]
and rs_player[event.group_id][2]
and time.time() - rs_player[event.group_id]["time"] <= 30
):
await russian.finish(
f'{rs_player[event.group_id]["player1"]} 和'
f' {rs_player[event.group_id]["player2"]}的对决还未结束!'
)
if (
rs_player[event.group_id][1]
and rs_player[event.group_id][2]
and time.time() - rs_player[event.group_id]["time"] > 30
):
await russian.send("决斗已过时,强行结算...")
await end_game(bot, event)
if (
not rs_player[event.group_id][2]
and time.time() - rs_player[event.group_id]["time"] > 30
):
rs_player[event.group_id][1] = 0
rs_player[event.group_id][2] = 0
rs_player[event.group_id]["at"] = 0
except KeyError:
pass
if msg:
msg = msg.split()
if len(msg) == 1:
msg = msg[0]
if is_number(msg) and not (int(msg) < 1 or int(msg) > 6):
state["bullet_num"] = int(msg)
else:
money = msg[1].strip()
msg = msg[0].strip()
if is_number(msg) and not (int(msg) < 1 or int(msg) > 6):
state["bullet_num"] = int(msg)
if is_number(money) and 0 < int(money) <= Config.get_config(
"russian", "MAX_RUSSIAN_BET_GOLD"
):
state["money"] = int(money)
else:
state["money"] = 200
await russian.send(
f"赌注金额超过限制({Config.get_config('russian', 'MAX_RUSSIAN_BET_GOLD')}),已改为200(默认)"
)
state["at"] = get_message_at(event.json())
@russian.got("bullet_num", prompt="请输入装填子弹的数量!(最多6颗)")
async def _(
event: GroupMessageEvent, state: T_State, bullet_num: str = ArgStr("bullet_num")
):
global rs_player
if bullet_num in ["取消", "算了"]:
await russian.finish("已取消操作...")
try:
if rs_player[event.group_id][1] != 0:
await russian.finish("决斗已开始...", at_sender=True)
except KeyError:
pass
if not is_number(bullet_num):
await russian.reject_arg("bullet_num", "输入子弹数量必须是数字啊喂!")
bullet_num = int(bullet_num)
if bullet_num < 1 or bullet_num > 6:
await russian.reject_arg("bullet_num", "子弹数量必须大于0小于7!")
at_ = state["at"] if state.get("at") else []
money = state["money"] if state.get("money") else 200
user_money = await BagUser.get_gold(event.user_id, event.group_id)
if bullet_num < 0 or bullet_num > 6:
await russian.reject("子弹数量必须大于0小于7!速速重新装弹!")
if money > Config.get_config("russian", "MAX_RUSSIAN_BET_GOLD"):
await russian.finish(
f"太多了!单次金额不能超过{Config.get_config('russian', 'MAX_RUSSIAN_BET_GOLD')}!",
at_sender=True,
)
if money > user_money:
await russian.finish("你没有足够的钱支撑起这场挑战", at_sender=True)
player1_name = event.sender.card or event.sender.nickname
if at_:
at_ = at_[0]
try:
at_player_name = (
await GroupInfoUser.get_member_info(at_, event.group_id)
).user_name
except AttributeError:
at_player_name = at(at_)
msg = f"{player1_name} 向 {at(at_)} 发起了决斗!请 {at_player_name} 在30秒内回复‘接受对决’ or ‘拒绝对决’,超时此次决斗作废!"
else:
at_ = 0
msg = "若30秒内无人接受挑战则此次对决作废【首次游玩请发送 ’俄罗斯轮盘帮助‘ 来查看命令】"
rs_player[event.group_id] = {
1: event.user_id,
"player1": player1_name,
2: 0,
"player2": "",
"at": at_,
"next": event.user_id,
"money": money,
"bullet": random_bullet(bullet_num),
"bullet_num": bullet_num,
"null_bullet_num": 7 - bullet_num,
"index": 0,
"time": time.time(),
}
await russian.send(
Message(
("咔 " * bullet_num)[:-1] + f",装填完毕\n挑战金额:{money}\n"
f"第一枪的概率为:{str(float(bullet_num) / 7.0 * 100)[:5]}%\n"
f"{msg}"
)
)
@shot.handle()
async def _(bot: Bot, event: GroupMessageEvent):
global rs_player
try:
if time.time() - rs_player[event.group_id]["time"] > 30:
if rs_player[event.group_id][2] == 0:
rs_player[event.group_id][1] = 0
await shot.finish("这场对决已经过时了,请重新装弹吧!", at_sender=True)
else:
await shot.send("决斗已过时,强行结算...")
await end_game(bot, event)
return
except KeyError:
await shot.finish("目前没有进行的决斗,请发送 装弹 开启决斗吧!", at_sender=True)
if rs_player[event.group_id][1] == 0:
await shot.finish("没有对决,也还没装弹呢,请先输入 装弹 吧!", at_sender=True)
if (
rs_player[event.group_id][1] == event.user_id
and rs_player[event.group_id][2] == 0
):
await shot.finish("baka,你是要枪毙自己嘛笨蛋!", at_sender=True)
if rs_player[event.group_id][2] == 0:
await shot.finish("请这位勇士先发送 接受对决 来站上擂台...", at_sender=True)
player1_name = rs_player[event.group_id]["player1"]
player2_name = rs_player[event.group_id]["player2"]
if rs_player[event.group_id]["next"] != event.user_id:
if (
event.user_id != rs_player[event.group_id][1]
and event.user_id != rs_player[event.group_id][2]
):
await shot.finish(
random.choice(
[
f"不要打扰 {player1_name} 和 {player2_name} 的决斗啊!",
f"给我好好做好一个观众!不然{NICKNAME}就要生气了",
f"不要捣乱啊baka{(await GroupInfoUser.get_member_info(event.user_id, event.group_id)).user_name}!",
]
),
at_sender=True,
)
await shot.finish(
f"你的左轮不是连发的!该 "
f'{(await GroupInfoUser.get_member_info(int(rs_player[event.group_id]["next"]), event.group_id)).user_name} 开枪了'
)
if rs_player[event.group_id]["bullet"][rs_player[event.group_id]["index"]] != 1:
await shot.send(
Message(
random.choice(
[
"呼呼,没有爆裂的声响,你活了下来",
"虽然黑洞洞的枪口很恐怖,但好在没有子弹射出来,你活下来了",
'"咔",你没死,看来运气不错',
]
)
+ f"\n下一枪中弹的概率"
f':{str(float((rs_player[event.group_id]["bullet_num"])) / float(rs_player[event.group_id]["null_bullet_num"] - 1 + rs_player[event.group_id]["bullet_num"]) * 100)[:5]}%\n'
f"轮到 {at(rs_player[event.group_id][1] if event.user_id == rs_player[event.group_id][2] else rs_player[event.group_id][2])}了"
)
)
rs_player[event.group_id]["null_bullet_num"] -= 1
rs_player[event.group_id]["next"] = (
rs_player[event.group_id][1]
if event.user_id == rs_player[event.group_id][2]
else rs_player[event.group_id][2]
)
rs_player[event.group_id]["time"] = time.time()
rs_player[event.group_id]["index"] += 1
else:
await shot.send(
random.choice(
[
'"嘭!",你直接去世了',
"眼前一黑,你直接穿越到了异世界...(死亡)",
"终究还是你先走一步...",
]
)
+ f'\n第 {rs_player[event.group_id]["index"] + 1} 发子弹送走了你...',
at_sender=True,
)
win_name = (
player1_name
if event.user_id == rs_player[event.group_id][2]
else player2_name
)
await asyncio.sleep(0.5)
await shot.send(f"这场对决是 {win_name} 胜利了")
await end_game(bot, event)
async def end_game(bot: Bot, event: GroupMessageEvent):
global rs_player
player1_name = rs_player[event.group_id]["player1"]
player2_name = rs_player[event.group_id]["player2"]
if rs_player[event.group_id]["next"] == rs_player[event.group_id][1]:
win_user_id = rs_player[event.group_id][2]
lose_user_id = rs_player[event.group_id][1]
win_name = player2_name
lose_name = player1_name
else:
win_user_id = rs_player[event.group_id][1]
lose_user_id = rs_player[event.group_id][2]
win_name = player1_name
lose_name = player2_name
rand = random.randint(0, 5)
money = rs_player[event.group_id]["money"]
if money > 10:
fee = int(money * float(rand) / 100)
fee = 1 if fee < 1 and rand != 0 else fee
else:
fee = 0
await RussianUser.add_count(win_user_id, event.group_id, "win")
await RussianUser.add_count(lose_user_id, event.group_id, "lose")
await RussianUser.money(win_user_id, event.group_id, "win", money - fee)
await RussianUser.money(lose_user_id, event.group_id, "lose", money)
await BagUser.add_gold(win_user_id, event.group_id, money - fee)
await BagUser.spend_gold(lose_user_id, event.group_id, money)
win_user = await RussianUser.ensure(win_user_id, event.group_id)
lose_user = await RussianUser.ensure(lose_user_id, event.group_id)
bullet_str = ""
for x in rs_player[event.group_id]["bullet"]:
bullet_str += "__ " if x == 0 else "| "
logger.info(f"俄罗斯轮盘:胜者:{win_name} - 败者:{lose_name} - 金币:{money}")
rs_player[event.group_id] = {}
await bot.send(
event,
message=f"结算:\n"
f"\t胜者:{win_name}\n"
f"\t赢取金币:{money - fee}\n"
f"\t累计胜场:{win_user.win_count}\n"
f"\t累计赚取金币:{win_user.make_money}\n"
f"-------------------\n"
f"\t败者:{lose_name}\n"
f"\t输掉金币:{money}\n"
f"\t累计败场:{lose_user.fail_count}\n"
f"\t累计输掉金币:{lose_user.lose_money}\n"
f"-------------------\n"
f"哼哼,{NICKNAME}从中收取了 {float(rand)}%({fee}金币) 作为手续费!\n"
f"子弹排列:{bullet_str[:-1]}",
)
@record.handle()
async def _(event: GroupMessageEvent):
user = await RussianUser.ensure(event.user_id, event.group_id)
await record.send(
f"俄罗斯轮盘\n"
f"总胜利场次:{user.win_count}\n"
f"当前连胜:{user.winning_streak}\n"
f"最高连胜:{user.max_winning_streak}\n"
f"总失败场次:{user.fail_count}\n"
f"当前连败:{user.losing_streak}\n"
f"最高连败:{user.max_losing_streak}\n"
f"赚取金币:{user.make_money}\n"
f"输掉金币:{user.lose_money}",
at_sender=True,
)
@russian_rank.handle()
async def _(
event: GroupMessageEvent,
cmd: Tuple[str, ...] = Command(),
arg: Message = CommandArg(),
):
num = arg.extract_plain_text().strip()
if is_number(num) and 51 > int(num) > 10:
num = int(num)
else:
num = 10
rank_image = None
if cmd[0] in ["胜场排行", "胜利排行"]:
rank_image = await rank(event.group_id, "win_rank", num)
if cmd[0] in ["败场排行", "失败排行"]:
rank_image = await rank(event.group_id, "lose_rank", num)
if cmd[0] == "欧洲人排行":
rank_image = await rank(event.group_id, "make_money", num)
if cmd[0] == "慈善家排行":
rank_image = await rank(event.group_id, "spend_money", num)
if cmd[0] == "最高连胜排行":
rank_image = await rank(event.group_id, "max_winning_streak", num)
if cmd[0] == "最高连败排行":
rank_image = await rank(event.group_id, "max_losing_streak", num)
if rank_image:
await russian_rank.send(image(b64=rank_image.pic2bs4()))
# 随机子弹排列
def random_bullet(num: int) -> list:
bullet_lst = [0, 0, 0, 0, 0, 0, 0]
for i in random.sample([0, 1, 2, 3, 4, 5, 6], num):
bullet_lst[i] = 1
return bullet_lst | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/russian/__init__.py | __init__.py |
from utils.utils import get_bot
from bs4 import BeautifulSoup
from utils.http_utils import AsyncHttpx
import asyncio
import platform
import os
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
url = "https://github.com/Mrs4s/go-cqhttp/releases"
async def download_gocq_lasted(path: str):
text = (await AsyncHttpx.get(url)).text
soup = BeautifulSoup(text, "lxml")
a = soup.find("div", {"class": "release-header"}).find("a")
title = a.text
_url = a.get("href")
for file in os.listdir(path):
if file.endswith(".zip"):
if (
file == title + "-windows-amd64.zip"
or file == title + "_windows_amd64.zip"
):
return "gocqhttp没有更新!"
for file in os.listdir(path):
os.remove(path + file)
text = (await AsyncHttpx.get("https://github.com" + _url)).text
update_info = ""
soup = BeautifulSoup(text, "lxml")
info_div = soup.find("div", {"class": "markdown-body"})
for p in info_div.find_all("p"):
update_info += p.text.replace("<br>", "\n") + "\n"
div_all = soup.select(
"div.d-flex.flex-justify-between.flex-items-center.py-1.py-md-2.Box-body.px-2"
)
for div in div_all:
if (
div.find("a").find("span").text == title + "-windows-amd64.zip"
or div.find("a").find("span").text == title + "-linux-arm64.tar.gz"
or div.find("a").find("span").text == "go-cqhttp_windows_amd64.zip"
or div.find("a").find("span").text == "go-cqhttp_linux_arm64.tar.gz"
):
file_url = div.find("a").get("href")
if div.find("a").find("span").text.find("windows") == -1:
tag = "-linux-arm64.tar.gz"
else:
tag = "-windows-amd64.zip"
await AsyncHttpx.download_file(
"https://github.com" + file_url, path + title + tag
)
return update_info
async def upload_gocq_lasted(path, name, group_id):
bot = get_bot()
folder_id = 0
for folder in (await bot.get_group_root_files(group_id=group_id))["folders"]:
if folder["folder_name"] == "gocq":
folder_id = folder["folder_id"]
if not folder_id:
await bot.send_group_msg(group_id=group_id, message=f"请创建gocq文件夹后重试!")
for file in os.listdir(path):
os.remove(path + file)
else:
await bot.upload_group_file(
group_id=group_id, folder=folder_id, file=path + name, name=name
)
# asyncio.get_event_loop().run_until_complete(download_gocq_lasted()) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/update_gocqhttp/data_source.py | data_source.py |
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from .data_source import download_gocq_lasted, upload_gocq_lasted
from services.log import logger
from utils.utils import scheduler, get_bot
from nonebot.permission import SUPERUSER
from configs.config import Config
from pathlib import Path
import os
__zx_plugin_name__ = "更新gocq [Superuser]"
__plugin_usage__ = """
usage:
下载最新版gocq并上传至群文件
指令:
更新gocq
""".strip()
__plugin_cmd__ = ["更新gocq"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_configs__ = {
"UPDATE_GOCQ_GROUP": {
"value": [],
"help": "需要为哪些群更新最新版gocq吗?(上传最新版gocq)示例:[434995955, 239483248]",
"default_value": [],
}
}
path = str((Path() / "resources" / "gocqhttp_file").absolute()) + "/"
lasted_gocqhttp = on_command("更新gocq", permission=SUPERUSER, priority=5, block=True)
@lasted_gocqhttp.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
# try:
if event.group_id in Config.get_config("update_gocqhttp", "UPDATE_GOCQ_GROUP"):
await lasted_gocqhttp.send("检测中...")
info = await download_gocq_lasted(path)
if info == "gocqhttp没有更新!":
await lasted_gocqhttp.finish("gocqhttp没有更新!")
try:
for file in os.listdir(path):
await upload_gocq_lasted(path, file, event.group_id)
logger.info(f"更新了cqhttp...{file}")
await lasted_gocqhttp.send(f"gocqhttp更新了,已上传成功!\n更新内容:\n{info}")
except Exception as e:
logger.error(f"更新gocq错误 e:{e}")
# 更新gocq
@scheduler.scheduled_job(
"cron",
hour=3,
minute=1,
)
async def _():
if Config.get_config("update_gocqhttp", "UPDATE_GOCQ_GROUP"):
bot = get_bot()
try:
info = await download_gocq_lasted(path)
if info == "gocqhttp没有更新!":
logger.info("gocqhttp没有更新!")
return
for group in Config.get_config("update_gocqhttp", "UPDATE_GOCQ_GROUP"):
for file in os.listdir(path):
await upload_gocq_lasted(path, file, group)
await bot.send_group_msg(
group_id=group, message=f"gocqhttp更新了,已上传成功!\n更新内容:\n{info}"
)
except Exception as e:
logger.error(f"自动更新gocq出错 e:{e}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/update_gocqhttp/__init__.py | __init__.py |
from nonebot import on_command
from utils.utils import is_number
from nonebot.permission import SUPERUSER
from ._data_source import start_update_image_url
from ._model.pixiv_keyword_user import PixivKeywordUser
from ._model.omega_pixiv_illusts import OmegaPixivIllusts
from ._model.pixiv import Pixiv
from nonebot.adapters.onebot.v11 import Message
from nonebot.params import CommandArg
import time
from services.log import logger
from pathlib import Path
from typing import List
from datetime import datetime
import asyncio
import os
__zx_plugin_name__ = "pix检查更新 [Superuser]"
__plugin_usage__ = """
usage:
更新pix收录的所有或指定数量的 关键词/uid/pid
指令:
更新pix关键词 *[keyword/uid/pid] [num=max]: 更新仅keyword/uid/pid或全部
pix检测更新:检测从未更新过的uid和pid
示例:更新pix关键词keyword
示例:更新pix关键词uid 10
""".strip()
__plugin_des__ = "pix图库收录数据检查更新"
__plugin_cmd__ = ["更新pix关键词 *[keyword/uid/pid] [num=max]", "pix检测更新"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
start_update = on_command(
"更新pix关键词", aliases={"更新pix关键字"}, permission=SUPERUSER, priority=1, block=True
)
check_not_update_uid_pid = on_command(
"pix检测更新",
aliases={"pix检查更新"},
permission=SUPERUSER,
priority=1,
block=True,
)
check_omega = on_command("检测omega图库", permission=SUPERUSER, priority=1, block=True)
@start_update.handle()
async def _(arg: Message = CommandArg()):
msg_sp = arg.extract_plain_text().strip().split()
_pass_keyword, _ = await PixivKeywordUser.get_current_keyword()
_pass_keyword.reverse()
black_pid = await PixivKeywordUser.get_black_pid()
_keyword = [
x
for x in _pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_uid = [x for x in _pass_keyword if x.startswith("uid:")]
_pid = [x for x in _pass_keyword if x.startswith("pid:")]
num = 9999
msg = msg_sp[0] if len(msg_sp) else ""
if len(msg_sp) == 2:
if is_number(msg_sp[1]):
num = int(msg_sp[1])
else:
await start_update.finish("参数错误...第二参数必须为数字")
if num < 10000:
keyword_str = ",".join(
_keyword[: num if num < len(_keyword) else len(_keyword)]
)
uid_str = ",".join(_uid[: num if num < len(_uid) else len(_uid)])
pid_str = ",".join(_pid[: num if num < len(_pid) else len(_pid)])
if msg.lower() == "pid":
update_lst = _pid
info = f"开始更新Pixiv搜图PID:\n{pid_str}"
elif msg.lower() == "uid":
update_lst = _uid
info = f"开始更新Pixiv搜图UID:\n{uid_str}"
elif msg.lower() == "keyword":
update_lst = _keyword
info = f"开始更新Pixiv搜图关键词:\n{keyword_str}"
else:
update_lst = _pass_keyword
info = f"开始更新Pixiv搜图关键词:\n{keyword_str}\n更新UID:{uid_str}\n更新PID:{pid_str}"
num = num if num < len(update_lst) else len(update_lst)
else:
if msg.lower() == "pid":
update_lst = [f"pid:{num}"]
info = f"开始更新Pixiv搜图UID:\npid:{num}"
else:
update_lst = [f"uid:{num}"]
info = f"开始更新Pixiv搜图UID:\nuid:{num}"
await start_update.send(info)
start_time = time.time()
pid_count, pic_count = await start_update_image_url(update_lst[:num], black_pid)
await start_update.send(
f"Pixiv搜图关键词搜图更新完成...\n"
f"累计更新PID {pid_count} 个\n"
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
)
@check_not_update_uid_pid.handle()
async def _(arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
flag = False
if msg == "update":
flag = True
_pass_keyword, _ = await PixivKeywordUser.get_current_keyword()
x_uid = []
x_pid = []
_uid = [int(x[4:]) for x in _pass_keyword if x.startswith("uid:")]
_pid = [int(x[4:]) for x in _pass_keyword if x.startswith("pid:")]
all_images = await Pixiv.query_images(r18=2)
for img in all_images:
if img.pid not in x_pid:
x_pid.append(img.pid)
if img.uid not in x_uid:
x_uid.append(img.uid)
await check_not_update_uid_pid.send(
"从未更新过的UID:"
+ ",".join([f"uid:{x}" for x in _uid if x not in x_uid])
+ "\n"
+ "从未更新过的PID:"
+ ",".join([f"pid:{x}" for x in _pid if x not in x_pid])
)
if flag:
await check_not_update_uid_pid.send("开始自动自动更新PID....")
update_lst = [f"pid:{x}" for x in _uid if x not in x_uid]
black_pid = await PixivKeywordUser.get_black_pid()
start_time = time.time()
pid_count, pic_count = await start_update_image_url(update_lst, black_pid)
await check_not_update_uid_pid.send(
f"Pixiv搜图关键词搜图更新完成...\n"
f"累计更新PID {pid_count} 个\n"
f"累计更新图片 {pic_count} 张" + "\n耗时:{:.2f}秒".format((time.time() - start_time))
)
@check_omega.handle()
async def _():
async def _tasks(line: str, all_pid: List[int], length: int, index: int):
data = line.split("VALUES", maxsplit=1)[-1].strip()
if data.startswith("("):
data = data[1:]
if data.endswith(");"):
data = data[:-2]
x = data.split(maxsplit=3)
pid = int(x[1][:-1].strip())
if pid in all_pid:
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
return
uid = int(x[2][:-1].strip())
x = x[3].split(", '")
title = x[0].strip()[1:-1]
tmp = x[1].split(", ")
author = tmp[0].strip()[:-1]
nsfw_tag = int(tmp[1])
width = int(tmp[2])
height = int(tmp[3])
tags = x[2][:-1]
url = x[3][:-1]
if await OmegaPixivIllusts.add_image_data(
pid,
title,
width,
height,
url,
uid,
author,
nsfw_tag,
tags,
datetime.min,
datetime.min,
):
logger.info(
f"成功添加OmegaPixivIllusts图库数据 pid:{pid} 本次预计存储 {length} 张,已更新第 {index} 张"
)
else:
logger.info(f"添加OmegaPixivIllusts图库数据已存在 ---> pid:{pid}")
omega_pixiv_illusts = None
for file in os.listdir("."):
if "omega_pixiv_illusts" in file and ".sql" in file:
omega_pixiv_illusts = Path() / file
if omega_pixiv_illusts:
with open(omega_pixiv_illusts, "r", encoding="utf8") as f:
lines = f.readlines()
tasks = []
length = len([x for x in lines if "INSERT INTO" in x.upper()])
all_pid = await OmegaPixivIllusts.get_all_pid()
index = 0
logger.info("检测到OmegaPixivIllusts数据库,准备开始更新....")
for line in lines:
if "INSERT INTO" in line.upper():
index += 1
tasks.append(
asyncio.ensure_future(_tasks(line, all_pid, length, index))
)
await asyncio.gather(*tasks)
omega_pixiv_illusts.unlink() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/pix_update.py | pix_update.py |
from nonebot import on_command
from utils.message_builder import image
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, Message
from ._data_source import gen_keyword_pic, get_keyword_num
from ._model.pixiv_keyword_user import PixivKeywordUser
from nonebot.params import CommandArg
import asyncio
__zx_plugin_name__ = "查看pix图库"
__plugin_usage__ = """
usage:
查看pix图库
指令:
查看pix图库 ?[tags]: 查看指定tag图片数量,为空时查看整个图库
""".strip()
__plugin_des__ = "让我看看管理员私藏了多少货"
__plugin_cmd__ = ["查看pix图库 ?[tags]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["查看pix图库"],
}
my_keyword = on_command("我的pix关键词", aliases={"我的pix关键字"}, priority=1, block=True)
show_keyword = on_command("显示pix关键词", aliases={"显示pix关键字"}, priority=1, block=True)
show_pix = on_command("查看pix图库", priority=1, block=True)
@my_keyword.handle()
async def _(event: MessageEvent):
data = await PixivKeywordUser.get_all_user_dict()
if data.get(event.user_id) is None or not data[event.user_id]["keyword"]:
await my_keyword.finish("您目前没有提供任何Pixiv搜图关键字...", at_sender=True)
await my_keyword.send(
f"您目前提供的如下关键字:\n\t" + ",".join(data[event.user_id]["keyword"])
)
@show_keyword.handle()
async def _(bot: Bot, event: MessageEvent):
_pass_keyword, not_pass_keyword = await PixivKeywordUser.get_current_keyword()
if _pass_keyword or not_pass_keyword:
await show_keyword.send(
image(
b64=await asyncio.get_event_loop().run_in_executor(
None,
gen_keyword_pic,
_pass_keyword,
not_pass_keyword,
str(event.user_id) in bot.config.superusers,
)
)
)
else:
if str(event.user_id) in bot.config.superusers:
await show_keyword.finish(f"目前没有已收录或待收录的搜索关键词...")
else:
await show_keyword.finish(f"目前没有已收录的搜索关键词...")
@show_pix.handle()
async def _(arg: Message = CommandArg()):
keyword = arg.extract_plain_text().strip()
count, r18_count, count_, setu_count, r18_count_ = await get_keyword_num(keyword)
await show_pix.send(
f"PIX图库:{keyword}\n"
f"总数:{count + r18_count}\n"
f"美图:{count}\n"
f"R18:{r18_count}\n"
f"---------------\n"
f"Omega图库:{keyword}\n"
f"总数:{count_ + setu_count + r18_count_}\n"
f"美图:{count_}\n"
f"色图:{setu_count}\n"
f"R18:{r18_count_}"
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/pix_show_info.py | pix_show_info.py |
from nonebot import on_command
from utils.utils import is_number
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg, Command
from typing import Tuple
from ._data_source import uid_pid_exists
from ._model.pixiv_keyword_user import PixivKeywordUser
from ._model.pixiv import Pixiv
from nonebot.permission import SUPERUSER
__zx_plugin_name__ = "PIX关键词/UID/PID添加管理 [Superuser]"
__plugin_usage__ = """
usage:
PIX关键词/UID/PID添加管理操作
指令:
添加pix关键词 [Tag]: 添加一个pix搜索收录Tag
添加pixuid [uid]: 添加一个pix搜索收录uid
添加pixpid [pid]: 添加一个pix收录pid
""".strip()
__plugin_des__ = "PIX关键词/UID/PID添加管理"
__plugin_cmd__ = ["添加pix关键词 [Tag]", "添加pixuid [uid]", "添加pixpid [pid]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
add_keyword = on_command("添加pix关键词", aliases={"添加pix关键字"}, priority=1, block=True)
add_black_pid = on_command("添加pix黑名单", permission=SUPERUSER, priority=1, block=True)
# 超级用户可以通过字符 -f 来强制收录不检查是否存在
add_uid_pid = on_command(
"添加pixuid",
aliases={
"添加pixpid",
},
priority=1,
block=True,
)
@add_keyword.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
group_id = -1
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
if msg:
if await PixivKeywordUser.add_keyword(
event.user_id, group_id, msg, bot.config.superusers
):
await add_keyword.send(
f"已成功添加pixiv搜图关键词:{msg},请等待管理员通过该关键词!", at_sender=True
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 添加了pixiv搜图关键词:" + msg
)
else:
await add_keyword.finish(f"该关键词 {msg} 已存在...")
else:
await add_keyword.finish(f"虚空关键词?.?.?.?")
@add_uid_pid.handle()
async def _(bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
exists_flag = True
if msg.find("-f") != -1 and str(event.user_id) in bot.config.superusers:
exists_flag = False
msg = msg.replace("-f", "").strip()
if msg:
for msg in msg.split():
if not is_number(msg):
await add_uid_pid.finish("UID只能是数字的说...", at_sender=True)
if cmd[0].lower().endswith("uid"):
msg = f"uid:{msg}"
else:
msg = f"pid:{msg}"
if await Pixiv.check_exists(int(msg[4:]), "p0"):
await add_uid_pid.finish(f"该PID:{msg[4:]}已存在...", at_sender=True)
if not await uid_pid_exists(msg) and exists_flag:
await add_uid_pid.finish("画师或作品不存在或搜索正在CD,请稍等...", at_sender=True)
group_id = -1
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
if await PixivKeywordUser.add_keyword(
event.user_id, group_id, msg, bot.config.superusers
):
await add_uid_pid.send(
f"已成功添加pixiv搜图UID/PID:{msg[4:]},请等待管理员通过!", at_sender=True
)
else:
await add_uid_pid.finish(f"该UID/PID:{msg[4:]} 已存在...")
else:
await add_uid_pid.finish("湮灭吧!虚空的UID!")
@add_black_pid.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
pid = arg.extract_plain_text().strip()
img_p = ""
if "p" in pid:
img_p = pid.split("p")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("p")]
if not is_number(pid):
await add_black_pid.finish("PID必须全部是数字!", at_sender=True)
if await PixivKeywordUser.add_keyword(
114514,
114514,
f"black:{pid}{f'_p{img_p}' if img_p else ''}",
bot.config.superusers,
):
await add_black_pid.send(f"已添加PID:{pid} 至黑名单中...")
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 添加了pixiv搜图黑名单 PID:{pid}"
)
else:
await add_black_pid.send(f"PID:{pid} 已添加黑名单中,添加失败...") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/pix_add_keyword.py | pix_add_keyword.py |
from nonebot import on_command
from utils.utils import is_number
from utils.message_builder import at
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg, Command
from nonebot.permission import SUPERUSER
from ._data_source import remove_image
from ._model.pixiv_keyword_user import PixivKeywordUser
from ._model.pixiv import Pixiv
from typing import Tuple
__zx_plugin_name__ = "PIX关键词/UID/PID删除管理 [Superuser]"
__plugin_usage__ = """
usage:
PIX关键词/UID/PID删除管理操作
指令:
通过pix关键词 [关键词/pid/uid]
取消pix关键词 [关键词/pid/uid]
删除pix关键词 [关键词/pid/uid]
删除pix图片 *[pid]
示例:通过pix关键词萝莉
示例:通过pix关键词uid:123456
示例:通过pix关键词pid:123456
示例:删除pix图片4223442
""".strip()
__plugin_des__ = "PIX关键词/UID/PID删除管理"
__plugin_cmd__ = [
"通过pix关键词 [关键词/pid/uid]",
"取消pix关键词 [关键词/pid/uid]",
"删除pix关键词 [关键词/pid/uid]",
"删除pix图片 *[pid]",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
pass_keyword = on_command(
"通过pix关键词",
aliases={"通过pix关键字", "取消pix关键词", "取消pix关键字"},
permission=SUPERUSER,
priority=1,
block=True,
)
del_keyword = on_command(
"删除pix关键词", aliases={"删除pix关键字"}, permission=SUPERUSER, priority=1, block=True
)
del_pic = on_command("删除pix图片", permission=SUPERUSER, priority=1, block=True)
@del_keyword.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
await del_keyword.finish("好好输入要删除什么关键字啊笨蛋!")
if is_number(msg):
msg = f"uid:{msg}"
if msg.lower().startswith("pid"):
msg = "pid:" + msg.replace("pid", "").replace(":", "")
if await PixivKeywordUser.delete_keyword(msg):
await del_keyword.send(f"删除搜图关键词/UID:{msg} 成功...")
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 删除了pixiv搜图关键词:" + msg
)
else:
await del_keyword.send(f"未查询到搜索关键词/UID/PID:{msg},删除失败!")
@del_pic.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
pid_arr = arg.extract_plain_text().strip()
if pid_arr:
msg = ""
black_pid = ""
flag = False
pid_arr = pid_arr.split()
if pid_arr[-1] in ["-black", "-b"]:
flag = True
pid_arr = pid_arr[:-1]
for pid in pid_arr:
img_p = None
if "p" in pid or "ugoira" in pid:
if "p" in pid:
img_p = pid.split("p")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("p")]
elif "ugoira" in pid:
img_p = pid.split("ugoira")[-1]
pid = pid.replace("_", "")
pid = pid[: pid.find("ugoira")]
if is_number(pid):
if await Pixiv.query_images(pid=int(pid), r18=2):
if await remove_image(int(pid), img_p):
msg += f'{pid}{f"_p{img_p}" if img_p else ""},'
if flag:
if await PixivKeywordUser.add_keyword(
114514,
114514,
f"black:{pid}{f'_p{img_p}' if img_p else ''}",
bot.config.superusers,
):
black_pid += f'{pid}{f"_p{img_p}" if img_p else ""},'
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 删除了PIX图片 PID:{pid}{f'_p{img_p}' if img_p else ''}"
)
else:
await del_pic.send(
f"PIX:删除pid:{pid}{f'_p{img_p}' if img_p else ''} 失败.."
)
else:
await del_pic.send(
f"PIX:图片pix:{pid}{f'_p{img_p}' if img_p else ''} 不存在...无法删除.."
)
else:
await del_pic.send(f"PID必须为数字!pid:{pid}", at_sender=True)
await del_pic.send(f"PIX:成功删除图片:{msg[:-1]}")
if flag:
await del_pic.send(f"成功图片PID加入黑名单:{black_pid[:-1]}")
else:
await del_pic.send("虚空删除?")
@pass_keyword.handle()
async def _(bot: Bot, event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
tmp = {"group": {}, "private": {}}
msg = arg.extract_plain_text().strip()
if not msg:
await pass_keyword.finish("通过虚空的关键词/UID?离谱...")
msg = msg.split()
flag = cmd[0][:2] == "通过"
for x in msg:
if x.lower().startswith("uid"):
x = x.replace("uid", "").replace(":", "")
x = f"uid:{x}"
elif x.lower().startswith("pid"):
x = x.replace("pid", "").replace(":", "")
x = f"pid:{x}"
if x.lower().find("pid") != -1 or x.lower().find("uid") != -1:
if not is_number(x[4:]):
await pass_keyword.send(f"UID/PID:{x} 非全数字,跳过该关键词...")
continue
user_id, group_id = await PixivKeywordUser.set_keyword_pass(x, flag)
if not user_id:
await pass_keyword.send(f"未找到关键词/UID:{x},请检查关键词/UID是否存在...")
continue
if flag:
if group_id == -1:
if not tmp["private"].get(user_id):
tmp["private"][user_id] = {"keyword": [x]}
else:
tmp["private"][user_id]["keyword"].append(x)
else:
if not tmp["group"].get(group_id):
tmp["group"][group_id] = {}
if not tmp["group"][group_id].get(user_id):
tmp["group"][group_id][user_id] = {"keyword": [x]}
else:
tmp["group"][group_id][user_id]["keyword"].append(x)
msg = " ".join(msg)
await pass_keyword.send(f'已成功{cmd[0][:2]}搜图关键词:{msg}....')
for user in tmp["private"]:
x = ",".join(tmp["private"][user]["keyword"])
await bot.send_private_msg(
user_id=user, message=f"你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..."
)
for group in tmp["group"]:
for user in tmp["group"][group]:
x = ",".join(tmp["group"][group][user]["keyword"])
await bot.send_group_msg(
group_id=group,
message=Message(f"{at(user)}你的关键词/UID/PID {x} 已被管理员通过,将在下一次进行更新..."),
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 通过了pixiv搜图关键词/UID:" + msg
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/pix_pass_del_keyword.py | pix_pass_del_keyword.py |
from utils.utils import is_number
from configs.config import Config
from ._model.omega_pixiv_illusts import OmegaPixivIllusts
from utils.message_builder import image, custom_forward_msg
from utils.manager import withdraw_message_manager
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg
from ._data_source import get_image
from ._model.pixiv import Pixiv
from nonebot import on_command
import random
__zx_plugin_name__ = "PIX"
__plugin_usage__ = """
usage:
查看 pix 好康图库
指令:
pix ?*[tags]: 通过 tag 获取相似图片,不含tag时随机抽取
pix pid[pid]: 查看图库中指定pid图片
""".strip()
__plugin_superuser_usage__ = """
usage:
超级用户额外的 pix 指令
指令:
pix -s ?*[tags]: 通过tag获取色图,不含tag时随机
pix -r ?*[tags]: 通过tag获取r18图,不含tag时随机
""".strip()
__plugin_des__ = "这里是PIX图库!"
__plugin_cmd__ = [
"pix ?*[tags]",
"pix pid [pid]",
"pix -s ?*[tags] [_superuser]",
"pix -r ?*[tags] [_superuser]",
]
__plugin_type__ = ("来点好康的",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["pix", "Pix", "PIX", "pIx"],
}
__plugin_block_limit__ = {"rst": "您有PIX图片正在处理,请稍等..."}
__plugin_configs__ = {
"MAX_ONCE_NUM2FORWARD": {
"value": None,
"help": "单次发送的图片数量达到指定值时转发为合并消息",
"default_value": None,
}
}
pix = on_command("pix", aliases={"PIX", "Pix"}, priority=5, block=True)
PIX_RATIO = None
OMEGA_RATIO = None
@pix.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
global PIX_RATIO, OMEGA_RATIO
if PIX_RATIO is None:
pix_omega_pixiv_ratio = Config.get_config("pix", "PIX_OMEGA_PIXIV_RATIO")
PIX_RATIO = pix_omega_pixiv_ratio[0] / (
pix_omega_pixiv_ratio[0] + pix_omega_pixiv_ratio[1]
)
OMEGA_RATIO = 1 - PIX_RATIO
num = 1
keyword = arg.extract_plain_text().strip()
x = keyword.split()
if "-s" in x:
x.remove("-s")
nsfw_tag = 1
elif "-r" in x:
x.remove("-r")
nsfw_tag = 2
else:
nsfw_tag = 0
if nsfw_tag != 0 and str(event.user_id) not in bot.config.superusers:
await pix.finish("你不能看这些噢,这些都是是留给管理员看的...")
if n := len(x) == 1 and is_number(x[0]):
num = int(x[-1])
keyword = ""
elif n > 1:
if is_number(x[-1]):
num = int(x[-1])
if num > 10:
if str(event.user_id) not in bot.config.superusers or (
str(event.user_id) in bot.config.superusers and num > 30
):
num = random.randint(1, 10)
await pix.send(f"太贪心了,就给你发 {num}张 好了")
x = x[:-1]
keyword = " ".join(x)
pix_num = int(num * PIX_RATIO) + 15 if PIX_RATIO != 0 else 0
omega_num = num - pix_num + 15
if is_number(keyword):
if num == 1:
pix_num = 15
omega_num = 15
all_image = await Pixiv.query_images(
uid=int(keyword), num=pix_num, r18=1 if nsfw_tag == 2 else 0
) + await OmegaPixivIllusts.query_images(
uid=int(keyword), num=omega_num, nsfw_tag=nsfw_tag
)
elif keyword.lower().startswith("pid"):
pid = keyword.replace("pid", "").replace(":", "").replace(":", "")
if not is_number(pid):
await pix.finish("PID必须是数字...", at_sender=True)
all_image = await Pixiv.query_images(
pid=int(pid), r18=1 if nsfw_tag == 2 else 0
)
if not all_image:
all_image = await OmegaPixivIllusts.query_images(
pid=int(pid), nsfw_tag=nsfw_tag
)
else:
tmp = await Pixiv.query_images(
x, r18=1 if nsfw_tag == 2 else 0, num=pix_num
) + await OmegaPixivIllusts.query_images(x, nsfw_tag=nsfw_tag, num=omega_num)
tmp_ = []
all_image = []
for x in tmp:
if x.pid not in tmp_:
all_image.append(x)
tmp_.append(x.pid)
if not all_image:
await pix.finish(f"未在图库中找到与 {keyword} 相关Tag/UID/PID的图片...", at_sender=True)
msg_list = []
for _ in range(num):
img_url = None
author = None
# if not all_image:
# await pix.finish("坏了...发完了,没图了...")
img = random.choice(all_image)
all_image.remove(img)
if isinstance(img, OmegaPixivIllusts):
img_url = img.url
author = img.uname
elif isinstance(img, Pixiv):
img_url = img.img_url
author = img.author
pid = img.pid
title = img.title
uid = img.uid
_img = await get_image(img_url, event.user_id)
if _img:
if Config.get_config("pix", "SHOW_INFO"):
msg_list.append(
Message(
f"title:{title}\n"
f"author:{author}\n"
f"PID:{pid}\nUID:{uid}\n"
f"{image(_img)}"
)
)
else:
msg_list.append(image(_img))
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看PIX图库PID: {pid}"
)
else:
msg_list.append("这张图似乎下载失败了")
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看PIX图库PID: {pid},下载图片出错"
)
if (
Config.get_config("pix", "MAX_ONCE_NUM2FORWARD")
and num >= Config.get_config("pix", "MAX_ONCE_NUM2FORWARD")
and isinstance(event, GroupMessageEvent)
):
msg_id = await bot.send_group_forward_msg(
group_id=event.group_id, messages=custom_forward_msg(msg_list, bot.self_id)
)
withdraw_message_manager.withdraw_message(
event, msg_id, Config.get_config("pix", "WITHDRAW_PIX_MESSAGE")
)
else:
for msg in msg_list:
msg_id = await pix.send(msg)
withdraw_message_manager.withdraw_message(
event, msg_id, Config.get_config("pix", "WITHDRAW_PIX_MESSAGE")
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/pix.py | pix.py |
from asyncpg.exceptions import UniqueViolationError
from ._model.omega_pixiv_illusts import OmegaPixivIllusts
from asyncio.locks import Semaphore
from asyncio.exceptions import TimeoutError
from ._model.pixiv import Pixiv
from typing import List, Optional
from utils.utils import change_pixiv_image_links
from utils.image_utils import BuildImage
from utils.http_utils import AsyncHttpx
from services.log import logger
from configs.config import Config
from configs.path_config import TEMP_PATH
import aiofiles
import platform
import asyncio
import math
try:
import ujson as json
except ModuleNotFoundError:
import json
if str(platform.system()).lower() == "windows":
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
HIBIAPI = Config.get_config("hibiapi", "HIBIAPI")
if not HIBIAPI:
HIBIAPI = "https://api.obfs.dev"
HIBIAPI = HIBIAPI[:-1] if HIBIAPI[-1] == "/" else HIBIAPI
async def start_update_image_url(
current_keyword: List[str], black_pid: List[str]
) -> "int, int":
"""
开始更新图片url
:param current_keyword: 关键词
:param black_pid: 黑名单pid
:return: pid数量和图片数量
"""
global HIBIAPI
pid_count = 0
pic_count = 0
tasks = []
semaphore = asyncio.Semaphore(10)
for keyword in current_keyword:
for page in range(1, 110):
if keyword.startswith("uid:"):
url = f"{HIBIAPI}/api/pixiv/member_illust"
params = {"id": keyword[4:], "page": page}
if page == 30:
break
elif keyword.startswith("pid:"):
url = f"{HIBIAPI}/api/pixiv/illust"
params = {"id": keyword[4:]}
else:
url = f"{HIBIAPI}/api/pixiv/search"
params = {"word": keyword, "page": page}
tasks.append(
asyncio.ensure_future(
search_image(
url, keyword, params, semaphore, page, black_pid
)
)
)
if keyword.startswith("pid:"):
break
result = await asyncio.gather(*tasks)
for x in result:
pid_count += x[0]
pic_count += x[1]
return pid_count, pic_count
async def search_image(
url: str,
keyword: str,
params: dict,
semaphore: Semaphore,
page: int = 1,
black: List[str] = None,
) -> "int, int":
"""
搜索图片
:param url: 搜索url
:param keyword: 关键词
:param params: params参数
:param semaphore: semaphore
:param page: 页面
:param black: pid黑名单
:return: pid数量和图片数量
"""
tmp_pid = []
pic_count = 0
pid_count = 0
async with semaphore:
try:
data = (await AsyncHttpx.get(url, params=params)).json()
if (
not data
or data.get("error")
or (not data.get("illusts") and not data.get("illust"))
):
return 0, 0
if url != f"{HIBIAPI}/api/pixiv/illust":
logger.info(f'{keyword}: 获取数据成功...数据总量:{len(data["illusts"])}')
data = data["illusts"]
else:
logger.info(f'获取数据成功...PID:{params.get("id")}')
data = [data["illust"]]
img_data = {}
for x in data:
pid = x["id"]
title = x["title"]
width = x["width"]
height = x["height"]
view = x["total_view"]
bookmarks = x["total_bookmarks"]
uid = x["user"]["id"]
author = x["user"]["name"]
tags = []
for tag in x["tags"]:
for i in tag:
if tag[i]:
tags.append(tag[i])
img_urls = []
if x["page_count"] == 1:
img_urls.append(x["meta_single_page"]["original_image_url"])
else:
for urls in x["meta_pages"]:
img_urls.append(urls["image_urls"]["original"])
if (
(
bookmarks
>= Config.get_config("pix", "SEARCH_HIBIAPI_BOOKMARKS")
or (
url == f"{HIBIAPI}/api/pixiv/member_illust"
and bookmarks >= 1500
)
or (url == f"{HIBIAPI}/api/pixiv/illust")
)
and len(img_urls) < 10
and _check_black(img_urls, black)
):
img_data[pid] = {
"pid": pid,
"title": title,
"width": width,
"height": height,
"view": view,
"bookmarks": bookmarks,
"img_urls": img_urls,
"uid": uid,
"author": author,
"tags": tags,
}
else:
continue
for x in img_data.keys():
data = img_data[x]
for img_url in data["img_urls"]:
img_p = img_url[img_url.rfind("_") + 1 : img_url.rfind(".")]
try:
if await Pixiv.add_image_data(
data["pid"],
data["title"],
data["width"],
data["height"],
data["view"],
data["bookmarks"],
img_url,
img_p,
data["uid"],
data["author"],
",".join(data["tags"]),
):
if data["pid"] not in tmp_pid:
pid_count += 1
tmp_pid.append(data["pid"])
pic_count += 1
logger.info(f'存储图片PID:{data["pid"]} IMG_P:{img_p}')
except UniqueViolationError:
logger.warning(f'{data["pid"]} | {img_url} 已存在...')
except Exception as e:
logger.warning(f"PIX在线搜索图片错误,已再次调用 {type(e)}:{e}")
await search_image(url, keyword, params, semaphore, page, black)
return pid_count, pic_count
async def get_image(img_url: str, user_id: int) -> Optional[str]:
"""
下载图片
:param img_url:
:param user_id:
:return: 图片名称
"""
if "https://www.pixiv.net/artworks" in img_url:
pid = img_url.rsplit("/", maxsplit=1)[-1]
params = {"id": pid}
for _ in range(3):
try:
response = await AsyncHttpx.get(f"{HIBIAPI}/api/pixiv/illust", params=params)
if response.status_code == 200:
data = response.json()
if data.get("illust"):
if data["illust"]["page_count"] == 1:
img_url = data["illust"]["meta_single_page"][
"original_image_url"
]
else:
img_url = data["illust"]["meta_pages"][0][
"image_urls"
]["original"]
break
except TimeoutError:
pass
old_img_url = img_url
img_url = change_pixiv_image_links(
img_url, Config.get_config("pix", "PIX_IMAGE_SIZE"), Config.get_config("pixiv", "PIXIV_NGINX_URL")
)
old_img_url = change_pixiv_image_links(
old_img_url, None, Config.get_config("pixiv", "PIXIV_NGINX_URL")
)
for _ in range(3):
try:
response = await AsyncHttpx.get(img_url, headers=headers, timeout=Config.get_config("pix", "TIMEOUT"),)
if response.status_code == 404:
img_url = old_img_url
continue
async with aiofiles.open(
TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg", "wb"
) as f:
await f.write(response.content)
return TEMP_PATH / f"pix_{user_id}_{img_url.split('/')[-1][:-4]}.jpg"
except TimeoutError:
logger.warning(f"PIX:{img_url} 图片下载超时...")
pass
return None
async def uid_pid_exists(id_: str) -> bool:
"""
检测 pid/uid 是否有效
:param id_: pid/uid
"""
if id_.startswith("uid:"):
url = f"{HIBIAPI}/api/pixiv/member"
elif id_.startswith("pid:"):
url = f"{HIBIAPI}/api/pixiv/illust"
else:
return False
params = {"id": int(id_[4:])}
data = (await AsyncHttpx.get(url, params=params)).json()
if data.get("error"):
return False
return True
async def get_keyword_num(keyword: str) -> "int, int, int, int, int":
"""
查看图片相关 tag 数量
:param keyword: 关键词tag
"""
count, r18_count = await Pixiv.get_keyword_num(keyword.split())
count_, setu_count, r18_count_ = await OmegaPixivIllusts.get_keyword_num(
keyword.split()
)
return count, r18_count, count_, setu_count, r18_count_
async def remove_image(pid: int, img_p: str) -> bool:
"""
删除置顶图片
:param pid: pid
:param img_p: 图片 p 如 p0,p1 等
"""
if img_p:
if "p" not in img_p:
img_p = f"p{img_p}"
return await Pixiv.remove_image_data(pid, img_p)
def gen_keyword_pic(
_pass_keyword: List[str], not_pass_keyword: List[str], is_superuser: bool
):
"""
已通过或未通过的所有关键词/uid/pid
:param _pass_keyword: 通过列表
:param not_pass_keyword: 未通过列表
:param is_superuser: 是否超级用户
"""
_keyword = [
x
for x in _pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_uid = [x for x in _pass_keyword if x.startswith("uid:")]
_pid = [x for x in _pass_keyword if x.startswith("pid:")]
_n_keyword = [
x
for x in not_pass_keyword
if not x.startswith("uid:")
and not x.startswith("pid:")
and not x.startswith("black:")
]
_n_uid = [
x
for x in not_pass_keyword
if x.startswith("uid:") and not x.startswith("black:")
]
_n_pid = [
x
for x in not_pass_keyword
if x.startswith("pid:") and not x.startswith("black:")
]
img_width = 0
img_data = {
"_keyword": {"width": 0, "data": _keyword},
"_uid": {"width": 0, "data": _uid},
"_pid": {"width": 0, "data": _pid},
"_n_keyword": {"width": 0, "data": _n_keyword},
"_n_uid": {"width": 0, "data": _n_uid},
"_n_pid": {"width": 0, "data": _n_pid},
}
for x in list(img_data.keys()):
img_data[x]["width"] = math.ceil(len(img_data[x]["data"]) / 40)
img_width += img_data[x]["width"] * 200
if not is_superuser:
img_width = (
img_width
- (
img_data["_n_keyword"]["width"]
+ img_data["_n_uid"]["width"]
+ img_data["_n_pid"]["width"]
)
* 200
)
del img_data["_n_keyword"]
del img_data["_n_pid"]
del img_data["_n_uid"]
current_width = 0
A = BuildImage(img_width, 1100)
for x in list(img_data.keys()):
if img_data[x]["data"]:
img = BuildImage(img_data[x]["width"] * 200, 1100, 200, 1100, font_size=40)
start_index = 0
end_index = 40
total_index = img_data[x]["width"] * 40
for _ in range(img_data[x]["width"]):
tmp = BuildImage(198, 1100, font_size=20)
text_img = BuildImage(198, 100, font_size=50)
key_str = "\n".join(
[key for key in img_data[x]["data"][start_index:end_index]]
)
tmp.text((10, 100), key_str)
if x.find("_n") == -1:
text_img.text((24, 24), "已收录")
else:
text_img.text((24, 24), "待收录")
tmp.paste(text_img, (0, 0))
start_index += 40
end_index = (
end_index + 40 if end_index + 40 <= total_index else total_index
)
background_img = BuildImage(200, 1100, color="#FFE4C4")
background_img.paste(tmp, (1, 1))
img.paste(background_img)
A.paste(img, (current_width, 0))
current_width += img_data[x]["width"] * 200
return A.pic2bs4()
def _check_black(img_urls: List[str], black: List[str]) -> bool:
"""
检测pid是否在黑名单中
:param img_urls: 图片img列表
:param black: 黑名单
:return:
"""
for b in black:
for img_url in img_urls:
if b in img_url:
return False
return True | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/_data_source.py | _data_source.py |
from services.db_context import db
from typing import Set, List
class PixivKeywordUser(db.Model):
__tablename__ = "pixiv_keyword_users"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger(), nullable=False)
keyword = db.Column(db.String(), nullable=False)
is_pass = db.Column(db.Boolean(), default=False)
_idx1 = db.Index("pixiv_keyword_users_idx1", "keyword", unique=True)
@classmethod
async def add_keyword(
cls, user_qq: int, group_id: int, keyword: str, superusers: Set[str]
) -> bool:
"""
说明:
添加搜图的关键词
参数:
:param user_qq: qq号
:param group_id: 群号
:param keyword: 关键词
:param superusers: 是否为超级用户
"""
is_pass = True if str(user_qq) in superusers else False
if not await cls._check_keyword_exists(keyword):
await cls.create(
user_qq=user_qq, group_id=group_id, keyword=keyword, is_pass=is_pass
)
return True
return False
@classmethod
async def delete_keyword(cls, keyword: str) -> bool:
"""
说明:
删除关键词
参数:
:param keyword: 关键词
"""
if await cls._check_keyword_exists(keyword):
query = cls.query.where(cls.keyword == keyword).with_for_update()
query = await query.gino.first()
await query.delete()
return True
return False
@classmethod
async def set_keyword_pass(cls, keyword: str, is_pass: bool) -> "int, int":
"""
说明:
通过或禁用关键词
参数:
:param keyword: 关键词
:param is_pass: 通过状态
"""
if await cls._check_keyword_exists(keyword):
query = cls.query.where(cls.keyword == keyword).with_for_update()
query = await query.gino.first()
await query.update(
is_pass=is_pass,
).apply()
return query.user_qq, query.group_id
return 0, 0
@classmethod
async def get_all_user_dict(cls) -> dict:
"""
说明:
获取关键词数据库各个用户贡献的关键词字典
"""
tmp = {}
query = await cls.query.gino.all()
for user in query:
if not tmp.get(user.user_qq):
tmp[user.user_qq] = {"keyword": []}
tmp[user.user_qq]["keyword"].append(user.keyword)
return tmp
@classmethod
async def get_current_keyword(cls) -> "List[str], List[str]":
"""
说明:
获取当前通过与未通过的关键词
"""
pass_keyword = []
not_pass_keyword = []
query = await cls.query.gino.all()
for user in query:
if user.is_pass:
pass_keyword.append(user.keyword)
else:
not_pass_keyword.append(user.keyword)
return pass_keyword, not_pass_keyword
@classmethod
async def get_black_pid(cls) -> List[str]:
"""
说明:
获取黑名单PID
"""
black_pid = []
query = await cls.query.where(cls.user_qq == 114514).gino.all()
for image in query:
black_pid.append(image.keyword[6:])
return black_pid
@classmethod
async def _check_keyword_exists(cls, keyword: str) -> bool:
"""
说明:
检测关键词是否已存在
参数:
:param keyword: 关键词
"""
current_keyword = []
query = await cls.query.gino.all()
for user in query:
current_keyword.append(user.keyword)
if keyword in current_keyword:
return True
return False | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/_model/pixiv_keyword_user.py | pixiv_keyword_user.py |
from typing import Optional, List
from datetime import datetime
from services.db_context import db
class OmegaPixivIllusts(db.Model):
__tablename__ = "omega_pixiv_illusts"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
pid = db.Column(db.BigInteger(), nullable=False)
uid = db.Column(db.BigInteger(), nullable=False)
title = db.Column(db.String(), nullable=False)
uname = db.Column(db.String(), nullable=False)
nsfw_tag = db.Column(db.Integer(), nullable=False)
width = db.Column(db.Integer(), nullable=False)
height = db.Column(db.Integer(), nullable=False)
tags = db.Column(db.String(), nullable=False)
url = db.Column(db.String(), nullable=False)
created_at = db.Column(db.DateTime(timezone=True))
updated_at = db.Column(db.DateTime(timezone=True))
_idx1 = db.Index("omega_pixiv_illusts_idx1", "pid", "url", unique=True)
@classmethod
async def add_image_data(
cls,
pid: int,
title: str,
width: int,
height: int,
url: str,
uid: int,
uname: str,
nsfw_tag: int,
tags: str,
created_at: datetime,
updated_at: datetime,
):
"""
说明:
添加图片信息
参数:
:param pid: pid
:param title: 标题
:param width: 宽度
:param height: 长度
:param url: url链接
:param uid: 作者uid
:param uname: 作者名称
:param nsfw_tag: nsfw标签, 0=safe, 1=setu. 2=r18
:param tags: 相关tag
:param created_at: 创建日期
:param updated_at: 更新日期
"""
if not await cls.check_exists(pid):
await cls.create(
pid=pid,
title=title,
width=width,
height=height,
url=url,
uid=uid,
uname=uname,
nsfw_tag=nsfw_tag,
tags=tags,
)
return True
return False
@classmethod
async def query_images(
cls,
keywords: Optional[List[str]] = None,
uid: Optional[int] = None,
pid: Optional[int] = None,
nsfw_tag: Optional[int] = 0,
num: int = 100
) -> List[Optional["OmegaPixivIllusts"]]:
"""
说明:
查找符合条件的图片
参数:
:param keywords: 关键词
:param uid: 画师uid
:param pid: 图片pid
:param nsfw_tag: nsfw标签, 0=safe, 1=setu. 2=r18
:param num: 获取图片数量
"""
if nsfw_tag is not None:
query = cls.query.where(cls.nsfw_tag == nsfw_tag)
else:
query = cls.query
if keywords:
for keyword in keywords:
query = query.where(cls.tags.contains(keyword))
elif uid:
query = query.where(cls.uid == uid)
elif pid:
query = query.where(cls.uid == pid)
query = query.order_by(db.func.random()).limit(num)
return await query.gino.all()
@classmethod
async def check_exists(cls, pid: int) -> bool:
"""
说明:
检测pid是否已存在
参数:
:param pid: 图片PID
"""
query = await cls.query.where(cls.pid == pid).gino.all()
return bool(query)
@classmethod
async def get_keyword_num(cls, tags: List[str] = None) -> "int, int, int":
"""
说明:
获取相关关键词(keyword, tag)在图库中的数量
参数:
:param tags: 关键词/Tag
"""
setattr(OmegaPixivIllusts, 'count', db.func.count(cls.pid).label('count'))
query = cls.select('count')
if tags:
for tag in tags:
query = query.where(cls.tags.contains(tag))
count = await query.where(cls.nsfw_tag == 0).gino.first()
setu_count = await query.where(cls.nsfw_tag == 1).gino.first()
r18_count = await query.where(cls.nsfw_tag == 2).gino.first()
return count[0], setu_count[0], r18_count[0]
@classmethod
async def get_all_pid(cls) -> List[int]:
"""
说明:
获取所有图片PID
"""
data = await cls.select('pid').gino.all()
return [x[0] for x in data]
@classmethod
async def test(cls, nsfw_tag: int = 1):
if nsfw_tag is not None:
query = cls.query.where(cls.nsfw_tag == nsfw_tag)
else:
query = cls.query
query = query.where((cls.width - cls.height) < 50)
for x in await query.gino.all():
print(x.pid) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/_model/omega_pixiv_illusts.py | omega_pixiv_illusts.py |
from typing import Optional, List
from services.db_context import db
class Pixiv(db.Model):
__tablename__ = "pixiv"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
pid = db.Column(db.BigInteger(), nullable=False)
title = db.Column(db.String(), nullable=False)
width = db.Column(db.Integer(), nullable=False)
height = db.Column(db.Integer(), nullable=False)
view = db.Column(db.Integer(), nullable=False)
bookmarks = db.Column(db.Integer(), nullable=False)
img_url = db.Column(db.String(), nullable=False)
img_p = db.Column(db.String(), nullable=False)
uid = db.Column(db.BigInteger(), nullable=False)
author = db.Column(db.String(), nullable=False)
is_r18 = db.Column(db.Boolean(), nullable=False)
tags = db.Column(db.String(), nullable=False)
_idx1 = db.Index("pixiv_idx1", "pid", "img_url", unique=True)
@classmethod
async def add_image_data(
cls,
pid: int,
title: str,
width: int,
height: int,
view: int,
bookmarks: int,
img_url: str,
img_p: str,
uid: int,
author: str,
tags: str,
):
"""
说明:
添加图片信息
参数:
:param pid: pid
:param title: 标题
:param width: 宽度
:param height: 长度
:param view: 被查看次数
:param bookmarks: 收藏数
:param img_url: url链接
:param img_p: 张数
:param uid: 作者uid
:param author: 作者名称
:param tags: 相关tag
"""
if not await cls.check_exists(pid, img_p):
await cls.create(
pid=pid,
title=title,
width=width,
height=height,
view=view,
bookmarks=bookmarks,
img_url=img_url,
img_p=img_p,
uid=uid,
author=author,
is_r18=True if "R-18" in tags else False,
tags=tags,
)
return True
return False
@classmethod
async def remove_image_data(cls, pid: int, img_p: str) -> bool:
"""
说明:
删除图片数据
参数:
:param pid: 图片pid
:param img_p: 图片pid的张数,如:p0,p1
"""
try:
if img_p:
await cls.delete.where(
(cls.pid == pid) & (cls.img_p == img_p)
).gino.status()
else:
await cls.delete.where(cls.pid == pid).gino.status()
return True
except Exception:
return False
@classmethod
async def get_all_pid(cls) -> List[int]:
"""
说明:
获取所有PID
"""
query = await cls.query.select("pid").gino.first()
pid = [x[0] for x in query]
return list(set(pid))
# 0:非r18 1:r18 2:混合
@classmethod
async def query_images(
cls,
keywords: Optional[List[str]] = None,
uid: Optional[int] = None,
pid: Optional[int] = None,
r18: Optional[int] = 0,
num: int = 100
) -> List[Optional["Pixiv"]]:
"""
说明:
查找符合条件的图片
参数:
:param keywords: 关键词
:param uid: 画师uid
:param pid: 图片pid
:param r18: 是否r18,0:非r18 1:r18 2:混合
:param num: 查找图片的数量
"""
if r18 == 0:
query = cls.query.where(cls.is_r18 == False)
elif r18 == 1:
query = cls.query.where(cls.is_r18 == True)
else:
query = cls.query
if keywords:
for keyword in keywords:
query = query.where(cls.tags.contains(keyword))
elif uid:
query = query.where(cls.uid == uid)
elif pid:
query = query.where(cls.pid == pid)
query = query.order_by(db.func.random()).limit(num)
return await query.gino.all()
@classmethod
async def check_exists(cls, pid: int, img_p: str) -> bool:
"""
说明:
检测pid是否已存在
参数:
:param pid: 图片PID
:param img_p: 张数
"""
query = await cls.query.where(
(cls.pid == pid) & (cls.img_p == img_p)
).gino.all()
return bool(query)
@classmethod
async def get_keyword_num(cls, tags: List[str] = None) -> "int, int":
"""
说明:
获取相关关键词(keyword, tag)在图库中的数量
参数:
:param tags: 关键词/Tag
"""
setattr(Pixiv, 'count', db.func.count(cls.pid).label('count'))
query = cls.select('count')
if tags:
for tag in tags:
query = query.where(cls.tags.contains(tag))
count = await query.where(cls.is_r18 == False).gino.first()
r18_count = await query.where(cls.is_r18 == True).gino.first()
return count[0], r18_count[0] | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pix_gallery/_model/pixiv.py | pixiv.py |
from nonebot import on_message, on_regex
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from utils.utils import is_number, get_message_text
from services.log import logger
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
from utils.utils import FreqLimiter, cn2py
from configs.config import Config
from utils.manager import withdraw_message_manager
from .rule import rule
import random
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "本地图库"
__plugin_usage__ = f"""
usage:
发送指定图库下的随机或指定id图片genshin_memo
指令:
{Config.get_config("image_management", "IMAGE_DIR_LIST")} ?[id]
示例:美图
示例: 萝莉 2
""".strip()
__plugin_des__ = "让看看我的私藏,指[图片]"
__plugin_cmd__ = Config.get_config("image_management", "IMAGE_DIR_LIST")
__plugin_type__ = ("来点好康的",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["发送图片"] + Config.get_config("image_management", "IMAGE_DIR_LIST"),
}
__plugin_resources__ = {"pa": IMAGE_PATH}
Config.add_plugin_config(
"_task",
"DEFAULT_PA",
True,
help_="被动 爬 进群默认开关状态",
default_value=True,
)
_flmt = FreqLimiter(1)
send_img = on_message(priority=5, rule=rule, block=True)
pa_reg = on_regex("^(爬|丢人爬|爪巴)$", priority=5, block=True)
_path = IMAGE_PATH / "image_management"
@send_img.handle()
async def _(event: MessageEvent):
msg = get_message_text(event.json()).split()
gallery = msg[0]
if gallery not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
return
img_id = None
if len(msg) > 1:
img_id = msg[1]
path = _path / cn2py(gallery)
if gallery in Config.get_config(
"image_management", "IMAGE_DIR_LIST"
):
if not path.exists() and (path.parent.parent / cn2py(gallery)).exists():
path = IMAGE_PATH / cn2py(gallery)
else:
path.mkdir(parents=True, exist_ok=True)
length = len(os.listdir(path))
if length == 0:
logger.warning(f'图库 {cn2py(gallery)} 为空,调用取消!')
await send_img.finish("该图库中没有图片噢")
index = img_id if img_id else str(random.randint(0, length - 1))
if not is_number(index):
return
if int(index) > length - 1 or int(index) < 0:
await send_img.finish(f"超过当前上下限!({length - 1})")
result = image(path / f"{index}.jpg")
if result:
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) "
f"发送{cn2py(gallery)}:"
+ result
)
msg_id = await send_img.send(
f"id:{index}" + result
if Config.get_config("image_management", "SHOW_ID")
else "" + result
)
withdraw_message_manager.withdraw_message(
event,
msg_id,
Config.get_config("image_management", "WITHDRAW_IMAGE_MESSAGE"),
)
else:
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) "
f"发送 {cn2py(gallery)} 失败"
)
await send_img.finish(f"不想给你看Ov|")
@pa_reg.handle()
async def _(event: MessageEvent):
if _flmt.check(event.user_id):
_flmt.start_cd(event.user_id)
await pa_reg.finish(image(random.choice(os.listdir(IMAGE_PATH / "pa")), "pa")) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/image_management/send_image/__init__.py | __init__.py |
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from configs.config import Config
from utils.utils import get_message_img
from .data_source import upload_image_to_local
from nonebot.params import CommandArg, Arg, ArgStr
from typing import List
__zx_plugin_name__ = "上传图片 [Admin]"
__plugin_usage__ = """
usage:
上传图片至指定图库
指令:
查看图库
上传图片 [图库] [图片]
连续上传图片 [图库]
示例:上传图片 美图 [图片]
* 连续上传图片可以通过发送 “stop” 表示停止收集发送的图片,可以开始上传 *
""".strip()
__plugin_des__ = "指定图库图片上传"
__plugin_cmd__ = ["上传图片 [图库] [图片]", "连续上传图片 [图库]", "查看公开图库"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"admin_level": Config.get_config("image_management", "UPLOAD_IMAGE_LEVEL")
}
upload_img = on_command("上传图片", rule=to_me(), priority=5, block=True)
continuous_upload_img = on_command("连续上传图片", rule=to_me(), priority=5, block=True)
show_gallery = on_command("查看公开图库", priority=1, block=True)
@show_gallery.handle()
async def _():
x = "公开图库列表:\n"
for i, e in enumerate(Config.get_config("image_management", "IMAGE_DIR_LIST")):
x += f"\t{i+1}.{e}\n"
await show_gallery.send(x[:-1])
@upload_img.handle()
async def _(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
args = arg.extract_plain_text().strip()
img_list = get_message_img(event.json())
if args:
if args in Config.get_config("image_management", "IMAGE_DIR_LIST"):
state["path"] = args
if img_list:
state["img_list"] = arg
@upload_img.got(
"path",
prompt=f"请选择要上传的图库\n- "
+ "\n- ".join(Config.get_config("image_management", "IMAGE_DIR_LIST")),
)
@upload_img.got("img_list", prompt="图呢图呢图呢图呢!GKD!")
async def _(
bot: Bot,
event: MessageEvent,
state: T_State,
path: str = ArgStr("path"),
img_list: Message = Arg("img_list"),
):
if path not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
await upload_img.reject_arg("path", "此目录不正确,请重新输入目录!")
if not get_message_img(img_list):
await upload_img.reject_arg("img_list", "图呢图呢图呢图呢!GKD!")
img_list = get_message_img(img_list)
group_id = 0
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
await upload_img.send(
await upload_image_to_local(img_list, path, event.user_id, group_id)
)
@continuous_upload_img.handle()
async def _(event: MessageEvent, state: T_State):
path = get_message_img(event.json())
if path in Config.get_config("image_management", "IMAGE_DIR_LIST"):
state["path"] = path
state["img_list"] = []
@continuous_upload_img.got(
"path",
prompt=f"请选择要上传的图库\n- "
+ "\n- ".join(Config.get_config("image_management", "IMAGE_DIR_LIST")),
)
@continuous_upload_img.got("img", prompt="图呢图呢图呢图呢!GKD!【发送‘stop’为停止】")
async def _(
event: MessageEvent,
state: T_State,
img_list: List[str] = Arg("img_list"),
path: str = ArgStr("path"),
img: Message = Arg("img"),
):
if path not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
await upload_img.reject_arg("path", "此目录不正确,请重新输入目录!")
if not img.extract_plain_text() == "stop":
img = get_message_img(img)
if img:
for i in img:
img_list.append(i)
await upload_img.reject_arg("img", "图再来!!【发送‘stop’为停止】")
group_id = 0
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
await continuous_upload_img.send(
await upload_image_to_local(img_list, path, event.user_id, group_id)
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/image_management/upload_image/__init__.py | __init__.py |
from services.log import logger
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from configs.config import Config
from utils.utils import is_number, cn2py
from configs.path_config import IMAGE_PATH
from nonebot.params import CommandArg, ArgStr
import os
__zx_plugin_name__ = "移动图片 [Admin]"
__plugin_usage__ = """
usage:
图库间的图片移动操作
指令:
移动图片 [源图库] [目标图库] [id]
查看图库
示例:移动图片 萝莉 美图 234
""".strip()
__plugin_des__ = "图库间的图片移动操作"
__plugin_cmd__ = ["移动图片 [源图库] [目标图库] [id]", "查看公开图库"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"admin_level": Config.get_config("image_management", "MOVE_IMAGE_LEVEL")
}
move_img = on_command("移动图片", priority=5, rule=to_me(), block=True)
_path = IMAGE_PATH / "image_management"
@move_img.handle()
async def _(state: T_State, arg: Message = CommandArg()):
args = arg.extract_plain_text().strip().split()
if args:
if n := len(args):
if args[0] in Config.get_config("image_management", "IMAGE_DIR_LIST"):
state["source_path"] = args[0]
if n > 1:
if args[1] in Config.get_config("image_management", "IMAGE_DIR_LIST"):
state["destination_path"] = args[1]
if n > 2 and is_number(args[2]):
state["id"] = args[2]
@move_img.got("source_path", prompt="要从哪个图库移出?")
@move_img.got("destination_path", prompt="要移动到哪个图库?")
@move_img.got("id", prompt="要移动的图片id是?")
async def _(
event: MessageEvent,
source_path: str = ArgStr("source_path"),
destination_path: str = ArgStr("destination_path"),
img_id: str = ArgStr("id"),
):
if (
source_path in ["取消", "算了"]
or img_id in ["取消", "算了"]
or destination_path in ["取消", "算了"]
):
await move_img.finish("已取消操作...")
if source_path not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
await move_img.reject_arg("source_path", "移除目录不正确,请重新输入!")
if destination_path not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
await move_img.reject_arg("destination_path", "移入目录不正确,请重新输入!")
if not is_number(img_id):
await move_img.reject_arg("id", "id不正确!请重新输入数字...")
source_path = _path / cn2py(source_path)
destination_path = _path / cn2py(destination_path)
if not source_path.exists():
if (source_path.parent.parent / cn2py(source_path.name)).exists():
source_path = source_path.parent.parent / cn2py(source_path.name)
if not destination_path.exists():
if (destination_path.parent.parent / cn2py(destination_path.name)).exists():
source_path = destination_path.parent.parent / cn2py(destination_path.name)
source_path.mkdir(exist_ok=True, parents=True)
destination_path.mkdir(exist_ok=True, parents=True)
if not len(os.listdir(source_path)):
await move_img.finish(f"{source_path}图库中没有任何图片,移动失败。")
max_id = len(os.listdir(source_path)) - 1
des_max_id = len(os.listdir(destination_path))
if int(img_id) > max_id or int(img_id) < 0:
await move_img.finish(f"Id超过上下限,上限:{max_id}", at_sender=True)
try:
move_file = source_path / f"{img_id}.jpg"
move_file.rename(destination_path / f"{des_max_id}.jpg")
logger.info(
f"移动 {source_path}/{img_id}.jpg ---> {destination_path}/{des_max_id} 移动成功"
)
except Exception as e:
logger.warning(
f"移动 {source_path}/{img_id}.jpg ---> {destination_path}/{des_max_id} 移动失败 e:{e}"
)
await move_img.finish(f"移动图片id:{img_id} 失败了...", at_sender=True)
if max_id > 0:
try:
rep_file = source_path / f"{max_id}.jpg"
rep_file.rename(source_path / f"{img_id}.jpg")
logger.info(f"{source_path}/{max_id}.jpg 替换 {source_path}/{img_id}.jpg 成功")
except Exception as e:
logger.warning(
f"{source_path}/{max_id}.jpg 替换 {source_path}/{img_id}.jpg 失败 e:{e}"
)
await move_img.finish(f"替换图片id:{max_id} -> {img_id} 失败了...", at_sender=True)
logger.info(
f"USER {event.user_id} GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'} ->"
f" {source_path} --> {destination_path} (id:{img_id}) 移动图片成功"
)
await move_img.finish(f"移动图片 id:{img_id} --> id:{des_max_id}成功", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/image_management/move_image/__init__.py | __init__.py |
from configs.path_config import IMAGE_PATH, TEMP_PATH
from utils.message_builder import image
from services.log import logger
from nonebot import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from utils.utils import is_number, cn2py
from configs.config import Config
from nonebot.params import CommandArg, Arg
import os
__zx_plugin_name__ = "删除图片 [Admin]"
__plugin_usage__ = """
usage:
删除图库指定图片
指令:
删除图片 [图库] [id]
查看图库
示例:删除图片 美图 666
""".strip()
__plugin_des__ = "不好看的图片删掉删掉!"
__plugin_cmd__ = ["删除图片 [图库] [id]", "查看公开图库"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"admin_level": Config.get_config("image_management", "DELETE_IMAGE_LEVEL")
}
delete_img = on_command("删除图片", priority=5, rule=to_me(), block=True)
_path = IMAGE_PATH / "image_management"
@delete_img.handle()
async def _(state: T_State, arg: Message = CommandArg()):
args = arg.extract_plain_text().strip().split()
if args:
if args[0] in Config.get_config("image_management", "IMAGE_DIR_LIST"):
state["path"] = args[0]
if len(args) > 1 and is_number(args[1]):
state["id"] = args[1]
@delete_img.got("path", prompt="请输入要删除的目标图库?")
@delete_img.got("id", prompt="请输入要删除的图片id?")
async def arg_handle(
event: MessageEvent,
state: T_State,
path: str = Arg("path"),
img_id: str = Arg("id"),
):
if path in ["取消", "算了"] or img_id in ["取消", "算了"]:
await delete_img.finish("已取消操作...")
if path not in Config.get_config("image_management", "IMAGE_DIR_LIST"):
await delete_img.reject_arg("path", "此目录不正确,请重新输入目录!")
if not is_number(img_id):
await delete_img.reject_arg("id", "id不正确!请重新输入数字...")
path = _path / cn2py(path)
if not path.exists() and (path.parent.parent / cn2py(state["path"])).exists():
path = path.parent.parent / cn2py(state["path"])
max_id = len(os.listdir(path)) - 1
if int(img_id) > max_id or int(img_id) < 0:
await delete_img.finish(f"Id超过上下限,上限:{max_id}", at_sender=True)
try:
if (TEMP_PATH / "delete.jpg").exists():
(TEMP_PATH / "delete.jpg").unlink()
logger.info(f"删除{cn2py(state['path'])}图片 {img_id}.jpg 成功")
except Exception as e:
logger.warning(f"删除图片 delete.jpg 失败 e{e}")
try:
os.rename(path / f"{img_id}.jpg", TEMP_PATH / f"{event.user_id}_delete.jpg")
logger.info(f"移动 {path}/{img_id}.jpg 移动成功")
except Exception as e:
logger.warning(f"{path}/{img_id}.jpg --> 移动失败 e:{e}")
if not os.path.exists(path / f"{img_id}.jpg"):
try:
if int(img_id) != max_id:
os.rename(path / f"{max_id}.jpg", path / f"{img_id}.jpg")
except FileExistsError as e:
logger.error(f"{path}/{max_id}.jpg 替换 {path}/{img_id}.jpg 失败 e:{e}")
logger.info(f"{path}/{max_id}.jpg 替换 {path}/{img_id}.jpg 成功")
logger.info(
f"USER {event.user_id} GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}"
f" -> id: {img_id} 删除成功"
)
await delete_img.finish(
f"id: {img_id} 删除成功" + image(TEMP_PATH / f"{event.user_id}_delete.jpg",), at_sender=True
)
await delete_img.finish(f"id: {img_id} 删除失败!") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/image_management/delete_image/__init__.py | __init__.py |
from nonebot import on_command
from .data_source import get_bt_info
from services.log import logger
from nonebot.adapters.onebot.v11 import PrivateMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import PRIVATE
from asyncio.exceptions import TimeoutError
from utils.utils import is_number
from nonebot.params import CommandArg, ArgStr
from nonebot.typing import T_State
__zx_plugin_name__ = "磁力搜索"
__plugin_usage__ = """
usage:
* 请各位使用后不要转发 *
* 拒绝反冲斗士! *
指令:
bt [关键词] ?[页数]
示例:bt 钢铁侠
示例:bt 钢铁侠 3
""".strip()
__plugin_des__ = "bt(磁力搜索)[仅支持私聊,懂的都懂]"
__plugin_cmd__ = ["bt [关键词] ?[页数]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["bt", "磁力搜索", "Bt", "BT"],
}
__plugin_block_limit__ = {"rst": "您有bt任务正在进行,请等待结束."}
__plugin_configs__ = {
"BT_MAX_NUM": {
"value": 10,
"help": "单次BT搜索返回最大消息数量",
"default_value": 10,
}
}
bt = on_command("bt", permission=PRIVATE, priority=5, block=True)
@bt.handle()
async def _(state: T_State, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip().split()
if msg:
keyword = None
page = 1
if n := len(msg):
keyword = msg[0]
if n > 1 and is_number(msg[1]) and int(msg[1]) > 0:
page = int(msg[1])
state["keyword"] = keyword
state["page"] = page
else:
state["page"] = 1
@bt.got("keyword", prompt="请输入要查询的内容!")
async def _(
event: PrivateMessageEvent,
state: T_State,
keyword: str = ArgStr("keyword"),
page: str = ArgStr("page"),
):
send_flag = False
try:
async for title, type_, create_time, file_size, link in get_bt_info(
keyword, page
):
await bt.send(
f"标题:{title}\n"
f"类型:{type_}\n"
f"创建时间:{create_time}\n"
f"文件大小:{file_size}\n"
f"种子:{link}"
)
send_flag = True
except TimeoutError:
await bt.finish(f"搜索 {keyword} 超时...")
except Exception as e:
await bt.finish(f"bt 其他未知错误..")
logger.error(f"bt 错误 {type(e)}:{e}")
if not send_flag:
await bt.send(f"{keyword} 未搜索到...")
logger.info(f"USER {event.user_id} BT搜索 {keyword} 第 {page} 页") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/bt/__init__.py | __init__.py |
from models.bag_user import BagUser
from utils.utils import is_number, get_user_avatar
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
from .model import RedbagUser
import random
import os
from io import BytesIO
import asyncio
# 检查金币数量合法性,并添加记录数据
async def check_gold(user_id: int, group_id: int, amount: str):
if is_number(amount):
amount = int(amount)
user_gold = await BagUser.get_gold(user_id, group_id)
if amount < 1:
return False, '小气鬼,要别人倒贴金币给你嘛!'
if user_gold < amount:
return False, '没有金币的话请不要发红包...'
await BagUser.spend_gold(user_id, group_id, amount)
await RedbagUser.add_redbag_data(user_id, group_id, 'send', amount)
return True, amount
else:
return False, '给我好好的输入红包里金币的数量啊喂!'
# 金币退回
async def return_gold(user_id: int, group_id: int, amount: int):
await BagUser.add_gold(user_id, group_id, amount)
# 开红包
async def open_redbag(user_id: int, group_id: int, redbag_data: dict):
amount = random.choice(redbag_data[group_id]['redbag'])
redbag_data[group_id]['redbag'].remove(amount)
redbag_data[group_id]['open_user'].append(user_id)
redbag_data[group_id]['open_amount'] += amount
await RedbagUser.add_redbag_data(user_id, group_id, 'get', amount)
await BagUser.add_gold(user_id, group_id, amount)
return amount, redbag_data
# 随机红包图片
async def generate_send_redbag_pic(user_id: int, msg: str = '恭喜发财 大吉大利'):
random_redbag = random.choice(os.listdir(f"{IMAGE_PATH}/prts/redbag_2"))
redbag = BuildImage(0, 0, font_size=38, background=f'{IMAGE_PATH}/prts/redbag_2/{random_redbag}')
ava = BuildImage(65, 65, background=BytesIO(await get_user_avatar(user_id)))
await asyncio.get_event_loop().run_in_executor(None, ava.circle)
redbag.text((int((redbag.size[0] - redbag.getsize(msg)[0]) / 2), 210), msg, (240, 218, 164))
redbag.paste(ava, (int((redbag.size[0] - ava.size[0])/2), 130), True)
return redbag.pic2bs4()
# 开红包图片
async def generate_open_redbag_pic(user_id: int, send_user_nickname: str, amount: int, text: str):
return await asyncio.create_task(_generate_open_redbag_pic(user_id, send_user_nickname, amount, text))
# 开红包图片
async def _generate_open_redbag_pic(user_id: int, send_user_nickname: str, amount: int, text: str):
send_user_nickname += '的红包'
amount = str(amount)
head = BuildImage(1000, 980, font_size=30, background=f'{IMAGE_PATH}/prts/redbag_12.png')
size = BuildImage(0, 0, font_size=50).getsize(send_user_nickname)
# QQ头像
ava_bk = BuildImage(100 + size[0], 66, color='white', font_size=50)
ava = BuildImage(66, 66, background=BytesIO(await get_user_avatar(user_id)))
ava_bk.paste(ava)
ava_bk.text((100, 7), send_user_nickname)
# ava_bk.show()
ava_bk_w, ava_bk_h = ava_bk.size
head.paste(ava_bk, (int((1000 - ava_bk_w) / 2), 300))
# 金额
size = BuildImage(0, 0, font_size=150).getsize(amount)
price = BuildImage(size[0], size[1], font_size=150)
price.text((0, 0), amount, fill=(209, 171, 108))
# 金币中文
head.paste(price, (int((1000 - size[0]) / 2) - 50, 460))
head.text((int((1000 - size[0]) / 2 + size[0]) - 50, 500 + size[1] - 70), '金币', fill=(209, 171, 108))
# 剩余数量和金额
head.text((350, 900), text, (198, 198, 198))
return head.pic2bs4() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/gold_redbag/data_source.py | data_source.py |
from services.db_context import db
from typing import List
class RedbagUser(db.Model):
__tablename__ = "redbag_users"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger(), nullable=False)
send_redbag_count = db.Column(db.Integer(), default=0)
get_redbag_count = db.Column(db.Integer(), default=0)
spend_gold = db.Column(db.Integer(), default=0)
get_gold = db.Column(db.Integer(), default=0)
_idx1 = db.Index("redbag_group_users_idx1", "user_qq", "group_id", unique=True)
@classmethod
async def add_redbag_data(cls, user_qq: int, group_id: int, itype: str, money: int):
"""
说明:
添加收发红包数据
参数:
:param user_qq: qq号
:param group_id: 群号
:param itype: 收或发
:param money: 金钱数量
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
user = await query.with_for_update().gino.first() or await cls.create(
user_qq=user_qq,
group_id=group_id,
)
if itype == "get":
await user.update(
get_redbag_count=user.get_redbag_count + 1,
get_gold=user.get_gold + money,
).apply()
else:
await user.update(
send_redbag_count=user.send_redbag_count + 1,
spend_gold=user.spend_gold + money,
).apply()
@classmethod
async def ensure(cls, user_qq: int, group_id: int) -> bool:
"""
说明:
获取用户对象
参数:
:param user_qq: qq号
:param group_id: 群号
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.group_id == group_id))
user = await query.gino.first() or await cls.create(
user_qq=user_qq,
group_id=group_id,
)
return user
@classmethod
async def get_user_all(cls, group_id: int = None) -> List["RedbagUser"]:
"""
说明:
获取所有用户对象
参数:
:param group_id: 群号
"""
if not group_id:
query = await cls.query.gino.all()
else:
query = await cls.query.where((cls.group_id == group_id)).gino.all()
return query | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/gold_redbag/model.py | model.py |
from nonebot import on_command, on_notice
from nonebot.adapters.onebot.v11 import (
Bot,
GroupMessageEvent,
PokeNotifyEvent,
Message
)
from .data_source import (
check_gold,
generate_send_redbag_pic,
open_redbag,
generate_open_redbag_pic,
return_gold,
)
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.message import run_preprocessor, IgnoredException
from nonebot.matcher import Matcher
from utils.utils import is_number, scheduler
from utils.message_builder import image
from services.log import logger
from configs.path_config import IMAGE_PATH
from nonebot.permission import SUPERUSER
from nonebot.rule import to_me
from datetime import datetime, timedelta
from configs.config import NICKNAME
from apscheduler.jobstores.base import JobLookupError
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.params import CommandArg
import random
import time
__zx_plugin_name__ = "金币红包"
__plugin_usage__ = """
usage:
在群内发送指定金额的红包,拼手气项目
指令:
塞红包 [金币数] ?[红包数=5]: 塞入红包
开/抢/*戳一戳*: 打开红包
退回: 退回未开完的红包,必须在一分钟后使用
示例:塞红包 1000
示例:塞红包 1000 10
""".strip()
__plugin_superuser_usage__ = """
usage:
节日全群红包指令
指令:
节日红包 [金额] [数量] ?[祝福语] ?[指定群]
""".strip()
__plugin_des__ = "运气项目又来了"
__plugin_cmd__ = [
"塞红包 [金币数] ?[红包数=5]",
"开/抢",
"退回",
"节日红包 [金额] [数量] ?[祝福语] ?[指定群] [_superuser]",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["金币红包", "塞红包"],
}
__plugin_resources__ = {"prts": IMAGE_PATH}
gold_redbag = on_command(
"塞红包", aliases={"金币红包"}, priority=5, block=True, permission=GROUP
)
open_ = on_command("开", aliases={"抢"}, priority=5, block=True, permission=GROUP)
poke_ = on_notice(priority=6, block=False)
return_ = on_command("退回", aliases={"退还"}, priority=5, block=True, permission=GROUP)
festive_redbag = on_command(
"节日红包", priority=5, block=True, permission=SUPERUSER, rule=to_me()
)
redbag_data = {}
festive_redbag_data = {}
# 阻断其他poke
@run_preprocessor
async def _(matcher: Matcher, event: PokeNotifyEvent):
try:
if matcher.type == "notice" and event.self_id == event.target_id:
flag1 = True
flag2 = True
try:
if festive_redbag_data[event.group_id]["user_id"]:
if (
event.user_id
in festive_redbag_data[event.group_id]["open_user"]
):
flag1 = False
except KeyError:
flag1 = False
try:
if redbag_data[event.group_id]["user_id"]:
if event.user_id in redbag_data[event.group_id]["open_user"]:
flag2 = False
except KeyError:
flag2 = False
if flag1 or flag2:
if matcher.plugin_name == "poke":
raise IgnoredException("目前正在抢红包...")
else:
if matcher.plugin_name == "gold_redbag":
raise IgnoredException("目前没有红包...")
except AttributeError:
pass
@gold_redbag.handle()
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
global redbag_data, festive_redbag_data
try:
if time.time() - redbag_data[event.group_id]["time"] > 60:
amount = (
redbag_data[event.group_id]["amount"]
- redbag_data[event.group_id]["open_amount"]
)
await return_gold(event.user_id, event.group_id, amount)
await gold_redbag.send(
f'{redbag_data[event.group_id]["nickname"]}的红包过时未开完,退还{amount}金币...'
)
redbag_data[event.group_id] = {}
else:
await gold_redbag.finish(
f'目前 {redbag_data[event.group_id]["nickname"]} 的红包还没有开完噢,'
f'还剩下 {len(redbag_data[event.group_id]["redbag"])} 个红包!'
f'(或等待{str(60 - time.time() + redbag_data[event.group_id]["time"])[:2]}秒红包过时)'
)
except KeyError:
pass
msg = arg.extract_plain_text().strip()
msg = msg.split()
if len(msg) == 1:
flag, amount = await check_gold(event.user_id, event.group_id, msg[0])
if not flag:
await gold_redbag.finish(amount)
num = 5
else:
amount = msg[0]
num = msg[1]
if not is_number(num) or int(num) < 1:
await gold_redbag.finish("红包个数给我输正确啊!", at_sender=True)
flag, amount = await check_gold(event.user_id, event.group_id, amount)
if not flag:
await gold_redbag.finish(amount, at_sender=True)
group_member_num = (await bot.get_group_info(group_id=event.group_id))[
"member_count"
]
num = int(num)
if num > group_member_num:
await gold_redbag.send("你发的红包数量也太多了,已经为你修改成与本群人数相同的红包数量...")
num = group_member_num
nickname = event.sender.card or event.sender.nickname
flag, result = init_redbag(
event.user_id, event.group_id, nickname, amount, num, int(bot.self_id)
)
if not flag:
await gold_redbag.finish(result, at_sender=True)
else:
await gold_redbag.send(
f"{nickname}发起了金币红包\n金额:{amount}\n数量:{num}\n"
+ image(
b64=await generate_send_redbag_pic(
redbag_data[event.group_id]["user_id"]
)
)
)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 塞入 {num} 个红包,共 {amount} 金币"
)
@open_.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
global redbag_data, festive_redbag_data
msg = arg.extract_plain_text().strip()
msg = (
msg.replace("!", "")
.replace("!", "")
.replace(",", "")
.replace(",", "")
.replace(".", "")
.replace("。", "")
)
if msg:
if "红包" not in msg:
return
flag1 = True
flag2 = True
open_flag1 = True
open_flag2 = True
try:
if festive_redbag_data[event.group_id]["user_id"]:
if event.user_id in festive_redbag_data[event.group_id]["open_user"]:
open_flag1 = False
except KeyError:
open_flag1 = False
flag1 = False
try:
if redbag_data[event.group_id]["user_id"]:
if event.user_id in redbag_data[event.group_id]["open_user"]:
open_flag2 = False
except KeyError:
flag2 = False
if not flag1 and not flag2:
await open_.finish("目前没有红包可以开...", at_sender=True)
if open_flag1 or open_flag2:
try:
await open_.send(
image(b64=await get_redbag_img(event.user_id, event.group_id)),
at_sender=True,
)
except KeyError:
await open_.finish("真贪心,明明已经开过这个红包了的说...", at_sender=True)
else:
await open_.finish("真贪心,明明已经开过这个红包了的说...", at_sender=True)
@poke_.handle()
async def _poke_(event: PokeNotifyEvent):
global redbag_data, festive_redbag_data
if event.self_id == event.target_id:
flag1 = True
flag2 = True
try:
if event.user_id in festive_redbag_data[event.group_id]["open_user"]:
flag1 = False
except KeyError:
flag1 = False
try:
if event.user_id in redbag_data[event.group_id]["open_user"]:
flag2 = False
except KeyError:
flag2 = False
if not flag1 and not flag2:
return
await poke_.send(
image(b64=await get_redbag_img(event.user_id, event.group_id)),
at_sender=True,
)
@return_.handle()
async def _(event: GroupMessageEvent):
global redbag_data
try:
if redbag_data[event.group_id]["user_id"] != event.user_id:
await return_.finish("不是你的红包你退回什么!", at_sender=True)
if time.time() - redbag_data[event.group_id]["time"] <= 60:
await return_.finish(
f'你的红包还没有过时,在 {str(60 - time.time() + redbag_data[event.group_id]["time"])[:2]} '
f"秒后可以退回..",
at_sender=True,
)
await return_gold(
event.user_id,
event.group_id,
redbag_data[event.group_id]["amount"]
- redbag_data[event.group_id]["open_amount"],
)
await return_.send(
f"已成功退还了 "
f"{redbag_data[event.group_id]['amount'] - redbag_data[event.group_id]['open_amount']} "
f"金币",
at_sender=True,
)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 退回了"
f"红包 {redbag_data[event.group_id]['amount'] - redbag_data[event.group_id]['open_amount']} 金币"
)
redbag_data[event.group_id] = {}
except KeyError:
await return_.finish("目前没有红包可以退回...", at_sender=True)
@festive_redbag.handle()
async def _(bot: Bot, arg: Message = CommandArg()):
global redbag_data
msg = arg.extract_plain_text().strip()
if msg:
msg = msg.split()
amount = 0
num = 0
greetings = "恭喜发财 大吉大利"
gl = []
if (lens := len(msg)) < 2:
await festive_redbag.finish("参数不足,格式:节日红包 [金额] [数量] [祝福语](可省) [指定群](可省)")
if lens > 1:
if not is_number(msg[0]):
await festive_redbag.finish("金额必须要是数字!", at_sender=True)
amount = int(msg[0])
if not is_number(msg[1]):
await festive_redbag.finish("数量必须要是数字!", at_sender=True)
num = int(msg[1])
if lens > 2:
greetings = msg[2]
if lens > 3:
for i in range(3, lens):
if not is_number(msg[i]):
await festive_redbag.finish("指定的群号必须要是数字啊!", at_sender=True)
gl.append(int(msg[i]))
if not gl:
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
for g in gl:
try:
scheduler.remove_job(f"festive_redbag_{g}")
await end_festive_redbag(bot, g)
except JobLookupError:
pass
init_redbag(
int(bot.self_id), g, f"{NICKNAME}", amount, num, int(bot.self_id), 1
)
scheduler.add_job(
end_festive_redbag,
"date",
run_date=(datetime.now() + timedelta(hours=24)).replace(microsecond=0),
id=f"festive_redbag_{g}",
args=[bot, g],
)
try:
await bot.send_group_msg(
group_id=g,
message=f"{NICKNAME}发起了金币红包\n金额:{amount}\n数量:{num}\n"
+ image(
b64=await generate_send_redbag_pic(int(bot.self_id), greetings)
),
)
except ActionFailed:
logger.warning(f"节日红包 GROUP {g} 发送失败..")
pass
# 红包数据初始化
def init_redbag(
user_id: int,
group_id: int,
nickname: str,
amount: int,
num: int,
bot_self_id: int,
mode: int = 0,
):
global redbag_data, festive_redbag_data
data = redbag_data if mode == 0 else festive_redbag_data
if not data.get(group_id):
data[group_id] = {}
try:
if data[group_id]["user_id"] and user_id != bot_self_id:
return False, f'{data[group_id]["nickname"]}的红包还没抢完呢...'
except KeyError:
pass
data[group_id]["user_id"] = user_id
data[group_id]["nickname"] = nickname
data[group_id]["amount"] = amount
data[group_id]["num"] = num
data[group_id]["open_amount"] = 0
data[group_id]["time"] = time.time()
data[group_id]["redbag"] = random_redbag(amount, num)
data[group_id]["open_user"] = []
if mode == 0:
redbag_data = data
else:
festive_redbag_data = data
return True, ""
# 随机红包排列
def random_redbag(amount: int, num: int) -> list:
redbag_lst = []
for _ in range(num - 1):
tmp = int(amount / random.choice(range(3, num + 3)))
redbag_lst.append(tmp)
amount -= tmp
redbag_lst.append(amount)
return redbag_lst
# 返回开红包图片
async def get_redbag_img(user_id: int, group_id: int):
global redbag_data, festive_redbag_data
data = redbag_data
mode = 0
if festive_redbag_data.get(group_id):
try:
if user_id not in festive_redbag_data[group_id]["open_user"]:
data = festive_redbag_data
mode = 1
except KeyError:
pass
amount, data = await open_redbag(user_id, group_id, data)
text = (
f"已领取"
f'{data[group_id]["num"] - len(data[group_id]["redbag"])}'
f'/{data[group_id]["num"]}个,'
f'共{data[group_id]["open_amount"]}/{data[group_id]["amount"]}金币'
)
logger.info(
f"USER {user_id} GROUP {group_id} 抢到了 {data[group_id]['user_id']} 的红包,获取了{amount}金币"
)
b64 = await generate_open_redbag_pic(
data[group_id]["user_id"], data[group_id]["nickname"], amount, text
)
if data[group_id]["open_amount"] == data[group_id]["amount"]:
data[group_id] = {}
if mode == 0:
redbag_data = data
else:
festive_redbag_data = data
return b64
async def end_festive_redbag(bot: Bot, group_id: int):
global festive_redbag_data
message = (
f"{NICKNAME}的节日红包过时了,一共开启了 "
f"{festive_redbag_data[group_id]['num'] - len(festive_redbag_data[group_id]['redbag'])}"
f" 个红包,共 {festive_redbag_data[group_id]['open_amount']} 金币"
)
await bot.send_group_msg(group_id=group_id, message=message)
festive_redbag_data[group_id] = {} | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/gold_redbag/__init__.py | __init__.py |
from nonebot.adapters.onebot.v11 import Bot, Message
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from utils.http_utils import AsyncHttpx
from typing import List
from services.log import logger
from pathlib import Path
import ujson as json
import nonebot
import asyncio
import platform
import tarfile
import shutil
import os
if str(platform.system()).lower() == "windows":
policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(policy)
driver = nonebot.get_driver()
release_url = "https://api.github.com/repos/HibiKier/zhenxun_bot/releases/latest"
_version_file = Path() / "__version__"
zhenxun_latest_tar_gz = Path() / "zhenxun_latest_file.tar.gz"
temp_dir = Path() / "temp"
backup_dir = Path() / "backup"
@driver.on_bot_connect
async def remind(bot: Bot):
if str(platform.system()).lower() != "windows":
restart = Path() / "restart.sh"
if not restart.exists():
with open(restart, "w", encoding="utf8") as f:
f.write(
f"pid=$(netstat -tunlp | grep "
+ str(bot.config.port)
+ " | awk '{print $7}')\n"
"pid=${pid%/*}\n"
"kill -9 $pid\n"
"sleep 3\n"
"python3 bot.py"
)
os.system("chmod +x ./restart.sh")
logger.info("已自动生成 restart.sh(重启) 文件,请检查脚本是否与本地指令符合...")
is_restart_file = Path() / "is_restart"
if is_restart_file.exists():
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"真寻重启完毕...",
)
is_restart_file.unlink()
async def check_update(bot: Bot) -> 'int, str':
logger.info("开始检查更新真寻酱....")
_version = "v0.0.0"
if _version_file.exists():
_version = (
open(_version_file, "r", encoding="utf8").readline().split(":")[-1].strip()
)
data = await get_latest_version_data()
if data:
latest_version = data["name"]
if _version != latest_version:
tar_gz_url = data["tarball_url"]
logger.info(f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"检测真寻已更新,当前版本:{_version},最新版本:{latest_version}\n" f"开始更新.....",
)
logger.info(f"开始下载真寻最新版文件....")
if await AsyncHttpx.download_file(tar_gz_url, zhenxun_latest_tar_gz):
logger.info("下载真寻最新版文件完成....")
error = await asyncio.get_event_loop().run_in_executor(
None, _file_handle, latest_version
)
if error:
return 998, error
logger.info("真寻更新完毕,清理文件完成....")
logger.info("开始获取真寻更新日志.....")
update_info = data["body"]
width = 0
height = len(update_info.split('\n')) * 24
A = BuildImage(width, height, font_size=20)
for m in update_info.split('\n'):
w, h = A.getsize(m)
if w > width:
width = w
A = BuildImage(width + 50, height, font_size=20)
A.text((10, 10), update_info)
A.save(f'{IMAGE_PATH}/update_info.png')
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=Message(f"真寻更新完成,版本:{_version} -> {latest_version}\n"
f"更新日期:{data['created_at']}\n"
f"更新日志:\n"
f"{image('update_info.png')}"),
)
return 200, ''
else:
logger.warning(f"下载真寻最新版本失败...版本号:{latest_version}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"下载真寻最新版本失败...版本号:{latest_version}.",
)
else:
logger.info(f"自动获取真寻版本成功:{latest_version},当前版本为最新版,无需更新...")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"自动获取真寻版本成功:{latest_version},当前版本为最新版,无需更新...",
)
else:
logger.warning("自动获取真寻版本失败....")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=f"自动获取真寻版本失败...."
)
return 999, ''
def _file_handle(latest_version: str) -> str:
if not temp_dir.exists():
temp_dir.mkdir(exist_ok=True, parents=True)
if backup_dir.exists():
shutil.rmtree(backup_dir)
tf = None
error = ''
# try:
backup_dir.mkdir(exist_ok=True, parents=True)
logger.info("开始解压真寻文件压缩包....")
tf = tarfile.open(zhenxun_latest_tar_gz)
tf.extractall(temp_dir)
logger.info("解压真寻文件压缩包完成....")
zhenxun_latest_file = Path(temp_dir) / os.listdir(temp_dir)[0]
update_info_file = Path(zhenxun_latest_file) / "update_info.json"
update_info = json.load(open(update_info_file, "r", encoding="utf8"))
update_file = update_info["update_file"]
add_file = update_info["add_file"]
delete_file = update_info["delete_file"]
config_file = Path() / "configs" / "config.py"
config_path_file = Path() / "configs" / "path_config.py"
for file in [config_file.name]:
tmp = ""
new_file = Path(zhenxun_latest_file) / "configs" / file
old_file = Path() / "configs" / file
new_lines = open(new_file, "r", encoding="utf8").readlines()
old_lines = open(old_file, "r", encoding="utf8").readlines()
for nl in new_lines:
tmp += check_old_lines(old_lines, nl)
with open(old_file, "w", encoding="utf8") as f:
f.write(tmp)
for file in delete_file + update_file:
if file != "configs":
file = Path() / file
backup_file = Path(backup_dir) / file
if file.exists():
backup_file.parent.mkdir(parents=True, exist_ok=True)
if backup_file.exists():
backup_file.unlink()
if file not in [config_file, config_path_file]:
os.rename(file.absolute(), backup_file.absolute())
else:
with open(file, "r", encoding="utf8") as rf:
data = rf.read()
with open(backup_file, "w", encoding="utf8") as wf:
wf.write(data)
logger.info(f"已备份文件:{file}")
for file in add_file + update_file:
new_file = Path(zhenxun_latest_file) / file
old_file = Path() / file
if old_file not in [config_file, config_path_file] and file != "configs":
if not old_file.exists() and new_file.exists():
os.rename(new_file.absolute(), old_file.absolute())
logger.info(f"已更新文件:{file}")
# except Exception as e:
# error = f'{type(e)}:{e}'
if tf:
tf.close()
if temp_dir.exists():
shutil.rmtree(temp_dir)
if zhenxun_latest_tar_gz.exists():
zhenxun_latest_tar_gz.unlink()
local_update_info_file = Path() / "update_info.json"
if local_update_info_file.exists():
local_update_info_file.unlink()
with open(_version_file, "w", encoding="utf8") as f:
f.write(f"__version__: {latest_version}")
return error
# 获取最新版本号
async def get_latest_version_data() -> dict:
for _ in range(3):
try:
res = await AsyncHttpx.get(release_url)
if res.status_code == 200:
return res.json()
except TimeoutError:
pass
except Exception as e:
logger.error(f"检查更新真寻获取版本失败 {type(e)}:{e}")
return {}
# 逐行检测
def check_old_lines(lines: List[str], line: str) -> str:
if "=" not in line:
return line
for l in lines:
if "=" in l and l.split("=")[0].strip() == line.split("=")[0].strip():
return l
return line | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/check_zhenxun_update/data_source.py | data_source.py |
from nonebot.adapters.onebot.v11 import Bot
from nonebot.permission import SUPERUSER
from nonebot import on_command
from .data_source import check_update, get_latest_version_data
from services.log import logger
from utils.utils import scheduler, get_bot
from pathlib import Path
from configs.config import Config
from nonebot.rule import to_me
from nonebot.params import ArgStr
import platform
import os
__zx_plugin_name__ = "自动更新 [Superuser]"
__plugin_usage__ = """
usage:
检查更新真寻最新版本,包括了自动更新
指令:
检查更新真寻
重启
""".strip()
__plugin_des__ = "就算是真寻也会成长的"
__plugin_cmd__ = ["检查更新真寻", "重启"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_configs__ = {
"AUTO_UPDATE_ZHENXUN": {
"value": False,
"help": "真寻是否自动检查更新",
"default": False,
}
}
update_zhenxun = on_command("检查更新真寻", permission=SUPERUSER, priority=1, block=True)
restart = on_command(
"重启",
aliases={"restart"},
permission=SUPERUSER,
rule=to_me(),
priority=1,
block=True,
)
@update_zhenxun.handle()
async def _(bot: Bot):
try:
code, error = await check_update(bot)
if error:
logger.error(f"更新真寻未知错误 {error}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=f"更新真寻未知错误 {error}"
)
except Exception as e:
logger.error(f"更新真寻未知错误 {type(e)}:{e}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"更新真寻未知错误 {type(e)}:{e}",
)
else:
if code == 200:
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=f"更新完毕,请重启真寻...."
)
@restart.handle()
async def _():
if str(platform.system()).lower() == "windows":
await restart.finish("暂无windows重启脚本...")
@restart.got("flag", prompt="确定是否重启真寻?(重启失败咱们将失去联系,请谨慎!)")
async def _(flag: str = ArgStr("flag")):
if flag.lower() in ["true", "是", "好", "确定", "确定是"]:
await restart.send("开始重启真寻..请稍等...")
open("is_restart", "w")
os.system("./restart.sh")
else:
await restart.send("已取消操作...")
@scheduler.scheduled_job(
"cron",
hour=12,
minute=0,
)
async def _():
if Config.get_config("check_zhenxun_update", "AUTO_UPDATE_ZHENXUN"):
_version = "v0.0.0"
_version_file = Path() / "__version__"
if _version_file.exists():
_version = (
open(_version_file, "r", encoding="utf8")
.readline()
.split(":")[-1]
.strip()
)
data = await get_latest_version_data()
if data:
latest_version = data["name"]
if _version != latest_version:
bot = get_bot()
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"检测到真寻版本更新\n"
f"当前版本:{_version},最新版本:{latest_version}",
)
# try:
# code = await check_update(bot)
# except Exception as e:
# logger.error(f"更新真寻未知错误 {type(e)}:{e}")
# await bot.send_private_msg(
# user_id=int(list(bot.config.superusers)[0]),
# message=f"更新真寻未知错误 {type(e)}:{e}\n",
# )
# else:
# if code == 200:
# await bot.send_private_msg(
# user_id=int(list(bot.config.superusers)[0]),
# message=f"更新完毕,请重启真寻....",
# ) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/check_zhenxun_update/__init__.py | __init__.py |
from configs.path_config import IMAGE_PATH
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from utils.message_builder import image
from services.log import logger
from utils.image_utils import BuildImage
from nonebot.params import CommandArg
__zx_plugin_name__ = "鲁迅说"
__plugin_usage__ = """
usage:
鲁迅说了啥?
指令:
鲁迅说 [文本]
""".strip()
__plugin_des__ = "鲁迅说他没说过这话!"
__plugin_cmd__ = ["鲁迅说"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["鲁迅说"],
}
__plugin_block_limit__ = {
"rst": "你的鲁迅正在说,等会"
}
luxun = on_command("鲁迅说过", aliases={"鲁迅说"}, priority=5, block=True)
luxun_author = BuildImage(0, 0, plain_text="--鲁迅", font_size=30, font='msyh.ttf', font_color=(255, 255, 255))
@luxun.handle()
async def handle(state: T_State, arg: Message = CommandArg()):
args = arg.extract_plain_text().strip()
if args:
state["content"] = args if args else "烦了,不说了"
@luxun.got("content", prompt="你让鲁迅说点啥?")
async def handle_event(event: MessageEvent, state: T_State):
content = state["content"].strip()
if content.startswith(",") or content.startswith(","):
content = content[1:]
A = BuildImage(0, 0, font_size=37, background=f'{IMAGE_PATH}/other/luxun.jpg', font='msyh.ttf')
x = ""
if len(content) > 40:
await luxun.finish('太长了,鲁迅说不完...')
while A.getsize(content)[0] > A.w - 50:
n = int(len(content) / 2)
x += content[:n] + '\n'
content = content[n:]
x += content
if len(x.split('\n')) > 2:
await luxun.finish('太长了,鲁迅说不完...')
A.text((int((480 - A.getsize(x.split("\n")[0])[0]) / 2), 300), x, (255, 255, 255))
A.paste(luxun_author, (320, 400), True)
await luxun.send(image(b64=A.pic2bs4()))
logger.info(
f"USER {event.user_id} GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'} 鲁迅说过 {content}"
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/luxun/__init__.py | __init__.py |
from utils.manager import StaticData
from configs.config import NICKNAME
from models.ban_user import BanUser
from typing import Optional
import random
import time
class AiMessageManager(StaticData):
def __init__(self):
super().__init__(None)
self._same_message = [
"为什么要发一样的话?",
"请不要再重复对我说一句话了,不然我就要生气了!",
"别再发这句话了,我已经知道了...",
"你是只会说这一句话吗?",
"[*],你发我也发!",
"[uname],[*]",
f"救命!有笨蛋一直给{NICKNAME}发一样的话!",
"这句话你已经给我发了{}次了,再发就生气!",
]
self._repeat_message = [
f"请不要学{NICKNAME}说话",
f"为什么要一直学{NICKNAME}说话?",
"你再学!你再学我就生气了!",
f"呜呜,你是想欺负{NICKNAME}嘛..",
"[uname]不要再学我说话了!",
"再学我说话,我就把你拉进黑名单(生气",
"你再学![uname]是个笨蛋!",
"你已经学我说话{}次了!别再学了!",
]
def add_message(self, user_id: int, message: str):
"""
添加用户消息
:param user_id: 用户id
:param message: 消息内容
"""
if message:
if self._data.get(user_id) is None:
self._data[user_id] = {
"time": time.time(),
"message": [],
"result": [],
"repeat_count": 0,
}
if time.time() - self._data[user_id]["time"] > 60 * 10:
self._data[user_id]["message"].clear()
self._data[user_id]["time"] = time.time()
self._data[user_id]["message"].append(message.strip())
def add_result(self, user_id: int, message: str):
"""
添加回复用户的消息
:param user_id: 用户id
:param message: 回复消息内容
"""
if message:
if self._data.get(user_id) is None:
self._data[user_id] = {
"time": time.time(),
"message": [],
"result": [],
"repeat_count": 0,
}
if time.time() - self._data[user_id]["time"] > 60 * 10:
self._data[user_id]["result"].clear()
self._data[user_id]["repeat_count"] = 0
self._data[user_id]["time"] = time.time()
self._data[user_id]["result"].append(message.strip())
async def get_result(self, user_id: int, nickname: str) -> Optional[str]:
"""
特殊消息特殊回复
:param user_id: 用户id
:param nickname: 用户昵称
"""
try:
if len(self._data[user_id]["message"]) < 2:
return None
except KeyError:
return None
msg = await self._get_user_repeat_message_result(user_id)
if not msg:
msg = await self._get_user_same_message_result(user_id)
if msg:
if "[uname]" in msg:
msg = msg.replace("[uname]", nickname)
if not msg.startswith("生气了!你好烦,闭嘴!") and "[*]" in msg:
msg = msg.replace("[*]", self._data[user_id]["message"][-1])
return msg
async def _get_user_same_message_result(self, user_id: int) -> Optional[str]:
"""
重复消息回复
:param user_id: 用户id
"""
msg = self._data[user_id]["message"][-1]
cnt = 0
_tmp = self._data[user_id]["message"][:-1]
_tmp.reverse()
for s in _tmp:
if s == msg:
cnt += 1
else:
break
if cnt > 1:
if random.random() < 0.5 and cnt > 3:
rand = random.randint(60, 300)
await BanUser.ban(user_id, 9, rand)
self._data[user_id]["message"].clear()
return f"生气了!你好烦,闭嘴!给我老实安静{rand}秒"
return random.choice(self._same_message).format(cnt)
return None
async def _get_user_repeat_message_result(self, user_id: int) -> Optional[str]:
"""
复读真寻的消息回复
:param user_id: 用户id
"""
msg = self._data[user_id]["message"][-1]
if self._data[user_id]["result"]:
rst = self._data[user_id]["result"][-1]
else:
return None
if msg == rst:
self._data[user_id]["repeat_count"] += 1
cnt = self._data[user_id]["repeat_count"]
if cnt > 1:
if random.random() < 0.5 and cnt > 3:
rand = random.randint(60, 300)
await BanUser.ban(user_id, 9, rand)
self._data[user_id]["result"].clear()
self._data[user_id]["repeat_count"] = 0
return f"生气了!你好烦,闭嘴!给我老实安静{rand}秒"
return random.choice(self._repeat_message).format(cnt)
return None
ai_message_manager = AiMessageManager() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/ai/utils.py | utils.py |
import os
import random
import re
from utils.http_utils import AsyncHttpx
from configs.path_config import IMAGE_PATH, DATA_PATH
from services.log import logger
from utils.message_builder import image, face
from configs.config import Config, NICKNAME
from .utils import ai_message_manager
try:
import ujson as json
except ModuleNotFoundError:
import json
url = "http://openapi.tuling123.com/openapi/api/v2"
check_url = "https://v2.alapi.cn/api/censor/text"
index = 0
anime_data = json.load(open(DATA_PATH / "anime.json", "r", encoding="utf8"))
async def get_chat_result(text: str, img_url: str, user_id: int, nickname: str) -> str:
"""
获取 AI 返回值,顺序: 特殊回复 -> 图灵 -> 青云客
:param text: 问题
:param img_url: 图片链接
:param user_id: 用户id
:param nickname: 用户昵称
:return: 回答
"""
global index
ai_message_manager.add_message(user_id, text)
special_rst = await ai_message_manager.get_result(user_id, nickname)
if special_rst:
ai_message_manager.add_result(user_id, special_rst)
return special_rst
if index == 5:
index = 0
if len(text) < 6 and random.random() < 0.6:
keys = anime_data.keys()
for key in keys:
if text.find(key) != -1:
return random.choice(anime_data[key]).replace("你", nickname)
rst = await tu_ling(text, img_url, user_id)
if not rst:
rst = await xie_ai(text)
if not rst:
return no_result()
if nickname:
if len(nickname) < 5:
if random.random() < 0.5:
nickname = "~".join(nickname) + "~"
if random.random() < 0.2:
if nickname.find("大人") == -1:
nickname += "大~人~"
rst = rst.replace("小主人", nickname).replace("小朋友", nickname)
ai_message_manager.add_result(user_id, rst)
return rst
# 图灵接口
async def tu_ling(text: str, img_url: str, user_id: int) -> str:
"""
获取图灵接口的回复
:param text: 问题
:param img_url: 图片链接
:param user_id: 用户id
:return: 图灵回复
"""
global index
TL_KEY = Config.get_config("ai", "TL_KEY")
req = None
if not TL_KEY:
return ""
try:
if text:
req = {
"perception": {
"inputText": {"text": text},
"selfInfo": {
"location": {"city": "陨石坑", "province": "火星", "street": "第5坑位"}
},
},
"userInfo": {"apiKey": TL_KEY[index], "userId": str(user_id)},
}
elif img_url:
req = {
"reqType": 1,
"perception": {
"inputImage": {"url": img_url},
"selfInfo": {
"location": {"city": "陨石坑", "province": "火星", "street": "第5坑位"}
},
},
"userInfo": {"apiKey": TL_KEY[index], "userId": str(user_id)},
}
except IndexError:
index = 0
return ""
text = ""
response = await AsyncHttpx.post(url, json=req)
if response.status_code != 200:
return no_result()
resp_payload = json.loads(response.text)
if int(resp_payload["intent"]["code"]) in [4003]:
return ""
if resp_payload["results"]:
for result in resp_payload["results"]:
if result["resultType"] == "text":
text = result["values"]["text"]
if "请求次数超过" in text:
text = ""
return text
# 屑 AI
async def xie_ai(text: str) -> str:
"""
获取青云客回复
:param text: 问题
:return: 青云可回复
"""
res = await AsyncHttpx.get(f"http://api.qingyunke.com/api.php?key=free&appid=0&msg={text}")
content = ""
data = json.loads(res.text)
if data["result"] == 0:
content = data["content"]
if "菲菲" in content:
content = content.replace("菲菲", NICKNAME)
if "艳儿" in content:
content = content.replace("艳儿", NICKNAME)
if "公众号" in content:
content = ""
if "{br}" in content:
content = content.replace("{br}", "\n")
if "提示" in content:
content = content[: content.find("提示")]
if "淘宝" in content or "taobao.com" in content:
return ""
while True:
r = re.search("{face:(.*)}", content)
if r:
id_ = r.group(1)
content = content.replace(
"{" + f"face:{id_}" + "}", str(face(int(id_)))
)
else:
break
return (
content
if not content and not Config.get_config("ai", "ALAPI_AI_CHECK")
else await check_text(content)
)
def hello() -> str:
"""
一些打招呼的内容
"""
result = random.choice(
(
"哦豁?!",
"你好!Ov<",
f"库库库,呼唤{NICKNAME}做什么呢",
"我在呢!",
"呼呼,叫俺干嘛",
)
)
img = random.choice(os.listdir(IMAGE_PATH / "zai"))
if img[-4:] == ".gif":
result += image(img, "zai")
else:
result += image(img, "zai")
return result
# 没有回答时回复内容
def no_result() -> str:
"""
没有回答时的回复
"""
return (
random.choice(
[
"你在说啥子?",
f"纯洁的{NICKNAME}没听懂",
"下次再告诉你(下次一定)",
"你觉得我听懂了吗?嗯?",
"我!不!知!道!",
]
)
+ image(random.choice(os.listdir(IMAGE_PATH / "noresult")), "noresult")
)
async def check_text(text: str) -> str:
"""
ALAPI文本检测,主要针对青云客API,检测为恶俗文本改为无回复的回答
:param text: 回复
"""
if not Config.get_config("alapi", "ALAPI_TOKEN"):
return text
params = {"token": Config.get_config("alapi", "ALAPI_TOKEN"), "text": text}
try:
data = (await AsyncHttpx.get(check_url, timeout=2, params=params)).json()
if data["code"] == 200:
if data["data"]["conclusion_type"] == 2:
return ""
except Exception as e:
logger.error(f"检测违规文本错误...{type(e)}:{e}")
return text | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/ai/data_source.py | data_source.py |
from nonebot import on_message
from nonebot.adapters.onebot.v11 import (
Bot,
GroupMessageEvent,
Message,
MessageEvent,
)
from nonebot.rule import to_me
from models.friend_user import FriendUser
from models.group_member_info import GroupInfoUser
from services.log import logger
from utils.utils import get_message_img, get_message_text
from .data_source import get_chat_result, hello, no_result
from configs.config import NICKNAME, Config
__zx_plugin_name__ = "AI"
__plugin_usage__ = f"""
usage:
与{NICKNAME}普普通通的对话吧!
"""
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"cmd": ["Ai", "ai", "AI", "aI"],
}
__plugin_configs__ = {
"TL_KEY": {"value": [], "help": "图灵Key"},
"ALAPI_AI_CHECK": {"value": False, "help": "是否检测青云客骂娘回复", "default_value": False},
"TEXT_FILTER": {
"value": ["鸡", "口交"],
"help": "文本过滤器,将敏感词更改为*",
"default_value": [],
},
}
Config.add_plugin_config(
"alapi", "ALAPI_TOKEN", None, help_="在 https://admin.alapi.cn/user/login 登录后获取token"
)
ai = on_message(rule=to_me(), priority=8)
@ai.handle()
async def _(bot: Bot, event: MessageEvent):
msg = get_message_text(event.json())
img = get_message_img(event.json())
if "CQ:xml" in str(event.get_message()):
return
# 打招呼
if (not msg and not img) or msg in [
"你好啊",
"你好",
"在吗",
"在不在",
"您好",
"您好啊",
"你好",
"在",
]:
await ai.finish(hello())
img = img[0] if img else ""
if isinstance(event, GroupMessageEvent):
nickname = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
else:
nickname = await FriendUser.get_friend_nickname(event.user_id)
if not nickname:
if isinstance(event, GroupMessageEvent):
nickname = event.sender.card or event.sender.nickname
else:
nickname = event.sender.nickname
result = await get_chat_result(msg, img, event.user_id, nickname)
logger.info(
f"USER {event.user_id} GROUP {event.group_id if isinstance(event, GroupMessageEvent) else ''} "
f"问题:{msg} ---- 回答:{result}"
)
if result:
for t in Config.get_config("ai", "TEXT_FILTER"):
result = result.replace(t, "*")
await ai.finish(Message(result))
else:
await ai.finish(no_result()) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/ai/__init__.py | __init__.py |
from utils.utils import cn2py, get_bot
from configs.path_config import DATA_PATH
from typing import Optional, Union
from .model import BlackWord
from configs.config import Config
from pathlib import Path
from services.log import logger
from models.ban_user import BanUser
from nonebot.adapters.onebot.v11.exception import ActionFailed
from models.group_member_info import GroupInfoUser
from utils.http_utils import AsyncHttpx
import random
try:
import ujson as json
except ModuleNotFoundError:
import json
class BlackWordManager:
"""
敏感词管理
"""
def __init__(self, file: Optional[Path]):
self._word_list = {
"1": [],
"2": [],
"3": [],
"4": ["sb", "nmsl", "mdzz", "2b", "jb", "操", "废物", "憨憨", "cnm", "rnm"],
"5": [],
}
self._py_list = {
"1": [],
"2": [],
"3": [],
"4": [
"shabi",
"wocaonima",
"sima",
"sabi",
"zhizhang",
"naocan",
"caonima",
"simadongxi",
"simawanyi",
"hanbi",
"hanpi",
"laji",
],
"5": [],
}
file.parent.mkdir(parents=True, exist_ok=True)
# if file.exists():
# # 清空默认配置
# with open(file, "r", encoding="utf8") as f:
# self._word_list = json.load(f)
# for i in self._word_list:
# for word in self._word_list[i]:
# if word.startswith("*py*"):
# self._word_list[i].remove(word)
# if word[4:].strip():
# self._py_list[i].append(word[4:])
# else:
# with open(file, "w", encoding="utf8") as f:
# json.dump(
# self._word_list,
# f,
# ensure_ascii=False,
# indent=4,
# )
async def check(
self, user_id: int, group_id: Optional[int], message: str
) -> Optional[Union[str, bool]]:
"""
检查是否包含黑名单词汇
:param user_id: 用户id
:param group_id: 群号
:param message: 消息
"""
if self._word_list or self._py_list:
if data := self._check(message):
if data[0]:
await _add_user_black_word(
user_id, group_id, data[0], message, int(data[1])
)
return True
if Config.get_config(
"black_word", "ALAPI_CHECK_FLAG"
) and not await check_text(message):
await send_msg(
0, None, f"USER {user_id} GROUP {group_id} ALAPI 疑似检测:{message}"
)
return False
def _check(self, message: str) -> "Optional[str], int":
"""
检测文本是否违规
:param message: 检测消息
"""
# 移除空格
message = message.replace(" ", "").strip()
py_msg = cn2py(message).lower()
for x in [self._word_list, self._py_list]:
for level in x:
if message in x[level] or py_msg in x[level]:
return message if message in x[level] else py_msg, level
for x in [self._word_list, self._py_list]:
for level in x:
for m in x[level]:
if m in message or m in py_msg:
return m, -1
return None, 0
async def _add_user_black_word(
user_id: int,
group_id: Optional[int],
black_word: str,
message: str,
punish_level: int,
):
"""
:param user_id: 用户id
:param group_id: 群号
:param black_word: 触发的黑名单词汇
:param message: 原始文本
:param punish_level: 惩罚等级
"""
cycle_days = Config.get_config("black_word", "CYCLE_DAYS")
cycle_days = cycle_days if cycle_days else 7
user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level)
# 周期内超过次数直接提升惩罚
if Config.get_config(
"black_word", "AUTO_ADD_PUNISH_LEVEL"
) and user_count > Config.get_config("black_word", "ADD_PUNISH_LEVEL_TO_COUNT"):
punish_level -= 1
await BlackWord.add_user_black_word(
user_id, group_id, black_word, message, punish_level
)
logger.info(
f"已将 USER {user_id} GROUP {group_id} 添加至黑名单词汇记录 Black_word:{black_word} Plant_text:{message}"
)
# 自动惩罚
if Config.get_config("black_word", "AUTO_PUNISH") and punish_level != -1:
await _punish_handle(user_id, group_id, punish_level, black_word)
async def _punish_handle(
user_id: int, group_id: Optional[int], punish_level: int, black_word: str
):
"""
惩罚措施,级别越低惩罚越严
:param user_id: 用户id
:param group_id: 群号
:param black_word: 触发的黑名单词汇
"""
logger.info(f"BlackWord USER {user_id} 触发 {punish_level} 级惩罚...")
# 周期天数
cycle_days = Config.get_config("black_word", "CYCLE_DAYS")
cycle_days = cycle_days if cycle_days else 7
# 用户周期内触发punish_level级惩罚的次数
user_count = await BlackWord.get_user_count(user_id, cycle_days, punish_level)
# 容忍次数:List[int]
tolerate_count = Config.get_config("black_word", "TOLERATE_COUNT")
if not tolerate_count or len(tolerate_count) < 5:
tolerate_count = [5, 2, 2, 2, 2]
if punish_level == 1 and user_count > tolerate_count[punish_level - 1]:
# 永久ban
await _get_punish(1, user_id, group_id)
# 删除好友
await _get_punish(2, user_id, group_id)
# 退出所在所有群聊
await _get_punish(3, user_id, group_id)
await BlackWord.set_user_punish(user_id, "永久ban 删除好友 退出所在所有群聊", black_word)
elif punish_level == 2 and user_count > tolerate_count[punish_level - 1]:
# 永久ban
await _get_punish(1, user_id, group_id)
# 删除好友
await _get_punish(2, user_id, group_id)
await BlackWord.set_user_punish(user_id, "永久ban 删除好友", black_word)
elif punish_level == 3 and user_count > tolerate_count[punish_level - 1]:
# 永久ban
await _get_punish(1, user_id, group_id)
await BlackWord.set_user_punish(user_id, "永久ban", black_word)
elif punish_level == 4 and user_count > tolerate_count[punish_level - 1]:
# ban指定时长
ban_time = await _get_punish(4, user_id, group_id)
await BlackWord.set_user_punish(user_id, f"ban {ban_time}分钟", black_word)
elif punish_level == 5 and user_count > tolerate_count[punish_level - 1]:
# 口头警告
warning_result = await _get_punish(5, user_id, group_id)
await BlackWord.set_user_punish(user_id, f"口头警告:{warning_result}", black_word)
await send_msg(
user_id,
group_id,
f"BlackWordChecker:该条发言已被记录,目前你在{cycle_days}天内的发表{punish_level}"
f"言论记录次数为:{user_count}次,请注意你的发言\n"
f"* 如果你不清楚惩罚机制,请发送“惩罚机制” *",
)
async def _get_punish(
id_: int, user_id: int, group_id: Optional[int] = None
) -> Optional[Union[int, str]]:
"""
通过id_获取惩罚
:param id_: id
:param user_id: 用户id
:param group_id: 群号
"""
bot = get_bot()
# 忽略的群聊
_ignore_group = Config.get_config("black_word", "IGNORE_GROUP")
# 处罚 id 4 ban 时间:int,List[int]
ban_duration = Config.get_config("black_word", "BAN_DURATION")
# 口头警告内容
warning_result = Config.get_config("black_word", "WARNING_RESULT")
# 永久ban
if id_ == 1:
if str(user_id) not in bot.config.superusers:
await BanUser.ban(user_id, 10, 99999999)
await send_msg(user_id, group_id, f"BlackWordChecker 永久ban USER {user_id}")
logger.info(f"BlackWord 永久封禁 USER {user_id}...")
# 删除好友
elif id_ == 2:
if str(user_id) not in bot.config.superusers:
try:
await bot.delete_friend(user_id=user_id)
await send_msg(
user_id, group_id, f"BlackWordChecker 删除好友 USER {user_id}"
)
logger.info(f"BlackWord 删除好友 {user_id}...")
except ActionFailed:
pass
# 退出所有所在群聊
elif id_ == 3:
for g in await GroupInfoUser.get_user_all_group(user_id):
if g not in _ignore_group:
try:
await send_msg(
user_id, g, f"BlackWordChecker 因用户 USER {user_id} 触发惩罚退出该群"
)
await bot.set_group_leave(group_id=g)
logger.info(f"BlackWord 退出 USER {user_id} 所在群聊:{g}...")
except ActionFailed:
pass
# 封禁用户指定时间
elif id_ == 4:
# if str(user_id) not in bot.config.superusers:
if isinstance(ban_duration, list):
ban_duration = random.randint(ban_duration[0], ban_duration[1])
await BanUser.ban(user_id, 9, ban_duration * 60)
await send_msg(
user_id,
group_id,
f"BlackWordChecker 对用户 USER {user_id} 进行封禁 {ban_duration} 分钟处罚。",
)
logger.info(f"BlackWord 封禁 USER {user_id} {ban_duration}分钟...")
return ban_duration
# 口头警告
elif id_ == 5:
if group_id:
await bot.send_group_msg(group_id=group_id, message=warning_result)
else:
await bot.send_private_msg(user_id=user_id, message=warning_result)
logger.info(f"BlackWord 口头警告 USER {user_id}")
return warning_result
return None
async def send_msg(user_id: int, group_id: Optional[int], message: str):
"""
发送消息
:param user_id: user_id
:param group_id: group_id
:param message: message
"""
bot = get_bot()
if not user_id:
user_id = int(list(bot.config.superusers)[0])
if group_id:
await bot.send_group_msg(group_id=group_id, message=message)
else:
await bot.send_private_msg(user_id=user_id, message=message)
async def check_text(text: str) -> bool:
"""
ALAPI文本检测,检测输入违规
:param text: 回复
"""
if not Config.get_config("alapi", "ALAPI_TOKEN"):
return True
params = {"token": Config.get_config("alapi", "ALAPI_TOKEN"), "text": text}
try:
data = (
await AsyncHttpx.get(
"https://v2.alapi.cn/api/censor/text", timeout=4, params=params
)
).json()
if data["code"] == 200:
return data["data"]["conclusion_type"] == 2
except Exception as e:
logger.error(f"检测违规文本错误...{type(e)}:{e}")
return True
black_word_manager = BlackWordManager(DATA_PATH / "black_word" / "black_word.json") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/black_word/utils.py | utils.py |
from nonebot.adapters.onebot.v11 import Bot
from utils.image_utils import BuildImage
from services.log import logger
from typing import Optional
from datetime import datetime
from .model import BlackWord
async def show_black_text_list(
bot: Bot,
user: Optional[int],
group_id: Optional[int],
date: Optional[datetime],
data_type: str = "=",
) -> BuildImage:
data = await BlackWord.get_black_data(user, group_id, date, data_type)
font_w, font_h = BuildImage(0, 0, font_size=20).getsize("正")
A = BuildImage(1600, len(data) * (font_h + 3), color="#f9f6f2", font_size=20)
# await A.apaste(BuildImage(0, 0, plain_text="昵称\tUSER_ID\t群号\t文本\t检测\t等级\t日期", font_size=30), (50, 10), True)
friend_list = await bot.get_friend_list()
user_name_list = []
user_id_list = []
group_id_list = []
plant_text_list = []
black_word_list = []
punish_list = []
punish_level_list = []
create_time_list = []
for x in data:
try:
if x.group_id:
user_name = (
await bot.get_group_member_info(
group_id=x.group_id, user_id=x.user_qq
)
)["card"]
else:
user_name = [
u["nickname"] for u in friend_list if u["user_id"] == x.user_qq
][0]
except Exception as e:
logger.warning(
f"show_black_text_list 获取 USER {x.user_qq} user_name 失败 {type(e)}:{e}"
)
user_name = x.user_qq
user_name_list.append(user_name)
user_id_list.append(x.user_qq)
group_id_list.append(x.group_id)
plant_text_list.append(" ".join(x.plant_text.split("\n")))
black_word_list.append(x.black_word)
punish_list.append(x.punish)
punish_level_list.append(x.punish_level)
create_time_list.append(x.create_time.replace(microsecond=0))
a_cur_w = 10
max_h = 0
line_list = []
for l in [
user_name_list,
user_id_list,
group_id_list,
plant_text_list,
black_word_list,
punish_list,
punish_level_list,
create_time_list,
]:
cur_h = 0
if l == plant_text_list:
tw = 220
elif l == create_time_list:
tw = 290
else:
tw = 160
tmp = BuildImage(tw, len(data) * (font_h + 2), color="#f9f6f2", font_size=20)
for x in l:
await tmp.atext((0, cur_h), str(x))
cur_h += font_h + 2
if cur_h > max_h:
max_h = cur_h
await A.apaste(tmp, (a_cur_w, 10))
if l == punish_level_list:
a_cur_w += 90
elif l == plant_text_list:
a_cur_w += 250
else:
a_cur_w += 175
if l != create_time_list:
line_list.append(a_cur_w)
# await A.aline((a_cur_w-10, 0, a_cur_w-10, A.h), fill=(202, 105, 137), width=3)
# A.show()
# return A
bk = BuildImage(A.w, A.h + 200, color="#f9f6f2", font_size=35)
cur_h = font_h + 1 + 10
for _ in range(len(data)):
await A.aline((0, cur_h, A.w, cur_h), fill=(202, 105, 137), width=1)
cur_h += font_h + 2
await bk.apaste(A, (0, 200))
for lw in line_list[:-1]:
await bk.aline((lw - 10, 0, lw - 10, A.h + 200), fill=(202, 105, 137), width=3)
await bk.aline((1200, 0, 1200, A.h + 200), fill=(202, 105, 137), width=3)
await bk.aline((0, 190, bk.w, 190), fill=(202, 105, 137), width=3)
await bk.atext((40, 80), "昵称")
await bk.atext((220, 80), "UID")
await bk.atext((400, 80), "GID")
await bk.atext((600, 80), "文本")
await bk.atext((800, 80), "检测")
await bk.atext((1000, 80), "惩罚")
await bk.atext((1128, 80), "等级")
await bk.atext((1300, 80), "记录日期")
if bk.w * bk.h > 5000000:
await bk.aresize(0.7)
return bk | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/black_word/data_source.py | data_source.py |
from services.db_context import db
from typing import Optional, List
from datetime import datetime, timedelta
class BlackWord(db.Model):
__tablename__ = "black_word"
id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
user_qq = db.Column(db.BigInteger(), nullable=False, primary_key=True)
group_id = db.Column(db.BigInteger())
plant_text = db.Column(db.String())
black_word = db.Column(db.String())
punish = db.Column(db.String(), default="")
punish_level = db.Column(db.Integer())
create_time = db.Column(db.DateTime(timezone=True), nullable=False)
@classmethod
async def add_user_black_word(
cls,
user_qq: int,
group_id: Optional[int],
black_word: str,
plant_text: str,
punish_level: int,
):
"""
说明:
添加用户发送的敏感词
参数:
:param user_qq: 用户id
:param group_id: 群号
:param black_word: 黑名单词汇
:param plant_text: 消息文本
:param punish_level: 惩罚等级
"""
await cls.create(
user_qq=user_qq,
group_id=group_id,
plant_text=plant_text,
black_word=black_word,
punish_level=punish_level,
create_time=datetime.now(),
)
@classmethod
async def set_user_punish(
cls,
user_qq: int,
punish: str,
black_word: Optional[str],
id_: Optional[int] = None,
) -> bool:
"""
说明:
设置处罚
参数:
:param user_qq: 用户id
:param punish: 处罚
:param black_word: 黑名单词汇
:param id_: 记录下标
"""
user = None
if (not black_word and not id_) or not punish:
return False
query = cls.query.where(cls.user_qq == user_qq).with_for_update()
if black_word:
user = (await query.where(cls.black_word == black_word).gino.all())[-1]
elif id_:
user_list = await query.gino.all()
if len(user_list) == 0 or (id_ < 0 or id_ > len(user_list)):
return False
user = user_list[id_]
if not user:
return False
await user.update(punish=cls.punish + punish).apply()
return True
@classmethod
async def get_user_count(
cls, user_qq: int, days: int = 7, punish_level: Optional[int] = None
) -> int:
"""
说明:
获取用户规定周期内的犯事次数
参数:
:param user_qq: 用户qq
:param days: 周期天数
:param punish_level: 惩罚等级
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.punish_level != -1))
if punish_level is not None:
query = query.where(cls.punish_level == punish_level)
query = await query.gino.all()
if not query:
return 0
date = datetime.now() - timedelta(days=days)
d = query[0].create_time.replace(tzinfo=None)
query = [x for x in query if x.create_time.replace(tzinfo=None) > date]
return len(query)
@classmethod
async def get_black_data(
cls,
user_qq: Optional[int],
group_id: Optional[int],
date: Optional[datetime],
date_type: str = "=",
) -> List["BlackWord"]:
"""
说明:
通过指定条件查询数据
参数:
:param user_qq: 用户qq
:param group_id: 群号
:param date: 日期
:param date_type: 日期查询类型
"""
query = cls.query
if user_qq:
query = query.where(cls.user_qq == user_qq)
if group_id:
query = query.where(cls.group_id == group_id)
if date:
if date_type == "=":
query = query.where(cls.create_time == date)
elif date_type == ">":
query = query.where(cls.create_time > date)
elif date_type == "<":
query = query.where(cls.create_time < date)
return await query.gino.all() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/black_word/model.py | model.py |
from nonebot.adapters.onebot.v11 import Event, MessageEvent, GroupMessageEvent, Message, Bot
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor
from utils.image_utils import BuildImage
from utils.utils import get_message_text, is_number
from nonebot.params import CommandArg
from .utils import black_word_manager
from nonebot import on_command
from configs.config import Config, NICKNAME
from nonebot.permission import SUPERUSER
from .data_source import show_black_text_list
from models.ban_user import BanUser
from datetime import datetime
from utils.message_builder import image
__zx_plugin_name__ = "敏感词检测"
__plugin_usage__ = """
usage:
注意你的发言!
""".strip()
__plugin_des__ = "请注意你的发言!!"
__plugin_type__ = ("其他",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
Config.add_plugin_config(
"black_word", "CYCLE_DAYS", 30, name="敏感词检测与惩罚", help_="黑名单词汇记录周期", default_value=30
)
Config.add_plugin_config(
"black_word",
"TOLERATE_COUNT",
[5, 1, 1, 1, 1],
help_="各个级别惩罚的容忍次数,依次为:1, 2, 3, 4, 5",
default_value=[5, 1, 1, 1, 1],
)
Config.add_plugin_config(
"black_word", "AUTO_PUNISH", True, help_="是否启动自动惩罚机制", default_value=True
)
Config.add_plugin_config(
"black_word", "IGNORE_GROUP", [], help_="退出群聊惩罚中忽略的群聊,即不会退出的群聊", default_value=[]
)
Config.add_plugin_config(
"black_word",
"BAN_DURATION",
360,
help_="Union[int, List[int, int]]Ban时长,可以为指定数字或指定列表区间(随机),例如 [30, 360]",
default_value=360,
)
Config.add_plugin_config(
"black_word",
"WARNING_RESULT",
f"请注意对{NICKNAME}的发言内容",
help_="口头警告内容",
default_value=f"请注意对{NICKNAME}的发言内容",
)
Config.add_plugin_config(
"black_word",
"AUTO_ADD_PUNISH_LEVEL",
True,
help_="自动提级机制,当周期内处罚次数大于某一特定值就提升惩罚等级",
default_value=True,
)
Config.add_plugin_config(
"black_word",
"ADD_PUNISH_LEVEL_TO_COUNT",
3,
help_="在CYCLE_DAYS周期内触发指定惩罚次数后提升惩罚等级",
default_value=3,
)
Config.add_plugin_config(
"black_word",
"ALAPI_CHECK_FLAG",
False,
help_="当未检测到已收录的敏感词时,开启ALAPI文本检测并将疑似文本发送给超级用户",
default_value=False,
)
Config.add_plugin_config(
"black_word",
"CONTAIN_BLACK_STOP_PROPAGATION",
True,
help_="当文本包含任意敏感词时,停止向下级插件传递,即不触发ai",
default_value=True,
)
set_punish = on_command("设置惩罚", priority=1, permission=SUPERUSER, block=True)
show_black = on_command("记录名单", priority=1, permission=SUPERUSER, block=True)
show_punish = on_command("惩罚机制", aliases={"敏感词检测"}, priority=1, block=True)
# 黑名单词汇检测
@run_preprocessor
async def _(
matcher: Matcher,
event: Event,
):
if (
isinstance(event, MessageEvent)
and event.is_tome()
and matcher.plugin_name == "black_word"
and not await BanUser.is_ban(event.user_id)
):
user_id = event.user_id
group_id = event.group_id if isinstance(event, GroupMessageEvent) else None
msg = get_message_text(event.json())
if await black_word_manager.check(user_id, group_id, msg) and Config.get_config(
"black_word", "CONTAIN_BLACK_STOP_PROPAGATION"
):
matcher.stop_propagation()
@show_black.handle()
async def _(bot: Bot, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip().split()
user_id = None
group_id = None
date = None
date_type = "="
if msg:
for x in msg:
if x.startswith("u:") and is_number(tmp := x.split(":")[-1]):
user_id = int(tmp)
elif x.startswith("g:") and is_number(tmp := x.split(":")[-1]):
group_id = int(tmp)
elif x.startswith("d"):
tmp = x.split(":")
if tmp[0][-1] in ["=", ">", "<"]:
date_type = tmp[0][-1]
try:
date = datetime.strptime(tmp, '%Y-%m-%d')
except ValueError:
await show_black.finish("日期格式错误,需要:年-月-日")
pic = await show_black_text_list(bot, user_id, group_id, date, date_type)
await show_black.send(image(b64=pic.pic2bs4()))
@show_punish.handle()
async def _():
text = f"""
** 惩罚机制 **
惩罚前包含容忍机制,在指定周期内会容忍偶尔少次数的敏感词只会进行警告提醒
多次触发同级惩罚会使惩罚等级提高,即惩罚自动提级机制
目前公开的惩罚等级:
1级:永久ban 删除好友 退出所在所有群聊
2级:永久ban 删除好友
3级:永久ban
4级:ban指定/随机时长
5级:警告
备注:
该功能为测试阶段,如果你有被误封情况,请联系管理员,会从数据库中提取出你的数据进行审核后判断
目前该功能暂不完善,部分情况会由管理员鉴定,请注意对真寻的发言
关于敏感词:
记住不要骂{NICKNAME}就对了!
""".strip()
max_width = 0
for m in text.split("\n"):
max_width = len(m) * 20 if len(m) * 20 > max_width else max_width
max_height = len(text.split("\n")) * 24
A = BuildImage(
max_width, max_height, font="CJGaoDeGuo.otf", font_size=24, color="#E3DBD1"
)
A.text((10, 10), text)
await show_punish.send(image(b64=A.pic2bs4())) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/black_word/__init__.py | __init__.py |
from utils.utils import get_message_at, is_number, get_message_img
from nonebot.params import CommandArg
from services.log import logger
from configs.path_config import DATA_PATH
from utils.http_utils import AsyncHttpx
from ._data_source import WordBankBuilder
from configs.config import Config
from utils.message_builder import image
from utils.image_utils import text2image
from .model import WordBank
from nonebot.adapters.onebot.v11 import (
Bot,
GroupMessageEvent,
Message
)
from nonebot.typing import T_State
from nonebot import on_command
import random
import os
import re
__zx_plugin_name__ = "词库问答 [Admin]"
__plugin_usage__ = """
usage:
对指定问题的随机回答,对相同问题可以设置多个不同回答
删除词条后每个词条的id可能会变化,请查看后再删除
指令:
添加词条问...答...:添加问答词条,可重复添加相同问题的不同回答
删除词条 [问题/下标] ?[下标]:删除指定词条指定或全部回答
查看词条 ?[问题/下标]:查看全部词条或对应词条回答
示例:添加词条问谁是萝莉答是我
示例:删除词条 谁是萝莉
示例:删除词条 谁是萝莉 0
示例:删除词条 id:0
示例:查看词条
示例:查看词条 谁是萝莉
示例:查看词条 id:0
""".strip()
__plugin_des__ = "自定义词条内容随机回复"
__plugin_cmd__ = [
"添加词条问...答..",
"删除词条 [问题/下标] ?[下标]",
"查看词条 ?[问题/下标]",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"admin_level": Config.get_config("word_bank", "WORD_BANK_LEVEL"),
"cmd": ["词库问答", "添加词条", "删除词条", "查看词条"],
}
data_dir = DATA_PATH / "word_bank"
data_dir.mkdir(parents=True, exist_ok=True)
add_word = on_command("添加词条", priority=5, block=True)
delete_word = on_command("删除词条", priority=5, block=True)
show_word = on_command("显示词条", aliases={"查看词条"}, priority=5, block=True)
@add_word.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State, arg: Message = CommandArg()):
msg = str(arg)
r = re.search(r"^问(.+)\s?答([\s\S]*)", msg)
if not r:
await add_word.finish("未检测到词条问题...")
problem = r.group(1).strip()
if not problem:
await add_word.finish("未检测到词条问题...")
answer = msg.split("答", maxsplit=1)[-1]
if not answer:
await add_word.finish("未检测到词条回答...")
idx = 0
for n in bot.config.nickname:
if n and problem.startswith(n):
_problem = f"[_to_me|{n}]" + problem[len(n) :]
break
else:
_problem = problem
(data_dir / f"{event.group_id}").mkdir(exist_ok=True, parents=True)
_builder = WordBankBuilder(event.user_id, event.group_id, _problem)
for at_ in get_message_at(event.json()):
r = re.search(rf"\[CQ:at,qq={at_}]", answer)
if r:
answer = answer.replace(f"[CQ:at,qq={at_}]", f"[__placeholder_{idx}]", 1)
_builder.set_placeholder(idx, at_)
idx += 1
for img in get_message_img(event.json()):
_x = img.split("?")[0]
r = re.search(rf"\[CQ:image,file=(.*),url={_x}.*?]", answer)
if r:
rand = random.randint(1, 10000) + random.randint(1, 114514)
for _ in range(10):
if f"__placeholder_{rand}_{idx}.jpg" not in os.listdir(data_dir / f"{event.group_id}"):
break
rand = random.randint(1, 10000) + random.randint(1, 114514)
for i in range(3):
answer = answer.replace(f",subType={i}", "")
answer = answer.replace(
rf"[CQ:image,file={r.group(1)},url={img}]",
f"[__placeholder_{idx}]",
)
await AsyncHttpx.download_file(
img, data_dir / f"{event.group_id}" / f"__placeholder_{rand}_{idx}.jpg"
)
_builder.set_placeholder(idx, f"__placeholder_{rand}_{idx}.jpg")
idx += 1
_builder.set_answer(answer)
await _builder.save()
logger.info(f"已保存词条 问:{problem} 答:{msg}")
await add_word.send(f"已保存词条:{problem}")
@delete_word.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
await delete_word.finish("此命令之后需要跟随指定词条,通过“显示词条“查看")
index = None
_sp_msg = msg.split()
if len(_sp_msg) > 1:
if is_number(_sp_msg[-1]):
index = int(_sp_msg[-1])
msg = " ".join(_sp_msg[:-1])
problem = msg
if problem.startswith("id:"):
x = problem.split(":")[-1]
if not is_number(x) or int(x) < 0:
await delete_word.finish("id必须为数字且符合规范!")
p = await WordBank.get_group_all_problem(event.group_id)
if p:
problem = p[int(x)]
try:
if answer := await WordBank.delete_problem_answer(
event.user_id, event.group_id, problem, index
):
await delete_word.send(f"删除词条成功:{problem}\n回答:\n{answer}")
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 删除词条: {problem}"
)
else:
await delete_word.send(f"删除词条:{problem} 失败,可能该词条不存在")
except IndexError:
await delete_word.send("指定下标错误...请通过查看词条来确定..")
@show_word.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
_problem_list = await WordBank.get_group_all_problem(event.group_id)
if not _problem_list:
await show_word.finish("该群未收录任何词条..")
_problem_list = [f"\t{i}. {x}" for i, x in enumerate(_problem_list)]
await show_word.send(
image(
b64=(await text2image(
"该群已收录的词条:\n\n" + "\n".join(_problem_list),
padding=10,
color="#f9f6f2",
)).pic2bs4()
)
)
else:
_answer_list = await WordBank.get_group_all_answer(event.group_id, msg)
if not _answer_list:
await show_word.send("未收录该词条...")
else:
_answer_list = [f"{i}. {x}" for i, x in enumerate(_answer_list)]
await show_word.send(f"词条 {msg} 回答:\n" + "\n".join(_answer_list)) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/word_bank/word_hanlde.py | word_hanlde.py |
from services.db_context import db
from typing import Optional, List, Union, Tuple
from datetime import datetime
from pathlib import Path
from configs.path_config import DATA_PATH
import re
import random
class WordBank(db.Model):
__tablename__ = "word_bank"
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.Integer())
search_type = db.Column(db.Integer(), nullable=False, default=0)
problem = db.Column(db.String(), nullable=False)
answer = db.Column(db.String(), nullable=False)
format = db.Column(db.String())
create_time = db.Column(db.DateTime(), nullable=False)
update_time = db.Column(db.DateTime(), nullable=False)
@classmethod
async def add_problem_answer(
cls,
user_id: int,
group_id: Optional[int],
problem: str,
answer: str,
format_: Optional[List[Tuple[int, Union[int, str]]]],
) -> bool:
"""
添加或新增一个问答
:param user_id: 用户id
:param group_id: 群号
:param problem: 问题
:param answer: 回答
:param format_: 格式化数据
"""
_str = None
if format_:
_str = ""
for x, y in format_:
_str += f"{x}<_s>{y}<format>"
return await cls._problem_answer_handle(
user_id, group_id, problem, "add", answer=answer, format_=_str
)
@classmethod
async def delete_problem_answer(
cls, user_id: int, group_id: Optional[int], problem: str, index: Optional[int]
) -> str:
"""
删除某问题一个或全部回答
:param user_id: 用户id
:param group_id: 群号
:param problem: 问题
:param index: 回答下标
"""
return await cls._problem_answer_handle(
user_id, group_id, problem, "delete", index=index
)
@classmethod
async def get_problem_answer(
cls, user_id: int, group_id: Optional[int], problem: str
) -> List[str]:
"""
获取问题的所有回答
:param user_id: 用户id
:param group_id: 群号
:param problem: 问题
"""
return await cls._problem_answer_handle(user_id, group_id, problem, "get")
@classmethod
async def get_group_all_answer(cls, group_id: int, problem: str) -> List[str]:
"""
获取群聊指定词条所有回答
:param group_id: 群号
:param problem: 问题
"""
if problem.startswith("id:"):
problem_index = int(problem.split(":")[-1])
q = await cls.get_group_all_problem(group_id)
if len(q) > problem_index:
problem = q[problem_index]
q = await cls.query.where(
(cls.group_id == group_id) & (cls.problem == problem)
).gino.all()
return [x.answer for x in q] if q else None
@classmethod
async def get_group_all_problem(cls, group_id: int) -> List[str]:
"""
获取群聊所有词条
:param group_id: 群号
"""
q = await cls.query.where(cls.group_id == group_id).gino.all()
q = [x.problem for x in q]
q.sort()
_tmp = []
for problem in q:
if "[_to_me" in problem:
r = re.search(r"\[_to_me\|(.*?)](.*)", problem)
if r:
bot_name = r.group(1)
problem = problem.replace(f"[_to_me|{bot_name}]", bot_name)
_tmp.append(problem)
return list(set(_tmp))
@classmethod
async def check(cls, group_id: int, problem: str, is_tome: bool = False) -> Optional["WordBank"]:
"""
检测词条并随机返回
:param group_id: 群号
:param problem: 问题
:param is_tome:是否at真寻
"""
if is_tome:
q = await cls.query.where(
(cls.group_id == group_id)
).gino.all()
q = [x for x in q if "[_to_me" in x.problem]
if q:
for x in q:
r = re.search(r"\[_to_me\|(.*?)](.*)", x.problem)
if r and r.group(2) == problem:
return x
return None
else:
q = await cls.query.where(
(cls.group_id == group_id) & (cls.problem == problem)
).gino.all()
return random.choice(q) if q else None
@classmethod
async def _problem_answer_handle(
cls,
user_id: int,
group_id: Optional[int],
problem: str,
type_: str,
*,
answer: Optional[str] = None,
index: Optional[int] = None,
format_: Optional[str] = None,
) -> Union[List[Union[str, Tuple[str, str]]], bool, str]:
"""
添加或新增一个问答
:param user_id: 用户id
:param group_id: 群号
:param problem: 问题
:param type_: 操作类型
:param answer: 回答
:param format_: 格式化数据
"""
if problem.startswith("id:"):
problem_index = int(problem.split(":")[-1])
q = await cls.get_group_all_problem(group_id)
if not q:
return []
if len(q) > problem_index:
problem = q[problem_index]
if group_id:
q = cls.query.where((cls.group_id == group_id) & (cls.problem == problem))
else:
q = cls.query.where((cls.user_qq == user_id) & (cls.problem == problem))
if type_ == "add":
q = await q.where(cls.answer == answer).gino.all()
if not q or ".jpg" in format_:
await cls.create(
user_qq=user_id,
group_id=group_id,
problem=problem,
answer=answer,
format=format_,
create_time=datetime.now().date(),
update_time=datetime.now().date(),
)
return True
elif type_ == "delete":
q = await q.with_for_update().gino.all()
if q:
path = DATA_PATH / "word_bank" / f"{group_id}"
if index is not None:
_q = [x.problem for x in q]
_q.sort()
prob = _q[index]
index = [x.problem for x in q].index(prob)
q = [q[index]]
answer = "\n".join([x.answer for x in q])
for x in q:
format_ = x.format
if format_:
for sp in format_.split("<format>")[:-1]:
_, image_name = sp.split("<_s>")
if image_name.endswith("jpg"):
_path = path / image_name
if _path.exists():
_path.unlink()
await cls.delete.where(
(cls.problem == problem)
& (cls.answer == x.answer)
& (cls.group_id == group_id)
).gino.status()
return answer
elif type_ == "get":
q = await q.gino.all()
if q:
return [(x.answer, x.format.split("<format>")[:-1]) for x in q]
return False | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/word_bank/model.py | model.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, Message, GroupMessageEvent
from nonebot.permission import SUPERUSER
from utils.utils import is_number, get_message_img
from utils.message_builder import image
from utils.message_builder import text as _text
from services.log import logger
from utils.message_builder import at
from nonebot.params import CommandArg
__zx_plugin_name__ = "联系管理员"
__plugin_usage__ = """
usage:
有什么话想对管理员说嘛?
指令:
[滴滴滴]/滴滴滴- ?[文本] ?[图片]
示例:滴滴滴- 我喜欢你
""".strip()
__plugin_superuser_usage__ = """
superuser usage:
管理员对消息的回复
指令[以下qq与group均为乱打]:
/t: 查看当前存储的消息
/t [qq] [group] [文本]: 在group回复指定用户
/t [qq] [文本]: 私聊用户
/t -1 [group] [文本]: 在group内发送消息
/t [id] [文本]: 回复指定id的对话,id在 /t 中获取
示例:/t 73747222 32848432 你好啊
示例:/t 73747222 你好不好
示例:/t -1 32848432 我不太好
示例:/t 0 我收到你的话了
"""
__plugin_des__ = "跨越空间与时间跟管理员对话"
__plugin_cmd__ = [
"滴滴滴-/[滴滴滴] ?[文本] ?[图片]",
"/t [_superuser]",
"t [qq] [group] [文本] [_superuser]",
"/t [qq] [文本] [_superuser]",
"/t -1 [group] [_superuser]",
"/t [id] [文本] [_superuser]",
]
__plugin_type__ = ("联系管理员",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["滴滴滴-", "滴滴滴"],
}
dialogue_data = {}
dialogue = on_command("[滴滴滴]", aliases={"滴滴滴-"}, priority=5, block=True)
reply = on_command("/t", priority=1, permission=SUPERUSER, block=True)
@dialogue.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
text = arg.extract_plain_text().strip()
img_msg = _text("")
for img in get_message_img(event.json()):
img_msg += image(img)
if not text and not img_msg:
await dialogue.send("请发送[滴滴滴]+您要说的内容~", at_sender=True)
else:
group_id = 0
group_name = "None"
nickname = event.sender.nickname
if isinstance(event, GroupMessageEvent):
group_id = event.group_id
group_name = (await bot.get_group_info(group_id=event.group_id))[
"group_name"
]
nickname = event.sender.card or event.sender.nickname
for coffee in bot.config.superusers:
await bot.send_private_msg(
user_id=int(coffee),
message=_text(
f"*****一份交流报告*****\n"
f"昵称:{nickname}({event.user_id})\n"
f"群聊:{group_name}({group_id})\n"
f"消息:{text}"
)
+ img_msg,
)
await dialogue.send(
_text(f"您的话已发送至管理员!\n======\n{text}") + img_msg, at_sender=True
)
nickname = event.sender.nickname if event.sender.nickname else event.sender.card
dialogue_data[len(dialogue_data)] = {
"nickname": nickname,
"user_id": event.user_id,
"group_id": group_id,
"group_name": group_name,
"msg": _text(text) + img_msg,
}
# print(dialogue_data)
logger.info(f"Q{event.user_id}@群{group_id} 联系管理员:text:{text}")
@reply.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
result = "*****待回复消息总览*****\n"
for key in dialogue_data.keys():
result += (
f"id:{key}\n"
f'\t昵称:{dialogue_data[key]["nickname"]}({dialogue_data[key]["user_id"]})\n'
f'\t群群:{dialogue_data[key]["group_name"]}({dialogue_data[key]["group_id"]})\n'
f'\t消息:{dialogue_data[key]["msg"]}'
f"\n--------------------\n"
)
await reply.finish(Message(result[:-1]))
msg = msg.split()
text = ""
group_id = 0
user_id = -1
if is_number(msg[0]):
if len(msg[0]) < 3:
msg[0] = int(msg[0])
if msg[0] >= 0:
id_ = msg[0]
user_id = dialogue_data[id_]["user_id"]
group_id = dialogue_data[id_]["group_id"]
text = " ".join(msg[1:])
dialogue_data.pop(id_)
else:
user_id = 0
if is_number(msg[1]):
group_id = int(msg[1])
text = " ".join(msg[2:])
else:
await reply.finish("群号错误...", at_sender=True)
else:
user_id = int(msg[0])
if is_number(msg[1]) and len(msg[1]) > 5:
group_id = int(msg[1])
text = " ".join(msg[2:])
else:
group_id = 0
text = " ".join(msg[1:])
else:
await reply.finish("第一参数,请输入数字.....", at_sender=True)
for img in get_message_img(event.json()):
text += image(img)
if group_id:
if user_id:
await bot.send_group_msg(
group_id=group_id, message=at(user_id) + "\n管理员回复\n=======\n" + text
)
else:
await bot.send_group_msg(group_id=group_id, message=text)
await reply.finish("消息发送成功...", at_sender=True)
else:
if user_id in [qq["user_id"] for qq in await bot.get_friend_list()]:
await bot.send_private_msg(
user_id=user_id, message="管理员回复\n=======\n" + text
)
await reply.finish("发送成功", at_sender=True)
else:
await reply.send(
f"对象不是{list(bot.config.nickname)[0]}的好友...", at_sender=True
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/dialogue/__init__.py | __init__.py |
from nonebot import on_command
from .data_source import from_anime_get_info
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.typing import T_State
from configs.config import Config
from utils.message_builder import custom_forward_msg
from nonebot.params import CommandArg, ArgStr
__zx_plugin_name__ = "搜番"
__plugin_usage__ = f"""
usage:
搜索动漫资源
指令:
搜番 [番剧名称或者关键词]
示例:搜番 刀剑神域
""".strip()
__plugin_des__ = "找不到想看的动漫吗?"
__plugin_cmd__ = ["搜番 [番剧名称或者关键词]"]
__plugin_type__ = ("一些工具",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["搜番"],
}
__plugin_block_limit__ = {"rst": "搜索还未完成,不要重复触发!"}
__plugin_configs__ = {
"SEARCH_ANIME_MAX_INFO": {"value": 20, "help": "搜索动漫返回的最大数量", "default_value": 20}
}
search_anime = on_command("搜番", aliases={"搜动漫"}, priority=5, block=True)
@search_anime.handle()
async def _(state: T_State, arg: Message = CommandArg()):
if arg.extract_plain_text().strip():
state["anime"] = arg.extract_plain_text().strip()
@search_anime.got("anime", prompt="是不是少了番名?")
async def _(bot: Bot, event: MessageEvent, state: T_State, key_word: str = ArgStr("anime")):
await search_anime.send(f"开始搜番 {key_word}", at_sender=True)
anime_report = await from_anime_get_info(
key_word,
Config.get_config("search_anime", "SEARCH_ANIME_MAX_INFO"),
)
if anime_report:
if isinstance(event, GroupMessageEvent):
mes_list = custom_forward_msg(anime_report, bot.self_id)
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
else:
await search_anime.send("\n\n".join(anime_report))
logger.info(
f"USER {event.user_id} GROUP"
f" {event.group_id if isinstance(event, GroupMessageEvent) else 'private'} 搜索番剧 {key_word} 成功"
)
else:
logger.warning(f"未找到番剧 {key_word}")
await search_anime.send(f"未找到番剧 {key_word}(也有可能是超时,再尝试一下?)") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/search_anime/__init__.py | __init__.py |
from configs.path_config import TEXT_PATH
from typing import List, Union
from utils.http_utils import AsyncHttpx
from utils.image_utils import text2image
from utils.message_builder import image
from nonebot.adapters.onebot.v11 import MessageSegment
import ujson as json
china_city = TEXT_PATH / "china_city.json"
data = {}
url = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5"
async def get_yiqing_data(area: str) -> Union[str, MessageSegment]:
"""
查看疫情数据
:param area: 省份/城市
"""
global data
province = None
city = None
province_type = "省"
if area == "中国":
province = area
province_type = ""
elif area[-1] == '省' or (area in data.keys() and area[-1] != "市"):
province = area if area[-1] != "省" else area[:-1]
if len(data[province]) == 1:
province_type = "市"
city = ""
else:
area = area[:-1] if area[-1] == "市" else area
for p in data.keys():
if area in data[p]:
province = p
city = area
epidemic_data = json.loads((await AsyncHttpx.get(url)).json()["data"])
last_update_time = epidemic_data["lastUpdateTime"]
if area == "中国":
data_ = epidemic_data["areaTree"][0]
else:
try:
data_ = [
x
for x in epidemic_data["areaTree"][0]["children"]
if x["name"] == province
][0]
if city:
data_ = [x for x in data_["children"] if x["name"] == city][0]
except IndexError:
return "未查询到..."
confirm = data_["total"]["confirm"] # 累计确诊
heal = data_["total"]["heal"] # 累计治愈
dead = data_["total"]["dead"] # 累计死亡
now_confirm = data_["total"]["nowConfirm"] # 目前确诊
add_confirm = data_["today"]["confirm"] # 新增确诊
grade = ""
_grade_color = ""
if data_["total"].get("grade"):
grade = data_["total"]["grade"]
if "中风险" in grade:
_grade_color = "#fa9424"
else:
_grade_color = "red"
dead_rate = f"{dead / confirm * 100:.2f}" # 死亡率
heal_rate = f"{heal / confirm * 100:.2f}" # 治愈率
x = f"{city}市" if city else f"{province}{province_type}"
return image(b64=(await text2image(
f"""
{x} 疫情数据 {f"(<f font_color={_grade_color}>{grade}</f>)" if grade else ""}:
目前确诊:
确诊人数:<f font_color=red>{now_confirm}(+{add_confirm})</f>
-----------------
累计数据:
确诊人数:<f font_color=red>{confirm}</f>
治愈人数:<f font_color=#39de4b>{heal}</f>
死亡人数:<f font_color=#191d19>{dead}</f>
治愈率:{heal_rate}%
死亡率:{dead_rate}%
更新日期:{last_update_time}
""", font_size=30, color="#f9f6f2"
)).pic2bs4())
def get_city_and_province_list() -> List[str]:
"""
获取城市省份列表
"""
global data
if not data:
try:
with open(china_city, "r", encoding="utf8") as f:
data = json.load(f)
except FileNotFoundError:
data = {}
city_list = ["中国"]
for p in data.keys():
for c in data[p]:
city_list.append(c)
city_list.append(p)
return city_list | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/yiqing/data_source.py | data_source.py |
from utils.http_utils import AsyncHttpx
from nonebot.adapters.onebot.v11 import MessageSegment
from typing import Optional
from services.log import logger
from utils.image_utils import text2image
from utils.message_builder import image
from json.decoder import JSONDecodeError
import re
import json
__doc__ = """爬虫实现国外疫情数据(找不到好接口)"""
def intcomma(value) -> str:
"""
数字格式化
"""
orig = str(value)
new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1>,\g<2>", orig)
return new if orig == new else intcomma(new)
async def get_other_data(place: str, count: int = 0) -> Optional[MessageSegment]:
"""
:param place: 地名
:param count: 递归次数
:return: 格式化字符串
"""
if count == 5:
return None
try:
html = (
(await AsyncHttpx.get("https://news.ifeng.com/c/special/7uLj4F83Cqm"))
.text.replace("\n", "")
.replace(" ", "")
)
find_data = re.compile(r"varallData=(.*?);</script>")
sum_ = re.findall(find_data, html)[0]
sum_ = json.loads(sum_)
except JSONDecodeError:
return await get_other_data(place, count + 1)
except Exception as e:
logger.error(f"疫情查询发生错误 {type(e)}:{e}")
return None
try:
other_country = sum_["yiqing_v2"]["dataList"][29]["child"]
for country in other_country:
if place == country["name2"]:
return image(
b64=(await text2image(
f" {place} 疫情数据:\n"
"——————————————\n"
f" 新增病例:<f font_color=red>{intcomma(country['quezhen_add'])}</f>\n"
f" 现有确诊:<f font_color=red>{intcomma(country['quezhen_xianyou'])}</f>\n"
f" 累计确诊:<f font_color=red>{intcomma(country['quezhen'])}</f>\n"
f" 累计治愈:<f font_color=#39de4b>{intcomma(country['zhiyu'])}</f>\n"
f" 死亡:{intcomma(country['siwang'])}\n"
"——————————————"
# f"更新时间:{country['sys_publishDateTime']}"
# 时间无法精确到分钟,网页用了js我暂时找不到
,
font_size=30,
color="#f9f6f2",
padding=15
)).pic2bs4()
)
else:
for city in country["child"]:
if place == city["name3"]:
return image(
b64=(await text2image(
f"\n{place} 疫情数据:\n"
"——————————————\n"
f"\t新增病例:<f font_color=red>{intcomma(city['quezhen_add'])}</f>\n"
f"\t累计确诊:<f font_color=red>{intcomma(city['quezhen'])}</f>\n"
f"\t累计治愈:<f font_color=#39de4b>{intcomma(city['zhiyu'])}</f>\n"
f"\t死亡:{intcomma(city['siwang'])}\n"
"——————————————\n",
font_size=30,
color="#f9f6f2",
padding=15
)).pic2bs4()
)
except Exception as e:
logger.error(f"疫情查询发生错误 {type(e)}:{e}")
return None | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/yiqing/other_than.py | other_than.py |
from nonebot import on_command
from .data_source import get_yiqing_data, get_city_and_province_list
from services.log import logger
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg
from configs.config import NICKNAME
from .other_than import get_other_data
__zx_plugin_name__ = "疫情查询"
__plugin_usage__ = """
usage:
全国疫情查询
指令:
疫情 中国/美国/英国...
疫情 [省份/城市]
* 当省份与城市重名时,可在后添加 "市" 或 "省" *
示例:疫情 吉林 <- [省]
示例:疫情 吉林市 <- [市]
""".strip()
__plugin_des__ = "实时疫情数据查询"
__plugin_cmd__ = ["疫情 [省份/城市]", "疫情 中国"]
__plugin_type__ = ("一些工具",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier & yzyyz1387"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["查询疫情", "疫情", "疫情查询"],
}
yiqing = on_command("疫情", aliases={"查询疫情", "疫情查询"}, priority=5, block=True)
@yiqing.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
city_and_province_list = get_city_and_province_list()
if msg:
if msg in city_and_province_list or msg[:-1] in city_and_province_list:
result = await get_yiqing_data(msg)
if result:
await yiqing.send(result)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询疫情: {msg}"
)
else:
await yiqing.send("查询失败!!!!", at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询疫情失败"
)
else:
rely = await get_other_data(msg)
if rely:
await yiqing.send(rely)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询疫情成功"
)
else:
await yiqing.send(f"{NICKNAME}没有查到{msg}的疫情查询...") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/yiqing/__init__.py | __init__.py |
from services.db_context import db
from typing import List, Optional
class Setu(db.Model):
__tablename__ = "setu"
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
local_id = db.Column(db.Integer(), nullable=False)
title = db.Column(db.String(), nullable=False)
author = db.Column(db.String(), nullable=False)
pid = db.Column(db.BigInteger(), nullable=False)
img_hash = db.Column(db.String(), nullable=False)
img_url = db.Column(db.String(), nullable=False)
is_r18 = db.Column(db.Boolean(), nullable=False)
tags = db.Column(db.String())
_idx1 = db.Index("setu_pid_img_url_idx1", "pid", "img_url", unique=True)
@classmethod
async def add_setu_data(
cls,
local_id: int,
title: str,
author: str,
pid: int,
img_hash: str,
img_url: str,
tags: str,
):
"""
说明:
添加一份色图数据
参数:
:param local_id: 本地存储id
:param title: 标题
:param author: 作者
:param pid: 图片pid
:param img_hash: 图片hash值
:param img_url: 图片链接
:param tags: 图片标签
"""
if not await cls._check_exists(pid, img_url):
await cls.create(
local_id=local_id,
title=title,
author=author,
pid=pid,
img_hash=img_hash,
img_url=img_url,
is_r18=True if "R-18" in tags else False,
tags=tags,
)
@classmethod
async def query_image(
cls,
local_id: Optional[int] = None,
tags: Optional[List[str]] = None,
r18: int = 0,
limit: int = 50,
):
"""
说明:
通过tag查找色图
参数:
:param local_id: 本地色图 id
:param tags: tags
:param r18: 是否 r18,0:非r18 1:r18 2:混合
:param limit: 获取数量
"""
if local_id:
flag = True if r18 == 1 else False
return await cls.query.where(
(cls.local_id == local_id) & (cls.is_r18 == flag)
).gino.first()
if r18 == 0:
query = cls.query.where(cls.is_r18 == False)
elif r18 == 1:
query = cls.query.where(cls.is_r18 == True)
else:
query = cls.query
if tags:
for tag in tags:
query = query.where(cls.tags.contains(tag) | cls.title.contains(tag) | cls.author.contains(tag))
query = query.order_by(db.func.random()).limit(limit)
return await query.gino.all()
@classmethod
async def get_image_count(cls, r18: int = 0) -> int:
"""
说明:
查询图片数量
"""
flag = False if r18 == 0 else True
setattr(Setu, 'count', db.func.count(cls.local_id).label('count'))
count = await cls.select('count').where(cls.is_r18 == flag).gino.first()
return count[0]
@classmethod
async def get_image_in_hash(cls, img_hash: str) -> "Setu":
"""
说明:
通过图像hash获取图像信息
参数:
:param img_hash: = 图像hash值
"""
query = await cls.query.where(cls.img_hash == img_hash).gino.first()
return query
@classmethod
async def _check_exists(cls, pid: int, img_url: str) -> bool:
"""
说明:
检测图片是否存在
参数:
:param pid: 图片pid
:param img_url: 图片链接
"""
return bool(
await cls.query.where(
(cls.pid == pid) & (cls.img_url == img_url)
).gino.first()
)
@classmethod
async def delete_image(cls, pid: int) -> int:
"""
说明:
删除图片并替换
参数:
:param pid: 图片pid
"""
query = await cls.query.where(cls.pid == pid).gino.first()
if query:
is_r18 = query.is_r18
num = await cls.get_image_count(is_r18)
x = await cls.query.where((cls.is_r18 == is_r18) & (cls.local_id == num - 1)).gino.first()
_tmp_local_id = x.local_id
if x:
x.update(local_id=query.local_id).apply()
await cls.delete.where(cls.pid == pid).gino.status()
return _tmp_local_id
return -1
@classmethod
async def update_setu_data(
cls,
pid: int,
*,
local_id: Optional[int] = None,
title: Optional[str] = None,
author: Optional[str] = None,
img_hash: Optional[str] = None,
img_url: Optional[str] = None,
tags: Optional[str] = None,
) -> bool:
"""
说明:
根据PID修改图片数据
参数:
:param local_id: 本地id
:param pid: 图片pid
:param title: 标题
:param author: 作者
:param img_hash: 图片hash值
:param img_url: 图片链接
:param tags: 图片标签
"""
query = cls.query.where(cls.pid == pid).with_for_update()
image_list = await query.gino.all()
if image_list:
for image in image_list:
if local_id:
await image.update(local_id=local_id).apply()
if title:
await image.update(title=title).apply()
if author:
await image.update(author=author).apply()
if img_hash:
await image.update(img_hash=img_hash).apply()
if img_url:
await image.update(img_url=img_url).apply()
if tags:
await image.update(tags=tags).apply()
return True
return False
@classmethod
async def get_all_setu(cls) -> List["Setu"]:
"""
说明:
获取所有图片对象
"""
return await cls.query.gino.all() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/send_setu_/_model.py | _model.py |
from configs.path_config import IMAGE_PATH, TEXT_PATH, TEMP_PATH
from services.log import logger
from datetime import datetime
from utils.image_utils import compressed_image, get_img_hash
from utils.utils import get_bot
from PIL import UnidentifiedImageError
from .._model import Setu
from asyncpg.exceptions import UniqueViolationError
from configs.config import Config
from utils.http_utils import AsyncHttpx
from nonebot import Driver
import nonebot
import os
import ujson as json
import shutil
driver: Driver = nonebot.get_driver()
_path = IMAGE_PATH
# 替换旧色图数据,修复local_id一直是50的问题
@driver.on_startup
async def update_old_setu_data():
path = TEXT_PATH
setu_data_file = path / "setu_data.json"
r18_data_file = path / "r18_setu_data.json"
if setu_data_file.exists() or r18_data_file.exists():
index = 0
r18_index = 0
count = 0
fail_count = 0
for file in [setu_data_file, r18_data_file]:
if file.exists():
data = json.load(open(file, "r", encoding="utf8"))
for x in data:
if file == setu_data_file:
idx = index
if "R-18" in data[x]["tags"]:
data[x]["tags"].remove("R-18")
else:
idx = r18_index
img_url = (
data[x]["img_url"].replace("i.pixiv.cat", "i.pximg.net")
if "i.pixiv.cat" in data[x]["img_url"]
else data[x]["img_url"]
)
# idx = r18_index if 'R-18' in data[x]["tags"] else index
try:
await Setu.add_setu_data(
idx,
data[x]["title"],
data[x]["author"],
data[x]["pid"],
data[x]["img_hash"],
img_url,
",".join(data[x]["tags"]),
)
count += 1
if "R-18" in data[x]["tags"]:
r18_index += 1
else:
index += 1
logger.info(f'添加旧色图数据成功 PID:{data[x]["pid"]} index:{idx}....')
except UniqueViolationError:
fail_count += 1
logger.info(
f'添加旧色图数据失败,色图重复 PID:{data[x]["pid"]} index:{idx}....'
)
file.unlink()
setu_url_path = path / "setu_url.json"
setu_r18_url_path = path / "setu_r18_url.json"
if setu_url_path.exists():
setu_url_path.unlink()
if setu_r18_url_path.exists():
setu_r18_url_path.unlink()
logger.info(f"更新旧色图数据完成,成功更新数据:{count} 条,累计失败:{fail_count} 条")
# 删除色图rar文件夹
shutil.rmtree(IMAGE_PATH / "setu_rar", ignore_errors=True)
shutil.rmtree(IMAGE_PATH / "r18_rar", ignore_errors=True)
shutil.rmtree(IMAGE_PATH / "rar", ignore_errors=True)
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
async def update_setu_img(flag: bool = False):
"""
更新色图
:param flag: 是否手动更新
"""
image_list = await Setu.get_all_setu()
image_list.reverse()
_success = 0
error_info = []
error_type = []
count = 0
for image in image_list:
count += 1
path = _path / "_r18" if image.is_r18 else _path / "_setu"
local_image = path / f"{image.local_id}.jpg"
path.mkdir(exist_ok=True, parents=True)
TEMP_PATH.mkdir(exist_ok=True, parents=True)
if not local_image.exists() or not image.img_hash:
temp_file = TEMP_PATH / f"{image.local_id}.jpg"
if temp_file.exists():
temp_file.unlink()
url_ = image.img_url
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url_ = url_.replace("i.pximg.net", ws_url).replace(
"i.pixiv.cat", ws_url
)
try:
if not await AsyncHttpx.download_file(
url_, TEMP_PATH / f"{image.local_id}.jpg"
):
continue
_success += 1
try:
if (
os.path.getsize(
TEMP_PATH / f"{image.local_id}.jpg",
)
> 1024 * 1024 * 1.5
):
compressed_image(
TEMP_PATH / f"{image.local_id}.jpg",
path / f"{image.local_id}.jpg",
)
else:
logger.info(
f"不需要压缩,移动图片{TEMP_PATH}/{image.local_id}.jpg "
f"--> /{path}/{image.local_id}.jpg"
)
os.rename(
TEMP_PATH / f"/{image.local_id}.jpg",
path / f"{image.local_id}.jpg",
)
except FileNotFoundError:
logger.warning(f"文件 {image.local_id}.jpg 不存在,跳过...")
continue
img_hash = str(get_img_hash(f"{path}/{image.local_id}.jpg"))
await Setu.update_setu_data(image.pid, img_hash=img_hash)
except UnidentifiedImageError:
# 图片已删除
with open(local_image, 'r') as f:
if '404 Not Found' in f.read():
max_num = await Setu.delete_image(image.pid)
local_image.unlink()
os.rename(path / f"{max_num}.jpg", local_image)
logger.warning(f"更新色图 PID:{image.pid} 404,已删除并替换")
except Exception as e:
_success -= 1
logger.error(f"更新色图 {image.local_id}.jpg 错误 {type(e)}: {e}")
if type(e) not in error_type:
error_type.append(type(e))
error_info.append(f"更新色图 {image.local_id}.jpg 错误 {type(e)}: {e}")
else:
logger.info(f"更新色图 {image.local_id}.jpg 已存在")
if _success or error_info or flag:
await get_bot().send_private_msg(
user_id=int(list(get_bot().config.superusers)[0]),
message=f'{str(datetime.now()).split(".")[0]} 更新 色图 完成,本地存在 {count} 张,实际更新 {_success} 张,'
f"以下为更新时未知错误:\n" + "\n".join(error_info),
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/send_setu_/update_setu/data_source.py | data_source.py |
from configs.path_config import IMAGE_PATH, TEMP_PATH
from utils.message_builder import image
from services.log import logger
from utils.image_utils import get_img_hash, compressed_image
from asyncpg.exceptions import UniqueViolationError
from asyncio.exceptions import TimeoutError
from typing import List, Optional
from configs.config import NICKNAME, Config
from utils.http_utils import AsyncHttpx
from .._model import Setu
import asyncio
import os
import random
try:
import ujson as json
except ModuleNotFoundError:
import json
url = "https://api.lolicon.app/setu/v2"
path = "_setu"
r18_path = "_r18"
# 获取url
async def get_setu_urls(
tags: List[str], num: int = 1, r18: int = 0, command: str = ""
) -> "List[str], List[str], List[tuple], int":
tags = tags[:3] if len(tags) > 3 else tags
params = {
"r18": r18, # 添加r18参数 0为否,1为是,2为混合
"tag": tags, # 若指定tag
"num": 100, # 一次返回的结果数量
"size": ["original"],
}
for count in range(3):
logger.info(f"get_setu_url: count --> {count}")
try:
response = await AsyncHttpx.get(
url, timeout=Config.get_config("send_setu", "TIMEOUT"), params=params
)
if response.status_code == 200:
data = response.json()
if not data["error"]:
data = data["data"]
(
urls,
text_list,
add_databases_list,
) = await asyncio.get_event_loop().run_in_executor(
None, _setu_data_process, data, command
)
num = num if num < len(data) else len(data)
random_idx = random.sample(range(len(data)), num)
x_urls = []
x_text_lst = []
for x in random_idx:
x_urls.append(urls[x])
x_text_lst.append(text_list[x])
if not x_urls:
return ["没找到符合条件的色图..."], [], [], 401
return x_urls, x_text_lst, add_databases_list, 200
else:
return ["没找到符合条件的色图..."], [], [], 401
except TimeoutError:
pass
except Exception as e:
logger.error(f"send_setu 访问页面错误 {type(e)}:{e}")
return ["我网线被人拔了..QAQ"], [], [], 999
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
async def search_online_setu(
url_: str, id_: Optional[int] = None, path_: Optional[str] = None
) -> "MessageSegment, int":
"""
下载色图
:param url_: 色图url
:param id_: 本地id
:param path_: 存储路径
"""
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url_ = url_.replace("i.pximg.net", ws_url).replace("i.pixiv.cat", ws_url)
index = random.randint(1, 100000) if id_ is None else id_
path_ = IMAGE_PATH / path_ if path_ else TEMP_PATH
file_name = f"{index}_temp_setu.jpg" if path_ == TEMP_PATH else f"{index}.jpg"
path_.mkdir(parents=True, exist_ok=True)
for i in range(3):
logger.info(f"search_online_setu --> {i}")
try:
if not await AsyncHttpx.download_file(
url_,
path_ / file_name,
timeout=Config.get_config("send_setu", "TIMEOUT"),
):
continue
if id_ is not None:
if (
os.path.getsize(path_ / f"{index}.jpg")
> 1024 * 1024 * 1.5
):
compressed_image(
path_ / f"{index}.jpg",
)
logger.info(f"下载 lolicon 图片 {url_} 成功, id:{index}")
return image(path_ / file_name), index
except TimeoutError:
pass
except Exception as e:
logger.error(f"send_setu 下载图片错误 {type(e)}:{e}")
return "图片被小怪兽恰掉啦..!QAQ", -1
# 检测本地是否有id涩图,无的话则下载
async def check_local_exists_or_download(setu_image: Setu) -> "MessageSegment, int":
path_ = None
id_ = None
if Config.get_config("send_setu", "DOWNLOAD_SETU"):
id_ = setu_image.local_id
path_ = r18_path if setu_image.is_r18 else path
file = IMAGE_PATH / path_ / f"{setu_image.local_id}.jpg"
if file.exists():
return image(f"{setu_image.local_id}.jpg", path_), 200
return await search_online_setu(setu_image.img_url, id_, path_)
# 添加涩图数据到数据库
async def add_data_to_database(lst: List[tuple]):
tmp = []
for x in lst:
if x not in tmp:
tmp.append(x)
if tmp:
for x in tmp:
try:
r18 = 1 if "R-18" in x[5] else 0
idx = await Setu.get_image_count(r18)
await Setu.add_setu_data(
idx,
x[0],
x[1],
x[2],
x[3],
x[4],
x[5],
)
except UniqueViolationError:
pass
# 拿到本地色图列表
async def get_setu_list(
index: Optional[int] = None, tags: Optional[List[str]] = None, r18: int = 0
) -> "list, int":
if index:
image_count = await Setu.get_image_count(r18) - 1
if index < 0 or index > image_count:
return [f"超过当前上下限!({image_count})"], 999
image_list = [await Setu.query_image(index, r18=r18)]
elif tags:
image_list = await Setu.query_image(tags=tags, r18=r18)
else:
image_list = await Setu.query_image(r18=r18)
if not image_list:
return ["没找到符合条件的色图..."], 998
return image_list, 200
# 初始化消息
def gen_message(setu_image: Setu, img_msg: bool = False) -> str:
local_id = setu_image.local_id
title = setu_image.title
author = setu_image.author
pid = setu_image.pid
if Config.get_config("send_setu", "SHOW_INFO"):
return (
f"id:{local_id}\n"
f"title:{title}\n"
f"author:{author}\n"
f"PID:{pid}\n"
f"{image(f'{local_id}', f'{r18_path if setu_image.is_r18 else path}') if img_msg else ''}"
)
return f"{image(f'{local_id}', f'{r18_path if setu_image.is_r18 else path}') if img_msg else ''}"
# 罗翔老师!
def get_luoxiang(impression):
probability = (
impression + Config.get_config("send_setu", "INITIAL_SETU_PROBABILITY") * 100
)
if probability < random.randint(1, 101):
return (
"我为什么要给你发这个?"
+ image(random.choice(os.listdir(IMAGE_PATH / "luoxiang")), "luoxiang")
+ f"\n(快向{NICKNAME}签到提升好感度吧!)"
)
return None
async def get_setu_count(r18: int) -> int:
"""
获取色图数量
:param r18: r18类型
"""
return await Setu.get_image_count(r18)
async def find_img_index(img_url, user_id):
if not await AsyncHttpx.download_file(
img_url,
TEMP_PATH / f"{user_id}_find_setu_index.jpg",
timeout=Config.get_config("send_setu", "TIMEOUT"),
):
return "检索图片下载上失败..."
img_hash = str(get_img_hash(TEMP_PATH / f"{user_id}_find_setu_index.jpg"))
setu_img = await Setu.get_image_in_hash(img_hash)
if setu_img:
return (
f"id:{setu_img.local_id}\n"
f"title:{setu_img.title}\n"
f"author:{setu_img.author}\n"
f"PID:{setu_img.pid}"
)
return "该图不在色图库中或色图库未更新!"
# 处理色图数据
def _setu_data_process(data: dict, command: str) -> "list, list, list":
urls = []
text_list = []
add_databases_list = []
for i in range(len(data)):
img_url = data[i]["urls"]["original"]
img_url = (
img_url.replace("i.pixiv.cat", "i.pximg.net")
if "i.pixiv.cat" in img_url
else img_url
)
title = data[i]["title"]
author = data[i]["author"]
pid = data[i]["pid"]
urls.append(img_url)
text_list.append(f"title:{title}\nauthor:{author}\nPID:{pid}")
tags = []
for j in range(len(data[i]["tags"])):
tags.append(data[i]["tags"][j])
if command != "色图r":
if "R-18" in tags:
tags.remove("R-18")
add_databases_list.append(
(
title,
author,
pid,
"",
img_url,
",".join(tags),
)
)
return urls, text_list, add_databases_list | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/send_setu_/send_setu/data_source.py | data_source.py |
import random
from nonebot import on_command, on_regex
from services.log import logger
from models.sign_group_user import SignGroupUser
from nonebot.message import run_postprocessor
from nonebot.matcher import Matcher
from typing import Optional, Type
from gino.exceptions import UninitializedError
from utils.utils import (
is_number,
get_message_img,
)
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
PrivateMessageEvent,
Message,
Event,
)
from .data_source import (
get_setu_list,
get_luoxiang,
search_online_setu,
get_setu_urls,
find_img_index,
gen_message,
check_local_exists_or_download,
add_data_to_database,
get_setu_count,
)
from nonebot.adapters.onebot.v11.exception import ActionFailed
from configs.config import Config, NICKNAME
from utils.manager import withdraw_message_manager
from nonebot.params import CommandArg, Command
from typing import Tuple
import re
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "色图"
__plugin_usage__ = f"""
usage:
搜索 lolicon 图库,每日色图time...
指令:
色图: 随机本地色图
色图r: 随机在线十张r18涩图
色图 [id]: 本地指定id色图
色图 *[tags]: 在线搜索指定tag色图
色图r *[tags]: 同上
[1-9]张涩图: 本地随机色图连发
[1-9]张[tags]的涩图: 指定tag色图连发
示例:色图 萝莉|少女 白丝|黑丝
示例:色图 萝莉 猫娘
注:
tag至多取前20项,| 为或,萝莉|少女=萝莉或者少女
""".strip()
__plugin_des__ = "不要小看涩图啊混蛋!"
__plugin_cmd__ = ["色图 ?[id]", "色图 ?[tags]", "色图r ?[tags]", "[1-9]张?[tags]色图"]
__plugin_type__ = ("来点好康的",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 9,
"default_status": True,
"limit_superuser": False,
"cmd": ["色图", "涩图", "瑟图"],
}
__plugin_block_limit__ = {}
__plugin_cd_limit__ = {
"rst": "您冲的太快了,请稍后再冲.",
}
__plugin_configs__ = {
"WITHDRAW_SETU_MESSAGE": {
"value": (0, 1),
"help": "自动撤回,参1:延迟撤回色图时间(秒),0 为关闭 | 参2:监控聊天类型,0(私聊) 1(群聊) 2(群聊+私聊)",
"default_value": (0, 1),
},
"ONLY_USE_LOCAL_SETU": {
"value": False,
"help": "仅仅使用本地色图,不在线搜索",
"default_value": False,
},
"INITIAL_SETU_PROBABILITY": {
"value": 0.7,
"help": "初始色图概率,总概率 = 初始色图概率 + 好感度",
"default_value": 0.7,
},
"DOWNLOAD_SETU": {
"value": True,
"help": "是否存储下载的色图,使用本地色图可以加快图片发送速度",
"default_value": True,
},
"TIMEOUT": {"value": 10, "help": "色图下载超时限制(秒)", "default_value": 10},
"SHOW_INFO": {"value": True, "help": "是否显示色图的基本信息,如PID等", "default_value": True},
}
Config.add_plugin_config("pixiv", "PIXIV_NGINX_URL", "i.pixiv.re", help_="Pixiv反向代理")
setu_data_list = []
@run_postprocessor
async def do_something(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: Event,
state: T_State,
):
global setu_data_list
if isinstance(event, MessageEvent):
if matcher.plugin_name == "send_setu":
# 添加数据至数据库
try:
await add_data_to_database(setu_data_list)
logger.info("色图数据自动存储数据库成功...")
setu_data_list = []
except UninitializedError:
pass
setu = on_command(
"色图", aliases={"涩图", "不够色", "来一发", "再来点", "色图r"}, priority=5, block=True
)
setu_reg = on_regex("(.*)[份|发|张|个|次|点](.*)[瑟|色|涩]图$", priority=5, block=True)
@setu.handle()
async def _(
event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()
):
msg = arg.extract_plain_text().strip()
if isinstance(event, GroupMessageEvent):
impression = (
await SignGroupUser.ensure(event.user_id, event.group_id)
).impression
luox = get_luoxiang(impression)
if luox:
await setu.finish(luox)
r18 = 0
num = 1
# 是否看r18
if cmd[0] == "色图r" and isinstance(event, PrivateMessageEvent):
r18 = 1
num = 10
elif cmd[0] == "色图r" and isinstance(event, GroupMessageEvent):
await setu.finish(
random.choice(["这种不好意思的东西怎么可能给这么多人看啦", "羞羞脸!给我滚出克私聊!", "变态变态变态变态大变态!"])
)
# 有 数字 的话先尝试本地色图id
if msg and is_number(msg):
setu_list, code = await get_setu_list(int(msg), r18=r18)
if code != 200:
await setu.finish(setu_list[0], at_sender=True)
setu_img, code = await check_local_exists_or_download(setu_list[0])
msg_id = await setu.send(gen_message(setu_list[0]) + setu_img, at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送色图 {setu_list[0].local_id}.png"
)
if msg_id:
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
return
await send_setu_handle(setu, event, cmd[0], msg, num, r18)
num_key = {
"一": 1,
"二": 2,
"两": 2,
"双": 2,
"三": 3,
"四": 4,
"五": 5,
"六": 6,
"七": 7,
"八": 8,
"九": 9,
}
@setu_reg.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
if isinstance(event, GroupMessageEvent):
impression = (
await SignGroupUser.ensure(event.user_id, event.group_id)
).impression
luox = get_luoxiang(impression)
if luox:
await setu.finish(luox, at_sender=True)
msg = arg.extract_plain_text().strip()
num = 1
msg = re.search(r"(.*)[份发张个次点](.*)[瑟涩色]图", msg)
# 解析 tags 以及 num
if msg:
num = msg.group(1)
tags = msg.group(2)
if tags:
tags = tags[:-1] if tags[-1] == "的" else tags
if num:
num = num[-1]
if num_key.get(num):
num = num_key[num]
elif is_number(num):
try:
num = int(num)
except ValueError:
num = 1
else:
num = 1
else:
return
await send_setu_handle(setu_reg, event, "色图", tags, num, 0)
async def send_setu_handle(
matcher: Type[Matcher],
event: MessageEvent,
command: str,
msg: str,
num: int,
r18: int,
):
global setu_data_list
# 非 id,在线搜索
tags = msg.split()
# 真寻的色图?怎么可能
if f"{NICKNAME}" in tags:
await matcher.finish("咳咳咳,虽然我很可爱,但是我木有自己的色图~~~有的话记得发我一份呀")
# 本地先拿图,下载失败补上去
setu_list, code = None, 200
setu_count = await get_setu_count(r18)
if (
not Config.get_config("send_setu", "ONLY_USE_LOCAL_SETU") and tags
) or setu_count <= 0:
# 先尝试获取在线图片
urls, text_list, add_databases_list, code = await get_setu_urls(
tags, num, r18, command
)
for x in add_databases_list:
setu_data_list.append(x)
# 未找到符合的色图,想来本地应该也没有
if code == 401:
await setu.finish(urls[0], at_sender=True)
if code == 200:
for i in range(len(urls)):
try:
setu_img, index = await search_online_setu(urls[i])
# 下载成功的话
if index != -1:
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送色图 {index}.png"
)
msg_id = await matcher.send(
Message(f"{text_list[i]}\n{setu_img}")
)
else:
if setu_list is None:
setu_list, code = await get_setu_list(tags=tags, r18=r18)
if code != 200:
await setu.finish(setu_list[0], at_sender=True)
if setu_list:
setu_image = random.choice(setu_list)
setu_list.remove(setu_image)
msg_id = await matcher.send(
Message(
gen_message(setu_image)
+ (
await check_local_exists_or_download(setu_image)
)[0]
)
)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送本地色图 {setu_image.local_id}.png"
)
else:
msg_id = await matcher.send(text_list[i] + "\n" + setu_img)
if msg_id:
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
except ActionFailed:
await matcher.finish("坏了,这张图色过头了,我自己看看就行了!", at_sender=True)
return
if code != 200:
await matcher.finish("网络连接失败...", at_sender=True)
# 本地无图
if setu_list is None:
setu_list, code = await get_setu_list(tags=tags, r18=r18)
if code != 200:
await matcher.finish(setu_list[0], at_sender=True)
# 开始发图
for _ in range(num):
if not setu_list:
await setu.finish("坏了,已经没图了,被榨干了!")
setu_image = random.choice(setu_list)
setu_list.remove(setu_image)
try:
msg_id = await matcher.send(
Message(
gen_message(setu_image)
+ (await check_local_exists_or_download(setu_image))[0]
)
)
withdraw_message_manager.withdraw_message(
event,
msg_id["message_id"],
Config.get_config("send_setu", "WITHDRAW_SETU_MESSAGE"),
)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送本地色图 {setu_image.local_id}.png"
)
except ActionFailed:
await matcher.finish("坏了,这张图色过头了,我自己看看就行了!", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/send_setu_/send_setu/__init__.py | __init__.py |
from nonebot import on_command
from .data_source import get_price, update_buff_cookie
from services.log import logger
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.rule import to_me
from nonebot.permission import SUPERUSER
from nonebot.params import CommandArg, ArgStr
from configs.config import NICKNAME
__zx_plugin_name__ = "BUFF查询皮肤"
__plugin_usage__ = """
usage:
在线实时获取BUFF指定皮肤所有磨损底价
指令:
查询皮肤 [枪械名] [皮肤名称]
示例:查询皮肤 ak47 二西莫夫
""".strip()
__plugin_des__ = "BUFF皮肤底价查询"
__plugin_cmd__ = ["查询皮肤 [枪械名] [皮肤名称]"]
__plugin_type__ = ("一些工具",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["查询皮肤"],
}
__plugin_block_limit__ = {"rst": "您有皮肤正在搜索,请稍等..."}
__plugin_configs__ = {
"BUFF_PROXY": {"value": None, "help": "BUFF代理,有些厂ip可能被屏蔽"},
"COOKIE": {"value": None, "help": "BUFF的账号cookie"},
}
search_skin = on_command("查询皮肤", aliases={"皮肤查询"}, priority=5, block=True)
@search_skin.handle()
async def _(event: MessageEvent, state: T_State, arg: Message = CommandArg()):
raw_arg = arg.extract_plain_text().strip()
if raw_arg:
args = raw_arg.split()
if len(args) >= 2:
state["name"] = args[0]
state["skin"] = args[1]
@search_skin.got("name", prompt="要查询什么武器呢?")
@search_skin.got("skin", prompt="要查询该武器的什么皮肤呢?")
async def arg_handle(
event: MessageEvent,
state: T_State,
name: str = ArgStr("name"),
skin: str = ArgStr("skin"),
):
if name in ["算了", "取消"] or skin in ["算了", "取消"]:
await search_skin.finish("已取消操作...")
result = ""
if name in ["ak", "ak47"]:
name = "ak-47"
name = name + " | " + skin
try:
result, status_code = await get_price(name)
except FileNotFoundError:
await search_skin.finish(f'请先对{NICKNAME}说"设置cookie"来设置cookie!')
if status_code in [996, 997, 998]:
await search_skin.finish(result)
if result:
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询皮肤:"
+ name
)
await search_skin.finish(result)
else:
logger.info(
f"USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}"
f" 查询皮肤:{name} 没有查询到"
)
await search_skin.finish("没有查询到哦,请检查格式吧")
update_buff_session = on_command(
"更新cookie", aliases={"设置cookie"}, rule=to_me(), permission=SUPERUSER, priority=1
)
@update_buff_session.handle()
async def _(event: MessageEvent):
await update_buff_session.finish(
update_buff_cookie(str(event.get_message())), at_sender=True
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/search_buff_skin_price/__init__.py | __init__.py |
from configs.path_config import DATA_PATH
from nonebot.matcher import Matcher
from nonebot.message import run_postprocessor
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from datetime import datetime
from utils.manager import plugins2settings_manager
from utils.utils import scheduler
from nonebot.typing import Optional
from pathlib import Path
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "功能调用统计 [Hidden]"
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
statistics_group_file = DATA_PATH / "statistics" / "_prefix_count.json"
statistics_user_file = DATA_PATH / "statistics" / "_prefix_user_count.json"
try:
with open(statistics_group_file, "r", encoding="utf8") as f:
_prefix_count_dict = json.load(f)
except (FileNotFoundError, ValueError):
_prefix_count_dict = {
"total_statistics": {
"total": {},
},
"day_statistics": {
"total": {},
},
"week_statistics": {
"total": {},
},
"month_statistics": {
"total": {},
},
"start_time": str(datetime.now().date()),
"day_index": 0,
}
try:
with open(statistics_user_file, "r", encoding="utf8") as f:
_prefix_user_count_dict = json.load(f)
except (FileNotFoundError, ValueError):
_prefix_user_count_dict = {
"total_statistics": {
"total": {},
},
"day_statistics": {
"total": {},
},
"week_statistics": {
"total": {},
},
"month_statistics": {
"total": {},
},
"start_time": str(datetime.now().date()),
"day_index": 0,
}
# 以前版本转换
if _prefix_count_dict.get("day_index") is None:
tmp = _prefix_count_dict.copy()
_prefix_count_dict = {
"total_statistics": tmp["total_statistics"],
"day_statistics": {
"total": {},
},
"week_statistics": {
"total": {},
},
"month_statistics": {
"total": {},
},
"start_time": tmp["start_time"],
"day_index": 0,
}
# 添加命令次数
@run_postprocessor
async def _(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: GroupMessageEvent,
state: T_State,
):
global _prefix_count_dict
if (
matcher.type == "message"
and matcher.priority not in [1, 9]
and matcher.plugin_name not in ["update_info", "statistics_handle"]
):
module = matcher.plugin_name
day_index = _prefix_count_dict["day_index"]
try:
group_id = str(event.group_id)
except AttributeError:
group_id = "total"
user_id = str(event.user_id)
plugin_name = plugins2settings_manager.get_plugin_data(module)
if plugin_name and plugin_name.get('cmd'):
plugin_name = plugin_name.get('cmd')[0]
check_exists_key(group_id, user_id, plugin_name)
for data in [_prefix_count_dict, _prefix_user_count_dict]:
data["total_statistics"]["total"][plugin_name] += 1
data["day_statistics"]["total"][plugin_name] += 1
data["week_statistics"]["total"][plugin_name] += 1
data["month_statistics"]["total"][plugin_name] += 1
# print(_prefix_count_dict)
if group_id != "total":
for data in [_prefix_count_dict, _prefix_user_count_dict]:
if data == _prefix_count_dict:
key = group_id
else:
key = user_id
data["total_statistics"][key][plugin_name] += 1
data["day_statistics"][key][plugin_name] += 1
data["week_statistics"][key][str(day_index % 7)][
plugin_name
] += 1
data["month_statistics"][key][str(day_index % 30)][
plugin_name
] += 1
with open(statistics_group_file, "w", encoding="utf8") as f:
json.dump(_prefix_count_dict, f, indent=4, ensure_ascii=False)
with open(
statistics_user_file, "w", encoding="utf8"
) as f:
json.dump(_prefix_user_count_dict, f, ensure_ascii=False, indent=4)
def check_exists_key(group_id: str, user_id: str, plugin_name: str):
global _prefix_count_dict, _prefix_user_count_dict
for data in [_prefix_count_dict, _prefix_user_count_dict]:
if data == _prefix_count_dict:
key = group_id
else:
key = user_id
if not data["total_statistics"]["total"].get(plugin_name):
data["total_statistics"]["total"][plugin_name] = 0
if not data["day_statistics"]["total"].get(plugin_name):
data["day_statistics"]["total"][plugin_name] = 0
if not data["week_statistics"]["total"].get(plugin_name):
data["week_statistics"]["total"][plugin_name] = 0
if not data["month_statistics"]["total"].get(plugin_name):
data["month_statistics"]["total"][plugin_name] = 0
if not data["total_statistics"].get(key):
data["total_statistics"][key] = {}
if not data["total_statistics"][key].get(plugin_name):
data["total_statistics"][key][plugin_name] = 0
if not data["day_statistics"].get(key):
data["day_statistics"][key] = {}
if not data["day_statistics"][key].get(plugin_name):
data["day_statistics"][key][plugin_name] = 0
if key != 'total':
if not data["week_statistics"].get(key):
data["week_statistics"][key] = {}
if data["week_statistics"][key].get("0") is None:
for i in range(7):
data["week_statistics"][key][str(i)] = {}
if data["week_statistics"][key]["0"].get(plugin_name) is None:
for i in range(7):
data["week_statistics"][key][str(i)][plugin_name] = 0
if not data["month_statistics"].get(key):
data["month_statistics"][key] = {}
if data["month_statistics"][key].get("0") is None:
for i in range(30):
data["month_statistics"][key][str(i)] = {}
if data["month_statistics"][key]["0"].get(plugin_name) is None:
for i in range(30):
data["month_statistics"][key][str(i)][plugin_name] = 0
# 天
@scheduler.scheduled_job(
"cron",
hour=0,
minute=1,
)
async def _():
for data in [_prefix_count_dict, _prefix_user_count_dict]:
data["day_index"] += 1
for x in data["day_statistics"].keys():
for key in data["day_statistics"][x].keys():
try:
data["day_statistics"][x][key] = 0
except KeyError:
pass
for type_ in ["week_statistics", "month_statistics"]:
index = str(
data["day_index"] % 7
if type_ == "week_statistics"
else data["day_index"] % 30
)
for x in data[type_].keys():
try:
for key in data[type_][x][index].keys():
data[type_][x][index][key] = 0
except KeyError:
pass
with open(statistics_group_file, "w", encoding="utf8") as f:
json.dump(_prefix_count_dict, f, indent=4, ensure_ascii=False)
with open(statistics_user_file, "w", encoding="utf8") as f:
json.dump(_prefix_user_count_dict, f, indent=4, ensure_ascii=False) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/statistics/statistics_hook.py | statistics_hook.py |
from configs.path_config import DATA_PATH
import nonebot
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
nonebot.load_plugins("plugins/statistics")
old_file1 = DATA_PATH / "_prefix_count.json"
old_file2 = DATA_PATH / "_prefix_user_count.json"
new_path = DATA_PATH / "statistics"
new_path.mkdir(parents=True, exist_ok=True)
if old_file1.exists():
os.rename(old_file1, new_path / "_prefix_count.json")
if old_file2.exists():
os.rename(old_file2, new_path / "_prefix_user_count.json")
# 修改旧数据
statistics_group_file = DATA_PATH / "statistics" / "_prefix_count.json"
statistics_user_file = DATA_PATH / "statistics" / "_prefix_user_count.json"
for file in [statistics_group_file, statistics_user_file]:
if file.exists():
with open(file, "r", encoding="utf8") as f:
data = json.load(f)
if not (statistics_group_file.parent / f"{file}.bak").exists():
with open(f"{file}.bak", "w", encoding="utf8") as wf:
json.dump(data, wf, ensure_ascii=False, indent=4)
for x in ["total_statistics", "day_statistics"]:
for key in data[x].keys():
num = 0
if data[x][key].get("ai") is not None:
if data[x][key].get("Ai") is not None:
data[x][key]["Ai"] += data[x][key]["ai"]
else:
data[x][key]["Ai"] = data[x][key]["ai"]
del data[x][key]["ai"]
if data[x][key].get("抽卡") is not None:
if data[x][key].get("游戏抽卡") is not None:
data[x][key]["游戏抽卡"] += data[x][key]["抽卡"]
else:
data[x][key]["游戏抽卡"] = data[x][key]["抽卡"]
del data[x][key]["抽卡"]
if data[x][key].get("我的道具") is not None:
num += data[x][key]["我的道具"]
del data[x][key]["我的道具"]
if data[x][key].get("使用道具") is not None:
num += data[x][key]["使用道具"]
del data[x][key]["使用道具"]
if data[x][key].get("我的金币") is not None:
num += data[x][key]["我的金币"]
del data[x][key]["我的金币"]
if data[x][key].get("购买") is not None:
num += data[x][key]["购买"]
del data[x][key]["购买"]
if data[x][key].get("商店") is not None:
data[x][key]["商店"] += num
else:
data[x][key]["商店"] = num
for x in ["week_statistics", "month_statistics"]:
for key in data[x].keys():
if key == "total":
if data[x][key].get("ai") is not None:
if data[x][key].get("Ai") is not None:
data[x][key]["Ai"] += data[x][key]["ai"]
else:
data[x][key]["Ai"] = data[x][key]["ai"]
del data[x][key]["ai"]
if data[x][key].get("抽卡") is not None:
if data[x][key].get("游戏抽卡") is not None:
data[x][key]["游戏抽卡"] += data[x][key]["抽卡"]
else:
data[x][key]["游戏抽卡"] = data[x][key]["抽卡"]
del data[x][key]["抽卡"]
if data[x][key].get("我的道具") is not None:
num += data[x][key]["我的道具"]
del data[x][key]["我的道具"]
if data[x][key].get("使用道具") is not None:
num += data[x][key]["使用道具"]
del data[x][key]["使用道具"]
if data[x][key].get("我的金币") is not None:
num += data[x][key]["我的金币"]
del data[x][key]["我的金币"]
if data[x][key].get("购买") is not None:
num += data[x][key]["购买"]
del data[x][key]["购买"]
if data[x][key].get("商店") is not None:
data[x][key]["商店"] += num
else:
data[x][key]["商店"] = num
else:
for day in data[x][key].keys():
num = 0
if data[x][key][day].get("ai") is not None:
if data[x][key][day].get("Ai") is not None:
data[x][key][day]["Ai"] += data[x][key][day]["ai"]
else:
data[x][key][day]["Ai"] = data[x][key][day]["ai"]
del data[x][key][day]["ai"]
if data[x][key][day].get("抽卡") is not None:
if data[x][key][day].get("游戏抽卡") is not None:
data[x][key][day]["游戏抽卡"] += data[x][key][day]["抽卡"]
else:
data[x][key][day]["游戏抽卡"] = data[x][key][day]["抽卡"]
del data[x][key][day]["抽卡"]
if data[x][key][day].get("我的道具") is not None:
num += data[x][key][day]["我的道具"]
del data[x][key][day]["我的道具"]
if data[x][key][day].get("使用道具") is not None:
num += data[x][key][day]["使用道具"]
del data[x][key][day]["使用道具"]
if data[x][key][day].get("我的金币") is not None:
num += data[x][key][day]["我的金币"]
del data[x][key][day]["我的金币"]
if data[x][key][day].get("购买") is not None:
num += data[x][key][day]["购买"]
del data[x][key][day]["购买"]
if data[x][key][day].get("商店") is not None:
data[x][key][day]["商店"] += num
else:
data[x][key][day]["商店"] = num
with open(file, "w", encoding="utf8") as f:
json.dump(data, f, ensure_ascii=False, indent=4) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/statistics/__init__.py | __init__.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from nonebot.params import CommandArg
from services.log import logger
from ._data_source import get_data, gen_wbtop_pic
from utils.utils import is_number
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncPlaywright
import asyncio
__zx_plugin_name__ = "微博热搜"
__plugin_usage__ = """
usage:
在QQ上吃个瓜
指令:
微博热搜:发送实时热搜
微博热搜 [id]:截图该热搜页面
示例:微博热搜 5
""".strip()
__plugin_des__ = "刚买完瓜,在吃瓜现场"
__plugin_cmd__ = ["微博热搜", "微博热搜 [id]"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["微博热搜"],
}
wbtop = on_command("wbtop", aliases={"微博热搜"}, priority=5, block=True)
wbtop_url = "https://v2.alapi.cn/api/new/wbtop"
wbtop_data = []
@wbtop.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
global wbtop_data
msg = arg.extract_plain_text().strip()
if not wbtop_data or not msg:
data, code = await get_data(wbtop_url)
if code != 200:
await wbtop.finish(data, at_sender=True)
wbtop_data = data["data"]
if not msg:
img = await asyncio.get_event_loop().run_in_executor(
None, gen_wbtop_pic, wbtop_data
)
await wbtop.send(img)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询微博热搜"
)
if is_number(msg) and 0 < int(msg) <= 50:
url = wbtop_data[int(msg) - 1]["url"]
try:
await wbtop.send("开始截取数据...")
img = await AsyncPlaywright.screenshot(
url,
f"{IMAGE_PATH}/temp/wbtop_{event.user_id}.png",
"#pl_feedlist_index",
sleep=5
)
await wbtop.send(img)
except Exception as e:
logger.error(f"微博热搜截图出错... {type(e)}: {e}")
await wbtop.send("发生了一些错误.....") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/alapi/wbtop.py | wbtop.py |
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from asyncio.exceptions import TimeoutError
from configs.config import Config
from utils.http_utils import AsyncHttpx
from typing import Optional
from services.log import logger
from pathlib import Path
import platform
if platform.system() == "Windows":
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6;"
" rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
"Referer": "https://www.pixiv.net",
}
async def get_pixiv_urls(
mode: str, num: int = 10, page: int = 1, date: Optional[str] = None
) -> "list, int":
"""
拿到pixiv rank图片url
:param mode: 模式
:param num: 数量
:param page: 页数
:param date: 日期
"""
params = {"mode": mode, "page": page}
if date:
params["date"] = date
hibiapi = Config.get_config("hibiapi", "HIBIAPI")
hibiapi = hibiapi[:-1] if hibiapi[-1] == "/" else hibiapi
rank_url = f"{hibiapi}/api/pixiv/rank"
return await parser_data(rank_url, num, params, "rank")
async def search_pixiv_urls(
keyword: str, num: int, page: int, r18: int
) -> "list, list":
"""
搜图图片的url
:param keyword: 关键词
:param num: 数量
:param page: 页数
:param r18: 是否r18
"""
params = {"word": keyword, "page": page}
hibiapi = Config.get_config("hibiapi", "HIBIAPI")
hibiapi = hibiapi[:-1] if hibiapi[-1] == "/" else hibiapi
search_url = f"{hibiapi}/api/pixiv/search"
return await parser_data(search_url, num, params, "search", r18)
async def parser_data(
url: str, num: int, params: dict, type_: str, r18: int = 0
) -> "list, int":
"""
解析数据
:param url: hibiapi搜索url
:param num: 数量
:param params: 参数
:param type_: 类型,rank或search
:param r18: 是否r18
"""
info_list = []
for _ in range(3):
try:
response = await AsyncHttpx.get(
url,
params=params,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
)
if response.status_code == 200:
data = response.json()
if data.get("illusts"):
data = data["illusts"]
break
except TimeoutError:
pass
except Exception as e:
logger.error(f"P站排行/搜图解析数据发生错误 {type(e)}:{e}")
return ["发生了一些些错误..."], 995
else:
return ["网络不太好?没有该页数?也许过一会就好了..."], 998
num = num if num < 30 else 30
_data = []
for x in data:
if x["page_count"] < Config.get_config("pixiv_rank_search", "MAX_PAGE_LIMIT"):
_data.append(x)
if len(_data) == num:
break
for x in _data:
if type_ == "search" and r18 == 1:
if "R-18" in str(x["tags"]):
continue
title = x["title"]
author = x["user"]["name"]
urls = []
if x["page_count"] == 1:
urls.append(x["image_urls"]["large"])
else:
for j in x["meta_pages"]:
urls.append(j["image_urls"]["large"])
info_list.append((title, author, urls))
return info_list, 200
async def download_pixiv_imgs(
urls: list, user_id: int, forward_msg_index: int = None
) -> str:
"""
下载图片
:param urls: 图片链接
:param user_id: 用户id
:param forward_msg_index: 转发消息中的图片排序
"""
result = ""
index = 0
for url in urls:
ws_url = Config.get_config("pixiv", "PIXIV_NGINX_URL")
if ws_url:
url = (
url.replace("i.pximg.net", ws_url)
.replace("i.pixiv.cat", ws_url)
.replace("_webp", "")
)
try:
file = (
f"{IMAGE_PATH}/temp/{user_id}_{forward_msg_index}_{index}_pixiv.jpg"
if forward_msg_index is not None
else f"{IMAGE_PATH}/temp/{user_id}_{index}_pixiv.jpg"
)
file = Path(file)
try:
if await AsyncHttpx.download_file(
url,
file,
timeout=Config.get_config("pixiv_rank_search", "TIMEOUT"),
):
if forward_msg_index is not None:
result += image(
f"{user_id}_{forward_msg_index}_{index}_pixiv.jpg",
"temp",
)
else:
result += image(f"{user_id}_{index}_pixiv.jpg", "temp")
index += 1
except OSError:
if file.exists():
file.unlink()
except Exception as e:
logger.error(f"P站排行/搜图下载图片错误 {type(e)}:{e}")
return result | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pixiv_rank_search/data_source.py | data_source.py |
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.matcher import Matcher
from nonebot.params import CommandArg
from nonebot import on_command
from utils.utils import is_number
from .data_source import get_pixiv_urls, download_pixiv_imgs, search_pixiv_urls
from services.log import logger
from nonebot.adapters.onebot.v11.exception import NetworkError
from asyncio.exceptions import TimeoutError
from utils.message_builder import custom_forward_msg
from configs.config import Config
from typing import Type
from nonebot.rule import to_me
import time
__zx_plugin_name__ = "P站排行/搜图"
__plugin_usage__ = """
usage:
P站排行:
可选参数:
类型:
1. 日排行
2. 周排行
3. 月排行
4. 原创排行
5. 新人排行
6. R18日排行
7. R18周排行
8. R18受男性欢迎排行
9. R18重口排行【慎重!】
【使用时选择参数序号即可,R18仅可私聊】
p站排行 ?[参数] ?[数量] ?[日期]
示例:
p站排行榜 [无参数默认为日榜]
p站排行榜 1
p站排行榜 1 5
p站排行榜 1 5 2018-4-25
【注意空格!!】【在线搜索会较慢】
---------------------------------
P站搜图:
搜图 [关键词] ?[数量] ?[页数=1] ?[r18](不屏蔽R-18)
示例:
搜图 樱岛麻衣
搜图 樱岛麻衣 5
搜图 樱岛麻衣 5 r18
【默认为 热度排序】
【注意空格!!】【在线搜索会较慢】【数量可能不符?可能该页数量不够,也可能被R-18屏蔽】
""".strip()
__plugin_des__ = "P站排行榜直接冲,P站搜图跟着冲"
__plugin_cmd__ = ["p站排行 ?[参数] ?[数量] ?[日期]", "搜图 [关键词] ?[数量] ?[页数=1] ?[r18](不屏蔽R-18)"]
__plugin_type__ = ("来点好康的",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 9,
"default_status": True,
"limit_superuser": False,
"cmd": ["p站排行", "搜图", "p站搜图", "P站搜图"],
}
__plugin_block_limit__ = {"rst": "P站排行榜或搜图正在搜索,请不要重复触发命令..."}
__plugin_configs__ = {
"TIMEOUT": {
"value": 10,
"help": "图片下载超时限制",
"default_value": 10
},
"MAX_PAGE_LIMIT": {
"value": 20,
"help": "作品最大页数限制,超过的作品会被略过",
"default_value": 20
}
}
Config.add_plugin_config(
"hibiapi",
"HIBIAPI",
"https://api.obfs.dev",
help_="如果没有自建或其他hibiapi请不要修改",
default_value="https://api.obfs.dev",
)
Config.add_plugin_config(
"pixiv",
"PIXIV_NGINX_URL",
"i.pixiv.re",
help_="Pixiv反向代理"
)
rank_dict = {
"1": "day",
"2": "week",
"3": "month",
"4": "week_original",
"5": "week_rookie",
"6": "day_r18",
"7": "week_r18",
"8": "day_male_r18",
"9": "week_r18g",
}
pixiv_rank = on_command(
"p站排行",
aliases={"P站排行榜", "p站排行榜", "P站排行榜", "P站排行"},
priority=5,
block=True,
rule=to_me(),
)
pixiv_keyword = on_command("搜图", priority=5, block=True, rule=to_me())
@pixiv_rank.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip().strip()
msg = msg.split(" ")
msg = [m for m in msg if m]
code = 0
info_list = []
if not msg:
msg = ["1"]
if msg[0] in ["6", "7", "8", "9"]:
if event.message_type == "group":
await pixiv_rank.finish("羞羞脸!私聊里自己看!", at_sender=True)
if (n := len(msg)) == 0 or msg[0] == "":
info_list, code = await get_pixiv_urls(rank_dict.get("1"))
elif n == 1:
if msg[0] not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
await pixiv_rank.finish("要好好输入要看什么类型的排行榜呀!", at_sender=True)
info_list, code = await get_pixiv_urls(rank_dict.get(msg[0]))
elif n == 2:
info_list, code = await get_pixiv_urls(rank_dict.get(msg[0]), int(msg[1]))
elif n == 3:
if not check_date(msg[2]):
await pixiv_rank.finish("日期格式错误了", at_sender=True)
info_list, code = await get_pixiv_urls(
rank_dict.get(msg[0]), int(msg[1]), date=msg[2]
)
else:
await pixiv_rank.finish("格式错了噢,参数不够?看看帮助?", at_sender=True)
if code != 200 and info_list:
await pixiv_rank.finish(info_list[0])
if not info_list:
await pixiv_rank.finish("没有找到啊,等等再试试吧~V", at_sender=True)
await send_image(info_list, pixiv_rank, bot, event)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看了P站排行榜 code:{msg[0]}"
)
@pixiv_keyword.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if isinstance(event, GroupMessageEvent):
if "r18" in msg.lower():
await pixiv_keyword.finish("(脸红#) 你不会害羞的 八嘎!", at_sender=True)
r18 = 0 if "r18" in msg else 1
msg = msg.replace("r18", "").strip().split()
msg = [m.strip() for m in msg if m]
keyword = None
info_list = None
num = 10
page = 1
if (n := len(msg)) == 1:
keyword = msg[0]
if n > 1:
if not is_number(msg[1]):
await pixiv_keyword.finish("图片数量必须是数字!", at_sender=True)
num = int(msg[1])
if n > 2:
if not is_number(msg[2]):
await pixiv_keyword.finish("页数数量必须是数字!", at_sender=True)
page = int(msg[2])
if keyword:
info_list, code = await search_pixiv_urls(keyword, num, page, r18)
if code != 200:
await pixiv_keyword.finish(info_list[0])
if not info_list:
await pixiv_keyword.finish("没有找到啊,等等再试试吧~V", at_sender=True)
await send_image(info_list, pixiv_keyword, bot, event)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查看了搜索 {keyword} R18:{r18}"
)
def check_date(date):
try:
time.strptime(date, "%Y-%m-%d")
return True
except:
return False
async def send_image(
info_list: list, matcher: Type[Matcher], bot: Bot, event: MessageEvent
):
if isinstance(event, GroupMessageEvent):
await pixiv_rank.send("开始下载整理数据...")
idx = 0
mes_list = []
for title, author, urls in info_list:
_message = f"title: {title}\nauthor: {author}\n" + await download_pixiv_imgs(urls, event.user_id, idx)
mes_list.append(_message)
idx += 1
mes_list = custom_forward_msg(mes_list, bot.self_id)
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
else:
for title, author, urls in info_list:
try:
await matcher.send(
f"title: {title}\n"
f"author: {author}\n"
+ await download_pixiv_imgs(urls, event.user_id)
)
except (NetworkError, TimeoutError):
await matcher.send("这张图网络直接炸掉了!", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/pixiv_rank_search/__init__.py | __init__.py |
from utils.message_builder import image
from configs.path_config import TEXT_PATH
from configs.config import NICKNAME
from typing import List
from nonebot import Driver
from utils.http_utils import AsyncHttpx
import ujson as json
import nonebot
driver: Driver = nonebot.get_driver()
china_city = TEXT_PATH / "china_city.json"
data = {}
async def get_weather_of_city(city: str) -> str:
"""
获取城市天气数据
:param city: 城市
"""
code = _check_exists_city(city)
if code == 999:
return "不要查一个省份的天气啊,很累人的!"
elif code == 998:
return f"{NICKNAME}没查到!!试试查火星的天气?"
else:
data_json = json.loads(
(
await AsyncHttpx.get(
f"http://wthrcdn.etouch.cn/weather_mini?city={city}"
)
).text
)
if "desc" in data_json:
if data_json["desc"] == "invilad-citykey":
return f"{NICKNAME}没查到!!试试查火星的天气?" + image("shengqi", "zhenxun")
elif data_json["desc"] == "OK":
w_type = data_json["data"]["forecast"][0]["type"]
w_max = data_json["data"]["forecast"][0]["high"][3:]
w_min = data_json["data"]["forecast"][0]["low"][3:]
fengli = data_json["data"]["forecast"][0]["fengli"][9:-3]
ganmao = data_json["data"]["ganmao"]
fengxiang = data_json["data"]["forecast"][0]["fengxiang"]
repass = f"{city}的天气是 {w_type} 天\n最高温度: {w_max}\n最低温度: {w_min}\n风力: {fengli} {fengxiang}\n{ganmao}"
return repass
else:
return "好像出错了?再试试?"
def _check_exists_city(city: str) -> int:
"""
检测城市是否存在合法
:param city: 城市名称
"""
global data
city = city if city[-1] != "市" else city[:-1]
for province in data.keys():
for city_ in data[province]:
if city_ == city:
return 200
for province in data.keys():
if city == province:
return 999
return 998
def get_city_list() -> List[str]:
"""
获取城市列表
"""
global data
if not data:
try:
with open(china_city, "r", encoding="utf8") as f:
data = json.load(f)
except FileNotFoundError:
data = {}
city_list = []
for p in data.keys():
for c in data[p]:
city_list.append(c)
city_list.append(p)
return city_list | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/weather/data_source.py | data_source.py |
from datetime import datetime, timedelta
from models.sign_group_user import SignGroupUser
from models.group_member_info import GroupInfoUser
from models.bag_user import BagUser
from configs.config import NICKNAME
from nonebot.adapters.onebot.v11 import MessageSegment
from utils.image_utils import BuildImage, BuildMat
from services.db_context import db
from .utils import get_card, SIGN_TODAY_CARD_PATH
from typing import Optional
from services.log import logger
from .random_event import random_event
from utils.data_utils import init_rank
from utils.utils import get_user_avatar
from io import BytesIO
import random
import math
import asyncio
import secrets
import os
async def group_user_check_in(
nickname: str, user_qq: int, group: int
) -> MessageSegment:
"Returns string describing the result of checking in"
present = datetime.now()
async with db.transaction():
# 取得相应用户
user = await SignGroupUser.ensure(user_qq, group, for_update=True)
# 如果同一天签到过,特殊处理
if (
user.checkin_time_last + timedelta(hours=8)
).date() >= present.date() or f"{user}_{group}_sign_{datetime.now().date()}" in os.listdir(
SIGN_TODAY_CARD_PATH
):
gold = await BagUser.get_gold(user_qq, group)
return await get_card(user, nickname, -1, gold, "")
return await _handle_check_in(nickname, user_qq, group, present) # ok
async def check_in_all(nickname: str, user_qq: int):
"""
说明:
签到所有群
参数:
:param nickname: 昵称
:param user_qq: 用户qq
"""
async with db.transaction():
present = datetime.now()
for u in await SignGroupUser.get_user_all_data(user_qq):
group = u.group_id
if not ((
u.checkin_time_last + timedelta(hours=8)
).date() >= present.date() or f"{u}_{group}_sign_{datetime.now().date()}" in os.listdir(
SIGN_TODAY_CARD_PATH
)):
await _handle_check_in(nickname, user_qq, group, present)
async def _handle_check_in(
nickname: str, user_qq: int, group: int, present: datetime
) -> MessageSegment:
user = await SignGroupUser.ensure(user_qq, group, for_update=True)
impression_added = (secrets.randbelow(99)+1)/100
critx2 = random.random()
add_probability = user.add_probability
specify_probability = user.specify_probability
if critx2 + add_probability > 0.97:
impression_added *= 2
elif critx2 < specify_probability:
impression_added *= 2
await SignGroupUser.sign(user, impression_added, present)
gold = random.randint(1, 100)
gift, gift_type = random_event(user.impression)
if gift_type == "gold":
await BagUser.add_gold(user_qq, group, gold + gift)
gift = f"额外金币 + {gift}"
else:
await BagUser.add_gold(user_qq, group, gold)
await BagUser.add_property(user_qq, group, gift)
gift += ' + 1'
if critx2 + add_probability > 0.97 or critx2 < specify_probability:
logger.info(
f"(USER {user.user_qq}, GROUP {user.group_id})"
f" CHECKED IN successfully. score: {user.impression:.2f} "
f"(+{impression_added * 2:.2f}).获取金币:{gold + gift if gift == 'gold' else gold}"
)
return await get_card(user, nickname, impression_added, gold, gift, True)
else:
logger.info(
f"(USER {user.user_qq}, GROUP {user.group_id})"
f" CHECKED IN successfully. score: {user.impression:.2f} "
f"(+{impression_added:.2f}).获取金币:{gold + gift if gift == 'gold' else gold}"
)
return await get_card(user, nickname, impression_added, gold, gift)
async def group_user_check(nickname: str, user_qq: int, group: int) -> MessageSegment:
# 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 await get_card(user, nickname, None, gold, "", is_card_view=True)
async def group_impression_rank(group: int, num: int) -> Optional[BuildMat]:
user_qq_list, impression_list, _ = await SignGroupUser.get_all_impression(group)
return await init_rank("好感度排行榜", user_qq_list, impression_list, group, num)
async def random_gold(user_id, group_id, impression):
if impression < 1:
impression = 1
gold = random.randint(1, 100) + random.randint(1, int(impression))
if await BagUser.add_gold(user_id, group_id, gold):
return gold
else:
return 0
# 签到总榜
async def impression_rank(group_id: int, data: dict):
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)):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
if user not in data["0"]:
users.append(user)
impressions.append(impression)
groups.append(group)
else:
num += 1
for i in range(num):
impression = max(impression_list)
index = impression_list.index(impression)
user = user_qq_list[index]
group = group_list[index]
user_qq_list.pop(index)
impression_list.pop(index)
group_list.pop(index)
if user not in users and impression < 100000:
users.append(user)
impressions.append(impression)
groups.append(group)
return (await asyncio.gather(*[_pst(users, impressions, groups)]))[0]
async def _pst(users: list, impressions: list, groups: list):
lens = len(users)
count = math.ceil(lens / 33)
width = 10
idx = 0
A = BuildImage(1740, 3300, color="#FFE4C4")
for _ in range(count):
col_img = BuildImage(550, 3300, 550, 100, color="#FFE4C4")
for _ in range(33 if int(lens / 33) >= 1 else lens % 33 - 1):
idx += 1
if idx > 100:
break
impression = max(impressions)
index = impressions.index(impression)
user = users[index]
group = groups[index]
impressions.pop(index)
users.pop(index)
groups.pop(index)
try:
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] + "..."
ava = await get_user_avatar(user)
if ava:
ava = BuildImage(
50, 50, background=BytesIO(ava)
)
else:
ava = BuildImage(50, 50, color="white")
ava.circle()
bk = BuildImage(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:.2f}]")
col_img.paste(bk)
A.paste(col_img, (width, 0))
lens -= 33
width += 580
W = BuildImage(1740, 3700, color="#FFE4C4", font_size=130)
W.paste(A, (0, 260))
font_w, font_h = W.getsize(f"{NICKNAME}的好感度总榜")
W.text((int((1740 - font_w) / 2), int((260 - font_h) / 2)), f"{NICKNAME}的好感度总榜")
return W.pic2bs4() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/sign_in/group_user_checkin.py | group_user_checkin.py |
from .config import (
SIGN_RESOURCE_PATH,
SIGN_TODAY_CARD_PATH,
SIGN_BORDER_PATH,
SIGN_BACKGROUND_PATH,
lik2level,
lik2relation,
level2attitude,
weekdays,
)
from models.sign_group_user import SignGroupUser
from models.group_member_info import GroupInfoUser
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import Config
from utils.utils import get_user_avatar
from utils.image_utils import BuildImage
from utils.message_builder import image
from configs.config import NICKNAME
from pathlib import Path
from datetime import datetime
from typing import Optional, List
from nonebot import Driver
from io import BytesIO
import asyncio
import random
import nonebot
import os
driver: Driver = nonebot.get_driver()
@driver.on_startup
async def init_image():
SIGN_RESOURCE_PATH.mkdir(parents=True, exist_ok=True)
SIGN_TODAY_CARD_PATH.mkdir(exist_ok=True, parents=True)
await GroupInfoUser.add_member_info(114514, 114514, "", datetime.min, 0)
_u = await GroupInfoUser.get_member_info(114514, 114514)
if _u.uid is None:
await _u.update(uid=0).apply()
generate_progress_bar_pic()
clear_sign_data_pic()
async def get_card(
user: "SignGroupUser",
nickname: str,
add_impression: Optional[float],
gold: Optional[int],
gift: str,
is_double: bool = False,
is_card_view: bool = False,
) -> MessageSegment:
user_id = user.user_qq
date = datetime.now().date()
_type = "view" if is_card_view else "sign"
card_file = (
Path(SIGN_TODAY_CARD_PATH)
/ f"{user_id}_{user.group_id}_{_type}_{date}.png"
)
if card_file.exists():
return image(
f"{user_id}_{user.group_id}_{_type}_{date}.png", "sign/today_card"
)
else:
if add_impression == -1:
card_file = (
Path(SIGN_TODAY_CARD_PATH)
/ f"{user_id}_{user.group_id}_view_{date}.png"
)
if card_file.exists():
return image(
f"{user_id}_{user.group_id}_view_{date}.png",
"sign/today_card",
)
is_card_view = True
ava = BytesIO(await get_user_avatar(user_id))
uid = await GroupInfoUser.get_group_member_uid(
user.user_qq, user.group_id
)
impression_list = None
if is_card_view:
_, impression_list, _ = await SignGroupUser.get_all_impression(
user.group_id
)
return await asyncio.get_event_loop().run_in_executor(
None,
_generate_card,
user,
nickname,
user_id,
add_impression,
gold,
gift,
uid,
ava,
impression_list,
is_double,
is_card_view,
)
def _generate_card(
user: "SignGroupUser",
nickname: str,
user_id: int,
impression: Optional[float],
gold: Optional[int],
gift: str,
uid: str,
ava_bytes: BytesIO,
impression_list: List[float],
is_double: bool = False,
is_card_view: bool = False,
) -> MessageSegment:
ava_bk = BuildImage(140, 140, is_alpha=True)
ava_border = BuildImage(
140,
140,
background=SIGN_BORDER_PATH / "ava_border_01.png",
)
ava = BuildImage(102, 102, background=ava_bytes)
ava.circle()
ava_bk.paste(ava, center_type="center")
ava_bk.paste(ava_border, alpha=True, center_type="center")
info_img = BuildImage(250, 150, color=(255, 255, 255, 0), font_size=15)
level, next_impression, previous_impression = get_level_and_next_impression(
user.impression
)
info_img.text((0, 0), f"· 好感度等级:{level} [{lik2relation[level]}]")
info_img.text((0, 20), f"· {NICKNAME}对你的态度:{level2attitude[level]}")
info_img.text((0, 40), f"· 距离升级还差 {next_impression - user.impression:.2f} 好感度")
bar_bk = BuildImage(220, 20, background=SIGN_RESOURCE_PATH / "bar_white.png")
bar = BuildImage(220, 20, background=SIGN_RESOURCE_PATH / "bar.png")
bar_bk.paste(
bar,
(
-int(
220
* (
(next_impression - user.impression)
/ (next_impression - previous_impression)
)
),
0,
),
True,
)
font_size = 30
if "好感度双倍加持卡" in gift:
font_size = 20
gift_border = BuildImage(
270,
100,
background=SIGN_BORDER_PATH / "gift_border_02.png",
font_size=font_size,
)
gift_border.text((0, 0), gift, center_type="center")
bk = BuildImage(
876,
424,
background=SIGN_BACKGROUND_PATH
/ random.choice(os.listdir(SIGN_BACKGROUND_PATH)),
font_size=25,
)
A = BuildImage(876, 274, background=SIGN_RESOURCE_PATH / "white.png")
line = BuildImage(2, 180, color="black")
A.transparent(2)
A.paste(ava_bk, (25, 80), True)
A.paste(line, (200, 70))
nickname_img = BuildImage(
0,
0,
plain_text=nickname,
color=(255, 255, 255, 0),
font_size=50,
font_color=(255, 255, 255),
)
if uid:
uid = f"{uid}".rjust(12, "0")
uid = uid[:4] + " " + uid[4:8] + " " + uid[8:]
else:
uid = "XXXX XXXX XXXX"
uid_img = BuildImage(
0,
0,
plain_text=f"UID: {uid}",
color=(255, 255, 255, 0),
font_size=30,
font_color=(255, 255, 255),
)
sign_day_img = BuildImage(
0,
0,
plain_text=f"{user.checkin_count}",
color=(255, 255, 255, 0),
font_size=40,
font_color=(211, 64, 33),
)
lik_text1_img = BuildImage(
0, 0, plain_text="当前", color=(255, 255, 255, 0), font_size=20
)
lik_text2_img = BuildImage(
0,
0,
plain_text=f"好感度:{user.impression:.2f}",
color=(255, 255, 255, 0),
font_size=30,
)
watermark = BuildImage(
0,
0,
plain_text=f"{NICKNAME}@{datetime.now().year}",
color=(255, 255, 255, 0),
font_size=15,
font_color=(155, 155, 155),
)
today_data = BuildImage(300, 300, color=(255, 255, 255, 0), font_size=20)
if is_card_view:
today_sign_text_img = BuildImage(
0, 0, plain_text="", color=(255, 255, 255, 0), font_size=30
)
if impression_list:
impression_list.sort(reverse=True)
index = impression_list.index(user.impression)
rank_img = BuildImage(
0,
0,
plain_text=f"* 此群好感排名第 {index + 1} 位",
color=(255, 255, 255, 0),
font_size=30,
)
A.paste(rank_img, ((A.w - rank_img.w - 10), 20), True)
today_data.text(
(0, 0),
f"上次签到日期:{'从未' if user.checkin_time_last == datetime.min else user.checkin_time_last.date()}",
)
today_data.text((0, 25), f"总金币:{gold}")
default_setu_prob = Config.get_config("send_setu", "INITIAL_SETU_PROBABILITY") * 100
today_data.text(
(0, 50),
f"色图概率:{(default_setu_prob + user.impression if user.impression < 100 else 100):.2f}%",
)
today_data.text((0, 75), f"开箱次数:{(20 + int(user.impression / 3))}")
_type = "view"
else:
A.paste(gift_border, (570, 140), True)
today_sign_text_img = BuildImage(
0, 0, plain_text="今日签到", color=(255, 255, 255, 0), font_size=30
)
if is_double:
today_data.text((0, 0), f"好感度 + {impression / 2:.2f} × 2")
else:
today_data.text((0, 0), f"好感度 + {impression:.2f}")
today_data.text((0, 25), f"金币 + {gold}")
_type = "sign"
current_date = datetime.now()
week = current_date.isoweekday()
data = current_date.date()
hour = current_date.hour
minute = current_date.minute
second = current_date.second
data_img = BuildImage(
0,
0,
plain_text=f"时间:{data} {weekdays[week]} {hour}:{minute}:{second}",
color=(255, 255, 255, 0),
font_size=20,
)
bk.paste(nickname_img, (30, 15), True)
bk.paste(uid_img, (30, 85), True)
bk.paste(A, (0, 150), alpha=True)
bk.text((30, 167), "Accumulative check-in for")
_x = bk.getsize("Accumulative check-in for")[0] + sign_day_img.w + 45
bk.paste(sign_day_img, (346, 158), True)
bk.text((_x, 167), "days")
bk.paste(data_img, (220, 370), True)
bk.paste(lik_text1_img, (220, 240), True)
bk.paste(lik_text2_img, (262, 234), True)
bk.paste(bar_bk, (225, 275), True)
bk.paste(info_img, (220, 305), True)
bk.paste(today_sign_text_img, (550, 180), True)
bk.paste(today_data, (580, 220), True)
bk.paste(watermark, (15, 400), True)
bk.save(
SIGN_TODAY_CARD_PATH / f"{user_id}_{user.group_id}_{_type}_{data}.png"
)
return image(
f"{user_id}_{user.group_id}_{_type}_{data}.png", "sign/today_card"
)
def generate_progress_bar_pic():
bg_2 = (254, 1, 254)
bg_1 = (0, 245, 246)
bk = BuildImage(1000, 50, is_alpha=True)
img_x = BuildImage(50, 50, color=bg_2)
img_x.circle()
img_x.crop((25, 0, 50, 50))
img_y = BuildImage(50, 50, color=bg_1)
img_y.circle()
img_y.crop((0, 0, 25, 50))
A = BuildImage(950, 50)
width, height = A.size
step_r = (bg_2[0] - bg_1[0]) / width
step_g = (bg_2[1] - bg_1[1]) / width
step_b = (bg_2[2] - bg_1[2]) / width
for y in range(0, width):
bg_r = round(bg_1[0] + step_r * y)
bg_g = round(bg_1[1] + step_g * y)
bg_b = round(bg_1[2] + step_b * y)
for x in range(0, height):
A.point((y, x), fill=(bg_r, bg_g, bg_b))
bk.paste(img_y, (0, 0), True)
bk.paste(A, (25, 0))
bk.paste(img_x, (975, 0), True)
bk.save(SIGN_RESOURCE_PATH / "bar.png")
A = BuildImage(950, 50)
bk = BuildImage(1000, 50, is_alpha=True)
img_x = BuildImage(50, 50)
img_x.circle()
img_x.crop((25, 0, 50, 50))
img_y = BuildImage(50, 50)
img_y.circle()
img_y.crop((0, 0, 25, 50))
bk.paste(img_y, (0, 0), True)
bk.paste(A, (25, 0))
bk.paste(img_x, (975, 0), True)
bk.save(SIGN_RESOURCE_PATH / "bar_white.png")
def get_level_and_next_impression(impression: float):
if impression == 0:
return lik2level[10], 10, 0
keys = list(lik2level.keys())
for i in range(len(keys)):
if impression > keys[i]:
return lik2level[keys[i]], keys[i - 1], keys[i]
return lik2level[10], 10, 0
def clear_sign_data_pic():
date = datetime.now().date()
for file in os.listdir(SIGN_TODAY_CARD_PATH):
if str(date) not in file:
os.remove(SIGN_TODAY_CARD_PATH / file) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/sign_in/utils.py | utils.py |
from .group_user_checkin import (
group_user_check_in,
group_user_check,
group_impression_rank,
impression_rank,
check_in_all
)
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from nonebot.adapters.onebot.v11.permission import GROUP
from utils.message_builder import image
from nonebot import on_command
from utils.utils import scheduler
from nonebot.params import CommandArg
from pathlib import Path
from configs.path_config import DATA_PATH
from services.log import logger
from .utils import clear_sign_data_pic
from utils.utils import is_number
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "签到"
__plugin_usage__ = """
usage:
每日签到
会影响色图概率和开箱次数,以及签到的随机道具获取
指令:
签到 ?[all]: all代表签到所有群
我的签到
好感度排行
好感度总排行
* 签到时有 3% 概率 * 2 *
""".strip()
__plugin_des__ = "每日签到,证明你在这里"
__plugin_cmd__ = ["签到 ?[all]", "我的签到", "好感度排行", "好感度总排行"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["签到"],
}
__plugin_cd_limit__ = {}
__plugin_configs__ = {
"MAX_SIGN_GOLD": {"value": 200, "help": "签到好感度加成额外获得的最大金币数", "default_value": 200},
"SIGN_CARD1_PROB": {"value": 0.2, "help": "签到好感度双倍加持卡Ⅰ掉落概率", "default_value": 0.2},
"SIGN_CARD2_PROB": {
"value": 0.09,
"help": "签到好感度双倍加持卡Ⅱ掉落概率",
"default_value": 0.09,
},
"SIGN_CARD3_PROB": {
"value": 0.05,
"help": "签到好感度双倍加持卡Ⅲ掉落概率",
"default_value": 0.05,
},
}
_file = Path(f"{DATA_PATH}/not_show_sign_rank_user.json")
try:
data = json.load(open(_file, "r", encoding="utf8"))
except (FileNotFoundError, ValueError, TypeError):
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
)
@sign.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
nickname = event.sender.card or event.sender.nickname
await sign.send(
await group_user_check_in(nickname, event.user_id, event.group_id),
at_sender=True,
)
if arg.extract_plain_text().strip() == "all":
await check_in_all(nickname, event.user_id)
@my_sign.handle()
async def _(event: GroupMessageEvent):
nickname = event.sender.card or event.sender.nickname
await my_sign.send(
await group_user_check(nickname, event.user_id, event.group_id),
at_sender=True,
)
@sign_rank.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
num = arg.extract_plain_text().strip()
if is_number(num) and 51 > int(num) > 10:
num = int(num)
else:
num = 10
_image = await group_impression_rank(event.group_id, num)
if _image:
await sign_rank.send(image(b64=_image.pic2bs4()))
@total_sign_rank.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
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:
json.dump(data, f, ensure_ascii=False, indent=4)
@scheduler.scheduled_job(
"interval",
hours=1,
)
async def _():
try:
clear_sign_data_pic()
logger.info("清理日常签到图片数据数据完成....")
except Exception as e:
logger.error(f"清理日常签到图片数据数据失败..{type(e)}: {e}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/sign_in/__init__.py | __init__.py |
from utils.utils import get_bot, scheduler
from nonebot import on_command
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent
from services.log import logger
from configs.path_config import IMAGE_PATH
from .data_source import get_alc_image
from utils.manager import group_manager
from configs.config import Config
__zx_plugin_name__ = "原神老黄历"
__plugin_usage__ = """
usage:
有时候也该迷信一回!特别是运气方面
指令:
原神黄历
""".strip()
__plugin_des__ = "有时候也该迷信一回!特别是运气方面"
__plugin_cmd__ = ["原神黄历"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神黄历", "原神老黄历"],
}
__plugin_task__ = {"genshin_alc": "原神黄历提醒"}
Config.add_plugin_config(
"_task",
"DEFAULT_GENSHIN_ALC",
True,
help_="被动 原神黄历提醒 进群默认开关状态",
default_value=True,
)
almanac = on_command("原神黄历", priority=5, block=True)
ALC_PATH = IMAGE_PATH / "genshin" / "alc"
ALC_PATH.mkdir(parents=True, exist_ok=True)
@almanac.handle()
async def _(event: MessageEvent,):
alc_img = await get_alc_image(ALC_PATH)
if alc_img:
mes = alc_img + "\n ※ 黄历数据来源于 genshin.pub"
await almanac.send(mes)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送查看原神黄历"
)
else:
await almanac.send("黄历图片下载失败...")
@scheduler.scheduled_job(
"cron",
hour=10,
minute=25,
)
async def _():
# 每日提醒
bot = get_bot()
if bot:
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
alc_img = await get_alc_image(ALC_PATH)
if alc_img:
mes = "[[_task|genshin_alc]]" + alc_img + "\n ※ 黄历数据来源于 genshin.pub"
for gid in gl:
if await group_manager.check_group_task_status(gid, "genshin_alc"):
await bot.send_group_msg(group_id=int(gid), message="" + mes) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/almanac/__init__.py | __init__.py |
from configs.path_config import IMAGE_PATH, TEMP_PATH
from utils.image_utils import BuildImage
from typing import List, Dict, Optional
from utils.message_builder import image
from nonebot.adapters.onebot.v11 import MessageSegment
from utils.http_utils import AsyncHttpx
from utils.utils import get_user_avatar
from io import BytesIO
import random
import asyncio
import os
image_path = IMAGE_PATH / "genshin" / "genshin_card"
async def get_genshin_image(
user_id: int,
uid: str,
char_data_list: List[Dict],
role_data: Dict,
world_data_dict: Dict,
home_data_list: List[Dict],
char_detailed_dict: dict = None,
mys_data: Optional[List[Dict]] = None,
nickname: Optional[str] = None,
) -> MessageSegment:
"""
生成图片数据
:param user_id:用户qq
:param uid: 原神uid
:param char_data_list: 角色列表
:param role_data: 玩家数据
:param world_data_dict: 国家数据字典
:param home_data_list: 家园列表
:param char_detailed_dict: 角色武器字典
:param mys_data: 用户米游社数据
:param nickname: 用户昵称
"""
user_ava = BytesIO(await get_user_avatar(user_id))
return await asyncio.get_event_loop().run_in_executor(
None,
_get_genshin_image,
uid,
char_data_list,
role_data,
world_data_dict,
home_data_list,
char_detailed_dict,
mys_data,
nickname,
user_ava,
)
def _get_genshin_image(
uid: str,
char_data_list: List[Dict],
role_data: Dict,
world_data_dict: Dict,
home_data_list: List[Dict],
char_detailed_dict: dict = None,
mys_data: Optional[Dict] = None,
nickname: Optional[str] = None,
user_ava: Optional[BytesIO] = None,
) -> MessageSegment:
"""
生成图片数据
:param uid: 原神uid
:param char_data_list: 角色列表
:param role_data: 玩家数据
:param world_data_dict: 国家数据字典
:param home_data_list: 家园列表
:param char_detailed_dict: 角色武器字典
:param mys_data: 用户米游社数据
:param nickname: 用户昵称
:param user_ava:用户头像
"""
user_image = get_user_data_image(uid, role_data, mys_data, nickname, user_ava)
home_image = get_home_data_image(home_data_list)
country_image = get_country_data_image(world_data_dict)
char_image = get_char_data_image(char_data_list, char_detailed_dict)
top_bk = BuildImage(user_image.w, user_image.h + max([home_image.h, country_image.h]) + 100, color="#F9F6F2")
top_bk.paste(user_image, alpha=True)
top_bk.paste(home_image, (0, user_image.h + 50), alpha=True)
top_bk.paste(country_image, (home_image.w + 100, user_image.h + 50), alpha=True)
bar = BuildImage(1600, 200, font_size=50, color="#F9F6F2", font="HYWenHei-85W.ttf")
bar.text((50, 10), "角色背包", (104, 103, 101))
bar.line((50, 90, 1550, 90), (227, 219, 209), width=10)
foot = BuildImage(1700, 87, background=image_path / "head.png")
head = BuildImage(1700, 87, background=image_path / "head.png")
head.rotate(180)
middle = BuildImage(
1700, top_bk.h + bar.h + char_image.h, background=image_path / "middle.png"
)
A = BuildImage(middle.w, middle.h + foot.h + head.h)
A.paste(head, (-5, 0), True)
A.paste(middle, (0, head.h), True)
A.paste(foot, (0, head.h + middle.h), True)
A.crop((0, 0, A.w - 5, A.h))
if A.h - top_bk.h - bar.h - char_image.h > 200:
_h = A.h - top_bk.h - bar.h - char_image.h - 200
A.crop((0, 0, A.w, A.h - _h))
A.paste(foot, (0, A.h - 87))
A.paste(top_bk, (0, 100), center_type="by_width")
A.paste(bar, (50, top_bk.h + 80))
A.paste(char_image, (0, top_bk.h + bar.h + 10), center_type="by_width")
rand = random.randint(1, 10000)
A.resize(0.8)
A.save(TEMP_PATH / f"genshin_user_card_{rand}.png")
return image(TEMP_PATH / f"genshin_user_card_{rand}.png")
def get_user_data_image(
uid: str,
role_data: Dict,
mys_data: Optional[Dict] = None,
nickname: Optional[str] = None,
user_ava: Optional[BytesIO] = None,
) -> BuildImage:
"""
画出玩家基本数据
:param uid: 原神uid
:param role_data: 玩家数据
:param mys_data: 玩家米游社数据
:param nickname: 用户昵称
:param user_ava:用户头像
"""
if mys_data:
nickname = [x["nickname"] for x in mys_data if x["game_id"] == 2][0]
region = BuildImage(1440, 450, color="#E3DBD1", font="HYWenHei-85W.ttf")
region.circle_corner(30)
uname_img = BuildImage(
0,
0,
plain_text=nickname,
font_size=40,
color=(255, 255, 255, 0),
font="HYWenHei-85W.ttf",
)
uid_img = BuildImage(
0,
0,
plain_text=f"UID: {uid}",
font_size=25,
color=(255, 255, 255, 0),
font="HYWenHei-85W.ttf",
font_color=(21, 167, 89),
)
ava_bk = BuildImage(270, 270, background=image_path / "cover.png")
# 用户头像
if user_ava:
ava_img = BuildImage(200, 200, background=user_ava)
ava_img.circle()
ava_bk.paste(ava_img, alpha=True, center_type="center")
else:
ava_img = BuildImage(
245,
245,
background=image_path
/ "chars_ava"
/ random.choice(os.listdir(image_path / "chars_ava")),
)
ava_bk.paste(ava_img, (12, 16), alpha=True)
region.paste(uname_img, (int(170 + uid_img.w / 2 - uname_img.w / 2), 305), True)
region.paste(uid_img, (170, 355), True)
region.paste(ava_bk, (int(550 / 2 - ava_bk.w / 2), 40), True)
data_img = BuildImage(
800, 400, color="#E3DBD1", font="HYWenHei-85W.ttf", font_size=40
)
_height = 0
keys = [
["活跃天数", "成就达成", "获得角色", "深境螺旋"],
["华丽宝箱", "珍贵宝箱", "精致宝箱", "普通宝箱"],
["奇馈宝箱", "风神瞳", "岩神瞳", "雷神瞳"],
]
values = [
[
role_data["active_day_number"],
role_data["achievement_number"],
role_data["avatar_number"],
role_data["spiral_abyss"],
],
[
role_data["luxurious_chest_number"],
role_data["precious_chest_number"],
role_data["exquisite_chest_number"],
role_data["common_chest_number"],
],
[
role_data["magic_chest_number"],
role_data["anemoculus_number"],
role_data["geoculus_number"],
role_data["electroculus_number"],
],
]
for key, value in zip(keys, values):
_tmp_data_img = BuildImage(
800, 200, color="#E3DBD1", font="HYWenHei-85W.ttf", font_size=40
)
_width = 10
for k, v in zip(key, value):
t_ = BuildImage(
0,
0,
plain_text=k,
color=(255, 255, 255, 0),
font_color=(138, 143, 143),
font="HYWenHei-85W.ttf",
font_size=30,
)
tmp_ = BuildImage(
t_.w, t_.h + 70, color="#E3DBD1", font="HYWenHei-85W.ttf", font_size=40
)
tmp_.text((0, 0), str(v), center_type="by_width")
tmp_.paste(t_, (0, 50), True, "by_width")
_tmp_data_img.paste(tmp_, (_width if len(key) > 3 else _width + 15, 0))
_width += 200
data_img.paste(_tmp_data_img, (0, _height))
_height += _tmp_data_img.h - 70
region.paste(data_img, (510, 50))
return region
def get_home_data_image(home_data_list: List[Dict]) -> BuildImage:
"""
画出家园数据
:param home_data_list: 家园列表
"""
h = 130 + 300 * 4
region = BuildImage(
550, h, color="#E3DBD1", font="HYWenHei-85W.ttf", font_size=40
)
try:
region.text(
(0, 30), f'尘歌壶 Lv.{home_data_list[0]["level"]}', center_type="by_width"
)
region.text(
(0, region.h - 70), f'仙力: {home_data_list[0]["comfort_num"]}', center_type="by_width"
)
except (IndexError, KeyError):
region.text((0, 30), f"尘歌壶 Lv.0", center_type="by_width")
region.text((0, region.h - 70), f"仙力: 0", center_type="by_width")
region.circle_corner(30)
height = 100
homes = os.listdir(image_path / "homes")
homes.remove("lock.png")
homes.sort()
unlock_home = [x["name"] for x in home_data_list]
for i, file in enumerate(homes):
home_img = image_path / "homes" / file
x = BuildImage(500, 250, background=home_img)
if file.split(".")[0] not in unlock_home:
black_img = BuildImage(500, 250, color="black")
lock_img = BuildImage(0, 0, background=image_path / "homes" / "lock.png")
black_img.circle_corner(50)
black_img.transparent(1)
black_img.paste(lock_img, alpha=True, center_type="center")
x.paste(black_img, alpha=True)
else:
black_img = BuildImage(
500, 150, color="black", font="HYWenHei-85W.ttf", font_size=40
)
black_img.text((55, 55), file.split(".")[0], fill=(226, 211, 146))
black_img.transparent(1)
text_img = BuildImage(
0,
0,
plain_text="洞天等级",
font="HYWenHei-85W.ttf",
font_color=(203, 200, 184),
font_size=35,
color=(255, 255, 255, 0),
)
level_img = BuildImage(
0,
0,
plain_text=f'{home_data_list[0]["comfort_level_name"]}',
font="HYWenHei-85W.ttf",
font_color=(211, 213, 207),
font_size=30,
color=(255, 255, 255, 0),
)
black_img.paste(text_img, (270, 25), True)
black_img.paste(level_img, (278, 85), True)
x.paste(black_img, alpha=True, center_type="center")
x.circle_corner(50)
region.paste(x, (0, height), True, "by_width")
height += 300
return region
def get_country_data_image(world_data_dict: Dict) -> BuildImage:
"""
画出国家探索供奉等图像
:param world_data_dict: 国家数据字典
"""
region = BuildImage(790, 267 * len(world_data_dict), color="#F9F6F2")
height = 0
for country in ["蒙德", "龙脊雪山", "璃月", "稻妻", "渊下宫"]:
x = BuildImage(790, 250, color="#3A4467")
logo = BuildImage(180, 180, background=image_path / "logo" / f"{country}.png")
tmp_bk = BuildImage(770, 230, color="#606779")
tmp_bk.circle_corner(10)
content_bk = BuildImage(
755, 215, color="#3A4467", font_size=40, font="HYWenHei-85W.ttf"
)
content_bk.paste(logo, (50, 0), True, "by_height")
if country in ["蒙德", "璃月"]:
content_bk.text((300, 40), "探索", fill=(239, 211, 114))
content_bk.text(
(450, 40),
f"{world_data_dict[country]['exploration_percentage'] / 10}%",
fill=(255, 255, 255),
)
content_bk.text((300, 120), "声望", fill=(239, 211, 114))
content_bk.text(
(450, 120),
f"Lv.{world_data_dict[country]['level']}",
fill=(255, 255, 255),
)
elif country in ["龙脊雪山"]:
content_bk.text((300, 40), "探索", fill=(239, 211, 114))
content_bk.text(
(450, 40),
f"{world_data_dict[country]['exploration_percentage'] / 10}%",
fill=(255, 255, 255),
)
content_bk.text((300, 120), "供奉", fill=(239, 211, 114))
content_bk.text(
(450, 120),
f"Lv.{world_data_dict[country]['offerings'][0]['level']}",
fill=(255, 255, 255),
)
elif country in ["稻妻"]:
content_bk.text((300, 20), "探索", fill=(239, 211, 114))
content_bk.text(
(450, 20),
f"{world_data_dict[country]['exploration_percentage'] / 10}%",
fill=(255, 255, 255),
)
content_bk.text((300, 85), "声望", fill=(239, 211, 114))
content_bk.text(
(450, 85),
f"Lv.{world_data_dict[country]['level']}",
fill=(255, 255, 255),
)
content_bk.text((300, 150), "神樱", fill=(239, 211, 114))
content_bk.text(
(450, 150),
f"Lv.{world_data_dict[country]['offerings'][0]['level']}",
fill=(255, 255, 255),
)
elif country in ["渊下宫"]:
content_bk.text((300, 0), "探索", fill=(239, 211, 114), center_type="by_height")
content_bk.text(
(450, 20),
f"{world_data_dict[country]['exploration_percentage'] / 10}%",
fill=(255, 255, 255),
center_type="by_height",
)
x.paste(tmp_bk, alpha=True, center_type="center")
x.paste(content_bk, alpha=True, center_type="center")
x.circle_corner(20)
region.paste(x, (0, height), center_type="by_width")
height += 267
return region
def get_char_data_image(
char_data_list: List[Dict], char_detailed_dict: dict
) -> "BuildImage, int":
"""
画出角色列表
:param char_data_list: 角色列表
:param char_detailed_dict: 角色武器
"""
lens = len(char_data_list) / 7 if len(char_data_list) % 7 == 0 else len(char_data_list) / 7 + 1
x = 500
_h = int(x * lens)
region = BuildImage(
1600,
_h,
color="#F9F6F2",
)
width = 120
height = 0
idx = 0
for char in char_data_list:
if width + 230 > 1550:
width = 120
height += 420
idx += 1
char_img = image_path / "chars" / f'{char["name"]}.png'
char_bk = BuildImage(
270,
500,
background=image_path / "element.png",
font="HYWenHei-85W.ttf",
font_size=35,
)
char_img = BuildImage(0, 0, background=char_img)
actived_constellation_num = BuildImage(
0,
0,
plain_text=f"命之座: {char['actived_constellation_num']}层",
font="HYWenHei-85W.ttf",
font_size=25,
color=(255, 255, 255, 0),
)
level = BuildImage(
0,
0,
plain_text=f"Lv.{char['level']}",
font="HYWenHei-85W.ttf",
font_size=30,
color=(255, 255, 255, 0),
font_color=(21, 167, 89),
)
love_log = BuildImage(
0,
0,
plain_text="♥",
font="HWZhongSong.ttf",
font_size=40,
color=(255, 255, 255, 0),
font_color=(232, 31, 168),
)
fetter = BuildImage(
0,
0,
plain_text=f'{char["fetter"]}',
font="HYWenHei-85W.ttf",
font_size=30,
color=(255, 255, 255, 0),
font_color=(232, 31, 168),
)
if char_detailed_dict.get(char["name"]):
weapon = BuildImage(
100,
100,
background=image_path
/ "weapons"
/ f'{char_detailed_dict[char["name"]]["weapon"]}.png',
)
weapon_name = BuildImage(
0,
0,
plain_text=f"{char_detailed_dict[char['name']]['weapon']}",
font="HYWenHei-85W.ttf",
font_size=25,
color=(255, 255, 255, 0),
)
weapon_affix_level = BuildImage(
0,
0,
plain_text=f"精炼: {char_detailed_dict[char['name']]['affix_level']}",
font="HYWenHei-85W.ttf",
font_size=20,
color=(255, 255, 255, 0),
)
weapon_level = BuildImage(
0,
0,
plain_text=f"Lv.{char_detailed_dict[char['name']]['level']}",
font="HYWenHei-85W.ttf",
font_size=25,
color=(255, 255, 255, 0),
font_color=(21, 167, 89),
)
char_bk.paste(weapon, (20, 380), True)
char_bk.paste(
weapon_name,
(100 + int((char_bk.w - 22 - weapon.w - weapon_name.w) / 2 - 10), 390),
True,
)
char_bk.paste(
weapon_affix_level,
(
(
100
+ int(
(char_bk.w - 10 - weapon.w - weapon_affix_level.w) / 2 - 10
),
420,
)
),
True,
)
char_bk.paste(
weapon_level,
(
(
100
+ int((char_bk.w - 10 - weapon.w - weapon_level.w) / 2 - 10),
450,
)
),
True,
)
char_bk.paste(char_img, (0, 5), alpha=True, center_type="by_width")
char_bk.text((0, 270), char["name"], center_type="by_width")
char_bk.paste(actived_constellation_num, (0, 310), True, "by_width")
char_bk.paste(level, (60, 340), True)
char_bk.paste(love_log, (155, 330), True)
char_bk.paste(fetter, (180, 340), True)
char_bk.resize(0.8)
region.paste(char_bk, (width, height), True)
width += 230
region.crop((0, 0, region.w, height + 430))
return region
async def init_image(world_data_dict: Dict[str, Dict[str, str]], char_data_list: List[Dict[str, str]], char_detailed_dict: dict, home_data_list: List[Dict]):
"""
下载头像
:param world_data_dict: 地图标志
:param char_data_list: 角色列表
:param char_detailed_dict: 角色武器
:param home_data_list: 家园列表
"""
for world in world_data_dict:
file = image_path / "logo" / f'{world_data_dict[world]["name"]}.png'
file.parent.mkdir(parents=True, exist_ok=True)
if not file.exists():
await AsyncHttpx.download_file(world_data_dict[world]["icon"], file)
for char in char_data_list:
file = image_path / "chars" / f'{char["name"]}.png'
file.parent.mkdir(parents=True, exist_ok=True)
if not file.exists():
await AsyncHttpx.download_file(char["image"], file)
for char in char_detailed_dict.keys():
file = image_path / "weapons" / f'{char_detailed_dict[char]["weapon"]}.png'
file.parent.mkdir(parents=True, exist_ok=True)
if not file.exists():
await AsyncHttpx.download_file(
char_detailed_dict[char]["weapon_image"], file
)
for home in home_data_list:
file = image_path / "homes" / f'{home["name"]}.png'
file.parent.mkdir(parents=True, exist_ok=True)
if not file.exists():
await AsyncHttpx.download_file(
home["icon"], file
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/query_role/draw_image.py | draw_image.py |
from typing import Optional, List, Dict, Union
from .draw_image import init_image, get_genshin_image
from nonebot.adapters.onebot.v11 import MessageSegment
from .._utils import get_ds, element_mastery
from services.log import logger
from utils.http_utils import AsyncHttpx
from configs.config import Config
from .._models import Genshin
try:
import ujson as json
except ModuleNotFoundError:
import json
async def query_role_data(
user_id: int, uid: int, mys_id: Optional[str] = None, nickname: Optional[str] = None
) -> Optional[Union[MessageSegment, str]]:
uid = str(uid)
if uid[0] == "1" or uid[0] == "2":
server_id = "cn_gf01"
elif uid[0] == "5":
server_id = "cn_qd01"
else:
return None
return await get_image(user_id, uid, server_id, mys_id, nickname)
async def get_image(
user_id: int,
uid: str,
server_id: str,
mys_id: Optional[str] = None,
nickname: Optional[str] = None,
) -> Optional[Union[MessageSegment, str]]:
"""
生成图片
:param user_id:用户qq
:param uid: 用户uid
:param server_id: 服务器
:param mys_id: 米游社id
:param nickname: QQ昵称
:return:
"""
data, code = await get_info(uid, server_id)
if code != 200:
return data
if data:
char_data_list, role_data, world_data_dict, home_data_list = parsed_data(data)
mys_data = await get_mys_data(uid, mys_id)
if mys_data:
nickname = None
if char_data_list:
char_detailed_data = await get_character(
uid, [x["id"] for x in char_data_list], server_id
)
_x = {}
if char_detailed_data:
for char in char_detailed_data["avatars"]:
_x[char["name"]] = {
"weapon": char["weapon"]["name"],
"weapon_image": char["weapon"]["icon"],
"level": char["weapon"]["level"],
"affix_level": char["weapon"]["affix_level"],
}
await init_image(world_data_dict, char_data_list, _x, home_data_list)
return await get_genshin_image(
user_id,
uid,
char_data_list,
role_data,
world_data_dict,
home_data_list,
_x,
mys_data,
nickname,
)
return "未找到用户数据..."
# Github-@lulu666lulu https://github.com/Azure99/GenshinPlayerQuery/issues/20
"""
{body:"",query:{"action_ticket": undefined, "game_biz": "hk4e_cn”}}
对应 https://api-takumi.mihoyo.com/binding/api/getUserGameRolesByCookie?game_biz=hk4e_cn //查询米哈游账号下绑定的游戏(game_biz可留空)
{body:"",query:{"uid": 12345(被查询账号米哈游uid)}}
对应 https://api-takumi.mihoyo.com/game_record/app/card/wapi/getGameRecordCard?uid=
{body:"",query:{'role_id': '查询账号的uid(游戏里的)' ,'server': '游戏服务器'}}
对应 https://api-takumi.mihoyo.com/game_record/app/genshin/api/index?server= server信息 &role_id= 游戏uid
{body:"",query:{'role_id': '查询账号的uid(游戏里的)' , 'schedule_type': 1(我这边只看到出现过1和2), 'server': 'cn_gf01'}}
对应 https://api-takumi.mihoyo.com/game_record/app/genshin/api/spiralAbyss?schedule_type=1&server= server信息 &role_id= 游戏uid
{body:"",query:{game_id: 2(目前我知道有崩坏3是1原神是2)}}
对应 https://api-takumi.mihoyo.com/game_record/app/card/wapi/getAnnouncement?game_id= 这个是公告api
b=body q=query
其中b只在post的时候有内容,q只在get的时候有内容
"""
async def get_info(uid_: str, server_id: str) -> "Optional[Union[dict, str]], int":
try:
req = await AsyncHttpx.get(
url=f"https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/index?server={server_id}&role_id={uid_}",
headers={
"Accept": "application/json, text/plain, */*",
"DS": get_ds(f"role_id={uid_}&server={server_id}"),
"Origin": "https://webstatic.mihoyo.com",
"x-rpc-app_version": Config.get_config("genshin", "mhyVersion"),
"User-Agent": "Mozilla/5.0 (Linux; Android 9; Unspecified Device) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Mobile Safari/537.36 miHoYoBBS/2.2.0",
"x-rpc-client_type": Config.get_config("genshin", "client_type"),
"Referer": "https://webstatic.mihoyo.com/app/community-game-records/index.html?v=6",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,en-US;q=0.8",
"X-Requested-With": "com.mihoyo.hyperion",
"Cookie": await Genshin.get_user_cookie(int(uid_))
},
)
data = req.json()
if data["message"] == "OK":
return data["data"], 200
return data["message"], 999
except Exception as e:
logger.error(f"访问失败,请重试! {type(e)}: {e}")
return None, -1
async def get_character(
uid: str, character_ids: List[str], server_id="cn_gf01"
) -> Optional[dict]:
try:
req = await AsyncHttpx.post(
url="https://api-takumi.mihoyo.com/game_record/app/genshin/api/character",
headers={
"Accept": "application/json, text/plain, */*",
"DS": get_ds(
"",
{
"character_ids": character_ids,
"role_id": uid,
"server": server_id,
},
),
"Origin": "https://webstatic.mihoyo.com",
"Cookie": await Genshin.get_user_cookie(int(uid)),
"x-rpc-app_version": Config.get_config("genshin", "mhyVersion"),
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
"x-rpc-client_type": "5",
"Referer": "https://webstatic.mihoyo.com/",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,en-US;q=0.8",
"X-Requested-With": "com.mihoyo.hyperion",
},
json={"character_ids": character_ids, "role_id": uid, "server": server_id},
)
data = req.json()
if data["message"] == "OK":
return data["data"]
except Exception as e:
logger.error(f"访问失败,请重试! {type(e)}: {e}")
return None
def parsed_data(
data: dict,
) -> "Optional[List[Dict[str, str]]], Dict[str, str], Optional[List[Dict[str, str]]], Optional[List[Dict[str, str]]]":
"""
解析数据
:param data: 数据
"""
char_data_list = []
for char in data["avatars"]:
_x = {
"id": char["id"],
"image": char["image"],
"name": char["name"],
"element": element_mastery[char["element"].lower()],
"fetter": char["fetter"],
"level": char["level"],
"rarity": char["rarity"],
"actived_constellation_num": char["actived_constellation_num"],
}
char_data_list.append(_x)
role_data = {
"active_day_number": data["stats"]["active_day_number"], # 活跃天数
"achievement_number": data["stats"]["achievement_number"], # 达成成就数量
"win_rate": data["stats"]["win_rate"],
"anemoculus_number": data["stats"]["anemoculus_number"], # 风神瞳已收集
"geoculus_number": data["stats"]["geoculus_number"], # 岩神瞳已收集
"avatar_number": data["stats"]["avatar_number"], # 获得角色数量
"way_point_number": data["stats"]["way_point_number"], # 传送点已解锁
"domain_number": data["stats"]["domain_number"], # 秘境解锁数量
"spiral_abyss": data["stats"]["spiral_abyss"], # 深渊当期进度
"precious_chest_number": data["stats"]["precious_chest_number"], # 珍贵宝箱
"luxurious_chest_number": data["stats"]["luxurious_chest_number"], # 华丽宝箱
"exquisite_chest_number": data["stats"]["exquisite_chest_number"], # 精致宝箱
"magic_chest_number": data["stats"]["magic_chest_number"], # 奇馈宝箱
"common_chest_number": data["stats"]["common_chest_number"], # 普通宝箱
"electroculus_number": data["stats"]["electroculus_number"], # 雷神瞳已收集
}
world_data_dict = {}
for world in data["world_explorations"]:
_x = {
"level": world["level"], # 声望等级
"exploration_percentage": world["exploration_percentage"], # 探索进度
"image": world["icon"],
"name": world["name"],
"offerings": world["offerings"],
"icon": world["icon"]
}
world_data_dict[world["name"]] = _x
home_data_list = []
for home in data["homes"]:
_x = {
"level": home["level"], # 最大信任等级
"visit_num": home["visit_num"], # 最高历史访客数
"comfort_num": home["comfort_num"], # 最高洞天仙力
"item_num": home["item_num"], # 已获得摆件数量
"name": home["name"],
"icon": home["icon"],
"comfort_level_name": home["comfort_level_name"],
"comfort_level_icon": home["comfort_level_icon"],
}
home_data_list.append(_x)
return char_data_list, role_data, world_data_dict, home_data_list
async def get_mys_data(uid: str, mys_id: Optional[str]) -> Optional[List[Dict]]:
"""
获取用户米游社数据
:param uid: 原神uid
:param mys_id: 米游社id
"""
if mys_id:
try:
req = await AsyncHttpx.get(
url=f"https://api-takumi.mihoyo.com/game_record/card/wapi/getGameRecordCard?uid={mys_id}",
headers={
"DS": get_ds(f"uid={mys_id}"),
"x-rpc-app_version": Config.get_config("genshin", "mhyVersion"),
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
"x-rpc-client_type": "5",
"Referer": "https://webstatic.mihoyo.com/",
"Cookie": await Genshin.get_user_cookie(int(uid))
},
)
data = req.json()
if data["message"] == "OK":
return data["data"]["list"]
except Exception as e:
logger.error(f"访问失败,请重试! {type(e)}: {e}")
return None | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/query_role/data_source.py | data_source.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent, Message
from utils.utils import is_number
from .._models import Genshin
from services.log import logger
from nonebot.params import CommandArg, Command
from typing import Tuple
__zx_plugin_name__ = "原神绑定"
__plugin_usage__ = """
usage:
绑定原神uid等数据,cookie极为重要,请谨慎绑定
** 如果对拥有者不熟悉,并不建议添加cookie **
该项目只会对cookie用于”米游社签到“,“原神玩家查询”,“原神便笺查询”
指令:
原神绑定uid [uid]
原神绑定米游社id [mys_id]
原神绑定cookie [cookie] # 该绑定请私聊
原神解绑
示例:原神绑定uid 92342233
如果不明白怎么获取cookie请输入“原神绑定cookie”。
""".strip()
__plugin_des__ = "绑定自己的原神uid等"
__plugin_cmd__ = ["原神绑定uid [uid]", "原神绑定米游社id [mys_id]", "原神绑定cookie [cookie]", "原神解绑"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神绑定"],
}
bind = on_command(
"原神绑定uid", aliases={"原神绑定米游社id", "原神绑定cookie"}, priority=5, block=True
)
unbind = on_command("原神解绑", priority=5, block=True)
@bind.handle()
async def _(event: MessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
msg = arg.extract_plain_text().strip()
if cmd in ["原神绑定uid", "原神绑定米游社id"]:
if not is_number(msg):
await bind.finish("uid/id必须为纯数字!", at_senders=True)
msg = int(msg)
if cmd == "原神绑定uid":
uid = await Genshin.get_user_uid(event.user_id)
if uid:
await bind.finish(f"您已绑定过uid:{uid},如果希望更换uid,请先发送原神解绑")
flag = await Genshin.add_uid(event.user_id, msg)
if not flag:
await bind.finish("添加失败,该uid可能已存在...")
_x = f"已成功添加原神uid:{msg}"
elif cmd == "原神绑定米游社id":
uid = await Genshin.get_user_uid(event.user_id)
if not uid:
await bind.finish("请先绑定原神uid..")
await Genshin.set_mys_id(uid, msg)
_x = f"已成功为uid:{uid} 设置米游社id:{msg}"
else:
if not msg:
await bind.finish(
"私聊发送!!\n打开 https://bbs.mihoyo.com/ys/\n登录后按F12点击控制台输入document.cookie复制输出的内容即可"
)
if isinstance(event, GroupMessageEvent):
await bind.finish("请立即撤回你的消息并私聊发送!")
uid = await Genshin.get_user_uid(event.user_id)
if not uid:
await bind.finish("请先绑定原神uid..")
if msg.startswith('"') or msg.startswith("'"):
msg = msg[1:]
if msg.endswith('"') or msg.endswith("'"):
msg = msg[:-1]
await Genshin.set_cookie(uid, msg)
_x = f"已成功为uid:{uid} 设置cookie"
if isinstance(event, GroupMessageEvent):
await Genshin.set_bind_group(uid, event.group_id)
await bind.send(_x)
logger.info(
f"(USER {event.user_id}, "
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" {cmd}:{msg}"
)
@unbind.handle()
async def _(event: MessageEvent):
if await Genshin.delete_user(event.user_id):
await unbind.send("用户数据删除成功...")
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f"原神解绑"
)
else:
await unbind.send("该用户数据不存在..") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/bind/__init__.py | __init__.py |
from typing import Optional, Union
from nonebot.adapters.onebot.v11 import MessageSegment
from configs.config import Config
from asyncio.exceptions import TimeoutError
from services.log import logger
from configs.path_config import IMAGE_PATH
from utils.image_utils import BuildImage
from utils.http_utils import AsyncHttpx
from utils.utils import get_user_avatar
from utils.message_builder import image
from .._utils import get_ds
from .._models import Genshin
from io import BytesIO
from nonebot import Driver
import asyncio
import nonebot
driver: Driver = nonebot.get_driver()
memo_path = IMAGE_PATH / "genshin" / "genshin_memo"
memo_path.mkdir(exist_ok=True, parents=True)
@driver.on_startup
async def _():
for name, url in zip(
["resin.png", "task.png", "resin_discount.png"],
[
"https://upload-bbs.mihoyo.com/upload/2021/09/29/8819732/54266243c7d15ba31690c8f5d63cc3c6_71491376413333325"
"20.png?x-oss-process=image//resize,s_600/quality,q_80/auto-orient,0/interlace,1/format,png",
"https://patchwiki.biligame.com/images/ys/thumb/c/cc/6k6kuj1kte6m1n7hexqfrn92z6h4yhh.png/60px-委托任务logo.png",
"https://patchwiki.biligame.com/images/ys/d/d9/t1hv6wpucbwucgkhjntmzroh90nmcdv.png",
],
):
file = memo_path / name
if not file.exists():
await AsyncHttpx.download_file(url, file)
logger.info(f"已下载原神便签资源 -> {file}...")
async def get_user_memo(user_id: int, uid: int, uname: str) -> Optional[Union[str, MessageSegment]]:
uid = str(uid)
if uid[0] in ["1", "2"]:
server_id = "cn_gf01"
elif uid[0] == "5":
server_id = "cn_qd01"
else:
return None
return await parse_data_and_draw(user_id, uid, server_id, uname)
async def get_memo(uid: str, server_id: str) -> "Union[str, dict], int":
try:
req = await AsyncHttpx.get(
url=f"https://api-takumi-record.mihoyo.com/game_record/app/genshin/api/dailyNote?server={server_id}&role_id={uid}",
headers={
"DS": get_ds(f"role_id={uid}&server={server_id}"),
"x-rpc-app_version": Config.get_config("genshin", "mhyVersion"),
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
"x-rpc-client_type": Config.get_config("genshin", "client_type"),
"Referer": "https://webstatic.mihoyo.com/",
"Cookie": await Genshin.get_user_cookie(int(uid))
},
)
data = req.json()
if data["message"] == "OK":
return data["data"], 200
return data["message"], 999
except TimeoutError:
return "访问超时,请稍后再试", 997
except Exception as e:
logger.error(f"便签查询获取失败未知错误 {e}:{e}")
return "发生了一些错误,请稍后再试", 998
def create_border(
image_name: str, content: str, notice_text: str, value: str
) -> BuildImage:
border = BuildImage(500, 100, color="#E0D9D1", font="HYWenHei-85W.ttf", font_size=20)
text_bk = BuildImage(350, 96, color="#F5F1EB", font_size=23, font="HYWenHei-85W.ttf")
_x = 70 if image_name == "resin.png" else 50
_px = 10 if image_name == "resin.png" else 20
text_bk.paste(
BuildImage(_x, _x, background=memo_path / image_name),
(_px, 0),
True,
center_type="by_height",
)
text_bk.text((87, 20), content)
text_bk.paste(
BuildImage(
0,
0,
plain_text=notice_text,
font_color=(203, 189, 175),
font="HYWenHei-85W.ttf",
font_size=17,
),
(87, 50),
True,
)
font_width, _ = border.getsize(value)
border.text((350 + 76 - int(font_width / 2), 0), value, center_type="by_height")
border.paste(text_bk, (2, 0), center_type="by_height")
return border
async def parse_data_and_draw(
user_id: int, uid: str, server_id: str, uname: str
) -> Union[str, MessageSegment]:
data, code = await get_memo(uid, server_id)
if code != 200:
return data
user_avatar = BytesIO(await get_user_avatar(user_id))
for x in data["expeditions"]:
file_name = x["avatar_side_icon"].split("_")[-1]
role_avatar = memo_path / "role_avatar" / file_name
if not role_avatar.exists():
await AsyncHttpx.download_file(x["avatar_side_icon"], role_avatar)
return await asyncio.get_event_loop().run_in_executor(
None, _parse_data_and_draw, data, user_avatar, uid, uname
)
def _parse_data_and_draw(
data: dict, user_avatar: BytesIO, uid: int, uname: str
) -> Union[str, MessageSegment]:
current_resin = data["current_resin"] # 当前树脂
max_resin = data["max_resin"] # 最大树脂
resin_recovery_time = data["resin_recovery_time"] # 树脂全部回复时间
finished_task_num = data["finished_task_num"] # 完成的每日任务
total_task_num = data["total_task_num"] # 每日任务总数
remain_resin_discount_num = data["remain_resin_discount_num"] # 值得铭记的强敌总数
resin_discount_num_limit = data["resin_discount_num_limit"] # 剩余值得铭记的强敌
current_expedition_num = data["current_expedition_num"] # 当前挖矿人数
max_expedition_num = data["max_expedition_num"] # 每日挖矿最大人数
expeditions = data["expeditions"] # 挖矿详情
minute, second = divmod(int(resin_recovery_time), 60)
hour, minute = divmod(minute, 60)
A = BuildImage(1030, 520, color="#f1e9e1", font_size=15, font="HYWenHei-85W.ttf")
A.text((10, 15), "原神便笺 | Create By ZhenXun", (198, 186, 177))
ava = BuildImage(100, 100, background=user_avatar)
ava.circle()
A.paste(ava, (40, 40), True)
A.paste(
BuildImage(0, 0, plain_text=uname, font_size=20, font="HYWenHei-85W.ttf"),
(160, 62),
True,
)
A.paste(
BuildImage(
0,
0,
plain_text=f"UID:{uid}",
font_size=15,
font="HYWenHei-85W.ttf",
font_color=(21, 167, 89),
),
(160, 92),
True,
)
border = create_border(
"resin.png",
"原粹树脂",
"将在{:0>2d}:{:0>2d}:{:0>2d}秒后全部恢复".format(hour, minute, second),
f"{current_resin}/{max_resin}",
)
A.paste(border, (10, 155))
border = create_border(
"task.png",
"每日委托",
"今日委托已全部完成" if finished_task_num == total_task_num else "今日委托完成数量不足",
f"{finished_task_num}/{total_task_num}",
)
A.paste(border, (10, 265))
border = create_border(
"resin_discount.png",
"值得铭记的强敌",
"本周剩余消耗减半次数",
f"{remain_resin_discount_num}/{resin_discount_num_limit}",
)
A.paste(border, (10, 375))
expeditions_border = BuildImage(
470, 430, color="#E0D9D1", font="HYWenHei-85W.ttf", font_size=20
)
expeditions_text = BuildImage(
466, 426, color="#F5F1EB", font_size=23, font="HYWenHei-85W.ttf"
)
expeditions_text.text(
(5, 5), f"探索派遣限制{current_expedition_num}/{max_expedition_num}", (100, 100, 98)
)
h = 45
for x in expeditions:
_bk = BuildImage(400, 66, color="#ECE3D8", font="HYWenHei-85W.ttf", font_size=21)
file_name = x["avatar_side_icon"].split("_")[-1]
role_avatar = memo_path / "role_avatar" / file_name
_ava_img = BuildImage(75, 75, background=role_avatar)
_ava_img.circle()
if x["status"] == "Finished":
msg = "探索完成"
font_color = (146, 188, 63)
_circle_color = (146, 188, 63)
else:
minute, second = divmod(int(x["remained_time"]), 60)
hour, minute = divmod(minute, 60)
font_color = (193, 180, 167)
msg = "还剩{:0>2d}小时{:0>2d}分钟{:0>2d}秒".format(hour, minute, second)
_circle_color = "#DE9C58"
_circle_bk = BuildImage(60, 60)
_circle_bk.circle()
a_circle = BuildImage(55, 55, color=_circle_color)
a_circle.circle()
b_circle = BuildImage(47, 47)
b_circle.circle()
a_circle.paste(b_circle, (4, 4), alpha=True)
_circle_bk.paste(a_circle, (4, 4), alpha=True)
_bk.paste(_circle_bk, (25, 0), True, center_type="by_height")
_bk.paste(_ava_img, (19, -13), True)
_bk.text((100, 0), msg, font_color, "by_height")
_bk.circle_corner(20)
expeditions_text.paste(_bk, (25, h), True)
h += 75
expeditions_border.paste(expeditions_text, center_type="center")
A.paste(expeditions_border, (550, 45))
return image(b64=A.pic2bs4()) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/query_memo/data_source.py | data_source.py |
from utils.utils import get_bot, scheduler
from utils.message_builder import at
from models.group_member_info import GroupInfoUser
from apscheduler.jobstores.base import ConflictingIdError
from nonebot import Driver
from .._models import Genshin
from datetime import datetime, timedelta
from apscheduler.jobstores.base import JobLookupError
from services.log import logger
from nonebot.plugin import require
from configs.config import Config
import random
import nonebot
import pytz
driver: Driver = nonebot.get_driver()
get_memo = require("query_memo").get_memo
class UserManager:
def __init__(self, max_error_count: int = 3):
self._data = []
self._overflow_data = []
self._error_count = {}
self.max_error_count = max_error_count
def append(self, o: str):
if o not in self._data:
self._data.append(o)
def remove(self, o: str):
if o in self._data:
self._data.remove(o)
def exists(self, o: str):
return o in self._data
def add_error_count(self, uid: str):
if uid in self._error_count.keys():
self._error_count[uid] += 1
else:
self._error_count[uid] = 1
def check(self, uid: str) -> bool:
if uid in self._error_count.keys():
return self._error_count[uid] == self.max_error_count
return False
def remove_error_count(self, uid):
if uid in self._error_count.keys():
del self._error_count[uid]
def add_overflow(self, uid: str):
if uid not in self._overflow_data:
self._overflow_data.append(uid)
def remove_overflow(self, uid: str):
if uid in self._overflow_data:
self._overflow_data.remove(uid)
def is_overflow(self, uid: str) -> bool:
return uid in self._overflow_data
user_manager = UserManager()
@driver.on_startup
async def _():
"""
启动时分配定时任务
"""
g_list = await Genshin.get_all_resin_remind_user()
date = datetime.now(pytz.timezone("Asia/Shanghai")) + timedelta(seconds=30)
for u in g_list:
if u.resin_remind:
if u.resin_recovery_time:
if await Genshin.get_user_resin_recovery_time(u.uid) > datetime.now(
pytz.timezone("Asia/Shanghai")
):
date = await Genshin.get_user_resin_recovery_time(u.uid)
scheduler.add_job(
_remind,
"date",
run_date=date.replace(microsecond=0),
id=f"genshin_resin_remind_{u.uid}_{u.user_qq}",
args=[u.user_qq, u.uid],
)
logger.info(
f"genshin_resin_remind add_job:USER:{u.user_qq} UID:{u.uid} "
f"{date} 原神树脂提醒"
)
else:
await Genshin.clear_resin_remind_time(u.uid)
add_job(u.user_qq, u.uid)
logger.info(
f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid} "
f"{date} 原神树脂提醒"
)
else:
add_job(u.user_qq, u.uid)
logger.info(
f"genshin_resin_remind add_job CHECK:USER:{u.user_qq} UID:{u.uid} "
f"{date} 原神树脂提醒"
)
def add_job(user_id: int, uid: int):
# 移除
try:
scheduler.remove_job(f"genshin_resin_remind_{uid}_{user_id}")
except JobLookupError:
pass
date = datetime.now(pytz.timezone("Asia/Shanghai")) + timedelta(seconds=30)
try:
scheduler.add_job(
_remind,
"date",
run_date=date.replace(microsecond=0),
id=f"genshin_resin_remind_{uid}_{user_id}",
args=[user_id, uid],
)
except ConflictingIdError:
pass
async def _remind(user_id: int, uid: str):
uid = str(uid)
if uid[0] in ["1", "2"]:
server_id = "cn_gf01"
elif uid[0] == "5":
server_id = "cn_qd01"
else:
return
data, code = await get_memo(uid, server_id)
now = datetime.now(pytz.timezone("Asia/Shanghai"))
next_time = None
if code == 200:
current_resin = data["current_resin"] # 当前树脂
max_resin = data["max_resin"] # 最大树脂
msg = f"你的已经存了 {current_resin} 个树脂了!不要忘记刷掉!"
# resin_recovery_time = data["resin_recovery_time"] # 树脂全部回复时间
if current_resin < max_resin:
user_manager.remove(uid)
user_manager.remove_overflow(uid)
if max_resin - 40 <= current_resin <= max_resin - 20:
next_time = now + timedelta(minutes=(max_resin - 20 - current_resin) * 8, seconds=10)
elif current_resin < max_resin:
next_time = now + timedelta(minutes=(max_resin - current_resin) * 8, seconds=10)
elif current_resin == max_resin:
custom_overflow_resin = Config.get_config("resin_remind", "CUSTOM_RESIN_OVERFLOW_REMIND")
if user_manager.is_overflow(uid) and custom_overflow_resin:
next_time = now + timedelta(minutes=custom_overflow_resin * 8)
user_manager.add_overflow(uid)
user_manager.remove(uid)
msg = f"你的树脂都溢出 {custom_overflow_resin} 个了!浪费可耻!"
else:
next_time = now + timedelta(minutes=40 * 8 + random.randint(5, 50))
if not user_manager.exists(uid) and current_resin >= max_resin - 40:
if current_resin == max_resin:
user_manager.append(uid)
bot = get_bot()
if bot:
if user_id in [x["user_id"] for x in await bot.get_friend_list()]:
await bot.send_private_msg(
user_id=user_id,
message=msg,
)
else:
group_id = await Genshin.get_bind_group(int(uid))
if not group_id:
group_list = await GroupInfoUser.get_user_all_group(user_id)
if group_list:
group_id = group_list[0]
await bot.send_group_msg(
group_id=group_id,
message=at(user_id) + msg
)
if not next_time:
if user_manager.check(uid) and Config.get_config("resin_remind", "AUTO_CLOSE_QUERY_FAIL_RESIN_REMIND"):
await Genshin.set_resin_remind(int(uid), False)
await Genshin.clear_resin_remind_time(int(uid))
next_time = now + timedelta(minutes=(20 + random.randint(5, 20)) * 8)
user_manager.add_error_count(uid)
else:
user_manager.remove_error_count(uid)
await Genshin.set_user_resin_recovery_time(int(uid), next_time)
scheduler.add_job(
_remind,
"date",
run_date=next_time,
id=f"genshin_resin_remind_{uid}_{user_id}",
args=[user_id, uid],
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/resin_remind/init_task.py | init_task.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
from apscheduler.jobstores.base import JobLookupError
from services.log import logger
from .init_task import scheduler, add_job
from .._models import Genshin
from nonebot.params import Command
from typing import Tuple
__zx_plugin_name__ = "原神树脂提醒"
__plugin_usage__ = """
usage:
即将满树脂的提醒
会在 120-140 140-160 160 以及溢出指定部分时提醒,
共提醒3-4次
指令:
开原神树脂提醒
关原神树脂提醒
""".strip()
__plugin_des__ = "时时刻刻警醒你!"
__plugin_cmd__ = ["开原神树脂提醒", "关原神树脂提醒"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神树脂提醒", "关原神树脂提醒", "开原神树脂提醒"],
}
__plugin_configs__ = {
"AUTO_CLOSE_QUERY_FAIL_RESIN_REMIND": {
"value": True,
"help": "当请求连续三次失败时,关闭用户的树脂提醒",
"default_value": True
},
"CUSTOM_RESIN_OVERFLOW_REMIND": {
"value": 20,
"help": "自定义树脂溢出指定数量时的提醒,空值是为关闭",
"default_value": None
}
}
resin_remind = on_command("开原神树脂提醒", aliases={"关原神树脂提醒"}, priority=5, block=True)
@resin_remind.handle()
async def _(event: MessageEvent, cmd: Tuple[str, ...] = Command()):
cmd = cmd[0]
uid = await Genshin.get_user_uid(event.user_id)
if not uid or not await Genshin.get_user_cookie(uid, True):
await resin_remind.finish("请先绑定uid和cookie!")
try:
scheduler.remove_job(f"genshin_resin_remind_{uid}_{event.user_id}")
except JobLookupError:
pass
if cmd[0] == "开":
await Genshin.set_resin_remind(uid, True)
add_job(event.user_id, uid)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 开启原神体力提醒"
)
await resin_remind.send("开启原神树脂提醒成功!", at_sender=True)
else:
await Genshin.set_resin_remind(uid, False)
await Genshin.clear_resin_remind_time(uid)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 关闭原神体力提醒"
)
await resin_remind.send("已关闭原神树脂提醒..", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/resin_remind/__init__.py | __init__.py |
from .data_source import genshin_sign
from models.group_member_info import GroupInfoUser
from utils.message_builder import at
from services.log import logger
from utils.utils import scheduler, get_bot
from apscheduler.jobstores.base import ConflictingIdError
from .._models import Genshin
from datetime import datetime, timedelta
from nonebot import Driver
import nonebot
import random
import pytz
driver: Driver = nonebot.get_driver()
@driver.on_startup
async def _():
"""
启动时分配定时任务
"""
g_list = await Genshin.get_all_auto_sign_user()
for u in g_list:
if u.auto_sign_time:
date = await Genshin.random_sign_time(u.uid)
scheduler.add_job(
_sign,
"date",
run_date=date.replace(microsecond=0),
id=f"genshin_auto_sign_{u.uid}_{u.user_qq}_0",
args=[u.user_qq, u.uid, 0],
)
logger.info(
f"genshin_sign add_job:USER:{u.user_qq} UID:{u.uid} " f"{date} 原神自动签到"
)
def add_job(user_id: int, uid: int, date: datetime):
try:
scheduler.add_job(
_sign,
"date",
run_date=date.replace(microsecond=0),
id=f"genshin_auto_sign_{uid}_{user_id}_0",
args=[user_id, uid, 0],
)
logger.debug(f"genshin_sign add_job:{date.replace(microsecond=0)} 原神自动签到")
except ConflictingIdError:
pass
async def _sign(user_id: int, uid: int, count: int):
"""
执行签到任务
:param user_id: 用户id
:param uid: uid
:param count: 执行次数
"""
if count < 3:
try:
msg = await genshin_sign(uid)
next_time = await Genshin.random_sign_time(uid)
msg += f"\n下一次签到时间为:{next_time.replace(microsecond=0)}"
logger.info(f"USER:{user_id} UID:{uid} 原神自动签到任务发生成功...")
try:
scheduler.add_job(
_sign,
"date",
run_date=next_time.replace(microsecond=0),
id=f"genshin_auto_sign_{uid}_{user_id}_0",
args=[user_id, uid, 0],
)
except ConflictingIdError:
msg += "\n定时任务设定失败..."
except Exception as e:
logger.error(f"USER:{user_id} UID:{uid} 原神自动签到任务发生错误 {type(e)}:{e}")
msg = None
if not msg:
now = datetime.now(pytz.timezone("Asia/Shanghai"))
if now.hour < 23:
random_hours = random.randint(1, 23 - now.hour)
next_time = now + timedelta(hours=random_hours)
scheduler.add_job(
_sign,
"date",
run_date=next_time.replace(microsecond=0),
id=f"genshin_auto_sign_{uid}_{user_id}_{count}",
args=[user_id, uid, count + 1],
)
msg = (
f"{now.replace(microsecond=0)} 原神"
f"签到失败,将在 {next_time.replace(microsecond=0)} 时重试!"
)
else:
msg = "今日原神签到失败,请手动签到..."
logger.debug(f"USER:{user_id} UID:{uid} 原神今日签到失败...")
else:
msg = "今日原神自动签到重试次数已达到3次,请手动签到。"
logger.debug(f"USER:{user_id} UID:{uid} 原神今日签到失败次数打到 3 次...")
bot = get_bot()
if bot:
if user_id in [x["user_id"] for x in await bot.get_friend_list()]:
await bot.send_private_msg(user_id=user_id, message=msg)
else:
if not (group_id := await Genshin.get_bind_group(uid)):
group_list = await GroupInfoUser.get_user_all_group(user_id)
if group_list:
group_id = group_list[0]
await bot.send_group_msg(
group_id=group_id, message=at(user_id) + msg
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/genshin_sign/init_task.py | init_task.py |
from utils.http_utils import AsyncHttpx
from configs.config import Config
from services.log import logger
from .._utils import random_hex, get_old_ds
from .._models import Genshin
from typing import Optional, Dict
async def genshin_sign(uid: int) -> Optional[str]:
"""
原神签到信息
:param uid: uid
"""
data = await _sign(uid)
if not data:
return "签到失败..."
status = data["message"]
if status == "OK":
sign_info = await _get_sign_info(uid)
if sign_info:
sign_info = sign_info["data"]
sign_list = await get_sign_reward_list()
get_reward = sign_list["data"]["awards"][
int(sign_info["total_sign_day"]) - 1
]["name"]
reward_num = sign_list["data"]["awards"][
int(sign_info["total_sign_day"]) - 1
]["cnt"]
get_im = f"本次签到获得:{get_reward}x{reward_num}"
if status == "OK" and sign_info["is_sign"]:
return f"\n原神签到成功!\n{get_im}\n本月漏签次数:{sign_info['sign_cnt_missed']}"
else:
return status
return None
async def _sign(uid: int, server_id: str = "cn_gf01") -> Optional[Dict[str, str]]:
"""
米游社签到
:param uid: uid
:param server_id: 服务器id
"""
if str(uid)[0] == "5":
server_id = "cn_qd01"
try:
req = await AsyncHttpx.post(
url="https://api-takumi.mihoyo.com/event/bbs_sign_reward/sign",
headers={
"User_Agent": "Mozilla/5.0 (Linux; Android 10; MIX 2 Build/QKQ1.190825.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.101 Mobile Safari/537.36 miHoYoBBS/2.3.0",
"Cookie": await Genshin.get_user_cookie(int(uid), True),
"x-rpc-device_id": random_hex(32),
"Origin": "https://webstatic.mihoyo.com",
"X_Requested_With": "com.mihoyo.hyperion",
"DS": get_old_ds(),
"x-rpc-client_type": "5",
"Referer": "https://webstatic.mihoyo.com/bbs/event/signin-ys/index.html?bbs_auth_required=true&act_id=e202009291139501&utm_source=bbs&utm_medium=mys&utm_campaign=icon",
"x-rpc-app_version": "2.3.0",
},
json={"act_id": "e202009291139501", "uid": uid, "region": server_id},
)
return req.json()
except Exception as e:
logger.error(f"米游社签到发生错误 UID:{uid} {type(e)}:{e}")
return None
async def get_sign_reward_list():
"""
获取签到奖励列表
"""
try:
req = await AsyncHttpx.get(
url="https://api-takumi.mihoyo.com/event/bbs_sign_reward/home?act_id=e202009291139501",
headers={
"x-rpc-app_version": str(Config.get_config("genshin", "mhyVersion")),
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
"x-rpc-client_type": str(Config.get_config("genshin", "client_type")),
"Referer": "https://webstatic.mihoyo.com/",
},
)
return req.json()
except Exception as e:
logger.error(f"获取签到奖励列表发生错误 {type(e)}:{e}")
return None
async def _get_sign_info(uid: int, server_id: str = "cn_gf01"):
if str(uid)[0] == "5":
server_id = "cn_qd01"
try:
req = await AsyncHttpx.get(
url=f"https://api-takumi.mihoyo.com/event/bbs_sign_reward/info?act_id=e202009291139501®ion={server_id}&uid={uid}",
headers={
"x-rpc-app_version": str(Config.get_config("genshin", "mhyVersion")),
"Cookie": await Genshin.get_user_cookie(int(uid), True),
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/2.11.1",
"x-rpc-client_type": str(Config.get_config("genshin", "client_type")),
"Referer": "https://webstatic.mihoyo.com/",
},
)
return req.json()
except Exception as e:
logger.error(f"获取签到信息发生错误 UID:{uid} {type(e)}:{e}")
return None | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/genshin_sign/data_source.py | data_source.py |
from .data_source import get_sign_reward_list, genshin_sign
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
from nonebot import on_command
from services.log import logger
from .init_task import add_job, scheduler, _sign
from apscheduler.jobstores.base import JobLookupError
from .._models import Genshin
from nonebot.params import Command
from typing import Tuple
__zx_plugin_name__ = "原神自动签到"
__plugin_usage__ = """
usage:
米游社原神签到,需要uid以及cookie
且在第二天自动排序签到时间
# 不听,就要手动签到!(使用命令 “原神我硬签 or 米游社我硬签”
指令:
开/关原神自动签到
原神我硬签
""".strip()
__plugin_des__ = "原神懒人签到"
__plugin_cmd__ = ["开启/关闭原神自动签到", "原神我硬签"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神签到"],
}
genshin_matcher = on_command(
"开原神自动签到", aliases={"关原神自动签到", "原神我硬签"}, priority=5, block=True
)
@genshin_matcher.handle()
async def _(event: MessageEvent, cmd: Tuple[str, ...] = Command()):
cmd = cmd[0]
uid = await Genshin.get_user_uid(event.user_id)
if not uid or not await Genshin.get_user_cookie(uid, True):
await genshin_matcher.finish("请先绑定uid和cookie!")
if "account_id" not in await Genshin.get_user_cookie(uid, True):
await genshin_matcher.finish("请更新cookie!")
if cmd == "原神我硬签":
try:
msg = await genshin_sign(uid)
logger.info(
f"(USER {event.user_id}, "
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) UID:{uid} 原神签到"
)
# 硬签,移除定时任务
try:
for i in range(3):
scheduler.remove_job(f"genshin_auto_sign_{uid}_{event.user_id}_{i}",)
except JobLookupError:
pass
u = await Genshin.get_user_by_uid(uid)
if u and u.auto_sign:
await u.clear_sign_time(uid)
next_date = await Genshin.random_sign_time(uid)
add_job(event.user_id, uid, next_date)
msg += f"因开启自动签到\n下一次签到时间为:{next_date.replace(microsecond=0)}"
except Exception as e:
msg = "原神签到失败..请尝试检查cookie或报告至管理员!"
logger.info(
f"(USER {event.user_id}, "
f"GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) UID:{uid} 原神签到发生错误 "
f"{type(e)}:{e}"
)
msg = msg or "请检查cookie是否更新!"
await genshin_matcher.send(msg, at_sender=True)
else:
for i in range(3):
try:
scheduler.remove_job(f"genshin_auto_sign_{uid}_{event.user_id}_{i}")
except JobLookupError:
pass
if cmd[0] == "开":
await Genshin.set_auto_sign(uid, True)
next_date = await Genshin.random_sign_time(uid)
add_job(event.user_id, uid, next_date)
await genshin_matcher.send(
f"已开启原神自动签到!\n下一次签到时间为:{next_date.replace(microsecond=0)}",
at_sender=True,
)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 开启原神自动签到"
)
else:
await Genshin.set_auto_sign(uid, False)
await Genshin.clear_sign_time(uid)
await genshin_matcher.send(f"已关闭原神自动签到!", at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 关闭原神自动签到"
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/genshin_sign/__init__.py | __init__.py |
from services.db_context import db
from typing import Optional, Union, List
from datetime import datetime, timedelta
import random
import pytz
class Genshin(db.Model):
__tablename__ = "genshin"
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
uid = db.Column(db.BigInteger())
mys_id = db.Column(db.BigInteger())
cookie = db.Column(db.String(), default="")
today_query_uid = db.Column(db.String(), default="") # 该cookie今日查询的uid
auto_sign = db.Column(db.Boolean(), default=False)
auto_sign_time = db.Column(db.DateTime(timezone=True))
resin_remind = db.Column(db.Boolean(), default=False) # 树脂提醒
resin_recovery_time = db.Column(db.DateTime(timezone=True)) # 满树脂提醒日期
bind_group = db.Column(db.BigInteger())
_idx1 = db.Index("genshin_uid_idx1", "user_qq", "uid", unique=True)
@classmethod
async def add_uid(cls, user_qq: int, uid: int):
"""
说明:
添加一个uid
参数:
:param user_qq: 用户qq
:param uid: 原神uid
"""
query = cls.query.where((cls.user_qq == user_qq) & (cls.uid == uid))
user = await query.gino.first()
if not user:
await cls.create(
user_qq=user_qq,
uid=uid,
)
return True
return False
@classmethod
async def set_mys_id(cls, uid: int, mys_id: int) -> bool:
"""
说明:
设置米游社id
参数:
:param uid: 原神uid
:param mys_id: 米游社id
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(mys_id=mys_id).apply()
return True
return False
@classmethod
async def set_bind_group(cls, uid: int, bind_group) -> bool:
"""
说明:
绑定group_id,除私聊外的提醒将在此群发送
参数:
:param uid: uid
:param bind_group: 群号
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(bind_group=bind_group).apply()
return True
return False
@classmethod
async def get_bind_group(cls, uid: int) -> Optional[int]:
"""
说明:
获取用户绑定的群聊
参数:
:param uid: uid
"""
user = await cls.query.where(cls.uid == uid).gino.first()
if user:
return user.bind_group
return None
@classmethod
async def set_cookie(cls, uid: int, cookie: str) -> bool:
"""
说明:
设置cookie
参数:
:param uid: 原神uid
:param cookie: 米游社id
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(cookie=cookie).apply()
return True
return False
@classmethod
async def set_resin_remind(cls, uid: int, flag: bool) -> bool:
"""
说明:
设置体力提醒
参数:
:param uid: 原神uid
:param flag: 开关状态
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(resin_remind=flag).apply()
return True
return False
@classmethod
async def set_user_resin_recovery_time(cls, uid: int, date: datetime):
"""
说明:
设置体力完成时间
参数:
:param uid: uid
:param date: 提醒日期
"""
u = await cls.query.where(cls.uid == uid).gino.first()
if u:
await u.update(resin_recovery_time=date).apply()
@classmethod
async def get_user_resin_recovery_time(cls, uid: int) -> Optional[datetime]:
"""
说明:
获取体力完成时间
参数:
:param uid: uid
"""
u = await cls.query.where(cls.uid == uid).gino.first()
if u:
return u.resin_recovery_time.astimezone(pytz.timezone("Asia/Shanghai"))
return None
@classmethod
async def get_all_resin_remind_user(cls) -> List["Genshin"]:
"""
说明:
获取所有开启体力提醒的用户
"""
return await cls.query.where(cls.resin_remind == True).gino.all()
@classmethod
async def clear_resin_remind_time(cls, uid: int) -> bool:
"""
说明:
清空提醒日期
参数:
:param uid: uid
"""
user = await cls.query.where(cls.uid == uid).gino.first()
if user:
await user.update(resin_recovery_time=None).apply()
return True
return False
@classmethod
async def set_auto_sign(cls, uid: int, flag: bool) -> bool:
"""
说明:
设置米游社/原神自动签到
参数:
:param uid: 原神uid
:param flag: 开关状态
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(auto_sign=flag).apply()
return True
return False
@classmethod
async def get_all_auto_sign_user(cls) -> List["Genshin"]:
"""
说明:
获取所有开启自动签到的用户
"""
return await cls.query.where(cls.auto_sign == True).gino.all()
@classmethod
async def get_all_sign_user(cls) -> List["Genshin"]:
"""
说明:
获取 原神 所有今日签到用户
"""
return await cls.query.where(cls.auto_sign_time != None).gino.all()
@classmethod
async def clear_sign_time(cls, uid: int) -> bool:
"""
说明:
清空签到日期
参数:
:param uid: uid
"""
user = await cls.query.where(cls.uid == uid).gino.first()
if user:
await user.update(auto_sign_time=None).apply()
return True
return False
@classmethod
async def random_sign_time(cls, uid: int) -> Optional[datetime]:
"""
说明:
随机签到时间
说明:
:param uid: uid
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user and user.cookie:
if user.auto_sign_time and user.auto_sign_time.astimezone(
pytz.timezone("Asia/Shanghai")
) - timedelta(seconds=2) >= datetime.now(pytz.timezone("Asia/Shanghai")):
return user.auto_sign_time.astimezone(pytz.timezone("Asia/Shanghai"))
hours = int(str(datetime.now()).split()[1].split(":")[0])
minutes = int(str(datetime.now()).split()[1].split(":")[1])
date = (
datetime.now()
+ timedelta(days=1)
- timedelta(hours=hours)
- timedelta(minutes=minutes - 1)
)
random_hours = random.randint(0, 22)
random_minutes = random.randint(1, 59)
date += timedelta(hours=random_hours) + timedelta(minutes=random_minutes)
await user.update(auto_sign_time=date).apply()
return date
return None
@classmethod
async def get_query_cookie(cls, uid: int) -> Optional[str]:
"""
说明:
获取查询角色信息cookie
参数:
:param uid: 原神uid
"""
# 查找用户今日是否已经查找过,防止重复
query = cls.query.where(cls.today_query_uid.contains(str(uid)))
x = await query.gino.first()
if x:
await cls._add_query_uid(uid, uid)
return x.cookie
for u in [
x for x in await cls.query.order_by(db.func.random()).gino.all() if x.cookie
]:
if not u.today_query_uid or len(u.today_query_uid[:-1].split()) < 30:
await cls._add_query_uid(uid, u.uid)
return u.cookie
return None
@classmethod
async def get_user_cookie(cls, uid: int, flag: bool = False) -> Optional[str]:
"""
说明:
获取用户cookie
参数:
:param uid:原神uid
:param flag:必须使用自己的cookie
"""
cookie = await cls._get_user_data(None, uid, "cookie")
if not cookie and not flag:
cookie = await cls.get_query_cookie(uid)
return cookie
@classmethod
async def get_user_by_qq(cls, user_qq: int) -> Optional["Genshin"]:
"""
说明:
通过qq获取用户对象
参数:
:param user_qq: qq
"""
return await cls.query.where(cls.user_qq == user_qq).gino.first()
@classmethod
async def get_user_by_uid(cls, uid: int) -> Optional["Genshin"]:
"""
说明:
通过uid获取用户对象
参数:
:param uid: qq
"""
return await cls.query.where(cls.uid == uid).gino.first()
@classmethod
async def get_user_uid(cls, user_qq: int) -> Optional[int]:
"""
说明:
获取用户uid
参数:
:param user_qq:用户qq
"""
return await cls._get_user_data(user_qq, None, "uid")
@classmethod
async def get_user_mys_id(cls, uid: int) -> Optional[int]:
"""
说嘛:
获取用户米游社id
参数:
:param uid:原神id
"""
return await cls._get_user_data(None, uid, "mys_id")
@classmethod
async def delete_user_cookie(cls, uid: int):
"""
说明:
删除用户cookie
参数:
:param uid: 原神uid
"""
query = cls.query.where(cls.uid == uid).with_for_update()
user = await query.gino.first()
if user:
await user.update(cookie="").apply()
@classmethod
async def delete_user(cls, user_qq: int):
"""
说明:
删除用户数据
参数:
:param user_qq: 用户qq
"""
query = cls.query.where(cls.user_qq == user_qq).with_for_update()
user = await query.gino.first()
if not user:
return False
await user.delete()
return True
@classmethod
async def _add_query_uid(cls, uid: int, cookie_uid: int):
"""
说明:
添加每日查询重复uid的cookie
参数:
:param uid: 原神uid
:param cookie_uid: cookie的uid
"""
query = cls.query.where(cls.uid == cookie_uid).with_for_update()
user = await query.gino.first()
await user.update(today_query_uid=user.today_query_uid + f"{uid} ").apply()
@classmethod
async def _get_user_data(
cls, user_qq: Optional[int], uid: Optional[int], type_: str
) -> Optional[Union[int, str]]:
"""
说明:
获取用户数据
参数:
:param user_qq: 用户qq
:param uid: uid
:param type_: 数据类型
"""
if type_ == "uid":
user = await cls.query.where(cls.user_qq == user_qq).gino.first()
return user.uid if user else None
user = await cls.query.where(cls.uid == uid).gino.first()
if not user:
return None
if type_ == "mys_id":
return user.mys_id
elif type_ == "cookie":
return user.cookie
return None
@classmethod
async def reset_today_query_uid(cls):
for u in await cls.query.with_for_update().gino.all():
if u.today_query_uid:
await u.update(today_query_uid="").apply() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_user/_models/__init__.py | __init__.py |
from nonebot import on_command, Driver
from nonebot.adapters.onebot.v11 import MessageEvent, Message, GroupMessageEvent
from utils.message_builder import image
from utils.image_utils import BuildImage
from utils.browser import get_browser
from configs.path_config import IMAGE_PATH
import nonebot
from services.log import logger
from nonebot.permission import SUPERUSER
from typing import List
from datetime import datetime, timedelta
import os
import asyncio
import time
__zx_plugin_name__ = "原神今日素材"
__plugin_usage__ = """
usage:
看看原神今天要刷什么
指令:
今日素材/今天素材
""".strip()
__plugin_superuser_usage__ = """
usage:
更新原神今日素材
指令:
更新原神今日素材
""".strip()
__plugin_des__ = "看看原神今天要刷什么"
__plugin_cmd__ = ["今日素材/今天素材", "更新原神今日素材 [_superuser]"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["今日素材", "今天素材"],
}
driver: Driver = nonebot.get_driver()
material = on_command("今日素材", aliases={"今日材料", "今天素材", "今天材料"}, priority=5, block=True)
super_cmd = on_command("更新原神今日素材", permission=SUPERUSER, priority=1, block=True)
@material.handle()
async def _(event: MessageEvent):
if time.strftime("%w") == "0":
await material.send("今天是周日,所有材料副本都开放了。")
return
file_name = str((datetime.now() - timedelta(hours=4)).date())
if not (IMAGE_PATH / "genshin" / "material" / f"{file_name}.png").exists():
await update_image()
await material.send(
Message(
image(f"{file_name}.png", "genshin/material")
+ "\n※ 每日素材数据来源于 genshin.pub"
)
)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 发送查看今日素材"
)
@super_cmd.handle()
async def _():
if await update_image():
await super_cmd.send("更新成功...")
logger.info(f"更新每日天赋素材成功...")
else:
await super_cmd.send(f"更新失败...")
async def update_image():
page = None
try:
if not os.path.exists(f"{IMAGE_PATH}/genshin/material"):
os.mkdir(f"{IMAGE_PATH}/genshin/material")
for file in os.listdir(f"{IMAGE_PATH}/genshin/material"):
os.remove(f"{IMAGE_PATH}/genshin/material/{file}")
browser = await get_browser()
if not browser:
logger.warning("获取 browser 失败,请部署至 linux 环境....")
return False
url = "https://genshin.pub/daily"
page = await browser.new_page()
await page.goto(url, wait_until="networkidle", timeout=10000)
await page.set_viewport_size({"width": 2560, "height": 1080})
await page.evaluate(
"""
document.getElementsByClassName('GSTitleBar_gs_titlebar__2IJqy')[0].remove();
e = document.getElementsByClassName('GSContainer_gs_container__2FbUz')[0];
e.setAttribute("style", "height:880px");
"""
)
await page.click("button")
div = await page.query_selector(".GSContainer_content_box__1sIXz")
for i, card in enumerate(
await page.query_selector_all(".GSTraitCotainer_trait_section__1f3bc")
):
index = 0
type_ = "char" if not i else "weapons"
for x in await card.query_selector_all("xpath=child::*"):
await x.screenshot(
path=f"{IMAGE_PATH}/genshin/material/{type_}_{index}.png",
timeout=100000,
)
# 下滑两次
for _ in range(3):
await div.press("PageDown")
index += 1
# 结束后上滑至顶
for _ in range(index * 3):
await div.press("PageUp")
file_list = os.listdir(f"{IMAGE_PATH}/genshin/material")
char_img = [
f"{IMAGE_PATH}/genshin/material/{x}"
for x in file_list
if x.startswith("char")
]
weapons_img = [
f"{IMAGE_PATH}/genshin/material/{x}"
for x in file_list
if x.startswith("weapons")
]
char_img.sort()
weapons_img.sort()
height = await asyncio.get_event_loop().run_in_executor(
None, get_background_height, weapons_img
)
background_img = BuildImage(1200, height + 100, color="#f6f2ee")
current_width = 50
for img_list in [char_img, weapons_img]:
current_height = 20
for img in img_list:
x = BuildImage(0, 0, background=img)
background_img.paste(x, (current_width, current_height))
current_height += x.size[1]
current_width += 600
file_name = str((datetime.now() - timedelta(hours=4)).date())
background_img.save(f"{IMAGE_PATH}/genshin/material/{file_name}.png")
await page.close()
return True
except Exception as e:
logger.error(f"原神每日素材更新出错... {type(e)}: {e}")
if page:
await page.close()
return False
# 获取背景高度以及修改最后一张图片的黑边
def get_background_height(weapons_img: List[str]) -> int:
height = 0
for weapons in weapons_img:
height += BuildImage(0, 0, background=weapons).size[1]
last_weapon = BuildImage(0, 0, background=weapons_img[-1])
w, h = last_weapon.size
last_weapon.crop((0, 0, w, h - 10))
last_weapon.save(weapons_img[-1])
return height | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/material_remind/__init__.py | __init__.py |
from configs.path_config import IMAGE_PATH, TEXT_PATH
from utils.image_utils import BuildImage
from typing import Tuple, List
from math import sqrt, pow
import random
try:
import ujson as json
except ModuleNotFoundError:
import json
icon_path = IMAGE_PATH / "genshin" / "genshin_icon"
map_path = IMAGE_PATH / "genshin" / "map" / "map.png"
resource_label_file = TEXT_PATH / "genshin" / "resource_label_file.json"
resource_point_file = TEXT_PATH / "genshin" / "resource_point_file.json"
class Map:
"""
原神资源生成类
"""
def __init__(
self,
resource_name: str,
center_point: Tuple[int, int],
deviation: Tuple[int, int] = (25, 51),
padding: int = 100,
planning_route: bool = False,
ratio: float = 1,
):
"""
参数:
:param resource_name: 资源名称
:param center_point: 中心点
:param deviation: 坐标误差
:param padding: 截图外边距
:param planning_route: 是否规划最佳线路
:param ratio: 压缩比率
"""
self.map = BuildImage(0, 0, background=map_path)
self.resource_name = resource_name
self.center_x = center_point[0]
self.center_y = center_point[1]
self.deviation = deviation
self.padding = int(padding * ratio)
self.planning_route = planning_route
self.ratio = ratio
self.deviation = (
int(self.deviation[0] * ratio),
int(self.deviation[1] * ratio),
)
data = json.load(open(resource_label_file, "r", encoding="utf8"))
# 资源 id
self.resource_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == resource_name
][0]
# 传送锚点 id
self.teleport_anchor_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == "传送锚点"
][0]
# 神像 id
self.teleport_god_id = [
data[x]["id"]
for x in data
if x != "CENTER_POINT" and data[x]["name"] == "七天神像"
][0]
# 资源坐标
data = json.load(open(resource_point_file, "r", encoding="utf8"))
self.resource_point = [
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.resource_id
]
# 传送锚点坐标
self.teleport_anchor_point = [
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_anchor_id
]
# 神像坐标
self.teleport_god_point = [
Resources(
int((self.center_x + data[x]["x_pos"]) * ratio),
int((self.center_y + data[x]["y_pos"]) * ratio),
)
for x in data
if x != "CENTER_POINT" and data[x]["label_id"] == self.teleport_god_id
]
# 将地图上生成资源图标
def generate_resource_icon_in_map(self) -> int:
x_list = [x.x for x in self.resource_point]
y_list = [x.y for x in self.resource_point]
min_width = min(x_list) - self.padding
max_width = max(x_list) + self.padding
min_height = min(y_list) - self.padding
max_height = max(y_list) + self.padding
self._generate_transfer_icon((min_width, min_height, max_width, max_height))
for res in self.resource_point:
icon = self._get_icon_image(self.resource_id)
self.map.paste(
icon, (res.x - self.deviation[0], res.y - self.deviation[1]), True
)
if self.planning_route:
self._generate_best_route()
self.map.crop((min_width, min_height, max_width, max_height))
rand = random.randint(1, 10000)
self.map.save(f"{IMAGE_PATH}/temp/genshin_map_{rand}.png")
return rand
# 资源数量
def get_resource_count(self) -> int:
return len(self.resource_point)
# 生成传送锚点和神像
def _generate_transfer_icon(self, box: Tuple[int, int, int, int]):
min_width, min_height, max_width, max_height = box
for resources in [self.teleport_anchor_point, self.teleport_god_point]:
id_ = (
self.teleport_anchor_id
if resources == self.teleport_anchor_point
else self.teleport_god_id
)
for res in resources:
if min_width < res.x < max_width and min_height < res.y < max_height:
icon = self._get_icon_image(id_)
self.map.paste(
icon,
(res.x - self.deviation[0], res.y - self.deviation[1]),
True,
)
# 生成最优路线(说是最优其实就是直线最短)
def _generate_best_route(self):
line_points = []
teleport_list = self.teleport_anchor_point + self.teleport_god_point
for teleport in teleport_list:
current_res, res_min_distance = teleport.get_resource_distance(self.resource_point)
current_teleport, teleport_min_distance = current_res.get_resource_distance(teleport_list)
if current_teleport == teleport:
self.map.line(
(current_teleport.x, current_teleport.y, current_res.x, current_res.y), (255, 0, 0), width=1
)
is_used_res_points = []
for res in self.resource_point:
if res in is_used_res_points:
continue
current_teleport, teleport_min_distance = res.get_resource_distance(teleport_list)
current_res, res_min_distance = res.get_resource_distance(self.resource_point)
if teleport_min_distance < res_min_distance:
self.map.line(
(current_teleport.x, current_teleport.y, res.x, res.y), (255, 0, 0), width=1
)
else:
is_used_res_points.append(current_res)
self.map.line(
(current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1
)
res_cp = self.resource_point[:]
res_cp.remove(current_res)
# for _ in res_cp:
current_teleport_, teleport_min_distance = res.get_resource_distance(teleport_list)
current_res, res_min_distance = res.get_resource_distance(res_cp)
if teleport_min_distance < res_min_distance:
self.map.line(
(current_teleport.x, current_teleport.y, res.x, res.y), (255, 0, 0), width=1
)
else:
self.map.line(
(current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1
)
is_used_res_points.append(current_res)
is_used_res_points.append(res)
# resources_route = []
# # 先连上最近的资源路径
# for res in self.resource_point:
# # 拿到最近的资源
# current_res, _ = res.get_resource_distance(
# self.resource_point
# + self.teleport_anchor_point
# + self.teleport_god_point
# )
# self.map.line(
# (current_res.x, current_res.y, res.x, res.y), (255, 0, 0), width=1
# )
# resources_route.append((current_res, res))
# teleport_list = self.teleport_anchor_point + self.teleport_god_point
# for res1, res2 in resources_route:
# point_list = [x for x in resources_route if res1 in x or res2 in x]
# if not list(set(point_list).intersection(set(teleport_list))):
# if res1 not in teleport_list and res2 not in teleport_list:
# # while True:
# # tmp = [x for x in point_list]
# # break
# teleport1, distance1 = res1.get_resource_distance(teleport_list)
# teleport2, distance2 = res2.get_resource_distance(teleport_list)
# if distance1 > distance2:
# self.map.line(
# (teleport1.x, teleport1.y, res1.x, res1.y),
# (255, 0, 0),
# width=1,
# )
# else:
# self.map.line(
# (teleport2.x, teleport2.y, res2.x, res2.y),
# (255, 0, 0),
# width=1,
# )
# self.map.line(xy, (255, 0, 0), width=3)
# 获取资源图标
def _get_icon_image(self, id_: int) -> "BuildImage":
icon = icon_path / f"{id_}.png"
if icon.exists():
return BuildImage(
int(50 * self.ratio), int(50 * self.ratio), background=icon
)
return BuildImage(
int(50 * self.ratio),
int(50 * self.ratio),
background=f"{icon_path}/box.png",
)
# def _get_shortest_path(self, res: 'Resources', res_2: 'Resources'):
# 资源类
class Resources:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def get_distance(self, x: int, y: int):
return int(sqrt(pow(abs(self.x - x), 2) + pow(abs(self.y - y), 2)))
# 拿到资源在该列表中的最短路径
def get_resource_distance(self, resources: List["Resources"]) -> "Resources, int":
current_res = None
min_distance = 999999
for res in resources:
distance = self.get_distance(res.x, res.y)
if distance < min_distance and res != self:
current_res = res
min_distance = distance
return current_res, min_distance | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_resource_points/map.py | map.py |
from nonebot import on_command, on_regex
from .query_resource import get_resource_type_list, query_resource, init, check_resource_exists
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from utils.utils import scheduler
from services.log import logger
from configs.config import NICKNAME
from nonebot.permission import SUPERUSER
from nonebot.params import CommandArg
import re
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "原神资源查询"
__plugin_usage__ = """
usage:
不需要打开网页,就能帮你生成资源图片
指令:
原神资源查询 [资源名称]
原神资源列表
[资源名称]在哪
哪有[资源名称]
""".strip()
__plugin_superuser_usage__ = """
usage:
更新原神资源信息
指令:
更新原神资源信息
""".strip()
__plugin_des__ = "原神大地图资源速速查看"
__plugin_cmd__ = ["原神资源查询 [资源名称]", "原神资源列表", "[资源名称]在哪/哪有[资源名称]", "更新原神资源信息 [_superuser]"]
__plugin_type__ = ("原神相关",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["原神资源查询", "原神资源列表"],
}
__plugin_block_limit__ = {
"rst": "您有资源正在查询!"
}
qr = on_command("原神资源查询", aliases={"原神资源查找"}, priority=5, block=True)
qr_lst = on_command("原神资源列表", priority=5, block=True)
rex_qr = on_regex(".*?(在哪|在哪里|哪有|哪里有).*?", priority=5, block=True)
update_info = on_command("更新原神资源信息", permission=SUPERUSER, priority=1, block=True)
@qr.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
resource_name = arg.extract_plain_text().strip()
if check_resource_exists(resource_name):
await qr.send("正在生成位置....")
resource = await query_resource(resource_name)
await qr.send(Message(resource), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
else:
await qr.send(f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称..")
@rex_qr.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if "在哪" in msg:
rs = re.search("(.*)在哪.*?", msg)
resource_name = rs.group(1) if rs else ""
else:
rs = re.search(".*?(哪有|哪里有)(.*)", msg)
resource_name = rs.group(2) if rs else ""
if check_resource_exists(resource_name):
await qr.send("正在生成位置....")
resource = await query_resource(resource_name)
if resource:
await rex_qr.send(Message(resource), at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 查询原神材料:" + resource_name
)
@qr_lst.handle()
async def _(bot: Bot, event: MessageEvent):
txt = get_resource_type_list()
txt_list = txt.split("\n")
if isinstance(event, GroupMessageEvent):
mes_list = []
for txt in txt_list:
data = {
"type": "node",
"data": {
"name": f"这里是{NICKNAME}酱",
"uin": f"{bot.self_id}",
"content": txt,
},
}
mes_list.append(data)
await bot.send_group_forward_msg(group_id=event.group_id, messages=mes_list)
else:
rst = ""
for i in range(len(txt_list)):
rst += txt_list[i] + "\n"
if i % 5 == 0:
if rst:
await qr_lst.send(rst)
rst = ""
@update_info.handle()
async def _():
await init(True)
await update_info.send("更新原神资源信息完成...")
@scheduler.scheduled_job(
"cron",
hour=5,
minute=1,
)
async def _():
try:
await init()
logger.info(f"每日更新原神材料信息成功!")
except Exception as e:
logger.error(f"每日更新原神材料信息错误:{e}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_resource_points/__init__.py | __init__.py |
from typing import Tuple, Optional, List
from configs.path_config import IMAGE_PATH, TEXT_PATH
from PIL.Image import UnidentifiedImageError
from utils.message_builder import image
from services.log import logger
from utils.image_utils import BuildImage
from asyncio.exceptions import TimeoutError
from asyncio import Semaphore
from utils.image_utils import is_valid
from utils.http_utils import AsyncHttpx
from httpx import ConnectTimeout
from .map import Map
import asyncio
import nonebot
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
driver: nonebot.Driver = nonebot.get_driver()
LABEL_URL = "https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/label/tree?app_sn=ys_obc"
POINT_LIST_URL = "https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/map/point/list?map_id=2&app_sn=ys_obc"
MAP_URL = "https://api-static.mihoyo.com/common/map_user/ys_obc/v1/map/info?map_id=2&app_sn=ys_obc&lang=zh-cn"
icon_path = IMAGE_PATH / "genshin" / "genshin_icon"
map_path = IMAGE_PATH / "genshin" / "map"
resource_label_file = TEXT_PATH / "genshin" / "resource_label_file.json"
resource_point_file = TEXT_PATH / "genshin" / "resource_point_file.json"
resource_type_file = TEXT_PATH / "genshin" / "resource_type_file.json"
# 地图中心坐标
CENTER_POINT: Optional[Tuple[int, int]] = None
resource_name_list: List[str] = []
MAP_RATIO = 0.5
# 查找资源
async def query_resource(resource_name: str) -> str:
global CENTER_POINT
planning_route: bool = False
if resource_name and resource_name[-2:] in ["路径", "路线"]:
resource_name = resource_name[:-2].strip()
planning_route = True
if not resource_name or resource_name not in resource_name_list:
# return f"未查找到 {resource_name} 资源,可通过 “原神资源列表” 获取全部资源名称.."
return ""
map_ = Map(
resource_name, CENTER_POINT, planning_route=planning_route, ratio=MAP_RATIO
)
count = map_.get_resource_count()
rand = await asyncio.get_event_loop().run_in_executor(
None, map_.generate_resource_icon_in_map
)
return (
f"{image(f'genshin_map_{rand}.png', 'temp')}"
f"\n\n※ {resource_name} 一共找到 {count} 个位置点\n※ 数据来源于米游社wiki"
)
# 原神资源列表
def get_resource_type_list():
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
temp = {}
for id_ in data.keys():
temp[data[id_]["name"]] = []
for x in data[id_]["children"]:
temp[data[id_]["name"]].append(x["name"])
mes = "当前资源列表如下:\n"
for resource_type in temp.keys():
mes += f"{resource_type}:{','.join(temp[resource_type])}\n"
return mes
def check_resource_exists(resource: str) -> bool:
"""
检查资源是否存在
:param resource: 资源名称
"""
resource = resource.replace("路径", "").replace("路线", "")
return resource in resource_name_list
@driver.on_startup
async def init(flag: bool = False):
global CENTER_POINT, resource_name_list
try:
semaphore = asyncio.Semaphore(10)
await download_map_init(semaphore, flag)
await download_resource_data(semaphore)
await download_resource_type()
if not CENTER_POINT:
if resource_label_file.exists():
CENTER_POINT = json.load(
open(resource_label_file, "r", encoding="utf8")
)["CENTER_POINT"]
if resource_label_file.exists():
with open(resource_type_file, "r", encoding="utf8") as f:
data = json.load(f)
for id_ in data:
for x in data[id_]["children"]:
resource_name_list.append(x["name"])
except TimeoutError:
logger.warning("原神资源查询信息初始化超时....")
# 图标及位置资源
async def download_resource_data(semaphore: Semaphore):
icon_path.mkdir(parents=True, exist_ok=True)
resource_label_file.parent.mkdir(parents=True, exist_ok=True)
try:
response = await AsyncHttpx.get(POINT_LIST_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
data = data["data"]
for lst in ["label_list", "point_list"]:
resource_data = {"CENTER_POINT": CENTER_POINT}
tasks = []
file = (
resource_label_file
if lst == "label_list"
else resource_point_file
)
for x in data[lst]:
id_ = x["id"]
if lst == "label_list":
img_url = x["icon"]
tasks.append(
asyncio.ensure_future(
download_image(
img_url,
f"{icon_path}/{id_}.png",
semaphore,
True,
)
)
)
resource_data[id_] = x
await asyncio.gather(*tasks)
with open(file, "w", encoding="utf8") as f:
json.dump(resource_data, f, ensure_ascii=False, indent=4)
else:
logger.warning(f'获取原神资源失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神资源失败 code:{response.status_code}")
except (TimeoutError, ConnectTimeout):
logger.warning("获取原神资源数据超时...已再次尝试...")
await download_resource_data(semaphore)
except Exception as e:
logger.error(f"获取原神资源数据未知错误 {type(e)}:{e}")
# 下载原神地图并拼图
async def download_map_init(semaphore: Semaphore, flag: bool = False):
global CENTER_POINT, MAP_RATIO
map_path.mkdir(exist_ok=True, parents=True)
_map = map_path / "map.png"
if _map.exists() and os.path.getsize(_map) > 1024 * 1024 * 30:
_map.unlink()
try:
response = await AsyncHttpx.get(MAP_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
data = json.loads(data["data"]["info"]["detail"])
CENTER_POINT = (data["origin"][0], data["origin"][1])
if not _map.exists():
data = data["slices"]
idx = 0
for _map_data in data[0]:
map_url = _map_data["url"]
await download_image(
map_url,
f"{map_path}/{idx}.png",
semaphore,
force_flag=flag,
)
BuildImage(
0, 0, background=f"{map_path}/{idx}.png", ratio=MAP_RATIO
).save()
idx += 1
_w, h = BuildImage(0, 0, background=f"{map_path}/0.png").size
w = _w * len(os.listdir(map_path))
map_file = BuildImage(w, h, _w, h, ratio=MAP_RATIO)
for i in range(idx):
map_file.paste(
BuildImage(0, 0, background=f"{map_path}/{i}.png")
)
map_file.save(f"{map_path}/map.png")
else:
logger.warning(f'获取原神地图失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神地图失败 code:{response.status_code}")
except (TimeoutError, ConnectTimeout):
logger.warning("下载原神地图数据超时....")
except Exception as e:
logger.error(f"下载原神地图数据超时 {type(e)}:{e}")
# 下载资源类型数据
async def download_resource_type():
resource_type_file.parent.mkdir(parents=True, exist_ok=True)
try:
response = await AsyncHttpx.get(LABEL_URL, timeout=10)
if response.status_code == 200:
data = response.json()
if data["message"] == "OK":
data = data["data"]["tree"]
resource_data = {}
for x in data:
id_ = x["id"]
resource_data[id_] = x
with open(resource_type_file, "w", encoding="utf8") as f:
json.dump(resource_data, f, ensure_ascii=False, indent=4)
logger.info(f"更新原神资源类型成功...")
else:
logger.warning(f'获取原神资源类型失败 msg: {data["message"]}')
else:
logger.warning(f"获取原神资源类型失败 code:{response.status_code}")
except (TimeoutError, ConnectTimeout):
logger.warning("下载原神资源类型数据超时....")
except Exception as e:
logger.error(f"载原神资源类型数据超时 {type(e)}:{e}")
# 初始化资源图标
def gen_icon(icon: str):
A = BuildImage(0, 0, background=f"{icon_path}/box.png")
B = BuildImage(0, 0, background=f"{icon_path}/box_alpha.png")
icon_ = icon_path / f"{icon}"
icon_img = BuildImage(115, 115, background=icon_)
icon_img.circle()
B.paste(icon_img, (17, 10), True)
B.paste(A, alpha=True)
B.save(icon)
logger.info(f"生成图片成功 file:{str(icon)}")
# 下载图片
async def download_image(
img_url: str,
path: str,
semaphore: Semaphore,
gen_flag: bool = False,
force_flag: bool = False,
):
async with semaphore:
try:
if not os.path.exists(path) or not is_valid or force_flag:
if await AsyncHttpx.download_file(img_url, path, timeout=10):
logger.info(f"下载原神资源图标:{img_url}")
if gen_flag:
gen_icon(path)
else:
logger.info(f"下载原神资源图标:{img_url} 失败,等待下次更新...")
except UnidentifiedImageError:
logger.warning(f"原神图片打开错误..已删除,等待下次更新... file: {path}")
if os.path.exists(path):
os.remove(path)
#
# def _get_point_ratio():
# | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/genshin/query_resource_points/query_resource.py | query_resource.py |
import random
import pypinyin
BLUE = 0.7981
BLUE_ST = 0.0699
PURPLE = 0.1626
PURPLE_ST = 0.0164
PINK = 0.0315
PINK_ST = 0.0048
RED = 0.0057
RED_ST = 0.00021
KNIFE = 0.0021
KNIFE_ST = 0.000041
# 崭新
FACTORY_NEW_S = 0
FACTORY_NEW_E = 0.0699999
# 略磨
MINIMAL_WEAR_S = 0.07
MINIMAL_WEAR_E = 0.14999
# 久经
FIELD_TESTED_S = 0.15
FIELD_TESTED_E = 0.37999
# 破损
WELL_WORN_S = 0.38
WELL_WORN_E = 0.44999
# 战痕
BATTLE_SCARED_S = 0.45
BATTLE_SCARED_E = 0.99999
# 狂牙大行动
KUANGYADAXINGDONG_CASE_KNIFE = ['摩托手套 | 第三特种兵连', '狂牙手套 | 翡翠', '驾驶手套 | 美洲豹女王', '运动手套 | 弹弓', '专业手套 | 老虎精英'
, '专业手套 | 渐变大理石', '运动手套 | 夜行衣', '驾驶手套 | 西装革履', '摩托手套 | 终点线', '摩托手套 | 血压',
'运动手套 | 猩红头巾', '驾驶手套 | 雪豹', '裹手 | 长颈鹿', '驾驶手套 | 绯红列赞', '裹手 | 沙漠头巾',
'专业手套 | 一线特工', '狂牙手套 | 黄色斑纹', '摩托手套 | 小心烟幕弹', '裹手 | 蟒蛇', '裹手 | 警告!',
'狂牙手套 | 精神错乱', '运动手套 | 大型猎物', '狂牙手套 | 针尖', '专业手套 | 陆军少尉长官']
KUANGYADAXINGDONG_CASE_RED = ['M4A1 | 印花集', '格洛克 | 黑色魅影']
KUANGYADAXINGDONG_CASE_PINK = ['FN57 | 童话城堡', 'M4A4 | 赛博', 'USP | 小绿怪']
KUANGYADAXINGDONG_CASE_PURPLE = ['AWP | 亡灵之主', '双持贝瑞塔 | 灾难', '新星 | 一见青心', 'SSG 08 | 抖枪', 'UMP-45 | 金铋辉煌']
KUANGYADAXINGDONG_CASE_BLUE = ['CZ75 | 世仇', 'P90 | 大怪兽RUSH', 'G3SG1 | 血腥迷彩', '加利尔 AR | 破坏者', 'P250 | 污染物',
'M249 | 等高线', 'MP5-SD | 零点行动']
# 突围大行动
TUWEIDAXINGDONG_CASE_KNIFE = ['蝴蝶刀 | 无涂装', '蝴蝶刀 | 蓝钢', '蝴蝶刀 | 屠夫', '蝴蝶刀 | 森林 DDPAT', '蝴蝶刀 | 北方森林',
'蝴蝶刀 | 狩猎网格', '蝴蝶刀 | 枯焦之色', '蝴蝶刀 | 人工染色', '蝴蝶刀 | 都市伪装', '蝴蝶刀 | 表面淬火',
'蝴蝶刀 | 深红之网', '蝴蝶刀 | 渐变之色', '蝴蝶刀 | 噩梦之夜']
TUWEIDAXINGDONG_CASE_RED = ['P90 | 二西莫夫', 'M4A1 | 次时代']
TUWEIDAXINGDONG_CASE_PINK = ['沙漠之鹰 | 阴谋者', 'FN57 | 狩猎利器', '格洛克 | 水灵']
TUWEIDAXINGDONG_CASE_PURPLE = ['PP-野牛 | 死亡主宰者', 'CZ75 | 猛虎', '新星 | 锦鲤', 'P250 | 超新星']
TUWEIDAXINGDONG_CASE_BLUE = ['MP7 | 都市危机', '内格夫 | 沙漠精英', 'P2000 | 乳白象牙', 'SSG 08 | 无尽深海', 'UMP-45 | 迷之宫']
# 命悬一线
MINGXUANYIXIAN_CASE_KNIFE = ['专业手套 | 大腕', '专业手套 | 深红之网', '专业手套 | 渐变之色', '专业手套 | 狩鹿', '九头蛇手套 | 响尾蛇',
'九头蛇手套 | 红树林', '九头蛇手套 | 翡翠色调', '九头蛇手套 | 表面淬火', '摩托手套 | 交运', '摩托手套 | 嘭!',
'摩托手套 | 多边形', '摩托手套 | 玳瑁', '裹手 | 套印', '裹手 | 森林色调', '裹手 | 钴蓝骷髅', '裹手 | 防水布胶带',
'运动手套 | 双栖', '运动手套 | 欧米伽', '运动手套 | 迈阿密风云', '运动手套 | 青铜形态', '驾驶手套 | 墨绿色调',
'驾驶手套 | 王蛇', '驾驶手套 | 蓝紫格子', '驾驶手套 | 超越']
MINGXUANYIXIAN_CASE_RED = ['M4A4 | 黑色魅影', 'MP7 | 血腥运动']
MINGXUANYIXIAN_CASE_PINK = ['AUG | 湖怪鸟', 'AWP | 死神', 'USP | 脑洞大开']
MINGXUANYIXIAN_CASE_PURPLE = ['MAG-7 | SWAG-7', 'UMP-45 | 白狼', '内格夫 | 狮子鱼', '新星 | 狂野六号', '格洛克 | 城里的月光']
MINGXUANYIXIAN_CASE_BLUE = ['FN57 | 焰色反应', 'MP9 | 黑砂', 'P2000 | 都市危机', 'PP-野牛 | 黑夜暴乱', 'R8 左轮手枪 | 稳',
'SG 553 | 阿罗哈', 'XM1014 | 锈蚀烈焰']
LIEKONG_CASE_KNIFE = ['求生匕首 | 无涂装', '求生匕首 | 人工染色', '求生匕首 | 北方森林', '求生匕首 | 夜色', '求生匕首 | 屠夫',
'求生匕首 | 枯焦之色', '求生匕首 | 森林 DDPAT', '求生匕首 | 深红之网', '求生匕首 | 渐变之色', '求生匕首 | 狩猎网格',
'求生匕首 | 蓝钢', '求生匕首 | 表面淬火', '求生匕首 | 都市伪装', '流浪者匕首 | 无涂装', '流浪者匕首 | 人工染色',
'流浪者匕首 | 北方森林', '流浪者匕首 | 夜色', '流浪者匕首 | 屠夫', '流浪者匕首 | 枯焦之色', '流浪者匕首 | 森林 DDPAT',
'流浪者匕首 | 深红之网', '流浪者匕首 | 渐变之色', '流浪者匕首 | 狩猎网格', '流浪者匕首 | 蓝钢', '流浪者匕首 | 表面淬火',
'流浪者匕首 | 都市伪装', '系绳匕首 | 无涂装', '系绳匕首 | 人工染色', '系绳匕首 | 北方森林', '系绳匕首 | 夜色',
'系绳匕首 | 屠夫', '系绳匕首 | 枯焦之色', '系绳匕首 | 森林 DDPAT', '系绳匕首 | 深红之网', '系绳匕首 | 渐变之色',
'系绳匕首 | 狩猎网格', '系绳匕首 | 蓝钢', '系绳匕首 | 表面淬火', '系绳匕首 | 都市伪装', '骷髅匕首 | 无涂装',
'骷髅匕首 | 人工染色', '骷髅匕首 | 北方森林', '骷髅匕首 | 夜色', '骷髅匕首 | 屠夫', '骷髅匕首 | 枯焦之色',
'骷髅匕首 | 森林 DDPAT', '骷髅匕首 | 深红之网', '骷髅匕首 | 渐变之色', '骷髅匕首 | 狩猎网格', '骷髅匕首 | 蓝钢',
'骷髅匕首 | 表面淬火', '骷髅匕首 | 都市伪装']
LIEKONG_CASE_RED = ['AK-47 | 阿努比斯军团', '沙漠之鹰 | 印花集']
LIEKONG_CASE_PINK = ['M4A4 | 齿仙', 'XM1014 | 埋葬之影', '格洛克 | 摩登时代']
LIEKONG_CASE_PURPLE = ['加利尔 AR | 凤凰商号', 'Tec-9 | 兄弟连', 'MP5-SD | 猛烈冲锋', 'MAG-7 | 北冥有鱼', 'MAC-10 | 魅惑']
LIEKONG_CASE_BLUE = ['内格夫 | 飞羽', 'SSG 08 | 主机001', 'SG 553 | 锈蚀之刃', 'PP-野牛 | 神秘碑文', 'P90 | 集装箱', 'P250 | 卡带',
'P2000 | 盘根错节']
GUANGPU_CASE_KNIFE = ['弯刀 | 外表生锈', '弯刀 | 多普勒', '弯刀 | 大马士革钢', '弯刀 | 渐变大理石', '弯刀 | 致命紫罗兰', '弯刀 | 虎牙',
'暗影双匕 | 外表生锈', '暗影双匕 | 多普勒', '暗影双匕 | 大马士革钢', '暗影双匕 | 渐变大理石', '暗影双匕 | 致命紫罗兰',
'暗影双匕 | 虎牙', '猎杀者匕首 | 外表生锈', '猎杀者匕首 | 多普勒', '猎杀者匕首 | 大马士革钢', '猎杀者匕首 | 渐变大理石',
'猎杀者匕首 | 致命紫罗兰', '猎杀者匕首 | 虎牙', '蝴蝶刀 | 外表生锈', '蝴蝶刀 | 多普勒', '蝴蝶刀 | 大马士革钢',
'蝴蝶刀 | 渐变大理石', '蝴蝶刀 | 致命紫罗兰', '蝴蝶刀 | 虎牙', '鲍伊猎刀 | 外表生锈', '鲍伊猎刀 | 多普勒',
'鲍伊猎刀 | 大马士革钢', '鲍伊猎刀 | 渐变大理石', '鲍伊猎刀 | 致命紫罗兰', '鲍伊猎刀 | 虎牙']
GUANGPU_CASE_RED = ['USP | 黑色魅影', 'AK-47 | 血腥运动']
GUANGPU_CASE_PINK = ['M4A1 | 毁灭者 2000', 'CZ75 | 相柳', 'AWP | 浮生如梦']
GUANGPU_CASE_PURPLE = ['加利尔 AR | 深红海啸', 'XM1014 | 四季', 'UMP-45 | 支架', 'MAC-10 | 绝界之行', 'M249 | 翠绿箭毒蛙']
GUANGPU_CASE_BLUE = ['沙漠之鹰 | 锈蚀烈焰', '截短霰弹枪 | 梭鲈', 'SCAR-20 | 蓝图', 'PP-野牛 | 丛林滑流', 'P250 | 涟漪', 'MP7 | 非洲部落',
'FN57 | 毛细血管']
NO_STA_KNIFE = ['求生匕首 | 北方森林', '求生匕首 | 夜色', '求生匕首 | 枯焦之色', '流浪者匕首 | 夜色', '流浪者匕首 | 枯焦之色', '流浪者匕首 | 森林 DDPAT',
'系绳匕首 | 夜色', '系绳匕首 | 狩猎网格', '骷髅匕首 | 夜色', '骷髅匕首 | 森林 DDPAT', '骷髅匕首 | 狩猎网格']
def get_wear(num: float) -> str:
if num <= FACTORY_NEW_E:
return "崭新出厂"
if MINIMAL_WEAR_S <= num <= MINIMAL_WEAR_E:
return "略有磨损"
if FIELD_TESTED_S <= num <= FIELD_TESTED_E:
return "久经沙场"
if WELL_WORN_S <= num <= WELL_WORN_E:
return "破损不堪"
return "战痕累累"
def get_color_quality(rand: float, case_name: str):
case = ""
mosun = random.random()/2 + random.random()/2
for i in pypinyin.pinyin(case_name, style=pypinyin.NORMAL):
case += ''.join(i)
case = case.upper()
CASE_KNIFE = eval(case + "_CASE_KNIFE")
CASE_RED = eval(case + "_CASE_RED")
CASE_PINK = eval(case + "_CASE_PINK")
CASE_PURPLE = eval(case + "_CASE_PURPLE")
CASE_BLUE = eval(case + "_CASE_BLUE")
if rand <= KNIFE:
skin = "罕见级(金色): " + random.choice(CASE_KNIFE)
if random.random() <= KNIFE_ST and (skin[2:4] != "手套" or skin[:2] != "裹手") and skin.split(':')[1] \
not in NO_STA_KNIFE:
skin_sp = skin.split("|")
skin = skin_sp[0] + "(StatTrak™) | " + skin_sp[1]
elif KNIFE < rand <= RED:
skin = "隐秘级(红色): " + random.choice(CASE_RED)
if random.random() <= RED_ST:
skin_sp = skin.split("|")
skin = skin_sp[0] + "(StatTrak™) | " + skin_sp[1]
elif RED < rand <= PINK:
skin = "保密级(粉色): " + random.choice(CASE_PINK)
if random.random() <= PINK_ST:
skin_sp = skin.split("|")
skin = skin_sp[0] + "(StatTrak™) | " + skin_sp[1]
elif PINK < rand <= PURPLE:
skin = "受限级(紫色): " + random.choice(CASE_PURPLE)
if random.random() <= PURPLE_ST:
skin_sp = skin.split("|")
skin = skin_sp[0] + "(StatTrak™) | " + skin_sp[1]
else:
skin = "军规级(蓝色): " + random.choice(CASE_BLUE)
if random.random() <= BLUE_ST:
skin_sp = skin.split("|")
skin = skin_sp[0] + "(StatTrak™) | " + skin_sp[1]
if skin.find("(") != -1:
cpskin = skin.split(":")[1]
ybskin = cpskin.split("|")
temp_skin = ybskin[0].strip()[:-11] + " | " + ybskin[1].strip()
else:
temp_skin = skin.split(":")[1].strip()
# 崭新 -> 略磨
if temp_skin in [] or temp_skin.find('渐变之色') != -1 or temp_skin.find('多普勒') != -1 or temp_skin.find('虎牙') != -1\
or temp_skin.find('渐变大理石') != -1:
mosun = random.uniform(FACTORY_NEW_S, MINIMAL_WEAR_E) / 2 + random.uniform(FACTORY_NEW_S, MINIMAL_WEAR_E) / 2
# 崭新 -> 久经
if temp_skin in ['沙漠之鹰 | 阴谋者', '新星 | 锦鲤'] or temp_skin.find('屠夫') != -1:
mosun = random.uniform(FACTORY_NEW_S, FIELD_TESTED_E) / 2 + random.uniform(FACTORY_NEW_S, FIELD_TESTED_E) / 2
# 崭新 -> 破损
if temp_skin in ['UMP-45 | 迷之宫', 'P250 | 超新星', '系绳匕首 | 深红之网', 'M249 | 翠绿箭毒蛙', 'AK-47 | 血腥运动']:
mosun = random.uniform(FACTORY_NEW_S, WELL_WORN_E) / 2 + random.uniform(FACTORY_NEW_S, WELL_WORN_E) / 2
# 破损 -> 战痕
if temp_skin in [] or temp_skin.find('外表生锈') != -1:
mosun = random.uniform(WELL_WORN_S, BATTLE_SCARED_E) / 2 + random.uniform(WELL_WORN_S, BATTLE_SCARED_E) / 2
if mosun > MINIMAL_WEAR_E:
for _ in range(2):
if random.random() < 5:
if random.random() < 0.2:
mosun /= 3
else:
mosun /= 2
break
skin += " (" + get_wear(mosun) + ")"
return skin, mosun
# M249(StatTrak™) | 等高线 | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/open_cases/config.py | config.py |
from datetime import datetime, timedelta
from .config import *
from services.log import logger
from services.db_context import db
from .models.open_cases_user import OpenCasesUser
from models.sign_group_user import SignGroupUser
from utils.message_builder import image
import pypinyin
import random
from .utils import get_price
from .models.buff_prices import BuffPrice
from PIL import Image
from utils.image_utils import alpha2white_pil, BuildImage
from configs.path_config import IMAGE_PATH
import asyncio
from utils.utils import cn2py
from configs.config import Config
async def open_case(user_qq: int, group: int, case_name: str = "狂牙大行动") -> str:
if case_name not in ["狂牙大行动", "突围大行动", "命悬一线", "裂空", "光谱"]:
return "武器箱未收录"
knifes_flag = False
# lan zi fen hong jin price
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]
case = ""
for i in pypinyin.pinyin(case_name, style=pypinyin.NORMAL):
case += "".join(i)
impression = (await SignGroupUser.ensure(user_qq, group)).impression
rand = random.random()
async with db.transaction():
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
# 一天次数上限
if user.today_open_total == int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression)
/ Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
):
return _handle_is_MAX_COUNT()
skin, mosun = get_color_quality(rand, case_name)
# 调侃
if skin[:2] == "军规":
if skin.find("StatTrak") == -1:
uplist[0] = 1
else:
uplist[1] = 1
ridicule_result = random.choice(["这样看着才舒服", "是自己人,大伙把刀收好", "非常舒适~"])
if skin[:2] == "受限":
if skin.find("StatTrak") == -1:
uplist[2] = 1
else:
uplist[3] = 1
ridicule_result = random.choice(
["还行吧,勉强接受一下下", "居然不是蓝色,太假了", "运气-1-1-1-1-1..."]
)
if skin[:2] == "保密":
if skin.find("StatTrak") == -1:
uplist[4] = 1
else:
uplist[5] = 1
ridicule_result = random.choice(
["开始不适....", "你妈妈买菜必涨价!涨三倍!", "你最近不适合出门,真的"]
)
if skin[:2] == "隐秘":
if skin.find("StatTrak") == -1:
uplist[6] = 1
else:
uplist[7] = 1
ridicule_result = random.choice(
["已经非常不适", "好兄弟你开的什么箱子啊,一般箱子不是只有蓝色的吗", "开始拿阳寿开箱子了?"]
)
if skin[:2] == "罕见":
knifes_flag = True
if skin.find("StatTrak") == -1:
uplist[8] = 1
else:
uplist[9] = 1
ridicule_result = random.choice(
["你的好运我收到了,你可以去喂鲨鱼了", "最近该吃啥就迟点啥吧,哎,好好的一个人怎么就....哎", "众所周知,欧皇寿命极短."]
)
if skin.find("(") != -1:
cskin = skin.split("(")
skin = cskin[0].strip() + "(" + cskin[1].strip()
skin = skin.split("|")[0].strip() + " | " + skin.split("|")[1].strip()
# 价格
if skin.find("无涂装") == -1:
dbprice = await BuffPrice.ensure(skin[9:])
else:
dbprice = await BuffPrice.ensure(skin[9 : skin.rfind("(")].strip())
if dbprice.skin_price != 0:
price_result = dbprice.skin_price
logger.info("数据库查询到价格: ", dbprice.skin_price)
uplist[10] = dbprice.skin_price
else:
price = -1
price_result = "未查询到"
price_list, status = await get_price(skin[9:])
if price_list not in ["访问超时! 请重试或稍后再试!", "访问失败!"]:
for price_l in price_list[1:]:
pcp = price_l.split(":")
if pcp[0] == skin[9:]:
price = float(pcp[1].strip())
break
if price != -1:
logger.info("存储入数据库---->", price)
uplist[10] = price
price_result = str(price)
await dbprice.update(
skin_price=price,
update_date=datetime.now(),
).apply()
# sp = skin.split("|")
# cskin_word = sp[1][:sp[1].find("(") - 1].strip()
if knifes_flag:
await user.update(
knifes_name=user.knifes_name
+ f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{uplist[10]},"
).apply()
cskin_word = skin.split(":")[1].replace("|", "-").replace("(StatTrak™)", "")
cskin_word = cskin_word[: cskin_word.rfind("(")].strip()
skin_name = cn2py(
cskin_word.replace("|", "-").replace("(StatTrak™)", "").strip()
)
img = image(f"{skin_name}.png", "cases/" + case)
# if knifes_flag:
# await user.update(
# knifes_name=user.knifes_name + f"{skin} 磨损:{mosun}, 价格:{uplist[10]}"
# ).apply()
if await update_user_total(user, uplist):
logger.info(
f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新成功"
)
else:
logger.warning(
f"qq:{user_qq} 群:{group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}, 数据更新失败"
)
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
over_count = int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression)
/ Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
) - user.today_open_total
return (
f"开启{case_name}武器箱.\n剩余开箱次数:{over_count}.\n" + img + "\n" + f"皮肤:{skin}\n"
f"磨损:{mosun:.9f}\n"
f"价格:{price_result}\n"
f"{ridicule_result}"
)
async def open_shilian_case(user_qq: int, group: int, case_name: str, num: int = 10):
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
impression = (await SignGroupUser.ensure(user_qq, group)).impression
max_count = int(
Config.get_config("open_cases", "INITIAL_OPEN_CASE_COUNT")
+ int(impression) / Config.get_config("open_cases", "EACH_IMPRESSION_ADD_COUNT")
)
if user.today_open_total == max_count:
return _handle_is_MAX_COUNT()
if max_count - user.today_open_total < num:
return (
f"今天开箱次数不足{num}次噢,请单抽试试看(也许单抽运气更好?)"
f"\n剩余开箱次数:{max_count - user.today_open_total}"
)
await user.update(
total_count=user.total_count + num,
spend_money=user.spend_money + 17 * num,
today_open_total=user.today_open_total + num,
).apply()
if num < 5:
h = 270
elif num % 5 == 0:
h = 270 * int(num / 5)
else:
h = 270 * int(num / 5) + 270
case = cn2py(case_name)
# lan zi fen hong jin
# skin_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# lan zi fen hong jin price
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0]
img_list = []
name_list = ["蓝", "蓝(暗金)", "紫", "紫(暗金)", "粉", "粉(暗金)", "红", "红(暗金)", "金", "金(暗金)"]
async with db.transaction():
for _ in range(num):
knifes_flag = False
rand = random.random()
skin, mosun = get_color_quality(rand, case_name)
if skin[:2] == "军规":
if skin.find("StatTrak") == -1:
uplist[0] += 1
else:
uplist[1] += 1
if skin[:2] == "受限":
if skin.find("StatTrak") == -1:
uplist[2] += 1
else:
uplist[3] += 1
if skin[:2] == "保密":
if skin.find("StatTrak") == -1:
uplist[4] += 1
else:
uplist[5] += 1
if skin[:2] == "隐秘":
if skin.find("StatTrak") == -1:
uplist[6] += 1
else:
uplist[7] += 1
if skin[:2] == "罕见":
knifes_flag = True
if skin.find("StatTrak") == -1:
uplist[8] += 1
else:
uplist[9] += 1
if skin.find("(") != -1:
cskin = skin.split("(")
skin = cskin[0].strip() + "(" + cskin[1].strip()
skin = skin.split("|")[0].strip() + " | " + skin.split("|")[1].strip()
# 价格
if skin.find("无涂装") == -1:
dbprice = await BuffPrice.ensure(skin[9:])
else:
dbprice = await BuffPrice.ensure(skin[9 : skin.rfind("(")].strip())
if dbprice.skin_price != 0:
price_result = dbprice.skin_price
uplist[10] += price_result
else:
price_result = "未查询到"
if knifes_flag:
await user.update(
knifes_name=user.knifes_name
+ f"{case}||{skin.split(':')[1].strip()} 磨损:{str(mosun)[:11]}, 价格:{dbprice.skin_price},"
).apply()
cskin_word = skin.split(":")[1].replace("|", "-").replace("(StatTrak™)", "")
cskin_word = cskin_word[: cskin_word.rfind("(")].strip()
skin_name = ""
for i in pypinyin.pinyin(
cskin_word.replace("|", "-").replace("(StatTrak™)", "").strip(),
style=pypinyin.NORMAL,
):
skin_name += "".join(i)
# img = image(skin_name, "cases/" + case, "png")
wImg = BuildImage(200, 270, 200, 200)
wImg.paste(
alpha2white_pil(
Image.open(IMAGE_PATH / "cases" / case / f"{skin_name}.png").resize(
(200, 200), Image.ANTIALIAS
)
),
(0, 0),
)
wImg.text((5, 200), skin)
wImg.text((5, 220), f"磨损:{str(mosun)[:9]}")
wImg.text((5, 240), f"价格:{price_result}")
img_list.append(wImg)
logger.info(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 获得 {skin} 磨损:{mosun}, 价格:{uplist[10]}"
)
if await update_user_total(user, uplist, 0):
logger.info(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 数据更新成功"
)
else:
logger.warning(
f"USER {user_qq} GROUP {group} 开启{case_name}武器箱 {num} 次, 价格:{uplist[10]}, 数据更新失败"
)
# markImg = BuildImage(1000, h, 200, 270)
# for img in img_list:
# markImg.paste(img)
markImg = await asyncio.get_event_loop().run_in_executor(
None, paste_markImg, h, img_list
)
over_count = max_count - user.today_open_total
result = ""
for i in range(len(name_list)):
if uplist[i]:
result += f"[{name_list[i]}:{uplist[i]}] "
return (
f"开启{case_name}武器箱\n剩余开箱次数:{over_count}\n"
+ image(b64=markImg.pic2bs4())
+ "\n"
+ result[:-1]
+ f"\n总获取金额:{uplist[-1]:.2f}\n总花费:{17 * num}"
)
def paste_markImg(h: int, img_list: list):
markImg = BuildImage(1000, h, 200, 270)
for img in img_list:
markImg.paste(img)
return markImg
def _handle_is_MAX_COUNT() -> str:
return f"今天已达开箱上限了喔,明天再来吧\n(提升好感度可以增加每日开箱数 #疯狂暗示)"
async def update_user_total(user: OpenCasesUser, up_list: list, num: int = 1) -> bool:
try:
await user.update(
total_count=user.total_count + num,
blue_count=user.blue_count + up_list[0],
blue_st_count=user.blue_st_count + up_list[1],
purple_count=user.purple_count + up_list[2],
purple_st_count=user.purple_st_count + up_list[3],
pink_count=user.pink_count + up_list[4],
pink_st_count=user.pink_st_count + up_list[5],
red_count=user.red_count + up_list[6],
red_st_count=user.red_st_count + up_list[7],
knife_count=user.knife_count + up_list[8],
knife_st_count=user.knife_st_count + up_list[9],
spend_money=user.spend_money + 17 * num,
make_money=user.make_money + up_list[10],
today_open_total=user.today_open_total + num,
open_cases_time_last=datetime.now(),
).apply()
return True
except:
return False
async def total_open_statistics(user_qq: int, group: int) -> str:
async with db.transaction():
user = await OpenCasesUser.ensure(user_qq, group, for_update=True)
return (
f"开箱总数:{user.total_count}\n"
f"今日开箱:{user.today_open_total}\n"
f"蓝色军规:{user.blue_count}\n"
f"蓝色暗金:{user.blue_st_count}\n"
f"紫色受限:{user.purple_count}\n"
f"紫色暗金:{user.purple_st_count}\n"
f"粉色保密:{user.pink_count}\n"
f"粉色暗金:{user.pink_st_count}\n"
f"红色隐秘:{user.red_count}\n"
f"红色暗金:{user.red_st_count}\n"
f"金色罕见:{user.knife_count}\n"
f"金色暗金:{user.knife_st_count}\n"
f"花费金额:{user.spend_money}\n"
f"获取金额:{user.make_money:.2f}\n"
f"最后开箱日期:{(user.open_cases_time_last + timedelta(hours=8)).date()}"
)
async def group_statistics(group: int):
user_list = await OpenCasesUser.get_user_all(group)
# lan zi fen hong jin pricei
uplist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.0, 0, 0]
for user in user_list:
uplist[0] += user.blue_count
uplist[1] += user.blue_st_count
uplist[2] += user.purple_count
uplist[3] += user.purple_st_count
uplist[4] += user.pink_count
uplist[5] += user.pink_st_count
uplist[6] += user.red_count
uplist[7] += user.red_st_count
uplist[8] += user.knife_count
uplist[9] += user.knife_st_count
uplist[10] += user.make_money
uplist[11] += user.total_count
uplist[12] += user.today_open_total
return (
f"群开箱总数:{uplist[11]}\n"
f"群今日开箱:{uplist[12]}\n"
f"蓝色军规:{uplist[0]}\n"
f"蓝色暗金:{uplist[1]}\n"
f"紫色受限:{uplist[2]}\n"
f"紫色暗金:{uplist[3]}\n"
f"粉色保密:{uplist[4]}\n"
f"粉色暗金:{uplist[5]}\n"
f"红色隐秘:{uplist[6]}\n"
f"红色暗金:{uplist[7]}\n"
f"金色罕见:{uplist[8]}\n"
f"金色暗金:{uplist[9]}\n"
f"花费金额:{uplist[11] * 17}\n"
f"获取金额:{uplist[10]:.2f}"
)
async def my_knifes_name(user_id: int, group: int):
knifes_name = (await OpenCasesUser.ensure(user_id, group)).knifes_name
if knifes_name:
knifes_list = knifes_name[:-1].split(",")
length = len(knifes_list)
if length < 5:
h = 600
w = length * 540
elif length % 5 == 0:
h = 600 * int(length / 5)
w = 540 * 5
else:
h = 600 * int(length / 5) + 600
w = 540 * 5
A = await asyncio.get_event_loop().run_in_executor(
None, _pst_my_knife, w, h, knifes_list
)
return image(b64=A.pic2bs4())
else:
return "您木有开出金色级别的皮肤喔"
def _pst_my_knife(w, h, knifes_list):
A = BuildImage(w, h, 540, 600)
for knife in knifes_list:
case = knife.split("||")[0]
knife = knife.split("||")[1]
name = knife[: knife.find("(")].strip()
itype = knife[knife.find("(") + 1 : knife.find(")")].strip()
mosun = knife[knife.find("磨损:") + 3 : knife.rfind("价格:")].strip()
if mosun[-1] == "," or mosun[-1] == ",":
mosun = mosun[:-1]
price = knife[knife.find("价格:") + 3 :]
skin_name = ""
for i in pypinyin.pinyin(
name.replace("|", "-").replace("(StatTrak™)", "").strip(),
style=pypinyin.NORMAL,
):
skin_name += "".join(i)
knife_img = BuildImage(470, 600, 470, 470, font_size=20)
knife_img.paste(
alpha2white_pil(
Image.open(IMAGE_PATH / f"cases" / case / f"{skin_name}.png").resize(
(470, 470), Image.ANTIALIAS
)
),
(0, 0),
)
knife_img.text((5, 500), f"\t{name}({itype})")
knife_img.text((5, 530), f"\t磨损:{mosun}")
knife_img.text((5, 560), f"\t价格:{price}")
A.paste(knife_img)
return A
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累)
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累)
# G3SG1(StatTrak™) | 血腥迷彩 (战痕累累) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/open_cases/open_cases_c.py | open_cases_c.py |
from .models.buff_prices import BuffPrice
from services.db_context import db
from datetime import datetime, timedelta
from configs.path_config import IMAGE_PATH
from utils.http_utils import AsyncHttpx
from .models.open_cases_user import OpenCasesUser
from services.log import logger
from utils.utils import get_bot, cn2py
from asyncio.exceptions import TimeoutError
from nonebot.adapters.onebot.v11.exception import ActionFailed
from configs.config import Config
from utils.manager import group_manager
from .config import *
import os
url = "https://buff.163.com/api/market/goods"
# proxies = 'http://49.75.59.242:3128'
async def util_get_buff_price(case_name: str = "狂牙大行动") -> str:
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
failed_list = []
case = cn2py(case_name)
if case_name == "狂牙大行动":
case_id = 1
elif case_name == "突围大行动":
case_id = 2
elif case_name == "命悬一线":
case_id = 3
elif case_name == "裂空":
case_id = 4
elif case_name == "光谱":
case_id = 5
else:
return "未查询到武器箱"
case = case.upper()
CASE_KNIFE = eval(case + "_CASE_KNIFE")
CASE_RED = eval(case + "_CASE_RED")
CASE_PINK = eval(case + "_CASE_PINK")
CASE_PURPLE = eval(case + "_CASE_PURPLE")
CASE_BLUE = eval(case + "_CASE_BLUE")
for total_list in [CASE_KNIFE, CASE_RED, CASE_PINK, CASE_PURPLE, CASE_BLUE]:
for skin in total_list:
if skin in [
"蝴蝶刀 | 无涂装",
"求生匕首 | 无涂装",
"流浪者匕首 | 无涂装",
"系绳匕首 | 无涂装",
"骷髅匕首 | 无涂装",
]:
skin = skin.split("|")[0].strip()
async with db.transaction():
name_list = []
price_list = []
parameter = {"game": "csgo", "page_num": "1", "search": skin}
try:
response = await AsyncHttpx.get(url, proxy=Config.get_config("open_cases", "BUFF_PROXY"),
params=parameter,
cookies=cookie,)
if response.status_code == 200:
data = response.json()["data"]
total_page = data["total_page"]
data = data["items"]
flag = False
if (
skin.find("|") == -1
): # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
for i in range(1, total_page + 1):
name_list = []
price_list = []
parameter = {
"game": "csgo",
"page_num": f"{i}",
"search": skin,
}
res = await AsyncHttpx.get(url, params=parameter)
data = res.json()["data"][
"items"
]
for j in range(len(data)):
if data[j]["name"] in [f"{skin}(★)"]:
name = data[j]["name"]
price = data[j][
"sell_reference_price"
]
name_list.append(
name.split("(")[0].strip()
+ " | 无涂装"
)
price_list.append(price)
flag = True
break
if flag:
break
else:
try:
for _ in range(total_page):
for i in range(len(data)):
name = data[i]["name"]
price = data[i]["sell_reference_price"]
name_list.append(name)
price_list.append(price)
except Exception as e:
failed_list.append(skin)
logger.warning(f"{skin}更新失败")
else:
failed_list.append(skin)
logger.warning(f"{skin}更新失败")
except Exception:
failed_list.append(skin)
logger.warning(f"{skin}更新失败")
continue
for i in range(len(name_list)):
name = name_list[i].strip()
price = float(price_list[i])
if name.find("(★)") != -1:
name = name[: name.find("(")] + name[name.find(")") + 1 :]
if name.find("消音") != -1 and name.find("(S") != -1:
name = name.split("(")[0][:-4] + "(" + name.split("(")[1]
name = (
name.split("|")[0].strip()
+ " | "
+ name.split("|")[1].strip()
)
elif name.find("消音") != -1:
name = (
name.split("|")[0][:-5].strip()
+ " | "
+ name.split("|")[1].strip()
)
if name.find(" 18 ") != -1 and name.find("(S") != -1:
name = name.split("(")[0][:-5] + "(" + name.split("(")[1]
name = (
name.split("|")[0].strip()
+ " | "
+ name.split("|")[1].strip()
)
elif name.find(" 18 ") != -1:
name = (
name.split("|")[0][:-6].strip()
+ " | "
+ name.split("|")[1].strip()
)
dbskin = await BuffPrice.ensure(name, True)
if (
dbskin.update_date + timedelta(8)
).date() == datetime.now().date():
continue
await dbskin.update(
case_id=case_id,
skin_price=price,
update_date=datetime.now(),
).apply()
logger.info(f"{name_list[i]}---------->成功更新")
result = None
if failed_list:
result = ""
for fail_skin in failed_list:
result += fail_skin + "\n"
return result[:-1] if result else "更新价格成功"
async def util_get_buff_img(case_name: str = "狂牙大行动") -> str:
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
error_list = []
case = cn2py(case_name)
path = IMAGE_PATH / "cases/" / case
path.mkdir(exist_ok=True, parents=True)
case = case.upper()
CASE_KNIFE = eval(case + "_CASE_KNIFE")
CASE_RED = eval(case + "_CASE_RED")
CASE_PINK = eval(case + "_CASE_PINK")
CASE_PURPLE = eval(case + "_CASE_PURPLE")
CASE_BLUE = eval(case + "_CASE_BLUE")
for total_list in [CASE_KNIFE, CASE_RED, CASE_PINK, CASE_PURPLE, CASE_BLUE]:
for skin in total_list:
parameter = {"game": "csgo", "page_num": "1", "search": skin}
if skin in [
"蝴蝶刀 | 无涂装",
"求生匕首 | 无涂装",
"流浪者匕首 | 无涂装",
"系绳匕首 | 无涂装",
"骷髅匕首 | 无涂装",
]:
skin = skin.split("|")[0].strip()
logger.info(f"开始更新----->{skin}")
skin_name = ""
# try:
response = await AsyncHttpx.get(url, proxy=Config.get_config("open_cases", "BUFF_PROXY"), params=parameter)
if response.status_code == 200:
data = response.json()["data"]
total_page = data["total_page"]
flag = False
if (
skin.find("|") == -1
): # in ['蝴蝶刀', '求生匕首', '流浪者匕首', '系绳匕首', '骷髅匕首']:
for i in range(1, total_page + 1):
res = await AsyncHttpx.get(url, params=parameter)
data = res.json()["data"]["items"]
for j in range(len(data)):
if data[j]["name"] in [f"{skin}(★)"]:
img_url = data[j]["goods_info"]["icon_url"]
skin_name = cn2py(skin + "无涂装")
await AsyncHttpx.download_file(img_url, path / f"{skin_name}.png")
flag = True
break
if flag:
break
else:
img_url = (await response.json())["data"]["items"][0][
"goods_info"
]["icon_url"]
skin_name += cn2py(skin.replace("|", "-").strip())
if await AsyncHttpx.download_file(img_url, path / f"{skin_name}.png"):
logger.info(f"------->写入 {skin} 成功")
else:
logger.info(f"------->写入 {skin} 失败")
result = None
if error_list:
result = ""
for err_skin in error_list:
result += err_skin + "\n"
return result[:-1] if result else "更新图片成功"
async def get_price(d_name):
cookie = {"session": Config.get_config("open_cases", "COOKIE")}
name_list = []
price_list = []
parameter = {"game": "csgo", "page_num": "1", "search": d_name}
try:
response = await AsyncHttpx.get(url, cookies=cookie, params=parameter)
if response.status_code == 200:
try:
data = response.json()["data"]
total_page = data["total_page"]
data = data["items"]
for _ in range(total_page):
for i in range(len(data)):
name = data[i]["name"]
price = data[i]["sell_reference_price"]
name_list.append(name)
price_list.append(price)
except Exception as e:
return "没有查询到...", 998
else:
return "访问失败!", response.status_code
except TimeoutError as e:
return "访问超时! 请重试或稍后再试!", 997
result = f"皮肤: {d_name}({len(name_list)})\n"
for i in range(len(name_list)):
result += name_list[i] + ": " + price_list[i] + "\n"
return result[:-1], 999
async def update_count_daily():
try:
users = await OpenCasesUser.get_user_all()
if users:
for user in users:
await user.update(
today_open_total=0,
).apply()
bot = get_bot()
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
for g in gl:
try:
await bot.send_group_msg(group_id=g, message="[[_task|open_case_reset_remind]]今日开箱次数重置成功")
except ActionFailed:
logger.warning(f"{g} 群被禁言,无法发送 开箱重置提醒")
logger.info("今日开箱次数重置成功")
except Exception as e:
logger.error(f"开箱重置错误 e:{e}")
# 蝴蝶刀(★) | 噩梦之夜 (久经沙场)
if __name__ == "__main__":
print(util_get_buff_img("xxxx/")) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/open_cases/utils.py | utils.py |
from typing import Type
from nonebot import on_command
from nonebot.matcher import Matcher
from utils.utils import scheduler, is_number
from nonebot.adapters.onebot.v11.permission import GROUP
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageEvent, Message
from nonebot.permission import SUPERUSER
import random
from nonebot.plugin import MatcherGroup
from configs.path_config import IMAGE_PATH
from nonebot.params import CommandArg
from .open_cases_c import (
open_case,
total_open_statistics,
group_statistics,
my_knifes_name,
open_shilian_case,
)
from .utils import util_get_buff_price, util_get_buff_img, update_count_daily
from configs.config import Config
__zx_plugin_name__ = "开箱"
__plugin_usage__ = """
usage:
看看你的人品罢了
模拟开箱,完美公布的真实概率,只想看看替你省了多少钱
指令:
开箱 ?[武器箱]
[1-30]连开箱 ?[武器箱]
我的开箱
我的金色
群开箱统计
* 不包含[武器箱]时随机开箱 *
目前支持的武器箱:
1.狂牙大行动武器箱
2.突围大行动武器箱
3.命悬一线武器箱
4.裂空武器箱
5.光谱武器箱
示例:开箱 命悬一线
""".strip()
__plugin_superuser_usage__ = """
usage:
更新皮肤指令
指令:
更新开箱图片 ?[武器箱]
更新开箱价格 ?[武器箱]
* 不指定武器箱时则全部更新 *
* 过多的爬取会导致账号API被封 *
""".strip()
__plugin_des__ = "csgo模拟开箱[戒赌]"
__plugin_cmd__ = [
"开箱 ?[武器箱]",
"[1-30]连开箱 ?[武器箱]",
"我的开箱",
"我的金色",
"群开箱统计",
"更新开箱图片 ?[武器箱] [_superuser]",
"更新开箱价格 ?[武器箱] [_superuser]",
]
__plugin_type__ = ("抽卡相关", 1)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["csgo开箱", "开箱"],
}
__plugin_task__ = {"open_case_reset_remind": "每日开箱重置提醒"}
__plugin_cd_limit__ = {"rst": "着什么急啊,慢慢来!"}
__plugin_resources__ = {f"cases": IMAGE_PATH}
__plugin_configs__ = {
"INITIAL_OPEN_CASE_COUNT": {"value": 20, "help": "初始每日开箱次数", "default_value": 20},
"EACH_IMPRESSION_ADD_COUNT": {
"value": 3,
"help": "每 * 点好感度额外增加开箱次数",
"default_value": 3,
},
"COOKIE": {
"value": None,
"help": "BUFF的cookie",
},
"BUFF_PROXY": {"value": None, "help": "使用代理访问BUFF"},
}
Config.add_plugin_config(
"_task",
"DEFAULT_OPEN_CASE_RESET_REMIND",
True,
help_="被动 每日开箱重置提醒 进群默认开关状态",
default_value=True,
)
cases_name = ["狂牙大行动", "突围大行动", "命悬一线", "裂空", "光谱"]
cases_matcher_group = MatcherGroup(priority=5, permission=GROUP, block=True)
k_open_case = cases_matcher_group.on_command("开箱")
@k_open_case.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
case_name = arg.extract_plain_text().strip()
case_name = case_name.replace("武器箱", "").strip()
if case_name:
result = await open_case(event.user_id, event.group_id, case_name)
else:
result = await open_case(
event.user_id, event.group_id, random.choice(cases_name)
)
await k_open_case.finish(result, at_sender=True)
total_case_data = cases_matcher_group.on_command(
"我的开箱", aliases={"开箱统计", "开箱查询", "查询开箱"}
)
@total_case_data.handle()
async def _(event: GroupMessageEvent):
await total_case_data.finish(
await total_open_statistics(event.user_id, event.group_id),
at_sender=True,
)
group_open_case_statistics = cases_matcher_group.on_command("群开箱统计")
@group_open_case_statistics.handle()
async def _(event: GroupMessageEvent):
await group_open_case_statistics.finish(await group_statistics(event.group_id))
my_kinfes = on_command("我的金色", priority=1, permission=GROUP, block=True)
@my_kinfes.handle()
async def _(event: GroupMessageEvent):
await my_kinfes.finish(
await my_knifes_name(event.user_id, event.group_id), at_sender=True
)
open_shilian: Type[Matcher] = cases_matcher_group.on_regex("(.*)连开箱(.*?)")
@open_shilian.handle()
async def _(event: GroupMessageEvent, state: T_State):
num = state["_matched_groups"][0].strip()
if is_number(num) or num_dict.get(num):
try:
num = num_dict[num]
except KeyError:
num = int(num)
if num > 30:
await open_shilian.finish("开箱次数不要超过30啊笨蛋!", at_sender=True)
if num < 0:
await open_shilian.finish("再负开箱就扣你明天开箱数了!", at_sender=True)
else:
await open_shilian.finish("必须要是数字切不要超过30啊笨蛋!中文也可!", at_sender=True)
case_name = state["_matched_groups"][1].strip()
case_name = case_name.replace("武器箱", "").strip()
if not case_name:
case_name = random.choice(cases_name)
elif case_name not in cases_name:
await open_shilian.finish("武器箱未收录!", at_sender=True)
await open_shilian.finish(
await open_shilian_case(event.user_id, event.group_id, case_name, num),
at_sender=True,
)
num_dict = {
"一": 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,
}
update_price = on_command("更新开箱价格", priority=1, permission=SUPERUSER, block=True)
@update_price.handle()
async def _( event: MessageEvent):
await update_price.send(await util_get_buff_price(str(event.get_message())))
update_img = on_command("更新开箱图片", priority=1, permission=SUPERUSER, block=True)
@update_img.handle()
async def _(event: MessageEvent):
await update_img.send(await util_get_buff_img(str(event.get_message())))
# 重置开箱
@scheduler.scheduled_job(
"cron",
hour=0,
minute=1,
)
async def _():
await update_count_daily() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/open_cases/__init__.py | __init__.py |
from datetime import datetime
from services.db_context import db
class OpenCasesUser(db.Model):
__tablename__ = 'open_cases_users'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer(), primary_key=True)
user_qq = db.Column(db.BigInteger(), nullable=False)
group_id = db.Column(db.BigInteger(), nullable=False)
total_count = db.Column(db.Integer(), nullable=False, default=0)
blue_count = db.Column(db.Integer(), nullable=False, default=0)
blue_st_count = db.Column(db.Integer(), nullable=False, default=0)
purple_count = db.Column(db.Integer(), nullable=False, default=0)
purple_st_count = db.Column(db.Integer(), nullable=False, default=0)
pink_count = db.Column(db.Integer(), nullable=False, default=0)
pink_st_count = db.Column(db.Integer(), nullable=False, default=0)
red_count = db.Column(db.Integer(), nullable=False, default=0)
red_st_count = db.Column(db.Integer(), nullable=False, default=0)
knife_count = db.Column(db.Integer(), nullable=False, default=0)
knife_st_count = db.Column(db.Integer(), nullable=False, default=0)
spend_money = db.Column(db.Integer(), nullable=False, default=0)
make_money = db.Column(db.Float(), nullable=False, default=0)
today_open_total = db.Column(db.Integer(), nullable=False, default=0)
open_cases_time_last = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime.now())
knifes_name = db.Column(db.Unicode(), nullable=False, default="")
_idx1 = db.Index('open_cases_group_users_idx1', 'user_qq', 'group_id', unique=True)
@classmethod
async def ensure(cls, user_qq: int, group_id: int, for_update: bool = False) -> 'OpenCasesUser':
query = cls.query.where(
(cls.user_qq == user_qq) & (cls.group_id == group_id)
)
if for_update:
query = query.with_for_update()
user = await query.gino.first()
return user or await cls.create(
user_qq=user_qq,
group_id=group_id,
)
@classmethod
async def get_user_all(cls, group_id: int = None) -> 'list':
user_list = []
if not group_id:
query = await cls.query.gino.all()
else:
query = await cls.query.where(
(cls.group_id == group_id)
).gino.all()
for user in query:
user_list.append(user)
return user_list | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/open_cases/models/open_cases_user.py | open_cases_user.py |
from nonebot.plugin import on_command
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent, Message
from nonebot.typing import T_State
from services.log import logger
from utils.utils import get_message_img
from utils.message_builder import custom_forward_msg
from nonebot.params import CommandArg, Arg, ArgStr, Depends
from .saucenao import get_saucenao_image
__zx_plugin_name__ = "识图"
__plugin_usage__ = """
usage:
识别图片 [二次元图片]
指令:
识图 [图片]
""".strip()
__plugin_des__ = "以图搜图,看破本源"
__plugin_cmd__ = ["识图"]
__plugin_type__ = ("一些工具",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["识图"],
}
__plugin_configs__ = {
"MAX_FIND_IMAGE_COUNT": {"value": 3, "help": "识图返回的最大结果数", "default_value": 3},
"API_KEY": {
"value": None,
"help": "Saucenao的API_KEY,通过 https://saucenao.com/user.php?page=search-api 注册获取",
},
}
search_image = on_command("识图", block=True, priority=5)
async def get_image_info(mod: str, url: str):
if mod == "saucenao":
return await get_saucenao_image(url)
def parse_image(key: str):
async def _key_parser(
state: T_State, img: Message = Arg(key)
):
if not get_message_img(img):
await search_image.reject_arg(key, "请发送要识别的图片!")
state[key] = img
return _key_parser
@search_image.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if msg:
state["mod"] = msg
else:
state["mod"] = "saucenao"
if get_message_img(event.json()):
state["img"] = event.message
@search_image.got("img", prompt="图来!", parameterless=[Depends(parse_image("img"))])
async def _(
bot: Bot,
event: MessageEvent,
state: T_State,
mod: str = ArgStr("mod"),
img: Message = Arg("img"),
):
img = get_message_img(img)[0]
await search_image.send("开始处理图片...")
msg = await get_image_info(mod, img)
if isinstance(msg, str):
await search_image.finish(msg, at_sender=True)
if isinstance(event, GroupMessageEvent):
await bot.send_group_forward_msg(
group_id=event.group_id, messages=custom_forward_msg(msg, bot.self_id)
)
else:
for m in msg[1:]:
await search_image.send(m)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 识图:" + img
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/search_image/__init__.py | __init__.py |
from nonebot import on_notice
from nonebot.adapters.onebot.v11 import PokeNotifyEvent
from configs.path_config import RECORD_PATH, IMAGE_PATH
from utils.message_builder import record, image, poke
from services.log import logger
import random
from utils.utils import CountLimiter
from models.ban_user import BanUser
import os
__zx_plugin_name__ = "戳一戳"
__plugin_usage__ = """
usage:
戳一戳随机掉落语音或美图萝莉图
""".strip()
__plugin_des__ = "戳一戳发送语音美图萝莉图不美哉?"
__plugin_type__ = ("其他",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["戳一戳"],
}
poke__reply = [
"lsp你再戳?",
"连个可爱美少女都要戳的肥宅真恶心啊。",
"你再戳!",
"?再戳试试?",
"别戳了别戳了再戳就坏了555",
"我爪巴爪巴,球球别再戳了",
"你戳你🐎呢?!",
"那...那里...那里不能戳...绝对...",
"(。´・ω・)ん?",
"有事恁叫我,别天天一个劲戳戳戳!",
"欸很烦欸!你戳🔨呢",
"?",
"再戳一下试试?",
"???",
"正在关闭对您的所有服务...关闭成功",
"啊呜,太舒服刚刚竟然睡着了。什么事?",
"正在定位您的真实地址...定位成功。轰炸机已起飞",
]
_clmt = CountLimiter(3)
poke_ = on_notice(priority=5, block=False)
@poke_.handle()
async def _poke_event(event: PokeNotifyEvent):
if event.self_id == event.target_id:
_clmt.add(event.user_id)
if _clmt.check(event.user_id) or random.random() < 0.3:
rst = ""
if random.random() < 0.15:
await BanUser.ban(event.user_id, 1, 60)
rst = "气死我了!"
await poke_.finish(rst + random.choice(poke__reply), at_sender=True)
rand = random.random()
if rand <= 0.3:
path = random.choice(["luoli", "meitu"])
index = random.randint(0, len(os.listdir(IMAGE_PATH / path)))
result = f"id:{index}" + image(f"{index}.jpg", path)
await poke_.send(result)
logger.info(f"USER {event.user_id} 戳了戳我 回复: {result} \n {result}")
elif 0.3 < rand < 0.6:
voice = random.choice(os.listdir(RECORD_PATH / "dinggong"))
result = record(voice, "dinggong")
await poke_.send(result)
await poke_.send(voice.split("_")[1])
logger.info(
f'USER {event.user_id} 戳了戳我 回复: {result} \n {voice.split("_")[1]}'
)
else:
await poke_.send(poke(event.user_id)) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/poke/__init__.py | __init__.py |
from httpx import AsyncClient
from datetime import datetime
from nonebot.log import logger
from nonebot.adapters.onebot.v11 import Bot
from configs.config import NICKNAME
# 获取所有 Epic Game Store 促销游戏
# 方法参考:RSSHub /epicgames 路由
# https://github.com/DIYgod/RSSHub/blob/master/lib/routes/epicgames/index.js
async def get_epic_game():
# 现在没用 graphql 辣
"""prv_graphql Code
epic_url = "https://www.epicgames.com/store/backend/graphql-proxy"
headers = {
"Referer": "https://www.epicgames.com/store/zh-CN/",
"Content-Type": "application/json; charset=utf-8",
}
data = {
"query": "query searchStoreQuery($allowCountries: String, $category: String, $count: Int, $country: String!, $keywords: String, $locale: String, $namespace: String, $sortBy: String, $sortDir: String, $start: Int, $tag: String, $withPrice: Boolean = false, $withPromotions: Boolean = false) {\n Catalog {\n searchStore(allowCountries: $allowCountries, category: $category, count: $count, country: $country, keywords: $keywords, locale: $locale, namespace: $namespace, sortBy: $sortBy, sortDir: $sortDir, start: $start, tag: $tag) {\n elements {\n title\n id\n namespace\n description\n effectiveDate\n keyImages {\n type\n url\n }\n seller {\n id\n name\n }\n productSlug\n urlSlug\n url\n items {\n id\n namespace\n }\n customAttributes {\n key\n value\n }\n categories {\n path\n }\n price(country: $country) @include(if: $withPrice) {\n totalPrice {\n discountPrice\n originalPrice\n voucherDiscount\n discount\n currencyCode\n currencyInfo {\n decimals\n }\n fmtPrice(locale: $locale) {\n originalPrice\n discountPrice\n intermediatePrice\n }\n }\n lineOffers {\n appliedRules {\n id\n endDate\n discountSetting {\n discountType\n }\n }\n }\n }\n promotions(category: $category) @include(if: $withPromotions) {\n promotionalOffers {\n promotionalOffers {\n startDate\n endDate\n discountSetting {\n discountType\n discountPercentage\n }\n }\n }\n upcomingPromotionalOffers {\n promotionalOffers {\n startDate\n endDate\n discountSetting {\n discountType\n discountPercentage\n }\n }\n }\n }\n }\n paging {\n count\n total\n }\n }\n }\n}\n",
"variables": {
"allowCountries": "CN",
"category": "freegames",
"count": 1000,
"country": "CN",
"locale": "zh-CN",
"sortBy": "effectiveDate",
"sortDir": "asc",
"withPrice": True,
"withPromotions": True,
},
}
"""
epic_url = "https://store-site-backend-static-ipv4.ak.epicgames.com/freeGamesPromotions?locale=zh-CN&country=CN&allowCountries=CN"
headers = {
"Referer": "https://www.epicgames.com/store/zh-CN/",
"Content-Type": "application/json; charset=utf-8",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36",
}
async with AsyncClient(headers=headers) as client:
try:
res = await client.get(epic_url, timeout=10.0)
res_json = res.json()
games = res_json["data"]["Catalog"]["searchStore"]["elements"]
return games
except Exception as e:
logger.error(str(e))
return None
# 获取 Epic Game Store 免费游戏信息
# 处理免费游戏的信息方法借鉴 pip 包 epicstore_api 示例
# https://github.com/SD4RK/epicstore_api/blob/master/examples/free_games_example.py
async def get_epic_free(bot: Bot, Type_Event: str):
games = await get_epic_game()
if not games:
return "Epic 可能又抽风啦,请稍后再试(", 404
else:
msg_list = []
for game in games:
game_name = game["title"]
game_corp = game["seller"]["name"]
game_price = game["price"]["totalPrice"]["fmtPrice"]["originalPrice"]
# 赋初值以避免 local variable referenced before assignment
game_dev, game_pub, game_thumbnail = (None, None, None)
try:
game_promotions = game["promotions"]["promotionalOffers"]
upcoming_promotions = game["promotions"]["upcomingPromotionalOffers"]
if not game_promotions and upcoming_promotions:
# 促销暂未上线,但即将上线
promotion_data = upcoming_promotions[0]["promotionalOffers"][0]
start_date_iso, end_date_iso = (
promotion_data["startDate"][:-1],
promotion_data["endDate"][:-1],
)
# 删除字符串中最后一个 "Z" 使 Python datetime 可处理此时间
start_date = datetime.fromisoformat(start_date_iso).strftime(
"%b.%d %H:%M"
)
end_date = datetime.fromisoformat(end_date_iso).strftime(
"%b.%d %H:%M"
)
if Type_Event == "Group":
_message = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format(
game_corp, game_name, game_price, start_date, end_date
)
data = {
"type": "node",
"data": {
"name": f"这里是{NICKNAME}酱",
"uin": f"{bot.self_id}",
"content": _message,
},
}
msg_list.append(data)
else:
msg = "\n由 {} 公司发行的游戏 {} ({}) 在 UTC 时间 {} 即将推出免费游玩,预计截至 {}。".format(
game_corp, game_name, game_price, start_date, end_date
)
msg_list.append(msg)
else:
for image in game["keyImages"]:
if image["type"] == "Thumbnail":
game_thumbnail = image["url"]
for pair in game["customAttributes"]:
if pair["key"] == "developerName":
game_dev = pair["value"]
if pair["key"] == "publisherName":
game_pub = pair["value"]
# 如 game['customAttributes'] 未找到则均使用 game_corp 值
game_dev = game_dev if game_dev is not None else game_corp
game_pub = game_pub if game_pub is not None else game_corp
game_desp = game["description"]
end_date_iso = game["promotions"]["promotionalOffers"][0][
"promotionalOffers"
][0]["endDate"][:-1]
end_date = datetime.fromisoformat(end_date_iso).strftime(
"%b.%d %H:%M"
)
# API 返回不包含游戏商店 URL,此处自行拼接,可能出现少数游戏 404 请反馈
game_url_part = (
(game["productSlug"].replace("/home", ""))
if ("/home" in game["productSlug"])
else game["productSlug"]
)
game_url = "https://www.epicgames.com/store/zh-CN/p/{}".format(
game_url_part
)
if Type_Event == "Group":
_message = "[CQ:image,file={}]\n\nFREE now :: {} ({})\n{}\n此游戏由 {} 开发、{} 发行,将在 UTC 时间 {} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{}\n".format(
game_thumbnail,
game_name,
game_price,
game_desp,
game_dev,
game_pub,
end_date,
game_url,
)
data = {
"type": "node",
"data": {
"name": f"这里是{NICKNAME}酱",
"uin": f"{bot.self_id}",
"content": _message,
},
}
msg_list.append(data)
else:
msg = "[CQ:image,file={}]\n\nFREE now :: {} ({})\n{}\n此游戏由 {} 开发、{} 发行,将在 UTC 时间 {} 结束免费游玩,戳链接速度加入你的游戏库吧~\n{}\n".format(
game_thumbnail,
game_name,
game_price,
game_desp,
game_dev,
game_pub,
end_date,
game_url,
)
msg_list.append(msg)
except TypeError as e:
# logger.info(str(e))
pass
return msg_list, 200 | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/epic/data_source.py | data_source.py |
from nonebot import on_regex
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from utils.utils import scheduler, get_bot
from .data_source import get_epic_free
from utils.manager import group_manager
from configs.config import Config
__zx_plugin_name__ = "epic免费游戏"
__plugin_usage__ = """
usage:
可以不玩,不能没有,每日白嫖
指令:
epic
""".strip()
__plugin_des__ = "可以不玩,不能没有,每日白嫖"
__plugin_cmd__ = ["epic"]
__plugin_version__ = 0.1
__plugin_author__ = "AkashiCoin"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["epic"],
}
__plugin_task__ = {"epic_free_game": "epic免费游戏"}
Config.add_plugin_config(
"_task",
"DEFAULT_EPIC_FREE_GAME",
True,
help_="被动 epic免费游戏 进群默认开关状态",
default_value=True,
)
epic = on_regex("^epic$", priority=5, block=True)
@epic.handle()
async def handle(bot: Bot, event: MessageEvent, state: T_State):
Type_Event = "Private"
if isinstance(event, GroupMessageEvent):
Type_Event = "Group"
msg_list, code = await get_epic_free(bot, Type_Event)
if code == 404:
await epic.send(msg_list)
elif isinstance(event, GroupMessageEvent):
await bot.send_group_forward_msg(group_id=event.group_id, messages=msg_list)
else:
for msg in msg_list:
await bot.send_private_msg(user_id=event.user_id, message=msg)
logger.info(
f"(USER {event.user_id}, GROUP {event.group_id if isinstance(event, GroupMessageEvent) else 'private'})"
f" 获取epic免费游戏"
)
# epic免费游戏
@scheduler.scheduled_job(
"cron",
hour=12,
minute=1,
)
async def _():
bot = get_bot()
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
msg_list, code = await get_epic_free(bot, "Group")
for g in gl:
if await group_manager.check_group_task_status(g, "epic_free_game"):
try:
if msg_list and code == 200:
await bot.send_group_forward_msg(group_id=g, messages=msg_list)
else:
await bot.send_group_msg(group_id=g)
except Exception as e:
logger.error(f"GROUP {g} epic免费游戏推送错误 {type(e)}: {e}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/epic/__init__.py | __init__.py |
import psutil
import time
from datetime import datetime
from utils.http_utils import AsyncHttpx
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
import asyncio
from services.log import logger
class Check:
def __init__(self):
self.cpu = None
self.memory = None
self.disk = None
self.user = None
self.baidu = 200
self.google = 200
async def check_all(self):
await self.check_network()
await asyncio.sleep(0.1)
self.check_system()
self.check_user()
def check_system(self):
self.cpu = psutil.cpu_percent()
self.memory = psutil.virtual_memory().percent
self.disk = psutil.disk_usage("/").percent
async def check_network(self):
try:
await AsyncHttpx.get("https://www.baidu.com/", timeout=5)
except Exception as e:
logger.warning(f"访问BaiDu失败... {type(e)}: {e}")
self.baidu = 404
try:
await AsyncHttpx.get("https://www.google.com/", timeout=5)
except Exception as e:
logger.warning(f"访问Google失败... {type(e)}: {e}")
self.google = 404
def check_user(self):
rst = ""
for user in psutil.users():
rst += f'[{user.name}] {time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user.started))}\n'
self.user = rst[:-1]
async def show(self):
await self.check_all()
A = BuildImage(0, 0, font_size=24)
rst = (
f'[Time] {str(datetime.now()).split(".")[0]}\n'
f"-----System-----\n"
f"[CPU] {self.cpu}%\n"
f"[Memory] {self.memory}%\n"
f"[Disk] {self.disk}%\n"
f"-----Network-----\n"
f"[BaiDu] {self.baidu}\n"
f"[Google] {self.google}\n"
)
if self.user:
rst += "-----User-----\n" + self.user
width = 0
height = 0
for x in rst.split('\n'):
w, h = A.getsize(x)
if w > width:
width = w
height += 30
A = BuildImage(width + 50, height + 10, font_size=24, font="HWZhongSong.ttf")
A.transparent(1)
A.text((10, 10), rst)
_x = max(width, height)
bk = BuildImage(_x + 100, _x + 100, background=IMAGE_PATH / "background" / "check" / "0.jpg")
bk.paste(A, alpha=True, center_type='center')
return bk.pic2bs4() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/plugins/check/data_source.py | data_source.py |
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, PrivateMessageEvent, Message
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.rule import to_me
from models.group_member_info import GroupInfoUser
from models.friend_user import FriendUser
from models.ban_user import BanUser
from services.log import logger
from configs.config import NICKNAME, Config
from nonebot.params import CommandArg
import random
__zx_plugin_name__ = "昵称系统"
__plugin_usage__ = f"""
usage:
个人昵称系统,群聊 与 私聊 昵称相互独立
指令:
以后叫我 [昵称]
{NICKNAME}我是谁
""".strip()
__plugin_des__ = "区区昵称,才不想叫呢!"
__plugin_cmd__ = ["以后叫我 [昵称]", f"{NICKNAME}我是谁"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_configs__ = {
"BLACK_WORD": {
"value": ["爸", "爹", "爷"],
"help": "昵称所屏蔽的关键词,会被替换为 *",
"default_value": None
}
}
nickname = on_command(
"nickname",
aliases={"以后叫我", "以后请叫我", "称呼我", "以后请称呼我", "以后称呼我", "叫我", "请叫我"},
rule=to_me(),
priority=5,
block=True,
)
my_nickname = on_command(
"my_name", aliases={"我叫什么", "我是谁", "我的名字"}, rule=to_me(), priority=5, block=True
)
cancel_nickname = on_command("取消昵称", rule=to_me(), priority=5, block=True)
@nickname.handle()
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if not msg:
await nickname.finish("叫你空白?叫你虚空?叫你无名??", at_sender=True)
if len(msg) > 10:
await nickname.finish("昵称可不能超过10个字!", at_sender=True)
if msg in bot.config.superusers:
await nickname.finish("笨蛋!休想占用我的名字!#", at_sender=True)
_tmp = ""
black_word = Config.get_config("nickname", "BLACK_WORD")
for x in msg:
_tmp += "*" if x in black_word else x
msg = _tmp
if isinstance(event, GroupMessageEvent):
if await GroupInfoUser.set_group_member_nickname(
event.user_id, event.group_id, msg
):
if len(msg) < 5:
if random.random() < 0.3:
msg = "~".join(msg)
await nickname.send(
random.choice(
[
f"好啦好啦,我知道啦,{msg},以后就这么叫你吧",
f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}",
f"好突然,突然要叫你昵称什么的...{msg}..",
f"{NICKNAME}会好好记住的{msg}的,放心吧",
f"好..好.,那窝以后就叫你{msg}了.",
]
)
)
logger.info(f"USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg}")
else:
await nickname.send("设置昵称失败,请更新群组成员信息!", at_sender=True)
logger.warning(f"USER {event.user_id} GROUP {event.group_id} 设置群昵称 {msg} 失败")
else:
if await FriendUser.set_friend_nickname(event.user_id, msg):
await nickname.send(
random.choice(
[
f"好啦好啦,我知道啦,{msg},以后就这么叫你吧",
f"嗯嗯,{NICKNAME}记住你的昵称了哦,{msg}",
f"好突然,突然要叫你昵称什么的...{msg}..",
f"{NICKNAME}会好好记住的{msg}的,放心吧",
f"好..好.,那窝以后就叫你{msg}了.",
]
)
)
logger.info(f"USER {event.user_id} 设置昵称 {msg}")
else:
await nickname.send("设置昵称失败了,明天再来试一试!或联系管理员更新好友!", at_sender=True)
logger.warning(f"USER {event.user_id} 设置昵称 {msg} 失败")
@my_nickname.handle()
async def _(event: GroupMessageEvent):
try:
nickname_ = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
except AttributeError:
nickname_ = ""
if nickname_:
await my_nickname.send(
random.choice(
[
f"我肯定记得你啊,你是{nickname_}啊",
f"我不会忘记你的,你也不要忘记我!{nickname_}",
f"哼哼,{NICKNAME}记忆力可是很好的,{nickname_}",
f"嗯?你是失忆了嘛...{nickname_}..",
f"不要小看{NICKNAME}的记忆力啊!笨蛋{nickname_}!QAQ",
f"哎?{nickname_}..怎么了吗..突然这样问..",
]
)
)
else:
nickname_ = event.sender.card or event.sender.nickname
await my_nickname.send(
random.choice(
["没..没有昵称嘛,{}", "啊,你是{}啊,我想叫你的昵称!", "是{}啊,有什么事吗?", "你是{}?"]
).format(nickname_)
)
@my_nickname.handle()
async def _(bot: Bot, event: PrivateMessageEvent, state: T_State):
nickname_ = await FriendUser.get_friend_nickname(event.user_id)
if nickname_:
await my_nickname.send(
random.choice(
[
f"我肯定记得你啊,你是{nickname_}啊",
f"我不会忘记你的,你也不要忘记我!{nickname_}",
f"哼哼,{NICKNAME}记忆力可是很好的,{nickname_}",
f"嗯?你是失忆了嘛...{nickname_}..",
f"不要小看{NICKNAME}的记忆力啊!笨蛋{nickname_}!QAQ",
f"哎?{nickname_}..怎么了吗..突然这样问..",
]
)
)
else:
nickname_ = (await bot.get_stranger_info(user_id=event.user_id))["nickname"]
await my_nickname.send(
random.choice(
["没..没有昵称嘛,{}", "啊,你是{}啊,我想叫你的昵称!", "是{}啊,有什么事吗?", "你是{}?"]
).format(nickname_)
)
@cancel_nickname.handle()
async def _(event: GroupMessageEvent):
nickname_ = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
if nickname_:
await cancel_nickname.send(
random.choice(
[
f"呜..{NICKNAME}睡一觉就会忘记的..和梦一样..{nickname_}",
f"窝知道了..{nickname_}..",
f"是{NICKNAME}哪里做的不好嘛..好吧..晚安{nickname_}",
f"呃,{nickname_},下次我绝对绝对绝对不会再忘记你!",
f"可..可恶!{nickname_}!太可恶了!呜",
]
)
)
await GroupInfoUser.set_group_member_nickname(event.user_id, event.group_id, "")
await BanUser.ban(event.user_id, 9, 60)
else:
await cancel_nickname.send("你在做梦吗?你没有昵称啊", at_sender=True)
@cancel_nickname.handle()
async def _(event: PrivateMessageEvent):
nickname_ = await FriendUser.get_friend_nickname(event.user_id)
if nickname_:
await cancel_nickname.send(
random.choice(
[
f"呜..{NICKNAME}睡一觉就会忘记的..和梦一样..{nickname_}",
f"窝知道了..{nickname_}..",
f"是{NICKNAME}哪里做的不好嘛..好吧..晚安{nickname_}",
f"呃,{nickname_},下次我绝对绝对绝对不会再忘记你!",
f"可..可恶!{nickname_}!太可恶了!呜",
]
)
)
await FriendUser.get_user_name(event.user_id)
await BanUser.ban(event.user_id, 9, 60)
else:
await cancel_nickname.send("你在做梦吗?你没有昵称啊", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/nickname.py | nickname.py |
from asyncpg.exceptions import (
DuplicateColumnError,
UndefinedColumnError,
PostgresSyntaxError,
)
from nonebot import Driver
from services.db_context import db
from models.group_info import GroupInfo
from models.bag_user import BagUser
from nonebot.adapters.onebot.v11 import Bot
from services.log import logger
from configs.path_config import TEXT_PATH
from asyncio.exceptions import TimeoutError
from typing import List
from utils.http_utils import AsyncHttpx
from utils.utils import scheduler
import nonebot
try:
import ujson as json
except ModuleNotFoundError:
import json
driver: Driver = nonebot.get_driver()
@driver.on_startup
async def update_city():
"""
部分插件需要中国省份城市
这里直接更新,避免插件内代码重复
"""
china_city = TEXT_PATH / "china_city.json"
data = {}
if not china_city.exists():
try:
res = await AsyncHttpx.get(
"http://www.weather.com.cn/data/city3jdata/china.html", timeout=5
)
res.encoding = "utf8"
provinces_data = json.loads(res.text)
for province in provinces_data.keys():
data[provinces_data[province]] = []
res = await AsyncHttpx.get(
f"http://www.weather.com.cn/data/city3jdata/provshi/{province}.html",
timeout=5,
)
res.encoding = "utf8"
city_data = json.loads(res.text)
for city in city_data.keys():
data[provinces_data[province]].append(city_data[city])
with open(china_city, "w", encoding="utf8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
logger.info("自动更新城市列表完成.....")
except TimeoutError:
logger.warning("自动更新城市列表超时.....")
except ValueError:
logger.warning("自动城市列表失败.....")
except Exception as e:
logger.error(f"自动城市列表未知错误 {type(e)}:{e}")
@driver.on_startup
async def _():
"""
数据库表结构变换
"""
_flag = []
sql_str = [
(
"ALTER TABLE group_info ADD group_flag Integer NOT NULL DEFAULT 0;",
"group_info",
), # group_info表添加一个group_flag
(
"ALTER TABLE bag_users rename belonging_group To group_id;",
"bag_users",
), # 将 bag_users 的 belonging_group 改为 group_id
(
"ALTER TABLE group_info_users rename belonging_group To group_id;",
"group_info_users",
),
(
"ALTER TABLE sign_group_users rename belonging_group To group_id;",
"sign_group_users",
),
(
"ALTER TABLE open_cases_users rename belonging_group To group_id;",
"open_cases_users",
),
(
"ALTER TABLE bag_users ADD property json NOT NULL DEFAULT '{}';",
"bag_users",
), # bag_users 新增字段 property 替代 props
(
"ALTER TABLE genshin ADD auto_sign_time timestamp with time zone;",
"genshin"
), # 新增原神自动签到字段
(
"ALTER TABLE genshin ADD resin_remind boolean DEFAULT False;",
"genshin"
), # 新增原神自动签到字段
(
"ALTER TABLE genshin ADD resin_recovery_time timestamp with time zone;",
"genshin"
), # 新增原神自动签到字段
(
"ALTER TABLE genshin ADD bind_group Integer;",
"genshin"
), # 新增原神群号绑定字段
]
for sql in sql_str:
try:
flag = sql[1]
sql = sql[0]
query = db.text(sql)
await db.first(query)
logger.info(f"完成sql操作:{sql}")
_flag.append(flag)
except (DuplicateColumnError, UndefinedColumnError):
pass
except PostgresSyntaxError:
logger.error(f"语法错误:执行sql失败:{sql}")
# bag_user 将文本转为字典格式
await __database_script(_flag)
# 完成后
end_sql_str = [
# "ALTER TABLE bag_users DROP COLUMN props;" # 删除 bag_users 的 props 字段(还不到时候)
]
for sql in end_sql_str:
try:
query = db.text(sql)
await db.first(query)
logger.info(f"完成执行sql操作:{sql}")
except (DuplicateColumnError, UndefinedColumnError):
pass
except PostgresSyntaxError:
logger.error(f"语法错误:执行sql失败:{sql}")
# str2json_sql = ["alter table bag_users alter COLUMN props type json USING props::json;"] # 字段类型替换
# rename_sql = 'alter table {} rename {} to {};' # 字段更名
# for sql in str2json_sql:
# try:
# query = db.text(sql)
# await db.first(query)
# except DuplicateColumnError:
# pass
@driver.on_bot_connect
async def _(bot: Bot):
"""
版本某些需要的变换
"""
# 清空不存在的群聊信息,并将已所有已存在的群聊group_flag设置为1(认证所有已存在的群)
if not await GroupInfo.get_group_info(114514):
# 标识符,该功能只需执行一次
await GroupInfo.add_group_info(114514, "114514", 114514, 114514, 1)
group_list = await bot.get_group_list()
group_list = [g["group_id"] for g in group_list]
_gl = [x.group_id for x in await GroupInfo.get_all_group()]
if 114514 in _gl:
_gl.remove(114514)
for group_id in _gl:
if group_id in group_list:
if await GroupInfo.get_group_info(group_id):
await GroupInfo.set_group_flag(group_id, 1)
else:
group_info = await bot.get_group_info(group_id=group_id)
await GroupInfo.add_group_info(
group_info["group_id"],
group_info["group_name"],
group_info["max_member_count"],
group_info["member_count"],
1,
)
logger.info(f"已将群聊 {group_id} 添加认证...")
else:
await GroupInfo.delete_group_info(group_id)
logger.info(f"移除不存在的群聊信息:{group_id}")
async def __database_script(_flag: List[str]):
# bag_user 将文本转为字典格式
if "bag_users" in _flag:
for x in await BagUser.get_all_users():
props = {}
if x.props:
for prop in [p for p in x.props.split(",") if p]:
if props.get(prop):
props[prop] += 1
else:
props[prop] = 1
logger.info(
f"__database_script USER {x.user_qq} GROUP {x.group_id} 更新数据 {props}"
)
await x.update(
property=props,
props="",
).apply()
# 自动更新城市列表
@scheduler.scheduled_job(
"cron",
hour=6,
minute=1,
)
async def _():
await update_city() | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/scripts.py | scripts.py |
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from models.friend_user import FriendUser
from models.group_member_info import GroupInfoUser
from models.bag_user import BagUser
from utils.manager import (
plugins2settings_manager,
admin_manager,
group_manager,
plugins_manager,
plugins2cd_manager,
plugins2block_manager,
plugins2count_manager,
)
from ._utils import set_block_limit_false, status_message_manager
from nonebot.typing import T_State
from typing import Optional
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
PokeNotifyEvent,
PrivateMessageEvent,
Message,
Event,
)
from configs.config import Config
from models.ban_user import BanUser
from utils.utils import FreqLimiter
from utils.message_builder import at
from models.level_user import LevelUser
import nonebot
_flmt = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
_flmt_g = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
_flmt_s = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
_flmt_c = FreqLimiter(Config.get_config("hook", "CHECK_NOTICE_INFO_CD"))
ignore_rst_module = ["ai", "poke", "dialogue"]
# 权限检测
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
module = matcher.plugin_name
plugins2info_dict = plugins2settings_manager.get_data()
# 功能的金币检测 #######################################
# 功能的金币检测 #######################################
# 功能的金币检测 #######################################
cost_gold = 0
if isinstance(
event, GroupMessageEvent
) and plugins2settings_manager.get_plugin_data(module).get("cost_gold"):
cost_gold = plugins2settings_manager.get_plugin_data(module).get("cost_gold")
if await BagUser.get_gold(event.user_id, event.group_id) < cost_gold:
await send_msg(f"金币不足..该功能需要{cost_gold}金币..", bot, event)
raise IgnoredException(f"{module} 金币限制...")
# 当插件不阻塞超级用户时,超级用户提前扣除金币
if (
str(event.user_id) in bot.config.superusers
and not plugins2info_dict[module]["limit_superuser"]
):
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
try:
if (
(not isinstance(event, MessageEvent) and module != "poke")
or await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
) or (
str(event.user_id) in bot.config.superusers
and plugins2info_dict.get(module)
and not plugins2info_dict[module]["limit_superuser"]
):
return
except AttributeError:
pass
# 超级用户命令
try:
_plugin = nonebot.plugin.get_plugin(module)
_module = _plugin.module
plugin_name = _module.__getattribute__("__zx_plugin_name__")
if (
"[superuser]" in plugin_name.lower()
and str(event.user_id) in bot.config.superusers
):
return
except AttributeError:
pass
# 群黑名单检测 群总开关检测
if isinstance(event, GroupMessageEvent) or matcher.plugin_name == "poke":
try:
if (
group_manager.get_group_level(event.group_id) < 0
and str(event.user_id) not in bot.config.superusers
):
raise IgnoredException("群黑名单")
if not group_manager.check_group_bot_status(event.group_id):
try:
if str(event.get_message()) != "醒来":
raise IgnoredException("功能总开关关闭状态")
except ValueError:
raise IgnoredException("功能总开关关闭状态")
except AttributeError:
pass
if module in admin_manager.keys() and matcher.priority not in [1, 9]:
if isinstance(event, GroupMessageEvent):
# 个人权限
if (
not await LevelUser.check_level(
event.user_id,
event.group_id,
admin_manager.get_plugin_level(module),
)
and admin_manager.get_plugin_level(module) > 0
):
try:
if _flmt.check(event.user_id):
_flmt.start_cd(event.user_id)
await bot.send_group_msg(
group_id=event.group_id,
message=f"{at(event.user_id)}你的权限不足喔,该功能需要的权限等级:"
f"{admin_manager.get_plugin_level(module)}",
)
except ActionFailed:
pass
set_block_limit_false(event, module)
if event.is_tome():
status_message_manager.add(event.group_id)
raise IgnoredException("权限不足")
else:
if not await LevelUser.check_level(
event.user_id, 0, admin_manager.get_plugin_level(module)
):
try:
await bot.send_private_msg(
user_id=event.user_id,
message=f"你的权限不足喔,该功能需要的权限等级:{admin_manager.get_plugin_level(module)}",
)
except ActionFailed:
pass
set_block_limit_false(event, module)
if event.is_tome():
status_message_manager.add(event.user_id)
raise IgnoredException("权限不足")
if module in plugins2info_dict.keys() and matcher.priority not in [1, 9]:
# 戳一戳单独判断
if isinstance(event, GroupMessageEvent) or (
isinstance(event, PokeNotifyEvent) and event.group_id
):
if status_message_manager.get(event.group_id) is None:
status_message_manager.delete(event.group_id)
if plugins2info_dict[module]["level"] > group_manager.get_group_level(
event.group_id
):
try:
if _flmt_g.check(event.user_id) and module not in ignore_rst_module:
_flmt_g.start_cd(event.user_id)
await bot.send_group_msg(
group_id=event.group_id, message="群权限不足..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(event.group_id)
set_block_limit_false(event, module)
raise IgnoredException("群权限不足")
# 插件状态
if not group_manager.get_plugin_status(module, event.group_id):
try:
if module not in ignore_rst_module and _flmt_s.check(
event.group_id
):
_flmt_s.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="该群未开启此功能.."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(event.group_id)
set_block_limit_false(event, module)
raise IgnoredException("未开启此功能...")
# 管理员禁用
if not group_manager.get_plugin_status(f"{module}:super", event.group_id):
try:
if (
_flmt_s.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_s.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="管理员禁用了此群该功能..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(event.group_id)
set_block_limit_false(event, module)
raise IgnoredException("管理员禁用了此群该功能...")
# 群聊禁用
if not plugins_manager.get_plugin_status(module, block_type="group"):
try:
if (
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_c.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="该功能在群聊中已被禁用..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(event.group_id)
set_block_limit_false(event, module)
raise IgnoredException("该插件在群聊中已被禁用...")
else:
# 私聊禁用
if not plugins_manager.get_plugin_status(module, block_type="private"):
try:
if _flmt_c.check(event.user_id):
_flmt_c.start_cd(event.user_id)
await bot.send_private_msg(
user_id=event.user_id, message="该功能在私聊中已被禁用..."
)
except ActionFailed:
pass
if event.is_tome():
status_message_manager.add(event.user_id)
set_block_limit_false(event, module)
raise IgnoredException("该插件在私聊中已被禁用...")
# 维护
if not plugins_manager.get_plugin_status(module, block_type="all"):
if isinstance(
event, GroupMessageEvent
) and group_manager.check_group_is_white(event.group_id):
return
try:
if isinstance(event, GroupMessageEvent):
if (
_flmt_c.check(event.group_id)
and module not in ignore_rst_module
):
_flmt_c.start_cd(event.group_id)
await bot.send_group_msg(
group_id=event.group_id, message="此功能正在维护..."
)
else:
await bot.send_private_msg(
user_id=event.user_id, message="此功能正在维护..."
)
except ActionFailed:
pass
if event.is_tome():
id_ = (
event.group_id
if isinstance(event, GroupMessageEvent)
else event.user_id
)
status_message_manager.add(id_)
set_block_limit_false(event, module)
raise IgnoredException("此功能正在维护...")
# 以下为限制检测 #######################################################
# 以下为限制检测 #######################################################
# 以下为限制检测 #######################################################
# 以下为限制检测 #######################################################
# 以下为限制检测 #######################################################
# 以下为限制检测 #######################################################
# Cd
if plugins2cd_manager.check_plugin_cd_status(module):
plugin_cd_data = plugins2cd_manager.get_plugin_cd_data(module)
check_type = plugin_cd_data["check_type"]
limit_type = plugin_cd_data["limit_type"]
rst = plugin_cd_data["rst"]
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or plugins2cd_manager.get_plugin_data(module).get("check_type") == "all"
):
cd_type_ = event.user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
cd_type_ = event.group_id
if not plugins2cd_manager.check(module, cd_type_):
if rst:
rst = await init_rst(rst, event)
await send_msg(rst, bot, event)
raise IgnoredException(f"{module} 正在cd中...")
else:
plugins2cd_manager.start_cd(module, cd_type_)
# Block
if plugins2block_manager.check_plugin_block_status(module):
plugin_block_data = plugins2block_manager.get_plugin_block_data(module)
check_type = plugin_block_data["check_type"]
limit_type = plugin_block_data["limit_type"]
rst = plugin_block_data["rst"]
if (
(isinstance(event, PrivateMessageEvent) and check_type == "private")
or (isinstance(event, GroupMessageEvent) and check_type == "group")
or check_type == "all"
):
block_type_ = event.user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
block_type_ = event.group_id
if plugins2block_manager.check(block_type_, module):
if rst:
rst = await init_rst(rst, event)
await send_msg(rst, bot, event)
raise IgnoredException(f"{event.user_id}正在调用{module}....")
else:
plugins2block_manager.set_true(block_type_, module)
# Count
if (
plugins2count_manager.check_plugin_count_status(module)
and event.user_id not in bot.config.superusers
):
plugin_count_data = plugins2count_manager.get_plugin_count_data(module)
limit_type = plugin_count_data["limit_type"]
rst = plugin_count_data["rst"]
count_type_ = event.user_id
if limit_type == "group" and isinstance(event, GroupMessageEvent):
count_type_ = event.group_id
if not plugins2count_manager.check(module, count_type_):
if rst:
rst = await init_rst(rst, event)
await send_msg(rst, bot, event)
raise IgnoredException(f"{module} count次数限制...")
else:
plugins2count_manager.increase(module, count_type_)
# 功能花费的金币 #######################################
# 功能花费的金币 #######################################
if cost_gold:
await BagUser.spend_gold(event.user_id, event.group_id, cost_gold)
async def send_msg(rst: str, bot: Bot, event: MessageEvent):
"""
发送信息
:param rst: pass
:param bot: pass
:param event: pass
"""
rst = await init_rst(rst, event)
try:
if isinstance(event, GroupMessageEvent):
status_message_manager.add(event.group_id)
await bot.send_group_msg(group_id=event.group_id, message=Message(rst))
else:
status_message_manager.add(event.user_id)
await bot.send_private_msg(user_id=event.user_id, message=Message(rst))
except ActionFailed:
pass
# 解除命令block阻塞
@run_postprocessor
async def _(
matcher: Matcher,
exception: Optional[Exception],
bot: Bot,
event: Event,
state: T_State,
):
if not isinstance(event, MessageEvent) and matcher.plugin_name != "poke":
return
module = matcher.plugin_name
set_block_limit_false(event, module)
async def init_rst(rst: str, event: MessageEvent):
if "[uname]" in rst:
uname = event.sender.card or event.sender.nickname
rst = rst.replace("[uname]", uname)
if "[nickname]" in rst:
if isinstance(event, GroupMessageEvent):
nickname = await GroupInfoUser.get_group_member_nickname(
event.user_id, event.group_id
)
else:
nickname = await FriendUser.get_friend_nickname(event.user_id)
rst = rst.replace("[nickname]", nickname)
if "[at]" in rst and isinstance(event, GroupMessageEvent):
rst = rst.replace("[at]", str(at(event.user_id)))
return rst | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/hooks/auth_hook.py | auth_hook.py |
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
)
from configs.config import Config
from models.ban_user import BanUser
from utils.utils import BanCheckLimiter
from utils.message_builder import at
from services.log import logger
_blmt = BanCheckLimiter(
Config.get_config("hook", "MALICIOUS_CHECK_TIME"),
Config.get_config("hook", "MALICIOUS_BAN_COUNT"),
)
# 恶意触发命令检测
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: GroupMessageEvent, state: T_State):
if not isinstance(event, MessageEvent):
return
if matcher.type == "message" and matcher.priority not in [1, 9]:
if state["_prefix"]["raw_command"]:
if _blmt.check(f'{event.user_id}{state["_prefix"]["raw_command"]}'):
if await BanUser.ban(
event.user_id,
9,
Config.get_config("hook", "MALICIOUS_BAN_TIME") * 60,
):
logger.info(f"USER {event.user_id} 触发了恶意触发检测")
if isinstance(event, GroupMessageEvent):
try:
await bot.send_group_msg(
group_id=event.group_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
except ActionFailed:
pass
else:
try:
await bot.send_private_msg(
user_id=event.user_id,
message=at(event.user_id) + "检测到恶意触发命令,您将被封禁 30 分钟",
)
except ActionFailed:
pass
raise IgnoredException("检测到恶意触发命令")
_blmt.add(f'{event.user_id}{state["_prefix"]["raw_command"]}') | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/hooks/chkdsk_hook.py | chkdsk_hook.py |
from nonebot.matcher import Matcher
from nonebot.message import run_preprocessor, IgnoredException
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.typing import T_State
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
)
from configs.config import Config
from models.ban_user import BanUser
from utils.utils import is_number, static_flmt, FreqLimiter
from utils.message_builder import at
Config.add_plugin_config(
"hook",
"BAN_RESULT",
"才不会给你发消息.",
help_="对被ban用户发送的消息",
)
_flmt = FreqLimiter(300)
# 检查是否被ban
@run_preprocessor
async def _(matcher: Matcher, bot: Bot, event: MessageEvent, state: T_State):
try:
if (
await BanUser.is_super_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
):
raise IgnoredException("用户处于超级黑名单中")
except AttributeError:
pass
if not isinstance(event, MessageEvent):
return
if matcher.type == "message" and matcher.priority not in [1, 9]:
if (
await BanUser.is_ban(event.user_id)
and str(event.user_id) not in bot.config.superusers
):
time = await BanUser.check_ban_time(event.user_id)
if is_number(time):
time = abs(int(time))
if time < 60:
time = str(time) + " 秒"
else:
time = str(int(time / 60)) + " 分钟"
else:
time = str(time) + " 分钟"
if isinstance(event, GroupMessageEvent):
if not static_flmt.check(event.user_id):
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(event.user_id)
if matcher.priority != 9:
try:
ban_result = Config.get_config("hook", "BAN_RESULT")
if ban_result and _flmt.check(event.user_id):
_flmt.start_cd(event.user_id)
await bot.send_group_msg(
group_id=event.group_id,
message=at(event.user_id)
+ ban_result
+ f" 在..在 {time} 后才会理你喔",
)
except ActionFailed:
pass
else:
if not static_flmt.check(event.user_id):
raise IgnoredException("用户处于黑名单中")
static_flmt.start_cd(event.user_id)
if matcher.priority != 9:
try:
ban_result = Config.get_config("hook", "BAN_RESULT")
if ban_result:
await bot.send_private_msg(
user_id=event.user_id,
message=at(event.user_id)
+ ban_result
+ f" 在..在 {time}后才会理你喔",
)
except ActionFailed:
pass
raise IgnoredException("用户处于黑名单中") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/hooks/ban_hook.py | ban_hook.py |
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.utils import get_matchers
from utils.manager import group_manager
from nonebot.adapters.onebot.v11 import Bot
from nonebot import Driver
import asyncio
import nonebot
driver: Driver = nonebot.get_driver()
background = IMAGE_PATH / "background" / "0.png"
admin_help_image = IMAGE_PATH / 'admin_help_img.png'
@driver.on_bot_connect
async def init_task(bot: Bot = None):
if not group_manager.get_task_data():
await group_manager.init_group_task()
logger.info(f'已成功加载 {len(group_manager.get_task_data())} 个被动技能.')
async def create_help_image():
"""
创建管理员帮助图片
"""
await asyncio.get_event_loop().run_in_executor(
None, _create_help_image
)
def _create_help_image():
"""
创建管理员帮助图片
"""
_matchers = get_matchers()
_plugin_name_list = []
width = 0
_plugin_level = {}
for matcher in _matchers:
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
_module = _plugin.module
try:
plugin_name = _module.__getattribute__("__zx_plugin_name__")
except AttributeError:
continue
try:
if (
"[admin]" in plugin_name.lower()
and plugin_name not in _plugin_name_list
and plugin_name != "管理帮助 [Admin]"
):
_plugin_name_list.append(plugin_name)
plugin_settings = _module.__getattribute__("__plugin_settings__")
plugin_des = _module.__getattribute__("__plugin_des__")
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" not in x]
admin_level = int(plugin_settings["admin_level"])
if _plugin_level.get(admin_level):
_plugin_level[admin_level].append(
f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)
)
else:
_plugin_level[admin_level] = [
f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)
]
x = len(f"[{admin_level}] {plugin_des} -> " + " / ".join(plugin_cmd)) * 23
width = width if width > x else x
except AttributeError:
logger.warning(f"获取管理插件 {matcher.plugin_name}: {plugin_name} 设置失败...")
help_str = "* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n" \
"[权限等级] 管理员帮助:\n\n"
x = list(_plugin_level.keys())
x.sort()
for level in x:
for help_ in _plugin_level[level]:
help_str += f"\t{help_}\n\n"
help_str += '-----[被动技能开关]-----\n\n'
task_data = group_manager.get_task_data()
for i, x in enumerate(task_data.keys()):
help_str += f'{i+1}.开启/关闭{task_data[x]}\n\n'
height = len(help_str.split("\n")) * 33
A = BuildImage(width, height, font_size=24)
_background = BuildImage(width, height, background=background)
A.text((150, 110), help_str)
A.paste(_background, alpha=True)
A.save(admin_help_image)
logger.info(f'已成功加载 {len(_plugin_name_list)} 条管理员命令') | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/admin_help/data_source.py | data_source.py |
from nonebot import on_notice, on_request
from configs.path_config import IMAGE_PATH, DATA_PATH
from utils.message_builder import image
from models.group_member_info import GroupInfoUser
from datetime import datetime
from services.log import logger
from nonebot.adapters.onebot.v11 import (
Bot,
GroupIncreaseNoticeEvent,
GroupDecreaseNoticeEvent,
)
from nonebot.adapters.onebot.v11.exception import ActionFailed
from utils.manager import group_manager, plugins2settings_manager, requests_manager
from configs.config import NICKNAME
from models.group_info import GroupInfo
from utils.utils import FreqLimiter
from configs.config import Config
from pathlib import Path
import random
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
__zx_plugin_name__ = "群事件处理 [Hidden]"
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_task__ = {"group_welcome": "进群欢迎", "refund_group_remind": "退群提醒"}
Config.add_plugin_config(
"invite_manager", "message", f"请不要未经同意就拉{NICKNAME}入群!告辞!", help_="强制拉群后进群回复的内容.."
)
Config.add_plugin_config(
"invite_manager", "flag", True, help_="被强制拉群后是否直接退出", default_value=True
)
Config.add_plugin_config(
"invite_manager", "welcome_msg_cd", 5, help_="群欢迎消息cd", default_value=5
)
Config.add_plugin_config(
"_task",
"DEFAULT_GROUP_WELCOME",
True,
help_="被动 进群欢迎 进群默认开关状态",
default_value=True,
)
Config.add_plugin_config(
"_task",
"DEFAULT_REFUND_GROUP_REMIND",
True,
help_="被动 退群提醒 进群默认开关状态",
default_value=True,
)
_flmt = FreqLimiter(Config.get_config("invite_manager", "welcome_msg_cd"))
# 群员增加处理
group_increase_handle = on_notice(priority=1, block=False)
# 群员减少处理
group_decrease_handle = on_notice(priority=1, block=False)
# (群管理)加群同意请求
add_group = on_request(priority=1, block=False)
@group_increase_handle.handle()
async def _(bot: Bot, event: GroupIncreaseNoticeEvent):
if event.user_id == int(bot.self_id):
group = await GroupInfo.get_group_info(event.group_id)
# 群聊不存在或被强制拉群,退出该群
if (not group or group.group_flag == 0) and Config.get_config(
"invite_manager", "flag"
):
try:
msg = Config.get_config("invite_manager", "message")
if msg:
await bot.send_group_msg(group_id=event.group_id, message=msg)
await bot.set_group_leave(group_id=event.group_id)
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"触发强制入群保护,已成功退出群聊 {event.group_id}..",
)
logger.info(f"强制拉群或未有群信息,退出群聊 {group} 成功")
requests_manager.remove_request("group", event.group_id)
except Exception as e:
logger.info(f"强制拉群或未有群信息,退出群聊 {group} 失败 e:{e}")
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"触发强制入群保护,退出群聊 {event.group_id} 失败..",
)
# 默认群功能开关
elif event.group_id not in group_manager["group_manager"].keys():
data = plugins2settings_manager.get_data()
for plugin in data.keys():
if not data[plugin]["default_status"]:
group_manager.block_plugin(plugin, event.group_id)
else:
join_time = datetime.now()
user_info = await bot.get_group_member_info(
group_id=event.group_id, user_id=event.user_id
)
if await GroupInfoUser.add_member_info(
user_info["user_id"],
user_info["group_id"],
user_info["nickname"],
join_time,
):
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
else:
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败")
# 群欢迎消息
if _flmt.check(event.group_id):
_flmt.start_cd(event.group_id)
msg = ""
img = ""
at_flag = False
custom_welcome_msg_json = (
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
)
if custom_welcome_msg_json.exists():
data = json.load(open(custom_welcome_msg_json, "r"))
if data.get(str(event.group_id)):
msg = data[str(event.group_id)]
if msg.find("[at]") != -1:
msg = msg.replace("[at]", "")
at_flag = True
if (DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg").exists():
img = image(
DATA_PATH / "custom_welcome_msg" / f"{event.group_id}.jpg"
)
if msg or img:
msg = msg.strip() + img
msg = "\n" + msg if at_flag else msg
await group_increase_handle.send(
"[[_task|group_welcome]]" + msg, at_sender=at_flag
)
else:
await group_increase_handle.send(
"[[_task|group_welcome]]新人快跑啊!!本群现状↓(快使用自定义!)"
+ image(random.choice(os.listdir(IMAGE_PATH / "qxz")), "qxz")
)
@group_decrease_handle.handle()
async def _(bot: Bot, event: GroupDecreaseNoticeEvent):
# 被踢出群
if event.sub_type == "kick_me":
group_id = event.group_id
operator_id = event.operator_id
try:
operator_name = (
await GroupInfoUser.get_member_info(event.operator_id, event.group_id)
).user_name
except AttributeError:
operator_name = "None"
group = await GroupInfo.get_group_info(group_id)
group_name = group.group_name if group else ""
coffee = int(list(bot.config.superusers)[0])
await bot.send_private_msg(
user_id=coffee,
message=f"****呜..一份踢出报告****\n"
f"我被 {operator_name}({operator_id})\n"
f"踢出了 {group_name}({group_id})\n"
f"日期:{str(datetime.now()).split('.')[0]}",
)
return
if event.user_id == int(bot.self_id):
group_manager.delete_group(event.group_id)
return
try:
user_name = (
await GroupInfoUser.get_member_info(event.user_id, event.group_id)
).user_name
except AttributeError:
user_name = str(event.user_id)
if await GroupInfoUser.delete_member_info(event.user_id, event.group_id):
logger.info(f"用户{user_name}, qq={event.user_id} 所属{event.group_id} 删除成功")
else:
logger.info(f"用户{user_name}, qq={event.user_id} 所属{event.group_id} 删除失败")
rst = ""
if event.sub_type == "leave":
rst = f"{user_name}离开了我们..."
if event.sub_type == "kick":
operator = await bot.get_group_member_info(
user_id=event.operator_id, group_id=event.group_id
)
operator_name = operator["card"] if operator["card"] else operator["nickname"]
rst = f"{user_name} 被 {operator_name} 送走了."
try:
await group_decrease_handle.send(f"[[_task|refund_group_remind]]{rst}")
except ActionFailed:
return | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/group_handle/__init__.py | __init__.py |
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
from utils.manager import (
plugins2settings_manager,
admin_manager,
plugins_manager,
group_manager,
)
from typing import Optional
from services.log import logger
from pathlib import Path
from utils.utils import get_matchers
import random
import asyncio
import nonebot
import os
random_bk_path = IMAGE_PATH / "background" / "help" / "simple_help"
background = IMAGE_PATH / "background" / "0.png"
async def create_help_img(
group_id: Optional[int], help_image: Path, simple_help_image: Path
):
"""
生成帮助图片
:param group_id: 群号
:param help_image: 图片路径
:param simple_help_image: 简易帮助图片路径
"""
return await asyncio.get_event_loop().run_in_executor(
None, _create_help_img, group_id, help_image, simple_help_image
)
def _create_help_img(
group_id: Optional[int], help_image: Path, simple_help_image: Path
):
"""
生成帮助图片
:param group_id: 群号
:param help_image: 图片路径
:param simple_help_image: 简易帮助图片路径
"""
_matchers = get_matchers()
width = 0
matchers_data = {}
_des_tmp = {}
_plugin_name_tmp = []
_tmp = []
tmp_img = BuildImage(0, 0, plain_text="1", font_size=24)
font_height = tmp_img.h
# 插件分类
for matcher in _matchers:
plugin_name = None
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
_module = _plugin.module
try:
plugin_name = _module.__getattribute__("__zx_plugin_name__")
try:
plugin_des = _module.__getattribute__("__plugin_des__")
except AttributeError:
plugin_des = "_"
if (
"[hidden]" in plugin_name.lower()
or "[admin]" in plugin_name.lower()
or "[superuser]" in plugin_name.lower()
or plugin_name in _plugin_name_tmp
or plugin_name == "帮助"
):
continue
plugin_type = ("normal",)
text_type = 0
if plugins2settings_manager.get(
matcher.plugin_name
) and plugins2settings_manager[matcher.plugin_name].get("plugin_type"):
plugin_type = tuple(
plugins2settings_manager.get_plugin_data(matcher.plugin_name)[
"plugin_type"
]
)
else:
try:
plugin_type = _module.__getattribute__("__plugin_type__")
except AttributeError:
pass
if len(plugin_type) > 1:
try:
text_type = int(plugin_type[1])
except ValueError as e:
logger.warning(f"生成列向帮助排列失败 {plugin_name}: {type(e)}: {e}")
plugin_type = plugin_type[0]
else:
plugin_type = plugin_type[0]
try:
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" not in x]
except AttributeError:
plugin_cmd = []
if plugin_type not in matchers_data.keys():
matchers_data[plugin_type] = {}
if plugin_des in _des_tmp.keys():
try:
matchers_data[plugin_type][_des_tmp[plugin_des]]["cmd"] = (
matchers_data[plugin_type][_des_tmp[plugin_des]]["cmd"]
+ plugin_cmd
)
except KeyError as e:
logger.warning(f"{type(e)}: {e}")
else:
matchers_data[plugin_type][plugin_name] = {
"modules": matcher.plugin_name,
"des": plugin_des,
"cmd": plugin_cmd,
"text_type": text_type,
}
try:
if text_type == 0:
x = tmp_img.getsize(
f'{plugin_name}: {matchers_data[plugin_type][plugin_name]["des"]} ->'
+ " / ".join(matchers_data[plugin_type][plugin_name]["cmd"])
)[0]
width = width if width > x else x
except KeyError:
pass
if plugin_des not in _des_tmp:
_des_tmp[plugin_des] = plugin_name
except AttributeError as e:
if plugin_name not in _plugin_name_tmp:
logger.warning(f"获取功能 {matcher.plugin_name}: {plugin_name} 设置失败...e:{e}")
if plugin_name not in _plugin_name_tmp:
_plugin_name_tmp.append(plugin_name)
help_img_list = []
simple_help_img_list = []
types = list(matchers_data.keys())
types.sort()
ix = 0
# 详细帮助
for type_ in types:
keys = list(matchers_data[type_].keys())
keys.sort()
help_str = f"{type_ if type_ != 'normal' else '功能'}:\n\n"
simple_help_str = f"{type_ if type_ != 'normal' else '功能'}:\n\n"
for i, k in enumerate(keys):
# 禁用flag
flag = True
if plugins_manager.get_plugin_status(
matchers_data[type_][k]["modules"], "all"
):
flag = False
if group_id:
flag = flag and plugins_manager.get_plugin_status(
matchers_data[type_][k]["modules"], "group"
)
simple_help_str += (
f"{i+1}.{k}<|_|~|>"
f"{group_manager.get_plugin_status(matchers_data[type_][k]['modules'], group_id) if group_id else '_'}|"
f"{flag}\n"
)
if matchers_data[type_][k]["text_type"] == 1:
_x = tmp_img.getsize(
f"{i+1}".rjust(5)
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
)[0]
_str = (
f"{i+1}".rjust(5)
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
)
_str += matchers_data[type_][k]["cmd"][0] + "\n"
for c in matchers_data[type_][k]["cmd"][1:]:
_str += "".rjust(int(_x * 0.125) + 1) + f"{c}\n"
help_str += _str
else:
help_str += (
f"{i+1}".rjust(5)
+ f'.{k}: {matchers_data[type_][k]["des"]} {"->" if matchers_data[type_][k]["cmd"] else ""} '
+ " / ".join(matchers_data[type_][k]["cmd"])
+ "\n"
)
height = len(help_str.split("\n")) * (font_height + 5)
simple_height = len(simple_help_str.split("\n")) * (font_height + 5)
A = BuildImage(
width + 150, height, font_size=24, color="white" if not ix % 2 else "black"
)
A.text((10, 10), help_str, (255, 255, 255) if ix % 2 else (0, 0, 0))
# 生成各个分类的插件简易帮助图片
simple_width = 0
for x in [
tmp_img.getsize(x.split("<|_|~|>")[0])[0]
for x in simple_help_str.split("\n")
]:
simple_width = simple_width if simple_width > x else x
bk = BuildImage(simple_width + 20, simple_height, font_size=24, color="#6495ED")
B = BuildImage(
simple_width + 20,
simple_height,
font_size=24,
color="white" if not ix % 2 else "black",
)
# 切分,判断插件开关状态
_s_height = 10
for _s in simple_help_str.split("\n"):
text_color = (255, 255, 255) if ix % 2 else (0, 0, 0)
_line_flag = False
if "<|_|~|>" in _s:
_x = _s.split("<|_|~|>")
_flag_sp = _x[-1].split("|")
if group_id:
if _flag_sp[0].lower() != "true":
text_color = (252, 75, 13)
if _flag_sp[1].lower() == "true":
_line_flag = True
_s = _x[0]
B.text((10, _s_height), _s, text_color)
if _line_flag:
B.line(
(
7,
_s_height + int(B.getsize(_s)[1] / 2) + 2,
B.getsize(_s)[0] + 11,
_s_height + int(B.getsize(_s)[1] / 2) + 2,
),
(236, 66, 7),
3,
)
_s_height += B.getsize("1")[1] + 5
# B.text((10, 10), simple_help_str, (255, 255, 255) if ix % 2 else (0, 0, 0))
bk.paste(B, center_type="center")
bk.transparent(2)
ix += 1
help_img_list.append(A)
simple_help_img_list.append(bk)
height = 0
for img in help_img_list:
height += img.h
if not group_id:
A = BuildImage(width + 150, height + 50, font_size=24)
A.text(
(10, 10), '* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n" "功能名: 功能简介 -> 指令\n\n'
)
current_height = 50
for img in help_img_list:
A.paste(img, (0, current_height))
current_height += img.h
A.save(help_image)
# 详细帮助生成完毕
# 简易帮助图片合成
height = 0
width = 0
for img in simple_help_img_list:
if img.h > height:
height = img.h
width += img.w + 10
B = BuildImage(width + 100, height + 250, font_size=24)
width, _ = get_max_width_or_paste(simple_help_img_list, B)
bk = None
random_bk = os.listdir(random_bk_path)
if random_bk:
bk = random.choice(random_bk)
x = max(width + 50, height + 250)
B = BuildImage(
x,
x,
font_size=24,
color="#FFEFD5",
background=random_bk_path / bk,
)
B.filter("GaussianBlur", 10)
_, B = get_max_width_or_paste(simple_help_img_list, B, True)
w = 10
h = 10
for msg in ["目前支持的功能列表:", "可以通过 ‘帮助[功能名称]’ 来获取对应功能的使用方法", "或者使用 ‘详细帮助’ 来获取所有功能方法"]:
text = BuildImage(
0,
0,
plain_text=msg,
font_size=24,
font="yuanshen.ttf",
)
B.paste(text, (w, h), True)
h += 50
if msg == "目前支持的功能列表:":
w += 50
B.paste(
BuildImage(
0,
0,
plain_text="注: 红字代表功能被群管理员禁用,红线代表功能正在维护",
font_size=24,
font="yuanshen.ttf",
font_color=(231, 74, 57)
),
(300, 10),
True,
)
B.save(simple_help_image)
def get_max_width_or_paste(
simple_help_img_list: list, B: BuildImage = None, is_paste: bool = False
) -> "int, BuildImage":
"""
获取最大宽度,或直接贴图
:param simple_help_img_list: 简单帮助图片列表
:param B: 背景图
:param is_paste: 是否直接贴图
"""
current_width = 50
current_height = 180
max_width = simple_help_img_list[0].w
for i in range(len(simple_help_img_list)):
try:
if is_paste and B:
B.paste(simple_help_img_list[i], (current_width, current_height), True)
current_height += simple_help_img_list[i].h + 40
if current_height + simple_help_img_list[i + 1].h > B.h - 10:
current_height = 180
current_width += max_width + 30
max_width = 0
elif simple_help_img_list[i].w > max_width:
max_width = simple_help_img_list[i].w
except IndexError:
pass
if current_width > simple_help_img_list[0].w + 50:
current_width += simple_help_img_list[-1].w
return current_width, B
def get_plugin_help(msg: str, is_super: bool = False) -> Optional[str]:
"""
获取功能的帮助信息
:param msg: 功能cmd
:param is_super: 是否为超级用户
"""
module = plugins2settings_manager.get_plugin_module(msg)
if not module:
module = admin_manager.get_plugin_module(msg)
if module:
try:
plugin = nonebot.plugin.get_plugin(module)
if plugin:
if is_super:
result = plugin.module.__getattribute__(
"__plugin_superuser_usage__"
)
else:
result = plugin.module.__getattribute__("__plugin_usage__")
if result:
width = 0
for x in result.split("\n"):
_width = len(x) * 24
width = width if width > _width else _width
height = len(result.split("\n")) * 45
A = BuildImage(width, height, font_size=24)
bk = BuildImage(
width,
height,
background=IMAGE_PATH / "background" / "1.png",
)
A.paste(bk, alpha=True)
A.text((int(width * 0.048), int(height * 0.21)), result)
return A.pic2bs4()
except AttributeError:
pass
return None | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/help/data_source.py | data_source.py |
from nonebot import on_command
from nonebot.adapters.onebot.v11 import (
Bot,
MessageEvent,
GroupMessageEvent,
Message
)
from nonebot.params import CommandArg
from nonebot.typing import T_State
from nonebot.rule import to_me
from configs.path_config import IMAGE_PATH, DATA_PATH
from utils.message_builder import image
from .data_source import create_help_img, get_plugin_help
import os
__zx_plugin_name__ = "帮助"
group_help_path = DATA_PATH / "group_help"
help_image = IMAGE_PATH / "help.png"
simple_help_image = IMAGE_PATH / "simple_help.png"
if help_image.exists():
help_image.unlink()
if simple_help_image.exists():
simple_help_image.unlink()
group_help_path.mkdir(exist_ok=True, parents=True)
for x in os.listdir(group_help_path):
group_help_image = group_help_path / x
group_help_image.unlink()
_help = on_command("详细功能", rule=to_me(), aliases={"详细帮助"}, priority=1, block=True)
simple_help = on_command("功能", rule=to_me(), aliases={"help", "帮助"}, priority=1, block=True)
@_help.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
if not help_image.exists():
if help_image.exists():
help_image.unlink()
if simple_help_image.exists():
simple_help_image.unlink()
await create_help_img(None, help_image, simple_help_image)
await _help.finish(image("help.png"))
@simple_help.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
is_super = False
if msg:
if '-super' in msg:
if str(event.user_id) in bot.config.superusers:
is_super = True
msg = msg.replace('-super', '').strip()
msg = get_plugin_help(msg, is_super)
if msg:
await _help.send(image(b64=msg))
else:
await _help.send("没有此功能的帮助信息...")
else:
if isinstance(event, GroupMessageEvent):
_image_path = group_help_path / f"{event.group_id}.png"
if not _image_path.exists():
await create_help_img(event.group_id, help_image, _image_path)
await simple_help.send(image(_image_path))
else:
if not simple_help_image.exists():
if help_image.exists():
help_image.unlink()
if simple_help_image.exists():
simple_help_image.unlink()
await create_help_img(None, help_image, simple_help_image)
await _help.finish(image("simple_help.png")) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/help/__init__.py | __init__.py |
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent, MessageEvent, Message, Bot
from nonebot.params import CommandArg, Command
from nonebot import on_command
from models.ban_user import BanUser
from models.level_user import LevelUser
from typing import Tuple
from utils.utils import get_message_at, is_number
from configs.config import NICKNAME, Config
from nonebot.permission import SUPERUSER
from .data_source import parse_ban_time, a_ban
from services.log import logger
__zx_plugin_name__ = "封禁Ban用户 [Admin]"
__plugin_usage__ = """
usage:
将用户拉入或拉出黑名单
指令:
.ban [at] ?[小时] ?[分钟]
.unban
示例:.ban @user
示例:.ban @user 6
示例:.ban @user 3 10
示例:.unban @user
""".strip()
__plugin_superuser_usage__ = """
usage:
b了=屏蔽用户消息,相当于最上级.ban
跨群ban以及跨群b了
指令:
b了 [at/qq]
.ban [user_id] ?[小时] ?[分钟]
示例:b了 @user
示例:b了 1234567
示例:.ban 12345567
""".strip()
__plugin_des__ = '你被逮捕了!丢进小黑屋!'
__plugin_cmd__ = ['.ban [at] ?[小时] ?[分钟]', '.unban [at]', 'b了 [at] [_superuser]']
__plugin_version__ = 0.1
__plugin_author__ = 'HibiKier'
__plugin_settings__ = {
"admin_level": Config.get_config("ban", "BAN_LEVEL"),
"cmd": ['.ban', '.unban', 'ban', 'unban']
}
__plugin_configs__ = {
"BAN_LEVEL [LEVEL]": {
"value": 5,
"help": "ban/unban所需要的管理员权限等级",
"default_value": 5
}
}
ban = on_command(
".ban",
aliases={".unban", "/ban", "/unban"},
priority=5,
block=True,
)
super_ban = on_command('b了', permission=SUPERUSER, priority=5, block=True)
@ban.handle()
async def _(bot: Bot, event: GroupMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
result = ""
qq = get_message_at(event.json())
if qq:
qq = qq[0]
user_name = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
user_name = user_name['card'] or user_name['nickname']
msg = arg.extract_plain_text().strip()
time = parse_ban_time(msg)
if isinstance(time, str):
await ban.finish(time, at_sender=True)
if cmd in [".ban", "/ban"]:
if (
await LevelUser.get_user_level(event.user_id, event.group_id)
<= await LevelUser.get_user_level(qq, event.group_id)
and str(event.user_id) not in bot.config.superusers
):
await ban.finish(
f"您的权限等级比对方低或相等, {NICKNAME}不能为您使用此功能!",
at_sender=True,
)
result = await a_ban(qq, time, user_name, event)
else:
if (
await BanUser.check_ban_level(
qq, await LevelUser.get_user_level(event.user_id, event.group_id)
)
and str(event.user_id) not in bot.config.superusers
):
await ban.finish(
f"ban掉 {user_name} 的管理员权限比您高,无法进行unban", at_sender=True
)
if await BanUser.unban(qq):
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 将 USER {qq} 解禁"
)
result = f"已经把 {user_name} 从黑名单中删除了!"
else:
result = f"{user_name} 不在黑名单!"
else:
await ban.finish("艾特人了吗??", at_sender=True)
await ban.send(result, at_sender=True)
@ban.handle()
async def _(bot: Bot, event: PrivateMessageEvent, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
msg = arg.extract_plain_text().strip()
if msg:
if str(event.user_id) in bot.config.superusers:
if is_number(arg.extract_plain_text().strip().split()[0]):
qq = int(msg[0])
msg = msg[1:]
if cmd in [".ban", "/ban"]:
time = parse_ban_time(msg)
if isinstance(time, str):
await ban.finish(time)
result = await a_ban(qq, time, str(qq), event, 9)
else:
if await BanUser.unban(qq):
logger.info(
f"USER {event.user_id} 将 USER {qq} 解禁"
)
result = f"已经把 {qq} 从黑名单中删除了!"
else:
result = f"{qq} 不在黑名单!"
await ban.send(result)
else:
await ban.finish('qq号必须是数字!\n格式:.ban [qq] [hour]? [minute]?', at_sender=True)
@super_ban.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
if isinstance(event, GroupMessageEvent):
qq = get_message_at(event.json())
else:
qq = arg.extract_plain_text().strip()
if not is_number(qq):
await super_ban.finish("对象qq必须为纯数字...")
qq = [qq]
if qq:
qq = qq[0]
user = await bot.get_group_member_info(group_id=event.group_id, user_id=qq)
user_name = user['card'] or user['nickname']
if not await BanUser.ban(qq, 10, 99999999):
await BanUser.unban(qq)
await BanUser.ban(qq, 10, 99999999)
await ban.send(f"已将 {user_name} 拉入黑名单!")
else:
await super_ban.send('需要添加被super ban的对象,可以使用at或者指定qq..') | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/ban/__init__.py | __init__.py |
from nonebot import on_request, on_message
from nonebot.adapters.onebot.v11 import (
Bot,
FriendRequestEvent,
GroupRequestEvent,
MessageEvent,
)
from models.friend_user import FriendUser
from datetime import datetime
from configs.config import NICKNAME, Config
from nonebot.adapters.onebot.v11.exception import ActionFailed
from utils.manager import requests_manager
from models.group_info import GroupInfo
from utils.utils import scheduler
import asyncio
import time
import re
__zx_plugin_name__ = "好友群聊处理请求 [Hidden]"
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_configs__ = {
"AUTO_ADD_FRIEND": {"value": False, "help": "是否自动同意好友添加", "default_value": False}
}
friend_req = on_request(priority=5, block=True)
group_req = on_request(priority=5, block=True)
x = on_message(priority=9, block=False)
exists_data = {"private": {}, "group": {}}
@friend_req.handle()
async def _(bot: Bot, event: FriendRequestEvent):
global exists_data
if exists_data["private"].get(event.user_id):
if time.time() - exists_data["private"][event.user_id] < 60 * 5:
return
exists_data["private"][event.user_id] = time.time()
user = await bot.get_stranger_info(user_id=event.user_id)
nickname = user["nickname"]
sex = user["sex"]
age = str(user["age"])
comment = event.comment
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"*****一份好友申请*****\n"
f"昵称:{nickname}({event.user_id})\n"
f"自动同意:{'√' if Config.get_config('invite_manager', 'AUTO_ADD_FRIEND') else '×'}\n"
f"日期:{str(datetime.now()).split('.')[0]}\n"
f"备注:{event.comment}",
)
if Config.get_config("invite_manager", "AUTO_ADD_FRIEND"):
await bot.set_friend_add_request(flag=event.flag, approve=True)
await FriendUser.add_friend_info(user["user_id"], user["nickname"])
else:
requests_manager.add_request(
event.user_id,
"private",
event.flag,
nickname=nickname,
sex=sex,
age=age,
comment=comment,
)
@group_req.handle()
async def _(bot: Bot, event: GroupRequestEvent):
global exists_data
if event.sub_type == "invite":
if str(event.user_id) in bot.config.superusers:
try:
if await GroupInfo.get_group_info(event.group_id):
await GroupInfo.set_group_flag(event.group_id, 1)
else:
group_info = await bot.get_group_info(group_id=event.group_id)
await GroupInfo.add_group_info(
group_info["group_id"],
group_info["group_name"],
group_info["max_member_count"],
group_info["member_count"],
1,
)
await bot.set_group_add_request(
flag=event.flag, sub_type="invite", approve=True
)
except ActionFailed:
pass
else:
user = await bot.get_stranger_info(user_id=event.user_id)
sex = user["sex"]
age = str(user["age"])
if exists_data["group"].get(f"{event.user_id}:{event.group_id}"):
if (
time.time()
- exists_data["group"][f"{event.user_id}:{event.group_id}"]
< 60 * 5
):
return
exists_data["group"][f"{event.user_id}:{event.group_id}"] = time.time()
nickname = await FriendUser.get_user_name(event.user_id)
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]),
message=f"*****一份入群申请*****\n"
f"申请人:{nickname}({event.user_id})\n"
f"群聊:{event.group_id}\n"
f"邀请日期:{str(datetime.now()).split('.')[0]}",
)
await bot.send_private_msg(
user_id=event.user_id,
message=f"想要邀请我偷偷入群嘛~已经提醒{NICKNAME}的管理员大人了\n"
"请确保已经群主或群管理沟通过!\n"
"等待管理员处理吧!",
)
requests_manager.add_request(
event.user_id,
"group",
event.flag,
invite_group=event.group_id,
nickname=nickname,
sex=sex,
age=age,
)
@x.handle()
async def _(event: MessageEvent):
await asyncio.sleep(0.1)
r = re.search(r'groupcode="(.*?)"', str(event.get_message()))
if r:
group_id = int(r.group(1))
else:
return
r = re.search(r'groupname="(.*?)"', str(event.get_message()))
if r:
group_name = r.group(1)
else:
group_name = "None"
requests_manager.set_group_name(group_name, group_id)
@scheduler.scheduled_job(
"interval",
minutes=5,
)
async def _():
global exists_data
exists_data = {"private": {}, "group": {}} | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/invite_manager/__init__.py | __init__.py |
from utils.image_utils import BuildImage
from configs.path_config import IMAGE_PATH
from services.log import logger
from utils.utils import get_matchers
from nonebot.adapters.onebot.v11 import Bot
from nonebot import Driver
import asyncio
import nonebot
driver: Driver = nonebot.get_driver()
background = IMAGE_PATH / "background" / "0.png"
superuser_help_image = IMAGE_PATH / "superuser_help.png"
@driver.on_bot_connect
async def create_help_image(bot: Bot = None):
"""
创建超级用户帮助图片
"""
await asyncio.get_event_loop().run_in_executor(None, _create_help_image)
def _create_help_image():
"""
创建管理员帮助图片
"""
_matchers = get_matchers()
_plugin_name_list = []
width = 0
help_str = "超级用户帮助\n\n* 注: ‘*’ 代表可有多个相同参数 ‘?’ 代表可省略该参数 *\n\n"
tmp_img = BuildImage(0, 0, plain_text='1', font_size=24)
for matcher in _matchers:
plugin_name = ""
try:
_plugin = nonebot.plugin.get_plugin(matcher.plugin_name)
_module = _plugin.module
try:
plugin_name = _module.__getattribute__("__zx_plugin_name__")
except AttributeError:
continue
is_superuser_usage = False
try:
_ = _module.__getattribute__("__plugin_superuser_usage__")
is_superuser_usage = True
except AttributeError:
pass
if (
("[superuser]" in plugin_name.lower() or is_superuser_usage)
and plugin_name != "超级用户帮助 [Superuser]"
and plugin_name not in _plugin_name_list
and "[hidden]" not in plugin_name.lower()
):
_plugin_name_list.append(plugin_name)
try:
plugin_des = _module.__getattribute__("__plugin_des__")
except AttributeError:
plugin_des = '_'
plugin_cmd = _module.__getattribute__("__plugin_cmd__")
if is_superuser_usage:
plugin_cmd = [x for x in plugin_cmd if "[_superuser]" in x]
plugin_cmd = " / ".join(plugin_cmd).replace('[_superuser]', '').strip()
help_str += f"{plugin_des} -> {plugin_cmd}\n\n"
x = tmp_img.getsize(f"{plugin_des} -> {plugin_cmd}")[0]
width = width if width > x else x
except Exception as e:
logger.warning(
f"获取超级用户插件 {matcher.plugin_name}: {plugin_name} 设置失败... {type(e)}:{e}"
)
height = len(help_str.split("\n")) * 33
width += 500
A = BuildImage(width, height, font_size=24)
_background = BuildImage(width, height, background=background)
A.text((300, 140), help_str)
A.paste(_background, alpha=True)
A.save(superuser_help_image)
logger.info(f"已成功加载 {len(_plugin_name_list)} 条超级用户命令") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/super_help/data_source.py | data_source.py |
from nonebot import on_command
from nonebot.permission import SUPERUSER
from models.level_user import LevelUser
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, Message, GroupMessageEvent
from utils.utils import get_message_at, is_number
from services.log import logger
from utils.message_builder import at
from nonebot.params import Command, CommandArg
from typing import Tuple
__zx_plugin_name__ = "用户权限管理 [Superuser]"
__plugin_usage__ = """
usage:
增删改用户的权限
指令:
添加权限 [at] [权限]
添加权限 [qq] [group_id] [权限]
删除权限 [at]
""".strip()
__plugin_des__ = "增删改用户的权限"
__plugin_cmd__ = [
"添加权限 [at] [权限]",
"添加权限 [qq] [group_id] [权限]",
"删除权限 [at]",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
super_cmd = on_command(
"添加管理",
aliases={"删除管理", "添加权限", "删除权限"},
priority=1,
permission=SUPERUSER,
block=True,
)
@super_cmd.handle()
async def _(
bot: Bot,
event: MessageEvent,
cmd: Tuple[str, ...] = Command(),
arg: Message = CommandArg(),
):
group_id = event.group_id if isinstance(event, GroupMessageEvent) else -1
level = None
args = arg.extract_plain_text().strip().split()
qq = get_message_at(event.json())
flag = 2
try:
if qq:
qq = qq[0]
if cmd[0][:2] == "添加" and args and is_number(args[0]):
level = int(args[0])
else:
if cmd[0][:2] == "添加":
if (
len(args) > 2
and is_number(args[0])
and is_number(args[1])
and is_number(args[2])
):
qq = int(args[0])
group_id = int(args[1])
level = int(args[2])
else:
if len(args) > 1 and is_number(args[0]) and is_number(args[1]):
qq = int(args[0])
group_id = int(args[1])
flag = 1
level = -1 if cmd[0][:2] == "删除" else level
if group_id == -1 or not level or not qq:
raise IndexError()
except IndexError:
await super_cmd.finish(__plugin_usage__)
try:
if cmd[0][:2] == "添加":
if await LevelUser.set_level(qq, group_id, level, 1):
result = f"添加管理成功, 权限: {level}"
else:
result = f"管理已存在, 更新权限: {level}"
else:
if await LevelUser.delete_level(qq, event.group_id):
result = "删除管理成功!"
else:
result = "该账号无管理权限!"
if flag == 2:
await super_cmd.send(result)
elif flag == 1:
await bot.send_group_msg(
group_id=group_id,
message=Message(
f"{at(qq)}管理员修改了你的权限"
f"\n--------\n你当前的权限等级:{level if level != -1 else 0}"
),
)
await super_cmd.send("修改成功")
except Exception as e:
await super_cmd.send("执行指令失败!")
logger.error(f"执行指令失败 e:{e}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/super_cmd/set_admin_permissions.py | set_admin_permissions.py |
from nonebot import on_command
from nonebot.permission import SUPERUSER
from nonebot.adapters.onebot.v11 import Bot, Message
from nonebot.params import Command, CommandArg
from typing import Tuple
from nonebot.rule import to_me
from utils.utils import is_number
from utils.manager import requests_manager
from utils.message_builder import image
from models.group_info import GroupInfo
__zx_plugin_name__ = "显示所有好友群组 [Superuser]"
__plugin_usage__ = """
usage:
显示所有好友群组
指令:
查看所有好友/查看所有群组
同意好友请求 [id]
拒绝好友请求 [id]
同意群聊请求 [id]
拒绝群聊请求 [id]
查看所有请求
清空所有请求
""".strip()
__plugin_des__ = "显示所有好友群组"
__plugin_cmd__ = [
"查看所有好友/查看所有群组",
"同意好友请求 [id]",
"拒绝好友请求 [id]",
"同意群聊请求 [id]",
"拒绝群聊请求 [id]",
"查看所有请求",
"清空所有请求",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
cls_group = on_command(
"查看所有群组", rule=to_me(), permission=SUPERUSER, priority=1, block=True
)
cls_friend = on_command(
"查看所有好友", rule=to_me(), permission=SUPERUSER, priority=1, block=True
)
friend_handle = on_command(
"同意好友请求", aliases={"拒绝好友请求"}, permission=SUPERUSER, priority=1, block=True
)
group_handle = on_command(
"同意群聊请求", aliases={"拒绝群聊请求"}, permission=SUPERUSER, priority=1, block=True
)
clear_request = on_command("清空所有请求", permission=SUPERUSER, priority=1, block=True)
cls_request = on_command("查看所有请求", permission=SUPERUSER, priority=1, block=True)
@cls_group.handle()
async def _(bot: Bot):
gl = await bot.get_group_list()
msg = ["{group_id} {group_name}".format_map(g) for g in gl]
msg = "\n".join(msg)
msg = f"bot:{bot.self_id}\n| 群号 | 群名 | 共{len(gl)}个群\n" + msg
await cls_group.send(msg)
@cls_friend.handle()
async def _(bot: Bot):
gl = await bot.get_friend_list()
msg = ["{user_id} {nickname}".format_map(g) for g in gl]
msg = "\n".join(msg)
msg = f"| QQ号 | 昵称 | 共{len(gl)}个好友\n" + msg
await cls_friend.send(msg)
@friend_handle.handle()
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
id_ = arg.extract_plain_text().strip()
if is_number(id_):
id_ = int(id_)
if cmd[:2] == "同意":
if await requests_manager.approve(bot, id_, "private"):
await friend_handle.send("同意好友请求成功..")
else:
await friend_handle.send("同意好友请求失败,可能是未找到此id的请求..")
else:
if await requests_manager.refused(bot, id_, "private"):
await friend_handle.send("拒绝好友请求成功..")
else:
await friend_handle.send("拒绝好友请求失败,可能是未找到此id的请求..")
else:
await friend_handle.send("id必须为纯数字!")
@group_handle.handle()
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
id_ = arg.extract_plain_text().strip()
if is_number(id_):
id_ = int(id_)
if cmd[:2] == "同意":
rid = requests_manager.get_group_id(id_)
if rid:
await friend_handle.send("同意群聊请求成功..")
if await GroupInfo.get_group_info(rid):
await GroupInfo.set_group_flag(rid, 1)
else:
group_info = await bot.get_group_info(group_id=rid)
await GroupInfo.add_group_info(
rid,
group_info["group_name"],
group_info["max_member_count"],
group_info["member_count"],
1
)
await requests_manager.approve(bot, id_, "group")
else:
await friend_handle.send("同意群聊请求失败,可能是未找到此id的请求..")
else:
if await requests_manager.refused(bot, id_, "group"):
await friend_handle.send("拒绝群聊请求成功..")
else:
await friend_handle.send("拒绝群聊请求失败,可能是未找到此id的请求..")
else:
await friend_handle.send("id必须为纯数字!")
@cls_request.handle()
async def _():
_str = ""
for type_ in ["private", "group"]:
msg = await requests_manager.show(type_)
if msg:
_str += image(b64=msg)
else:
_str += "没有任何好友请求.." if type_ == "private" else "没有任何群聊请求.."
if type_ == "private":
_str += '\n--------------------\n'
await cls_request.send(Message(_str))
@clear_request.handle()
async def _():
requests_manager.clear()
await cls_request.send("已清空所有好友/群聊请求..") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/super_cmd/bot_friend_group.py | bot_friend_group.py |
from nonebot.adapters.onebot.v11 import Bot, MessageEvent, GROUP, GroupMessageEvent, Message
from nonebot import on_command, on_regex
from nonebot.permission import SUPERUSER
from nonebot.typing import T_State
from nonebot.rule import to_me
from utils.utils import is_number
from utils.manager import group_manager, plugins2settings_manager
from models.group_info import GroupInfo
from services.log import logger
from configs.config import NICKNAME
from nonebot.adapters.onebot.v11.exception import ActionFailed
from nonebot.params import Command, CommandArg
from typing import Tuple
__zx_plugin_name__ = "管理群操作 [Superuser]"
__plugin_usage__ = """
usage:
群权限 | 群白名单 | 退出群 操作
指令:
退群 [group_id]
修改群权限 [group_id] [等级]
添加群白名单 *[group_id]
删除群白名单 *[group_id]
添加群认证 *[group_id]
删除群认证 *[group_id]
查看群白名单
""".strip()
__plugin_des__ = "管理群操作"
__plugin_cmd__ = [
"退群 [group_id]",
"修改群权限 [group_id] [等级]",
"添加群白名单 *[group_id]",
"删除群白名单 *[group_id]",
"添加群认证 *[group_id]",
"删除群认证 *[group_id]",
"查看群白名单",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
del_group = on_command("退群", rule=to_me(), permission=SUPERUSER, priority=1, block=True)
add_group_level = on_command("修改群权限", priority=1, permission=SUPERUSER, block=True)
my_group_level = on_command(
"查看群权限", aliases={"群权限"}, priority=5, permission=GROUP, block=True
)
what_up_group_level = on_regex(
".*?(提高|提升|升高|增加|加上)(.*?)群权限.*?",
rule=to_me(),
priority=5,
permission=GROUP,
block=True,
)
manager_group_whitelist = on_command(
"添加群白名单", aliases={"删除群白名单"}, priority=1, permission=SUPERUSER, block=True
)
show_group_whitelist = on_command(
"查看群白名单", priority=1, permission=SUPERUSER, block=True
)
group_auth = on_command(
"添加群认证", aliases={"删除群认证"}, priority=1, permission=SUPERUSER, block=True
)
@del_group.handle()
async def _(bot: Bot, arg: Message = CommandArg()):
group_id = arg.extract_plain_text().strip()
if group_id:
if is_number(group_id):
try:
await bot.set_group_leave(group_id=int(group_id))
logger.info(f"退出群聊 {group_id} 成功")
await del_group.send(f"退出群聊 {group_id} 成功", at_sender=True)
group_manager.delete_group(int(group_id))
await GroupInfo.delete_group_info(int(group_id))
except Exception as e:
logger.info(f"退出群聊 {group_id} 失败 e:{e}")
else:
await del_group.finish(f"请输入正确的群号", at_sender=True)
else:
await del_group.finish(f"请输入群号", at_sender=True)
@add_group_level.handle()
async def _(bot: Bot, event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
group_id = 0
level = 0
if not msg:
await add_group_level.finish("用法:修改群权限 [group] [level]")
msg = msg.split(" ")
if len(msg) < 2:
await add_group_level.finish("参数不完全..[group] [level]")
if is_number(msg[0]) and is_number(msg[1]):
group_id = msg[0]
level = int(msg[1])
else:
await add_group_level.finish("参数错误...group和level必须是数字..")
old_level = group_manager.get_group_level(group_id)
group_manager.set_group_level(group_id, level)
await add_group_level.send("修改成功...", at_sender=True)
if level > -1:
await bot.send_group_msg(
group_id=int(group_id), message=f"管理员修改了此群权限:{old_level} -> {level}"
)
logger.info(f"{event.user_id} 修改了 {group_id} 的权限:{level}")
@my_group_level.handle()
async def _(event: GroupMessageEvent):
level = group_manager.get_group_level(event.group_id)
tmp = ""
data = plugins2settings_manager.get_data()
for module in data:
if data[module]["level"] > level:
plugin_name = data[module]["cmd"][0]
if plugin_name == "pixiv":
plugin_name = "搜图 p站排行"
tmp += f"{plugin_name}\n"
if tmp:
tmp = "\n目前无法使用的功能:\n" + tmp
await my_group_level.finish(f"当前群权限:{level}{tmp}")
@what_up_group_level.handle()
async def _():
await what_up_group_level.finish(
f"[此功能用于防止内鬼,如果引起不便那真是抱歉了]\n" f"目前提高群权限的方法:\n" f"\t1.管理员修改权限"
)
@manager_group_whitelist.handle()
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
msg = arg.extract_plain_text().strip()
all_group = [
g["group_id"] for g in await bot.get_group_list()
]
group_list = []
for group in msg:
if is_number(group) and int(group) in all_group:
group_list.append(int(group))
if group_list:
for group in group_list:
if cmd in ["添加群白名单"]:
group_manager.add_group_white_list(group)
else:
group_manager.delete_group_white_list(group)
group_list = [str(x) for x in group_list]
await manager_group_whitelist.send(
"已成功将 " + "\n".join(group_list) + " " + cmd
)
else:
await manager_group_whitelist.send(f"添加失败,请检查{NICKNAME}是否已加入这些群聊或重复添加/删除群白单名")
@show_group_whitelist.handle()
async def _():
x = group_manager.get_group_white_list()
x = [str(g) for g in x]
if x:
await show_group_whitelist.send("目前的群白名单:\n" + "\n".join(x))
else:
await show_group_whitelist.send("没有任何群在群白名单...")
@group_auth.handle()
async def _(bot: Bot, cmd: Tuple[str, ...] = Command(), arg: Message = CommandArg()):
cmd = cmd[0]
msg = arg.extract_plain_text().strip().split()
for group_id in msg:
if not is_number(group_id):
await group_auth.send(f"{group_id}非纯数字,已跳过该项..")
group_id = int(group_id)
if cmd[:2] == "添加":
if await GroupInfo.get_group_info(group_id):
await GroupInfo.set_group_flag(group_id, 1)
else:
try:
group_info = await bot.get_group_info(group_id=group_id)
except ActionFailed:
group_info = {
"group_id": group_id,
"group_name": "_",
"max_member_count": -1,
"member_count": -1,
}
await GroupInfo.add_group_info(
group_info["group_id"],
group_info["group_name"],
group_info["max_member_count"],
group_info["member_count"],
1,
)
else:
if await GroupInfo.get_group_info(group_id):
await GroupInfo.set_group_flag(group_id, 0)
await group_auth.send(
f'已为 {group_id} {cmd[:2]}群认证..'
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/super_cmd/manager_group.py | manager_group.py |
from typing import List
from nonebot.adapters.onebot.v11.message import MessageSegment
from services.log import logger
from configs.path_config import DATA_PATH
from utils.message_builder import image
from utils.utils import get_bot, get_matchers
from pathlib import Path
from models.group_member_info import GroupInfoUser
from datetime import datetime
from services.db_context import db
from models.level_user import LevelUser
from configs.config import Config
from utils.manager import group_manager, plugins2settings_manager, plugins_manager
from utils.image_utils import BuildImage
from utils.http_utils import AsyncHttpx
import asyncio
import time
import os
try:
import ujson as json
except ModuleNotFoundError:
import json
async def group_current_status(group_id: int) -> str:
"""
获取当前所有通知的开关
:param group_id: 群号
"""
rst = "[被动技能 状态]\n"
_data = group_manager.get_task_data()
for task in _data.keys():
rst += f'{_data[task]}: {"√" if await group_manager.check_group_task_status(group_id, task) else "×"}\n'
return rst.strip()
custom_welcome_msg_json = (
Path() / "data" / "custom_welcome_msg" / "custom_welcome_msg.json"
)
async def custom_group_welcome(
msg: str, imgs: List[str], user_id: int, group_id: int
) -> str:
"""
替换群欢迎消息
:param msg: 欢迎消息文本
:param imgs: 欢迎消息图片,只取第一张
:param user_id: 用户id,用于log记录
:param group_id: 群号
"""
img_result = ""
img = imgs[0] if imgs else ""
result = ""
if (DATA_PATH / f"custom_welcome_msg/{group_id}.jpg").exists():
(DATA_PATH / f"custom_welcome_msg/{group_id}.jpg").unlink()
if not custom_welcome_msg_json.exists():
custom_welcome_msg_json.parent.mkdir(parents=True, exist_ok=True)
data = {}
else:
try:
data = json.load(open(custom_welcome_msg_json, "r"))
except FileNotFoundError:
data = {}
try:
if msg:
data[str(group_id)] = str(msg)
json.dump(
data, open(custom_welcome_msg_json, "w"), indent=4, ensure_ascii=False
)
logger.info(f"USER {user_id} GROUP {group_id} 更换群欢迎消息 {msg}")
result += msg
if img:
await AsyncHttpx.download_file(
img, DATA_PATH / "custom_welcome_msg" / f"{group_id}.jpg"
)
img_result = image(DATA_PATH / "custom_welcome_msg" / f"{group_id}.jpg")
logger.info(f"USER {user_id} GROUP {group_id} 更换群欢迎消息图片")
except Exception as e:
logger.error(f"GROUP {group_id} 替换群消息失败 e:{e}")
return "替换群消息失败.."
return f"替换群欢迎消息成功:\n{result}" + img_result
task_data = None
async def change_group_switch(cmd: str, group_id: int, is_super: bool = False):
global task_data
"""
修改群功能状态
:param cmd: 功能名称
:param group_id: 群号
:param is_super: 是否位超级用户,超级用户用于私聊开关功能状态
"""
if not task_data:
task_data = group_manager.get_task_data()
group_help_file = DATA_PATH / "group_help" / f"{group_id}.png"
status = cmd[:2]
cmd = cmd[2:]
type_ = "plugin"
modules = plugins2settings_manager.get_plugin_module(cmd, True)
if cmd == "全部被动":
for task in task_data:
if status == "开启":
if not await group_manager.check_group_task_status(group_id, task):
await group_manager.open_group_task(group_id, task)
else:
if await group_manager.check_group_task_status(group_id, task):
await group_manager.close_group_task(group_id, task)
if group_help_file.exists():
group_help_file.unlink()
return f"已 {status} 全部被动技能!"
if cmd == "全部功能":
for f in plugins2settings_manager.get_data():
if status == "开启":
group_manager.unblock_plugin(f, group_id)
else:
group_manager.block_plugin(f, group_id)
return f"已 {status} 全部功能!"
if cmd in [task_data[x] for x in task_data.keys()]:
type_ = "task"
modules = [x for x in task_data.keys() if task_data[x] == cmd]
for module in modules:
if is_super:
module = f"{module}:super"
if status == "开启":
if type_ == "task":
if await group_manager.check_group_task_status(group_id, module):
return f"被动 {task_data[module]} 正处于开启状态!不要重复开启."
await group_manager.open_group_task(group_id, module)
else:
if group_manager.get_plugin_status(module, group_id):
return f"功能 {cmd} 正处于开启状态!不要重复开启."
group_manager.unblock_plugin(module, group_id)
else:
if type_ == "task":
if not await group_manager.check_group_task_status(group_id, module):
return f"被动 {task_data[module]} 正处于关闭状态!不要重复关闭."
await group_manager.close_group_task(group_id, module)
else:
if not group_manager.get_plugin_status(module, group_id):
return f"功能 {cmd} 正处于关闭状态!不要重复关闭."
group_manager.block_plugin(module, group_id)
if group_help_file.exists():
group_help_file.unlink()
if is_super:
for file in os.listdir(DATA_PATH / "group_help"):
file = DATA_PATH / "group_help" / file
file.unlink()
else:
_help_image = DATA_PATH / "group_help" / f"{group_id}.png"
if _help_image.exists():
_help_image.unlink()
return f"{status} {cmd} 功能!"
def set_plugin_status(cmd: str, block_type: str = "all"):
"""
设置插件功能状态(超级用户使用)
:param cmd: 功能名称
:param block_type: 限制类型, 'all': 私聊+群里, 'private': 私聊, 'group': 群聊
"""
status = cmd[:2]
cmd = cmd[2:]
module = plugins2settings_manager.get_plugin_module(cmd)
if status == "开启":
plugins_manager.unblock_plugin(module)
else:
plugins_manager.block_plugin(module, block_type=block_type)
for file in os.listdir(DATA_PATH / "group_help"):
file = DATA_PATH / "group_help" / file
file.unlink()
async def get_plugin_status():
"""
获取功能状态
"""
return await asyncio.get_event_loop().run_in_executor(None, _get_plugin_status)
def _get_plugin_status() -> MessageSegment:
"""
合成功能状态图片
"""
rst = "\t功能\n"
flag_str = "状态".rjust(4) + "\n"
tmp_name = []
for matcher in get_matchers():
if matcher.plugin_name not in tmp_name:
tmp_name.append(matcher.plugin_name)
module = matcher.plugin_name
flag = plugins_manager.get_plugin_block_type(module)
flag = flag.upper() + " CLOSE" if flag else "OPEN"
try:
plugin_name = plugins_manager.get(module)["plugin_name"]
if (
"[Hidden]" in plugin_name
or "[Admin]" in plugin_name
or "[Superuser]" in plugin_name
):
continue
rst += f"{plugin_name}"
except KeyError:
rst += f"{module}"
if plugins_manager.get(module)["error"]:
rst += "[ERROR]"
rst += "\n"
flag_str += f"{flag}\n"
height = len(rst.split("\n")) * 24
a = BuildImage(250, height, font_size=20)
a.text((10, 10), rst)
b = BuildImage(200, height, font_size=20)
b.text((10, 10), flag_str)
A = BuildImage(500, height)
A.paste(a)
A.paste(b, (270, 0))
return image(b64=A.pic2bs4())
async def update_member_info(group_id: int, remind_superuser: bool = False) -> bool:
"""
更新群成员信息
:param group_id: 群号
:param remind_superuser: 失败信息提醒超级用户
"""
bot = get_bot()
_group_user_list = await bot.get_group_member_list(group_id=group_id)
_error_member_list = []
_exist_member_list = []
# try:
for user_info in _group_user_list:
if user_info["card"] == "":
nickname = user_info["nickname"]
else:
nickname = user_info["card"]
async with db.transaction():
# 更新权限
if (
user_info["role"]
in [
"owner",
"admin",
]
and not await LevelUser.is_group_flag(user_info["user_id"], group_id)
):
await LevelUser.set_level(
user_info["user_id"],
user_info["group_id"],
Config.get_config("admin_bot_manage", "ADMIN_DEFAULT_AUTH"),
)
if str(user_info["user_id"]) in bot.config.superusers:
await LevelUser.set_level(
user_info["user_id"], user_info["group_id"], 9
)
user = await GroupInfoUser.get_member_info(
user_info["user_id"], user_info["group_id"]
)
if user:
if user.user_name != nickname:
await user.update(user_name=nickname).apply()
logger.info(
f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新群昵称成功"
)
_exist_member_list.append(int(user_info["user_id"]))
continue
join_time = datetime.strptime(
time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(user_info["join_time"])
),
"%Y-%m-%d %H:%M:%S",
)
if await GroupInfoUser.add_member_info(
user_info["user_id"],
user_info["group_id"],
nickname,
join_time,
):
_exist_member_list.append(int(user_info["user_id"]))
logger.info(f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新成功")
else:
_error_member_list.append(
f"用户{user_info['user_id']} 所属{user_info['group_id']} 更新失败\n"
)
_del_member_list = list(
set(_exist_member_list).difference(
set(await GroupInfoUser.get_group_member_id_list(group_id))
)
)
if _del_member_list:
for del_user in _del_member_list:
if await GroupInfoUser.delete_member_info(del_user, group_id):
logger.info(f"退群用户{del_user} 所属{group_id} 已删除")
else:
logger.info(f"退群用户{del_user} 所属{group_id} 删除失败")
if _error_member_list and remind_superuser:
result = ""
for error_user in _error_member_list:
result += error_user
await bot.send_private_msg(
user_id=int(list(bot.config.superusers)[0]), message=result[:-1]
)
return True
def set_group_bot_status(group_id: int, status: bool) -> str:
"""
设置群聊bot开关状态
:param group_id: 群号
:param status: 状态
"""
if status:
if group_manager.check_group_bot_status(group_id):
return "我还醒着呢!"
group_manager.turn_on_group_bot_status(group_id)
return "呜..醒来了..."
else:
group_manager.shutdown_group_bot_status(group_id)
# for x in group_manager.get_task_data():
# group_manager.close_group_task(group_id, x)
return "那我先睡觉了..." | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/admin_bot_manage/_data_source.py | _data_source.py |
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, MessageEvent, GROUP
from nonebot import on_command, on_message, on_regex
from nonebot.params import RegexGroup
from ._data_source import (
change_group_switch,
set_plugin_status,
get_plugin_status,
group_current_status,
set_group_bot_status
)
from services.log import logger
from configs.config import NICKNAME, Config
from utils.utils import get_message_text, is_number
from nonebot.permission import SUPERUSER
from typing import Tuple, Any
from .rule import switch_rule
__zx_plugin_name__ = "群功能开关 [Admin]"
__plugin_usage__ = """
usage:
群内功能与被动技能开关
指令:
开启/关闭[功能]
群被动状态
开启全部被动
关闭全部被动
醒来/休息吧
示例:开启/关闭色图
""".strip()
__plugin_superuser_usage__ = """
usage:
功能总开关与指定群禁用
指令:
功能状态
开启/关闭[功能] [group]
开启/关闭[功能] ['private'/'group']
""".strip()
__plugin_des__ = "群内功能开关"
__plugin_cmd__ = [
"开启/关闭[功能]",
"群被动状态",
"开启全部被动",
"关闭全部被动",
"醒来/休息吧",
"功能状态 [_superuser]",
"开启/关闭[功能] [group] [_superuser]",
"开启/关闭[功能] ['private'/'group'] [_superuser]",
]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"admin_level": Config.get_config("admin_bot_manage", "CHANGE_GROUP_SWITCH_LEVEL"),
"cmd": ["开启功能", "关闭功能", "开关"]
}
switch_rule_matcher = on_message(rule=switch_rule, priority=4, block=True)
plugins_status = on_command("功能状态", permission=SUPERUSER, priority=5, block=True)
group_task_status = on_command("群被动状态", permission=GROUP, priority=5, block=True)
group_status = on_regex("^(休息吧|醒来)$", permission=GROUP, priority=5, block=True)
@switch_rule_matcher.handle()
async def _(bot: Bot, event: MessageEvent):
_cmd = get_message_text(event.json()).split()[0]
if isinstance(event, GroupMessageEvent):
await switch_rule_matcher.send(await change_group_switch(_cmd, event.group_id))
logger.info(f"USER {event.user_id} GROUP {event.group_id} 使用群功能管理命令 {_cmd}")
else:
if str(event.user_id) in bot.config.superusers:
block_type = " ".join(get_message_text(event.json()).split()[1:])
block_type = block_type if block_type else "a"
if is_number(block_type):
if not int(block_type) in [
g["group_id"]
for g in await bot.get_group_list()
]:
await switch_rule_matcher.finish(f"{NICKNAME}未加入群聊:{block_type}")
await change_group_switch(_cmd, int(block_type), True)
group_name = (await bot.get_group_info(group_id=int(block_type)))[
"group_name"
]
await switch_rule_matcher.send(
f"已禁用群聊 {group_name}({block_type}) 的 {_cmd[2:]} 功能"
)
elif block_type in ["all", "private", "group", "a", "p", "g"]:
block_type = "all" if block_type == "a" else block_type
block_type = "private" if block_type == "p" else block_type
block_type = "group" if block_type == "g" else block_type
set_plugin_status(_cmd, block_type)
if block_type == "all":
await switch_rule_matcher.send(f"已{_cmd[:2]}功能:{_cmd[2:]}")
elif block_type == "private":
await switch_rule_matcher.send(f"已在私聊中{_cmd[:2]}功能:{_cmd[2:]}")
else:
await switch_rule_matcher.send(f"已在群聊中{_cmd[:2]}功能:{_cmd[2:]}")
else:
await switch_rule_matcher.finish("格式错误:关闭[功能] [group]/[p/g]")
logger.info(f"USER {event.user_id} 使用功能管理命令 {_cmd} | {block_type}")
@plugins_status.handle()
async def _():
await plugins_status.send(await get_plugin_status())
@group_task_status.handle()
async def _(event: GroupMessageEvent):
await group_task_status.send(await group_current_status(event.group_id))
@group_status.handle()
async def _(event: GroupMessageEvent, reg_group: Tuple[Any, ...] = RegexGroup()):
cmd = reg_group[0]
if cmd == "休息吧":
msg = set_group_bot_status(event.group_id, False)
else:
msg = set_group_bot_status(event.group_id, True)
await group_status.send(msg)
logger.info(f"USER {event.user_id} GROUP {event.group_id} 使用总开关命令:{cmd}") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/admin_bot_manage/switch_rule.py | switch_rule.py |
from nonebot import on_command
from services.log import logger
from nonebot.adapters.onebot.v11 import GroupMessageEvent, Message
from nonebot.params import CommandArg
from utils.utils import is_number
from models.bag_user import BagUser
from services.db_context import db
from nonebot.adapters.onebot.v11.permission import GROUP
from models.goods_info import GoodsInfo
import time
__zx_plugin_name__ = "商店 - 购买道具"
__plugin_usage__ = """
usage:
购买道具
指令:
购买 [序号或名称] ?[数量=1]
示例:购买 好感双倍加持卡Ⅰ
示例:购买 1 4
""".strip()
__plugin_des__ = "商店 - 购买道具"
__plugin_cmd__ = ["购买 [序号或名称] ?[数量=1]"]
__plugin_type__ = ("商店",)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["商店", "购买道具"],
}
__plugin_cd_limit__ = {"cd": 3}
buy = on_command("购买", aliases={"购买道具"}, priority=5, block=True, permission=GROUP)
@buy.handle()
async def _(event: GroupMessageEvent, arg: Message = CommandArg()):
goods = None
if arg.extract_plain_text().strip() in ["神秘药水"]:
await buy.finish("你们看看就好啦,这是不可能卖给你们的~", at_sender=True)
goods_list = [
x
for x in await GoodsInfo.get_all_goods()
if x.goods_limit_time > time.time() or x.goods_limit_time == 0
]
goods_name_list = [
x.goods_name
for x in goods_list
]
msg = arg.extract_plain_text().strip().split()
num = 1
if len(msg) > 1:
if is_number(msg[1]) and int(msg[1]) > 0:
num = int(msg[1])
else:
await buy.finish("购买的数量要是数字且大于0!", at_sender=True)
if is_number(msg[0]):
msg = int(msg[0])
if msg > len(goods_name_list) or msg < 1:
await buy.finish("请输入正确的商品id!", at_sender=True)
goods = goods_list[msg - 1]
else:
if msg[0] in goods_name_list:
for i in range(len(goods_name_list)):
if msg[0] == goods_name_list[i]:
goods = goods_list[i]
break
else:
await buy.finish("请输入正确的商品名称!")
else:
await buy.finish("请输入正确的商品名称!", at_sender=True)
async with db.transaction():
if (
await BagUser.get_gold(event.user_id, event.group_id)
) < goods.goods_price * num * goods.goods_discount:
await buy.finish("您的金币好像不太够哦", at_sender=True)
if await BagUser.buy_property(event.user_id, event.group_id, goods, num):
await buy.send(
f"花费 {goods.goods_price * num * goods.goods_discount} 金币购买 {goods.goods_name} ×{num} 成功!",
at_sender=True,
)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} "
f"花费 {goods.goods_price*num} 金币购买 {goods.goods_name} ×{num} 成功!"
)
else:
await buy.send(f"{goods.goods_name} 购买失败!", at_sender=True)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} "
f"花费 {goods.goods_price * num * goods.goods_discount} 金币购买 {goods.goods_name} ×{num} 失败!"
) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/shop/buy.py | buy.py |
from models.goods_info import GoodsInfo
from utils.image_utils import BuildImage
from models.sign_group_user import SignGroupUser
from utils.utils import is_number
from configs.path_config import IMAGE_PATH
from typing import Optional, Union
from configs.config import Config
from nonebot import Driver
from nonebot.plugin import require
import nonebot
import time
driver: Driver = nonebot.get_driver()
use = require("use")
@driver.on_startup
async def init_default_shop_goods():
"""
导入内置的三个商品
"""
async def sign_card(**kwargs):
user_id = kwargs['user_id']
group_id = kwargs['group_id']
prob = kwargs["prob"]
user = await SignGroupUser.ensure(user_id, group_id)
await user.update(add_probability=prob).apply()
if Config.get_config("shop", "IMPORT_DEFAULT_SHOP_GOODS"):
await register_goods(
"好感度双倍加持卡Ⅰ", 30, "下次签到双倍好感度概率 + 10%(谁才是真命天子?)(同类商品将覆盖)"
)
use.register_use("好感度双倍加持卡Ⅰ", sign_card, **{"prob": 0.1})
await register_goods("好感度双倍加持卡Ⅱ", 150, "下次签到双倍好感度概率 + 20%(平平庸庸)(同类商品将覆盖)")
use.register_use("好感度双倍加持卡Ⅱ", sign_card, **{"prob": 0.2})
await register_goods(
"好感度双倍加持卡Ⅲ", 250, "下次签到双倍好感度概率 + 30%(金币才是真命天子!)(同类商品将覆盖)"
)
use.register_use("好感度双倍加持卡Ⅲ", sign_card, **{"prob": 0.3})
# 创建商店界面
async def create_shop_help() -> str:
"""
制作商店图片
:return: 图片base64
"""
goods_lst = await GoodsInfo.get_all_goods()
idx = 1
_dc = {}
font_h = BuildImage(0, 0).getsize("正")[1]
h = 10
_list = []
for goods in goods_lst:
if goods.goods_limit_time == 0 or time.time() < goods.goods_limit_time:
h += len(goods.goods_description.strip().split("\n")) * font_h + 80
_list.append(goods)
A = BuildImage(1000, h, color="#f9f6f2")
current_h = 0
for goods in _list:
bk = BuildImage(
700, 80, font_size=15, color="#f9f6f2", font="CJGaoDeGuo.otf"
)
goods_image = BuildImage(
600, 80, font_size=20, color="#a29ad6", font="CJGaoDeGuo.otf"
)
name_image = BuildImage(
580, 40, font_size=25, color="#e67b6b", font="CJGaoDeGuo.otf"
)
await name_image.atext(
(15, 0), f"{idx}.{goods.goods_name}", center_type="by_height"
)
await name_image.aline((380, -5, 280, 45), "#a29ad6", 5)
await name_image.atext((390, 0), "售价:", center_type="by_height")
await name_image.atext(
(440, 0), str(goods.goods_price), (255, 255, 255), center_type="by_height"
)
await name_image.atext(
(
440
+ BuildImage(0, 0, plain_text=str(goods.goods_price), font_size=25).w,
0,
),
" 金币",
center_type="by_height",
)
await name_image.acircle_corner(5)
await goods_image.apaste(name_image, (0, 5), True, center_type="by_width")
await goods_image.atext((15, 50), f"简介:{goods.goods_description}")
await goods_image.acircle_corner(20)
await bk.apaste(goods_image, alpha=True)
# 添加限时图标和时间
if goods.goods_limit_time > 0:
_limit_time_logo = BuildImage(40, 40, background=f"{IMAGE_PATH}/other/time.png")
await bk.apaste(_limit_time_logo, (600, 0), True)
await bk.apaste(BuildImage(0, 0, plain_text="限时!", font_size=23, font="CJGaoDeGuo.otf"), (640, 10), True)
limit_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(goods.goods_limit_time)).split()
y_m_d = limit_time[0]
_h_m = limit_time[1].split(":")
h_m = _h_m[0] + "时 " + _h_m[1] + "分"
await bk.atext((605, 38), str(y_m_d))
await bk.atext((615, 57), str(h_m))
await bk.aline((550, -1, 710, -1), "#a29ad6", 5)
await bk.aline((550, 80, 710, 80), "#a29ad6", 5)
idx += 1
await A.apaste(bk, (0, current_h), True)
current_h += 90
w = 1000
h = A.h + 230 + 100
h = 1000 if h < 1000 else h
shop_logo = BuildImage(100, 100, background=f"{IMAGE_PATH}/other/shop_text.png")
shop = BuildImage(w, h, font_size=20, color="#f9f6f2")
shop.paste(A, (20, 230))
zx_img = BuildImage(0, 0, background=f"{IMAGE_PATH}/zhenxun/toukan.png")
zx_img.replace_color_tran(((240, 240, 240), (255, 255, 255)), (249, 246, 242))
await shop.apaste(zx_img, (780, 100))
await shop.apaste(shop_logo, (450, 30), True)
shop.text(
(int((1000 - shop.getsize("注【通过 序号 或者 商品名称 购买】")[0]) / 2), 170),
"注【通过 序号 或者 商品名称 购买】",
)
shop.text((20, h - 100), "神秘药水\t\t售价:9999999金币\n\t\t鬼知道会有什么效果~")
return shop.pic2bs4()
async def register_goods(
name: str,
price: int,
des: str,
discount: Optional[float] = 1,
limit_time: Optional[int] = 0,
**kwargs,
):
"""
添加商品
例如: 折扣:可选参数↓ 限时时间:可选,单位为小时
添加商品 name:萝莉酒杯 price:9999 des:普通的酒杯,但是里面.. discount:0.4 limit_time:90
添加商品 name:可疑的药 price:5 des:效果未知
:param name: 商品名称
:param price: 商品价格
:param des: 商品简介
:param discount: 商品折扣
:param limit_time: 商品限时销售时间,单位为小时
:param kwargs: kwargs
:return: 是否添加成功
"""
if kwargs:
name = kwargs.get("name")
price = kwargs.get("price")
des = kwargs.get("des")
discount = kwargs.get("discount")
limit_time = kwargs.get("time_limit")
limit_time = float(limit_time) if limit_time else limit_time
discount = discount if discount is None else 1
limit_time = int(time.time() + limit_time * 60 * 60) if limit_time is not None and limit_time != 0 else 0
return await GoodsInfo.add_goods(
name, int(price), des, float(discount), limit_time
)
# 删除商品
async def delete_goods(name: str, id_: int) -> "str, str, int":
"""
删除商品
:param name: 商品名称
:param id_: 商品id
:return: 删除状况
"""
goods_lst = await GoodsInfo.get_all_goods()
if id_:
if id_ < 1 or id_ > len(goods_lst):
return "序号错误,没有该序号商品...", "", 999
goods_name = goods_lst[id_ - 1].goods_name
if await GoodsInfo.delete_goods(goods_name):
return f"删除商品 {goods_name} 成功!", goods_name, 200
else:
return f"删除商品 {goods_name} 失败!", goods_name, 999
if name:
if await GoodsInfo.delete_goods(name):
return f"删除商品 {name} 成功!", name, 200
else:
return f"删除商品 {name} 失败!", name, 999
# 更新商品信息
async def update_goods(**kwargs) -> "str, str, int":
"""
更新商品信息
:param kwargs: kwargs
:return: 更新状况
"""
if kwargs:
goods_lst = await GoodsInfo.get_all_goods()
if is_number(kwargs["name"]):
if int(kwargs["name"]) < 1 or int(kwargs["name"]) > len(goods_lst):
return "序号错误,没有该序号的商品...", "", 999
goods = goods_lst[int(kwargs["name"]) - 1]
else:
goods = await GoodsInfo.get_goods_info(kwargs["name"])
if not goods:
return "名称错误,没有该名称的商品...", "", 999
name = goods.goods_name
price = goods.goods_price
des = goods.goods_description
discount = goods.goods_discount
limit_time = goods.goods_limit_time
new_time = 0
tmp = ""
if kwargs.get("price"):
tmp += f'价格:{price} --> {kwargs["price"]}\n'
price = kwargs["price"]
if kwargs.get("des"):
tmp += f'描述:{des} --> {kwargs["des"]}\n'
des = kwargs["des"]
if kwargs.get("discount"):
tmp += f'折扣:{discount} --> {kwargs["discount"]}\n'
discount = kwargs["discount"]
if kwargs.get("limit_time"):
kwargs["limit_time"] = float(kwargs["limit_time"])
new_time = time.strftime(
"%Y-%m-%d %H:%M:%S",
time.localtime(time.time() + kwargs["limit_time"] * 60 * 60),
)
tmp += f"限时至: {new_time}\n"
limit_time = kwargs["limit_time"]
return (
await GoodsInfo.update_goods(
name,
int(price),
des,
float(discount),
int(time.time() + limit_time * 60 * 60 if limit_time != 0 and new_time else 0),
),
name,
tmp[:-1],
)
def parse_goods_info(msg: str) -> Union[dict, str]:
"""
解析格式数据
:param msg: 消息
:return: 解析完毕的数据data
"""
if "name:" not in msg:
return "必须指定修改的商品名称或序号!"
data = {}
for x in msg.split():
sp = x.split(":", maxsplit=1)
if str(sp[1]).strip():
sp[1] = sp[1].strip()
if sp[0] == "name":
data["name"] = sp[1]
elif sp[0] == "price":
if not is_number(sp[1]) or int(sp[1]) < 0:
return "price参数不合法,必须大于等于0!"
data["price"] = sp[1]
elif sp[0] == "des":
data["des"] = sp[1]
elif sp[0] == "discount":
if not is_number(sp[1]) or float(sp[1]) < 0:
return "discount参数不合法,必须大于0!"
data["discount"] = sp[1]
elif sp[0] == "limit_time":
if not is_number(sp[1]) or float(sp[1]) < 0:
return "limit_time参数不合法,必须大于0!"
data["limit_time"] = sp[1]
return data | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/shop/shop_handle/data_source.py | data_source.py |
from .data_source import create_shop_help, delete_goods, update_goods, register_goods, parse_goods_info
from nonebot.adapters.onebot.v11 import MessageEvent, Message
from nonebot import on_command
from configs.path_config import IMAGE_PATH
from utils.message_builder import image
from nonebot.permission import SUPERUSER
from utils.utils import is_number
from nonebot.params import CommandArg
from nonebot.plugin import export
from services.log import logger
import os
__zx_plugin_name__ = "商店"
__plugin_usage__ = """
usage:
商店项目,这可不是奸商
指令:
商店
""".strip()
__plugin_superuser_usage__ = """
usage:
商品操作
指令:
添加商品 name:[名称] price:[价格] des:[描述] ?discount:[折扣](小数) ?limit_time:[限时时间](小时)
删除商品 [名称或序号]
修改商品 name:[名称或序号] price:[价格] des:[描述] discount:[折扣] limit_time:[限时]
示例:添加商品 name:萝莉酒杯 price:9999 des:普通的酒杯,但是里面.. discount:0.4 limit_time:90
示例:添加商品 name:可疑的药 price:5 des:效果未知
示例:删除商品 2
示例:修改商品 name:1 price:900 修改序号为1的商品的价格为900
* 修改商品只需添加需要值即可 *
""".strip()
__plugin_des__ = "商店系统[金币回收计划]"
__plugin_cmd__ = [
"商店",
"添加商品 name:[名称] price:[价格] des:[描述] ?discount:[折扣](小数) ?limit_time:[限时时间](小时)) [_superuser]",
"删除商品 [名称或序号] [_superuser]",
"修改商品 name:[名称或序号] price:[价格] des:[描述] discount:[折扣] limit_time:[限时] [_superuser]",
]
__plugin_type__ = ('商店',)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["商店"],
}
__plugin_block_limit__ = {
"limit_type": "group"
}
# 导出方法供其他插件使用
export = export()
export.register_goods = register_goods
export.delete_goods = delete_goods
export.update_goods = update_goods
shop_help = on_command("商店", priority=5, block=True)
shop_add_goods = on_command("添加商品", priority=5, permission=SUPERUSER, block=True)
shop_del_goods = on_command("删除商品", priority=5, permission=SUPERUSER, block=True)
shop_update_goods = on_command("修改商品", priority=5, permission=SUPERUSER, block=True)
@shop_help.handle()
async def _():
await shop_help.send(image(b64=await create_shop_help()))
@shop_add_goods.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if msg:
data = parse_goods_info(msg)
if isinstance(data, str):
await shop_add_goods.finish(data)
if not data.get("name") or not data.get("price") or not data.get("des"):
await shop_add_goods.finish("name:price:des 参数不可缺少!")
if await register_goods(**data):
await shop_add_goods.send(f"添加商品 {data['name']} 成功!\n"
f"名称:{data['name']}\n"
f"价格:{data['price']}金币\n"
f"简介:{data['des']}\n"
f"折扣:{data.get('discount')}\n"
f"限时:{data.get('limit_time')}", at_sender=True)
logger.info(f"USER {event.user_id} 添加商品 {msg} 成功")
else:
await shop_add_goods.send(f"添加商品 {msg} 失败了...", at_sender=True)
logger.warning(f"USER {event.user_id} 添加商品 {msg} 失败")
@shop_del_goods.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if msg:
name = ""
id_ = 0
if is_number(msg):
id_ = int(msg)
else:
name = msg
rst, goods_name, code = await delete_goods(name, id_)
if code == 200:
await shop_del_goods.send(f"删除商品 {goods_name} 成功了...", at_sender=True)
if os.path.exists(f"{IMAGE_PATH}/shop_help.png"):
os.remove(f"{IMAGE_PATH}/shop_help.png")
logger.info(f"USER {event.user_id} 删除商品 {goods_name} 成功")
else:
await shop_del_goods.send(f"删除商品 {goods_name} 失败了...", at_sender=True)
logger.info(f"USER {event.user_id} 删除商品 {goods_name} 失败")
@shop_update_goods.handle()
async def _(event: MessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
if msg:
data = parse_goods_info(msg)
if isinstance(data, str):
await shop_add_goods.finish(data)
if not data.get("name"):
await shop_add_goods.finish("name 参数不可缺少!")
flag, name, text = await update_goods(**data)
if flag:
await shop_update_goods.send(f"修改商品 {name} 成功了...\n{text}", at_sender=True)
logger.info(f"USER {event.user_id} 修改商品 {name} 数据 {text} 成功")
else:
await shop_update_goods.send(f"修改商品 {name} 失败了...", at_sender=True)
logger.info(f"USER {event.user_id} 修改商品 {name} 数据 {text} 失败") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/shop/shop_handle/__init__.py | __init__.py |
from nonebot.adapters.onebot.v11 import GroupMessageEvent, MessageSegment
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot
from typing import Optional, Union
import asyncio
class GoodsUseFuncManager:
def __init__(self):
self._data = {}
def register_use(self, goods_name: str, **kwargs):
"""
注册商品使用方法
:param goods_name: 商品名称
:param kwargs: kwargs
"""
self._data[goods_name] = kwargs
def exists(self, goods_name: str) -> bool:
"""
判断商品使用方法是否被注册
:param goods_name: 商品名称
"""
return bool(self._data.get(goods_name))
def get_max_num_limit(self, goods_name: str) -> int:
"""
获取单次商品使用数量
:param goods_name: 商品名称
"""
if self.exists(goods_name):
return self._data[goods_name]["kwargs"]["_max_num_limit"]
return 1
async def use(self, **kwargs) -> Optional[Union[str, MessageSegment]]:
"""
使用道具
:param kwargs: kwargs
"""
goods_name = kwargs.get("goods_name")
if self.exists(goods_name):
if asyncio.iscoroutinefunction(self._data[goods_name]["func"]):
return await self._data[goods_name]["func"](
**kwargs,
)
else:
return self._data[goods_name]["func"](
**kwargs,
)
def check_send_success_message(self, goods_name: str) -> bool:
"""
检查是否发送使用成功信息
:param goods_name: 商品名称
"""
if self.exists(goods_name):
return bool(self._data[goods_name]["kwargs"]["send_success_msg"])
return False
def get_kwargs(self, goods_name: str) -> dict:
"""
获取商品使用方法的kwargs
:param goods_name: 商品名称
"""
if self.exists(goods_name):
return self._data[goods_name]["kwargs"]
return {}
func_manager = GoodsUseFuncManager()
async def effect(
bot: Bot, event: GroupMessageEvent, goods_name: str, num: int
) -> Optional[Union[str, MessageSegment]]:
"""
商品生效
:param bot: Bot
:param event: GroupMessageEvent
:param goods_name: 商品名称
:param num: 使用数量
:return: 使用是否成功
"""
# 优先使用注册的商品插件
try:
if func_manager.exists(goods_name):
_kwargs = func_manager.get_kwargs(goods_name)
return await func_manager.use(
**{
**_kwargs,
"_bot": bot,
"event": event,
"group_id": event.group_id,
"user_id": event.user_id,
"num": num,
"goods_name": goods_name,
}
)
except Exception as e:
logger.error(f"use 商品生效函数effect 发生错误 {type(e)}:{e}")
return None
def register_use(goods_name: str, func, **kwargs):
"""
注册商品使用方法
:param goods_name: 商品名称
:param func: 使用函数
:param kwargs: kwargs
"""
if func_manager.exists(goods_name):
raise ValueError("该商品使用函数已被注册!")
# 发送使用成功信息
if kwargs.get("send_success_msg") is None:
kwargs["send_success_msg"] = True
kwargs["_max_num_limit"] = (
kwargs.get("_max_num_limit") if kwargs.get("_max_num_limit") else 1
)
func_manager.register_use(goods_name, **{"func": func, "kwargs": kwargs})
logger.info(f"register_use 成功注册商品:{goods_name} 的使用函数") | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/shop/use/data_source.py | data_source.py |
from nonebot import on_command
from services.log import logger
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, Message
from nonebot.params import CommandArg
from utils.utils import is_number
from models.bag_user import BagUser
from nonebot.adapters.onebot.v11.permission import GROUP
from services.db_context import db
from nonebot.plugin import export
from .data_source import effect, register_use, func_manager
__zx_plugin_name__ = "商店 - 使用道具"
__plugin_usage__ = """
usage:
普通的使用道具
指令:
使用道具 [序号或道具名称] ?[数量]=1
* 序号以 ”我的道具“ 为准 *
""".strip()
__plugin_des__ = "商店 - 使用道具"
__plugin_cmd__ = ["使用道具 [序号或道具名称]"]
__plugin_type__ = ('商店',)
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["商店", "使用道具"],
}
# 导出方法供其他插件使用
export = export()
export.register_use = register_use
use_props = on_command("使用道具", priority=5, block=True, permission=GROUP)
@use_props.handle()
async def _(bot: Bot, event: GroupMessageEvent, arg: Message = CommandArg()):
msg = arg.extract_plain_text().strip()
num = 1
msg_sp = msg.split()
if len(msg_sp) > 1 and is_number(msg_sp[-1]) and int(msg_sp[-1]) > 0:
num = int(msg.split()[-1])
msg = " ".join(msg.split()[:-1])
property_ = await BagUser.get_property(event.user_id, event.group_id)
if property_:
async with db.transaction():
if is_number(msg):
if 0 < int(msg) <= len(property_):
name = list(property_.keys())[int(msg) - 1]
else:
await use_props.finish("仔细看看自己的道具仓库有没有这个道具?", at_sender=True)
else:
if msg not in property_.keys():
await use_props.finish("道具名称错误!", at_sender=True)
name = msg
_user_prop_count = property_[name]
if num > _user_prop_count:
await use_props.finish(f"道具数量不足,无法使用{num}次!")
if num > (n := func_manager.get_max_num_limit(name)):
await use_props.finish(f"该道具单次只能使用 {n} 个!")
if await BagUser.delete_property(
event.user_id, event.group_id, name, num
):
if func_manager.check_send_success_message(name):
await use_props.send(f"使用道具 {name} {num} 次成功!", at_sender=True)
if msg := await effect(bot, event, name, num):
await use_props.send(msg, at_sender=True)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 使用道具 {name} {num} 次成功"
)
else:
await use_props.send(f"使用道具 {name} {num} 次失败!", at_sender=True)
logger.info(
f"USER {event.user_id} GROUP {event.group_id} 使用道具 {name} {num} 次失败"
)
else:
await use_props.send("您的背包里没有任何的道具噢", at_sender=True) | zhenxun-bot | /zhenxun_bot-0.1.4.3-py3-none-any.whl/zhenxun_bot/basic_plugins/shop/use/__init__.py | __init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.