Skip to content

Commit

Permalink
fixed: 修复了因为跨文件全局变量修改不共享的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
fireinsect committed Feb 19, 2024
1 parent d0d0186 commit 49cab66
Show file tree
Hide file tree
Showing 14 changed files with 161 additions and 126 deletions.
35 changes: 18 additions & 17 deletions nonebot_plugin_ocgbot_v2/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import asyncio
import json
import os.path
from pathlib import Path
from threading import Thread
import httpx
from nonebot import logger, get_driver
from nonebot_plugin_ocgbot_v2.libraries.forbideGet import forbiddenGet
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import json_path, pics_path, static_path_abso, deck_path, \
font_path
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import json_path, pics_path, deck_path, font_path
from nonebot_plugin_ocgbot_v2.libraries.staticvar import nick_name_0, nick_name_1, forbidden, daily_card
from nonebot.plugin import PluginMetadata
import nonebot_plugin_ocgbot_v2.data_update
Expand Down Expand Up @@ -62,46 +62,47 @@ def save(wj_path: str, img: bytes):


async def download(base_url, folder_path, file_name):
file_path = folder_path + file_name
file_path = folder_path / file_name
byte = await download_url(base_url + file_name)
save(file_path, byte)
logger.info(f"文件{file_name}下载成功")


# 卡运专用
async def download_img(files_path, file_name, deck):
wj_path = files_path + "/" + file_name
if not os.path.exists(wj_path):
wj_path = files_path / file_name
if not wj_path.exists():
byte = await download_url(deck_url + f"{deck}/{file_name}")
save(wj_path, byte)
logger.info(f"图片{file_name}下载成功")


def deckDownloadInit():
deck_json = deck_path + "deck_list.json"
if not os.path.exists(deck_json):
deck_json = Path(deck_path) / "deck_list.json"
if not deck_json.exists():
return
with open(deck_json, 'r', encoding='utf-8') as f:
js = json.loads(f.read())
for deck in js['list']:
wjs_path = deck_path + deck
if not os.path.exists(wjs_path):
wjs_path = Path(deck_path) / deck
if not wjs_path.exists():
logger.info("文件夹decks/" + deck + " 不存在,已经创建")
os.mkdir(wjs_path)
wjs_path.mkdir(parents=True, exist_ok=True)
for wj in js['list'][deck]:
asyncio.run(download_img(wjs_path, wj, deck))


def fontDownloadInit():
for font in fonts:
if not os.path.exists(font_path + font):
if not (Path(font_path) / font).exists():
logger.info(f"字体文件{font}缺失,正在下载")
asyncio.run(download(font_url, font_path, font))
asyncio.run(download(font_url, Path(font_path), font))
font_init()
logger.info(f"字体初始化完成")


async def nickNameInit():
nick_path = json_path + "nickname.json"
nick_path = Path(json_path) / "nickname.json"
try:
# 尝试读取
with open(nick_path, 'r', encoding='utf-8') as f:
Expand All @@ -118,7 +119,7 @@ async def nickNameInit():


async def forbideInit():
forbide_path = json_path + "forbidden.json"
forbide_path = Path(json_path) / "forbidden.json"
try:
# 尝试读取
with open(forbide_path, 'r', encoding='utf-8') as f:
Expand All @@ -133,7 +134,7 @@ async def forbideInit():


async def dailyInit():
nick_path = json_path + "daily_card.json"
nick_path = Path(json_path) / "daily_card.json"
try:
# 尝试读取
with open(nick_path, 'r', encoding='utf-8') as f:
Expand All @@ -155,9 +156,9 @@ async def download_init():

async def init():
logger.info("开始初始化")
if not os.path.exists(pics_path):
if not Path(pics_path).exists():
logger.info("未发现图片文件夹,已经创建")
os.mkdir(pics_path + "pics")
(Path(pics_path) / "pics").mkdir(parents=True, exist_ok=True)
await download_init()
await nickNameInit()
await forbideInit()
Expand Down
9 changes: 5 additions & 4 deletions nonebot_plugin_ocgbot_v2/cardPieChart.py

Large diffs are not rendered by default.

21 changes: 11 additions & 10 deletions nonebot_plugin_ocgbot_v2/daily.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import datetime
from pathlib import Path

from PIL import Image, ImageDraw
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, Event, Message, MessageSegment
from nonebot.typing import T_State

from nonebot_plugin_ocgbot_v2.libraries.FontUtil import *
from nonebot_plugin_ocgbot_v2.libraries.FontUtil import fonts
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import image_path, deck_path
from nonebot_plugin_ocgbot_v2.libraries.staticvar import daily_card
from nonebot_plugin_ocgbot_v2.libraries.tool import hash
Expand Down Expand Up @@ -35,10 +36,10 @@ def getDailyPic(point: int, wm_value):
card = obj[point % len(obj)]
no = point % int(card['nums'])
if card['type'] == "系列":
back_pic = Image.open(image_path + "daily_xilie.png")
back_pic = Image.open(Path(image_path) / "daily_xilie.png")
else:
back_pic = Image.open(image_path + "daily_kapai.png")
url = deck_path + f"{card['id']}/{card['id']}-{no}.jpg"
back_pic = Image.open(Path(image_path) / "daily_kapai.png")
url = Path(deck_path) / f"{card['id']}/{card['id']}-{no}.jpg"
cardPic = Image.open(url)
proper_list = []
envy_list = []
Expand Down Expand Up @@ -100,25 +101,25 @@ def pic_joint(backPic: Image, cardPic: Image, daily: int, extra_text: str, weekd
week = f"星期{num_dict.get(str(weekday))}"
# 文字写入通过不同fill指定颜色
# 写入星期
draw.text((550, 50), week, font=fontWeek, fill=(92, 128, 160))
draw.text((550, 50), week, font=fonts['fontWeek'], fill=(92, 128, 160))
# 写入宜忌
for i in range(len(proper_list)):
if i > 5:
break
else:
draw.text((60 + i % 3 * 102, 325 + int(i / 3) * 40), proper_list[i], font=fontList, fill=(92, 128, 160))
draw.text((60 + i % 3 * 102, 325 + int(i / 3) * 40), proper_list[i], font=fonts['fontList'], fill=(92, 128, 160))
for i in range(len(envy_list)):
if i > 5:
break
else:
draw.text((60 + i % 3 * 102, 507 + int(i / 3) * 40), envy_list[i], font=fontList, fill=(92, 128, 160))
draw.text((60 + i % 3 * 102, 507 + int(i / 3) * 40), envy_list[i], font=fonts['fontList'], fill=(92, 128, 160))
# 写入小贴士
draw.text(((backPic.width - fontText.size * len(extra_text)) / 2, 690), extra_text, font=fontText,
draw.text(((backPic.width - fonts['fontText'].size * len(extra_text)) / 2, 690), extra_text, font=fonts['fontText'],
fill=(92, 128, 160))
# 贴入卡图
backPic.paste(cardPic.resize((280, 280)), (460, 290))
# 写入卡牌信息
draw.text((430 + (400 - fontCardStr.size * len(card_str)) / 2, 580), card_str, font=fontCardStr,
draw.text((430 + (400 - fonts['fontCardStr'].size * len(card_str)) / 2, 580), card_str, font=fonts['fontCardStr'],
fill=(92, 128, 160))
# 写入点数
draw.text((260, 200), str(daily), font=fontPoint, fill=(92, 128, 160))
draw.text((260, 200), str(daily), font=fonts['fontPoint'], fill=(92, 128, 160))
2 changes: 1 addition & 1 deletion nonebot_plugin_ocgbot_v2/guess_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from nonebot.params import CommandArg
from nonebot.permission import SUPERUSER

from nonebot_plugin_ocgbot_v2.libraries.Card import getRandomCard, getCard, Card
from nonebot_plugin_ocgbot_v2.libraries.Card import getRandomCard, getCard
from nonebot_plugin_ocgbot_v2.libraries.Guess import Guess
from nonebot_plugin_ocgbot_v2.libraries.charpic import charPic
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import *
Expand Down
22 changes: 14 additions & 8 deletions nonebot_plugin_ocgbot_v2/libraries/Card.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import copy
import json
import math
import os.path
from pathlib import Path
from typing import Optional, Dict
import httpx
from nonebot_plugin_ocgbot_v2.libraries.SqliteUtils import SqliteUtils
Expand All @@ -12,14 +12,14 @@

pre_flag = 0
extra_flag = 0
conn, cursor = sqlite.connect(cdb_path + "cards.cdb")
conn, cursor = sqlite.connect(Path(cdb_path) / "cards.cdb")

if os.path.exists(cdb_path + "pre-release.cdb"):
conn_pre, cursor_pre = sqlite.connect(cdb_path + "pre-release.cdb")
if (Path(cdb_path) / "pre-release.cdb").exists():
conn_pre, cursor_pre = sqlite.connect(Path(cdb_path) / "pre-release.cdb")
pre_flag = 1

if os.path.exists(cdb_path + "extra_card.cdb"):
conn_extra, cursor_extra = sqlite.connect(cdb_path + "extra_card.cdb")
if (Path(cdb_path) / "extra_card.cdb").exists():
conn_extra, cursor_extra = sqlite.connect(Path(cdb_path) / "extra_card.cdb")
extra_flag = 1

typeList = ['怪兽', '魔法', '陷阱']
Expand Down Expand Up @@ -73,6 +73,7 @@ def __getattribute__(self, item):
return self[item]
return super().__getattribute__(item)


class Card(Dict):
cardId: Optional[int] = None
name: Optional[str] = None
Expand Down Expand Up @@ -252,7 +253,9 @@ def searchByName(name: str):
card = Card_Extra(row)
cards.append(card)
if len(cards) == 0:
cards = searchById(searchFromBG(org_name))
bg_temp = searchFromBG(org_name)
if bg_temp is not None:
cards = searchById()
cards.sort(key=sortCard)
return cards

Expand Down Expand Up @@ -283,7 +286,10 @@ def searchFromBG(name):
url = bg_url + name
response = httpx.get(url)
js = json.loads(response.text)
return js['result'][0]['id']
if len(js["result"]) == 0:
return None
else:
return js['result'][0]['id']


def nickNameMatch(name: str):
Expand Down
21 changes: 13 additions & 8 deletions nonebot_plugin_ocgbot_v2/libraries/FontUtil.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
from pathlib import Path

from PIL import ImageFont
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import font_path

font = font_path + "qmzl.ttf"
fontWeek, fontList, fontCardStr, fontText, fontPoint = None, None, None, None, None
font = str(Path(font_path) / "qmzl.ttf")
fonts = {}


# fontWeek, fontList, fontCardStr, fontText, fontPoint = None, None, None, None, None


def font_init():
global fontWeek, fontList, fontCardStr, fontText, fontPoint
# global fontWeek, fontList, fontCardStr, fontText, fontPoint
# 星期显示字体
fontWeek = ImageFont.truetype(font, 45)
fonts['fontWeek'] = ImageFont.truetype(font, 45)
# 宜忌显示字体
fontList = ImageFont.truetype(font, 30)
fonts['fontList'] = ImageFont.truetype(font, 30)
# 卡牌信息字体
fontCardStr = ImageFont.truetype(font, 40)
fonts['fontCardStr'] = ImageFont.truetype(font, 40)
# 小贴士字体
fontText = ImageFont.truetype(font, 28)
fonts['fontText'] = ImageFont.truetype(font, 28)
# 点数字体
fontPoint = ImageFont.truetype(font, 60)
fonts['fontPoint'] = ImageFont.truetype(font, 60)
6 changes: 4 additions & 2 deletions nonebot_plugin_ocgbot_v2/libraries/forbideGet.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import json
from pathlib import Path

from requests_html import HTMLSession
from nonebot_plugin_ocgbot_v2.libraries.SqliteUtils import SqliteUtils
from nonebot_plugin_ocgbot_v2.libraries.globalMessage import json_path, cdb_path
Expand All @@ -17,7 +19,7 @@
# 准限制卡cid
pres = []
sqlite = SqliteUtils()
conn, cursor = sqlite.connect(cdb_path + "cards.cdb")
conn, cursor = sqlite.connect(Path(cdb_path) / "cards.cdb")


def cidGet():
Expand Down Expand Up @@ -51,7 +53,7 @@ def insert(card_id, name, status):

def WriteForbidden(js):
# 写入数据
with open(json_path + "forbidden.json", 'w', encoding='utf-8') as f:
with open(Path(json_path) / "forbidden.json", 'w', encoding='utf-8') as f:
f.write(json.dumps(js, ensure_ascii=False, indent=4))


Expand Down
Loading

0 comments on commit 49cab66

Please sign in to comment.