Compare commits

...
17 Commits
Author SHA1 Message Date
HibiKier 71026542df Update image_utils.py 2021-10-05 15:53:58 +08:00
HibiKier e756a50d97 Update README.md 2021-10-04 22:59:00 +08:00
HibiKier 49c47c01a3 Update data_source.py 2021-10-04 22:58:11 +08:00
HibiKier e7eea2a7d9 Update __init__.py 2021-10-04 22:57:59 +08:00
HibiKier 311ae7d4e8 Update README.md 2021-10-04 20:23:31 +08:00
HibiKier 058f0885f7 fix 0.0.5.1 2021-10-04 20:22:09 +08:00
HibiKier c6eaf435f2 Update update_info.json 2021-10-04 14:31:31 +08:00
HibiKier 22676f3bfa Merge pull request #59 from AkashiCoin/main
epic
2021-10-03 21:40:12 +08:00
HibiKier fedcb37b1a Update data_source.py 2021-10-03 21:40:05 +08:00
HibiKier 54025c9cfc Update __init__.py 2021-10-03 21:39:03 +08:00
AkashiCoin 2cdf3c28b6 Update __init__.py 2021-10-03 20:35:55 +08:00
AkashiCoin ba29232c9f Update __init__.py 2021-10-03 20:17:08 +08:00
HibiKier 5fd0667061 Update README.md 2021-10-03 18:46:06 +08:00
HibiKier 2c9f99ac3c Update README.md 2021-10-03 18:45:39 +08:00
HibiKier 775b1b937b Merge pull request #58 from AkashiCoin/main
epic
2021-10-03 18:44:42 +08:00
AkashiCoin 65723aee15 Update __init__.py 2021-10-03 18:34:56 +08:00
AkashiCoin 46b55e4224 Update data_source.py 2021-10-03 18:34:31 +08:00
14 changed files with 228 additions and 93 deletions
+10 -2
View File
@@ -313,6 +313,13 @@ python bot.py
## 更新
### 2021/10/4
* 修复了功能调用统计失效问题
* 当色图库中没有色图时,会在线搜索色图而不是‘没找到符合条件的色图...’
* 快速更新权限再给超级用户发送错误日志
* 修复疫情未加载省份城市无法正常使用
### 2021/10/3
* 对插件进行分离
@@ -333,8 +340,9 @@ python bot.py
* 当群权限为-1时,不会对群发送修改权限通知,并屏蔽此群一切命令(包括提醒)
* 修复了红包数量可以过大或为负数,红包数量大于群员数量时会修改为群员数量
* 修复了负数开箱
* 签到最低好感度设置为0.01 [pull/53](https://github.com/HibiKier/zhenxun_bot/pull/53)
* 签到最低好感度设置为0.01 [@pull/53](https://github.com/HibiKier/zhenxun_bot/pull/53)
* pip安装新依赖 ruamel.yaml
* 修复功能 EPIC [@pull/58](https://github.com/HibiKier/zhenxun_bot/pull/58)
### 2021/9/10
@@ -358,7 +366,7 @@ python bot.py
* 修改 更新信息 图片大小
* 修复 查看订阅 命令 UP和番剧无法正常显示
* 修复订阅推送无法正确推送
* 修复搜图返回列表为空时无法正确回复 @[pull/40](https://github.com/HibiKier/zhenxun_bot/pull/40)
* 修复搜图返回列表为空时无法正确回复 [@pull/40](https://github.com/HibiKier/zhenxun_bot/pull/40)
### 2021/9/5
* 添加配置PIX_IMAGE_SIZE,调整PIX下载图片大小,当设置的图片404时,改为原图
View File
+3 -2
View File
@@ -190,10 +190,11 @@ def _get_plugin_status() -> MessageSegment:
return image(b64=A.pic2bs4())
async def update_member_info(group_id: int) -> bool:
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)
@@ -262,7 +263,7 @@ async def update_member_info(group_id: int) -> bool:
logger.info(f"退群用户{del_user} 所属{group_id} 已删除")
else:
logger.info(f"退群用户{del_user} 所属{group_id} 删除失败")
if _error_member_list:
if _error_member_list and remind_superuser:
result = ""
for error_user in _error_member_list:
result += error_user
+1 -1
View File
@@ -45,7 +45,7 @@ async def _():
all_group = [x.group_id for x in await GroupInfo.get_all_group()]
for g in gl:
if g not in all_group:
await update_member_info(g)
await update_member_info(g, False)
logger.info(f"快速更新群信息以及权限:{g}")
except (IndexError, ConnectionDoesNotExistError):
pass
+17 -11
View File
@@ -3,7 +3,7 @@ from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from utils.utils import scheduler, get_bot
from .data_source import get_epic_game
from .data_source import get_epic_free
from utils.manager import group_manager
__zx_plugin_name__ = "epic免费游戏"
@@ -16,24 +16,28 @@ usage:
__plugin_des__ = "可以不玩,不能没有,每日白嫖"
__plugin_cmd__ = ["epic"]
__plugin_version__ = 0.1
__plugin_author__ = "HibiKier"
__plugin_author__ = "AkashiCoin"
__plugin_settings__ = {
"level": 5,
"default_status": True,
"limit_superuser": False,
"cmd": ["epic"],
}
__plugin_task__ = {
'epic_free_game': 'epic免费游戏'
}
__plugin_task__ = {"epic_free_game": "epic免费游戏"}
epic = on_command("epic", priority=5, block=True)
@epic.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
result, code = await get_epic_game()
await epic.send(result)
async def handle(bot: Bot, event: MessageEvent, state: T_State):
msg_list, code = await get_epic_free(bot, 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免费游戏"
@@ -51,10 +55,12 @@ async def _():
gl = await bot.get_group_list()
gl = [g["group_id"] for g in gl]
for g in gl:
if await group_manager.check_group_task_status(g, 'epic_free_game'):
if await group_manager.check_group_task_status(g, "epic_free_game"):
try:
result, code = await get_epic_game()
msg_list, code = await get_epic_free(bot, GroupMessageEvent)
if code == 200:
await bot.send_group_msg(group_id=g, message=result)
await bot.send_group_forward_msg(group_id=g, messages=msg_list)
else:
await bot.send_group_msg(group_id=g, message=msg_list)
except Exception as e:
logger.error(f"GROUP {g} epic免费游戏推送错误 {type(e)}: {e}")
+154 -51
View File
@@ -1,56 +1,159 @@
import aiohttp
import aiofiles
from utils.utils import get_local_proxy
import feedparser
import platform
from utils.message_builder import image
from configs.path_config import IMAGE_PATH
from utils.user_agent import get_user_agent
from asyncio.exceptions import TimeoutError
from configs.config import RSSHUBAPP
if platform.system() == "Windows":
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
from httpx import AsyncClient
from datetime import datetime
from nonebot.log import logger
from nonebot.adapters.cqhttp import (
Bot,
Event,
GroupMessageEvent,
)
from configs.config import NICKNAME
url = f"{RSSHUBAPP}/epicgames/freegames"
# 获取所有 Epic Game Store 促销游戏
# 方法参考:RSSHub /epicgames 路由
# https://github.com/DIYgod/RSSHub/blob/master/lib/routes/epicgames/index.js
async def get_epic_game():
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,
},
}
async with AsyncClient(headers=headers) as client:
try:
res = await client.post(epic_url, json=data, 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
async def get_epic_game() -> "str, int":
result = "今天没有游戏可以白嫖了!"
code = 999
try:
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, proxy=get_local_proxy(), timeout=7) as response:
data = feedparser.parse(await response.text())["entries"]
if len(data) == 0:
return result
index = 0
for item in data:
title = item["title"]
img_url = item["summary"][
item["summary"].find('src="') + 5 : item["summary"].rfind('"')
]
async with session.get(
img_url, proxy=get_local_proxy(), timeout=7
) as res:
async with aiofiles.open(
IMAGE_PATH + f"temp/epic_{index}.jpg", "wb"
) as f:
await f.write(await res.read())
link = item["link"]
result += (
image(f"epic_{index}.jpg", "temp")
+ f"\n【游戏】| {title}\n【链接】 | {link}\n"
# 获取 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, event: Event):
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],
)
code = 200
index += 1
if result != "":
result = "epic限免游戏(速速白嫖):\n" + result
else:
result = "今天没有游戏可以白嫖了!"
except TimeoutError:
return "请求超时!", code
return result, code
# 删除字符串中最后一个 "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 isinstance(event, GroupMessageEvent):
_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 isinstance(event, GroupMessageEvent):
_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
-1
View File
@@ -121,7 +121,6 @@ def init_plugins_settings(data_path: str):
with open(plugins2config_file, "w", encoding="utf8") as wf:
round_trip_dump(_data, wf)
logger.info(f"已成功加载 {len(plugins2settings_manager.get_data())} 个非限制插件.")
print(admin_manager)
def init_plugins_cd_limit(data_path):
+4 -3
View File
@@ -29,6 +29,7 @@ from .data_source import (
gen_message,
check_local_exists_or_download,
add_data_to_database,
get_setu_count
)
from nonebot.adapters.cqhttp.exception import ActionFailed
from configs.config import ONLY_USE_LOCAL_SETU, WITHDRAW_SETU_TIME, NICKNAME
@@ -237,8 +238,8 @@ async def send_setu_handle(
await matcher.finish("咳咳咳,虽然我很可爱,但是我木有自己的色图~~~有的话记得发我一份呀")
# 本地先拿图,下载失败补上去
setu_list, code = None, 200
msg_id = None
if not ONLY_USE_LOCAL_SETU and tags:
setu_count = await get_setu_count(r18)
if (not 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
@@ -288,9 +289,9 @@ async def send_setu_handle(
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:
+8
View File
@@ -210,6 +210,14 @@ def get_luoxiang(impression):
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):
async with aiohttp.ClientSession() as session:
async with session.get(img_url, proxy=get_local_proxy(), timeout=5) as res:
+4 -1
View File
@@ -157,6 +157,10 @@ async def _(bot: Bot, event: MessageEvent, state: T_State):
async def generate_statistics_img(
data: dict, arg: str, name: str, plugin: str, day_index: int
):
try:
plugin = plugins2settings_manager.get_plugin_data(plugin)['cmd'][0]
except (KeyError, IndexError):
pass
bar_graph = None
if arg == "day_statistics":
bar_graph = await init_bar_graph(data, f"{name} 日功能调用统计")
@@ -180,7 +184,6 @@ async def generate_statistics_img(
count.append(0)
else:
try:
print(data[str(week_lst[i])][plugin])
count.append(data[str(week_lst[i])][plugin])
except KeyError:
count.append(0)
+19 -14
View File
@@ -1,9 +1,10 @@
from nonebot import on_command
from .data_source import get_yiqing_data
from .data_source import get_yiqing_data, get_city_and_province_list
from services.log import logger
from nonebot.adapters.cqhttp import Bot, MessageEvent, GroupMessageEvent
from nonebot.typing import T_State
from utils.utils import get_message_text
from configs.config import NICKNAME
__zx_plugin_name__ = "疫情查询"
@@ -13,7 +14,7 @@ usage:
指令:
疫情 中国
疫情 [省份/城市]
* 当省份与城市重名时,可在后添加 “市” *
* 当省份与城市重名时,可在后添加 "市" 或 "省" *
示例:疫情 吉林 <- [省]
示例:疫情 吉林市 <- [市]
""".strip()
@@ -36,17 +37,21 @@ yiqing = on_command("疫情", aliases={"查询疫情", "疫情查询"}, priority
@yiqing.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = get_message_text(event.json())
city_and_province_list = get_city_and_province_list()
if msg:
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}"
)
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:
await yiqing.send("查询失败!!!!", at_sender=True)
logger.info(
f"(USER {event.user_id}, GROUP "
f"{event.group_id if isinstance(event, GroupMessageEvent) else 'private'}) 查询疫情失败"
)
await yiqing.send(f"{NICKNAME}只支持国内的疫情查询喔...")
+2 -5
View File
@@ -1,6 +1,5 @@
from utils.user_agent import get_user_agent
from configs.path_config import TEXT_PATH
from configs.config import NICKNAME
from typing import List
from pathlib import Path
import ujson as json
@@ -22,7 +21,7 @@ async def get_yiqing_data(area: str):
if area == "中国":
province = area
province_type = ""
elif area in data.keys() and area[-1] != "市":
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 = "市"
@@ -33,8 +32,6 @@ async def get_yiqing_data(area: str):
if area in data[p]:
province = p
city = area
if not province and not city:
return f"{NICKNAME}只支持国内的疫情查询喔..."
async with aiohttp.ClientSession(headers=get_user_agent()) as session:
async with session.get(url, timeout=7) as response:
epidemic_data = json.loads((await response.json())["data"])
@@ -77,7 +74,7 @@ async def get_yiqing_data(area: str):
)
def get_city_list() -> List[str]:
def get_city_and_province_list() -> List[str]:
global data
if not data:
try:
+2 -1
View File
@@ -5,7 +5,8 @@
"models",
"services",
"utils",
"resources/ttf"
"resources/ttf",
"bot.py"
],
"add_file": ["resources/img/background"],
"delete_file": []
+4 -1
View File
@@ -640,6 +640,7 @@ class CreateMat:
_max_value = ceil(
_max_value / eval("1" + "0" * (len(str(_max_value)) - 1))
) * eval("1" + "0" * (len(str(_max_value)) - 1))
_max_value = _max_value if _max_value >= 10 else 100
_step = int(_max_value / 10)
for i in range(_step, _max_value + _step, _step):
_y_index.append(i)
@@ -986,7 +987,8 @@ class CreateMat:
font_size=self.font_size,
color=(255, 255, 255, 0),
)
while text.size[0] > self.padding_w - 10:
idx = 0
while text.size[0] > self.padding_w - 10 and idx < 3:
text = CreateImg(
0,
0,
@@ -995,6 +997,7 @@ class CreateMat:
color=(255, 255, 255, 0),
)
w, _ = text.getsize(f"{_y}")
idx += 1
A.paste(text, (padding_w - w - 10, current_h - h), alpha=True)
current_h -= _interval
if x_name: