Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
fangtiancheng committed May 1, 2024
1 parent b20d7c1 commit d7335f8
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 73 deletions.
14 changes: 10 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,13 @@
from plugins.superEmoji import FirecrackersFace, FireworksFace, BasketballFace, HotFace
from plugins.news import ShowNews, YesterdayNews, UpdateNewsAndReport
from plugins.hotSearch import WeiboHotSearch, BaiduHotSearch, ZhihuHotSearch
from plugins.signIn import SignIn
## tmp
from plugins.signIn_v2 import SignIn
try:
from resources.api.getMddTea24 import IcokeUserBind
except:
IcokeUserBind = EmptyPlugin

from plugins.thanksLUB import ThanksLUB
from plugins.stocks import QueryStocksHelper, QueryStocks, BuyStocksHelper, BuyStocks, QueryStocksPriceHelper, QueryStocksPrice
from plugins.sjtuInfo import SjtuCanteenInfo, SjtuLibInfo
Expand Down Expand Up @@ -138,7 +144,7 @@
except NotPublishedException as e:
SjtuPlusGroupingVerify = EmptyAddGroupPlugin
print('SjtuPlusGroupingVerify not imported: {}'.format(e))

from plugins.gocqWatchDog import GocqWatchDog
from plugins.xhsSubscribe import XhsSubscribe, XhsSubscribeHelper
from plugins.douyinSubscribe import DouyinSubscribe, DouyinSubscribeHelper
Expand Down Expand Up @@ -185,7 +191,7 @@ def sqlInit():
PluginGroupManager([MonitorMddStatus()], 'mddmonitor'),],'sjtuinfo'),
# PluginGroupManager([QueryStocksHelper(), QueryStocks(), BuyStocksHelper(), BuyStocks(), QueryStocksPriceHelper(), QueryStocksPrice()],'stocks'), # 股票
PluginGroupManager([Chai_Jile(), Yuan_Jile()],'jile'), # 柴/元神寄了
PluginGroupManager([SignIn()], 'signin'), # 签到
PluginGroupManager([SignIn(), IcokeUserBind()], 'signin'), # 签到
PluginGroupManager([ShowSjmcStatus(), GetSjmcLive(), GetBilibiliLive(24716629, '基岩社', '-fdmclive'),
PluginGroupManager([BilibiliLiveMonitor(25567444, '交大MC社', 'mclive'),
BilibiliLiveMonitor(24716629, '基岩社', 'mclive'), ], 'mclive'),
Expand Down Expand Up @@ -228,7 +234,7 @@ def sqlInit():
PluginGroupManager([EmojiKitchen()], 'emoji'),
PluginGroupManager([ShowLeetcode(), LeetcodeReport()], 'leetcode'),
PluginGroupManager([XhsSubscribeHelper(),XhsSubscribe()], 'xhs'),
PluginGroupManager([DouyinSubscribeHelper(),DouyinSubscribe()], 'douyin')
PluginGroupManager([DouyinSubscribeHelper(),DouyinSubscribe()], 'douyin'),
# PluginGroupManager([], 'arxiv'),
]
PrivatePluginList:List[StandardPlugin]=[ # 私聊启用插件
Expand Down
30 changes: 20 additions & 10 deletions plugins/canvasSync.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,25 +154,35 @@ def getCanvas(qq_id) -> Tuple[bool, str]:
gcal = Calendar.from_ical(data)
event_list = []
for component in gcal.walk():

if component.name == "VEVENT":

now = time.localtime()
ddl_time = component.get('dtend').dt
if not isinstance(ddl_time,datetime):
tmp=datetime.strftime(ddl_time,"%Y-%m-%d")+" 23:59:59"
ddl_time = datetime.strptime(tmp,"%Y-%m-%d %H:%M:%S")
ddl_time1 = component.get('dtend', None)
ddl_time2 = component.get('dtstart', None)
if ddl_time1 is None and ddl_time2 is None:
ddl_time = '未知'
else:
ddl_time+=timedelta(hours=8)
tmp = datetime.strftime(ddl_time, "%Y-%m-%d %H:%M:%S")
if time.mktime(time.strptime(tmp, "%Y-%m-%d %H:%M:%S")) < time.mktime(now):
continue
ddl_time = datetime.strftime(ddl_time,"%Y-%m-%d %H:%M")
if ddl_time1 is not None:
ddl_time = ddl_time1.dt
else:
ddl_time = ddl_time2.dt
if not isinstance(ddl_time,datetime):
tmp=datetime.strftime(ddl_time,"%Y-%m-%d")+" 23:59:59"
ddl_time = datetime.strptime(tmp,"%Y-%m-%d %H:%M:%S")
else:
ddl_time+=timedelta(hours=8)
tmp = datetime.strftime(ddl_time, "%Y-%m-%d %H:%M:%S")
if time.mktime(time.strptime(tmp, "%Y-%m-%d %H:%M:%S")) < time.mktime(now):
continue
ddl_time = datetime.strftime(ddl_time,"%Y-%m-%d %H:%M")
event_list.append([component.get('summary'), component.get('description'), ddl_time])
return True, DrawEventListPic(event_list, qq_id)
except Exception as e:
print(e)
return False, "查询失败\n无法获取或解析日历文件"

def DrawEventListPic(event_list, qq_id):
def DrawEventListPic(event_list:List[Tuple[str, str, datetime]], qq_id:int):
proceed_list = []
width=880
h_title, h_des = 0, 0
Expand Down
125 changes: 89 additions & 36 deletions plugins/groupActReport.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from utils.sqlUtils import newSqlSession, mysql
from utils.responseImage_beta import *
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import datetime
from copy import deepcopy
from io import BytesIO
Expand Down Expand Up @@ -120,7 +122,7 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
messageDescript = ''
messageMedal = []
messageWithBotMedal = []
messageImgEmjMedal = []
# messageImgEmjMedal = []
try:
mydb, mycursor = newSqlSession()
mycursor.execute("SELECT message_seq from `clearChatLog` where user_id = %d and group_id = %d"%(user_id, group_id))
Expand All @@ -139,7 +141,8 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
time_meswithbot = {}
time_meswithimgemoji = {} #图片类动画表情
st:datetime.datetime = result[0][0]
et:datetime.datetime = result[-1][0]
et:datetime.datetime = datetime.datetime.now()
st1y:datetime.datetime = et - datetime.timedelta(days=364)
for time, message in result:
time: datetime.datetime
message: str
Expand All @@ -153,10 +156,12 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
y += 1
time_meswithbot[t] = y
# pattern= re.compile(r'^\[CQ\:image\,file.*subType\=1\,.*\]')
if ('[CQ:image,file' in message and 'subType=1' in message):
y = time_meswithimgemoji.get(t,0)
y += 1
time_meswithimgemoji[t] = y

# 以下表情信息分辨方式已废弃
# if ('[CQ:image,file' in message and 'subType=1' in message):
# y = time_meswithimgemoji.get(t,0)
# y += 1
# time_meswithimgemoji[t] = y
ct:datetime.datetime = deepcopy(st)
while (ct<et):
ct += datetime.timedelta(days=1)
Expand All @@ -169,9 +174,9 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
y = time_meswithbot.get(t,0)
if y==0:
time_meswithbot[t] = 0
y = time_meswithimgemoji.get(t,0)
if y==0:
time_meswithimgemoji[t] = 0
# y = time_meswithimgemoji.get(t,0)
# if y==0:
# time_meswithimgemoji[t] = 0
# sorted(time_mes.keys())
x_list = list(time_mes.keys())
y_list = list(time_mes.values())
Expand Down Expand Up @@ -207,10 +212,58 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
plt.margins(0.002, 0.1)
plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)
plt.savefig(time_dis_path, dpi=200, bbox_inches='tight')

# 绿墙图
date_list = [st1y + datetime.timedelta(days=d) for d in range(365)]
daily_message_counts = [time_mes.get(date.strftime('%Y-%m-%d'), 0) for date in date_list]
print(daily_message_counts)
max_messages = max(daily_message_counts) if daily_message_counts else 0

cmap = LinearSegmentedColormap.from_list("custom_green", [(0.773, 1, 0.804, 1), (0.129, 0.431, 0.224, 1)]) # PALETTE_LIGHEGREEN, PALETTE_SJTU_GREEN
weekdays_per_date = [(date.weekday() + 1) % 7 for date in date_list] # 获取每天是周几
weeks_in_year = int(np.ceil(len(date_list) / 7)) # 计算所需列数
data_matrix = np.zeros((7, weeks_in_year)) # 创建矩阵

# 填充数据
for i, count in enumerate(daily_message_counts):
week_col = i // 7
day_row = weekdays_per_date[i]
data_matrix[day_row, week_col] = count

# 根据消息数调整颜色
colors_matrix = np.full(shape=data_matrix.shape + (4,), fill_value=(0.98, 0.98, 0.98, 1))

# 仅为非零数据计算颜色
for i in range(data_matrix.shape[0]):
for j in range(data_matrix.shape[1]):
if data_matrix[i, j] > 0: # 非零消息数
normalized_value = data_matrix[i, j] / max_messages
colors_matrix[i, j] = cmap(normalized_value)
# colors = [cmap(count/max_messages) if max_messages > 0 else (0.9, 0.9, 0.9, 1) for count in daily_message_counts]
# print(colors)
plt.figure(figsize=(14, 2))
ax = plt.gca()
ax.imshow(colors_matrix, aspect='auto', cmap=cmap)
ax.set_yticks(range(7))
ax.set_yticklabels(['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'])

month_starts_indices = [i for i, date in enumerate(date_list) if date.day == 1]
month_starts_week_indices = [i // 7 for i in month_starts_indices]
month_labels = [date_list[i].strftime('%b') for i in month_starts_indices]
ax.set_xticks(month_starts_week_indices)
ax.set_xticklabels(month_labels, rotation=90)

plt.subplots_adjust(top=1, bottom=0, left=0, right=1, hspace=0, wspace=0)
plt.margins(0.002, 0.1)
contribution_chart_path = BytesIO()
plt.savefig(contribution_chart_path, dpi=200, bbox_inches='tight')

card_content1 = [
('subtitle','共发送信息 %d 条\n'%(messageNumber),PALETTE_SJTU_BLUE),
('separator',),
('illustration', time_dis_path),
('body', ' '),
('illustration', contribution_chart_path),
('body', messageDescript)
]
if len(messageMedal) > 0:
Expand Down Expand Up @@ -248,30 +301,30 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
if len(messageWithBotMedal) > 0:
card_content2.append(('subtitle', ' '.join(messageWithBotMedal), PALETTE_SJTU_ORANGE))

# 图片信息-时间图
x_list = list(time_meswithimgemoji.keys())
y_list = list(time_meswithimgemoji.values())
x_list = [datetime.datetime.strptime(x,'%Y-%m-%d') for x in x_list]
messageImgEmojiNumber = sum(y_list)
if (messageImgEmojiNumber>=500):
messageImgEmjMedal.append('🎖️表情包之神')
plt.figure(figsize=(10, 3))
plt.bar(x_list, y_list, color='#7DC473')
ax = plt.gca()
ax.set_facecolor('#E5FBE2')
plt.xticks(rotation=25,size=9)
time_dis3_path = BytesIO()
plt.margins(0.002, 0.1)
plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)
plt.savefig(time_dis3_path, dpi=200, bbox_inches='tight')
plt.close()
card_content3 = [
('subtitle','共发送动画表情 %d 次\n'%(messageImgEmojiNumber),PALETTE_SJTU_GREEN),
('separator',),
('illustration', time_dis3_path)
]
if len(messageImgEmjMedal) > 0:
card_content3.append(('subtitle', ' '.join(messageImgEmjMedal), PALETTE_SJTU_GREEN))
# 图片信息-时间图 (图片信息分辨方式废弃)
# x_list = list(time_meswithimgemoji.keys())
# y_list = list(time_meswithimgemoji.values())
# x_list = [datetime.datetime.strptime(x,'%Y-%m-%d') for x in x_list]
# messageImgEmojiNumber = sum(y_list)
# if (messageImgEmojiNumber>=500):
# messageImgEmjMedal.append('🎖️表情包之神')
# plt.figure(figsize=(10, 3))
# plt.bar(x_list, y_list, color='#7DC473')
# ax = plt.gca()
# ax.set_facecolor('#E5FBE2')
# plt.xticks(rotation=25,size=9)
# time_dis3_path = BytesIO()
# plt.margins(0.002, 0.1)
# plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)
# plt.savefig(time_dis3_path, dpi=200, bbox_inches='tight')
# plt.close()
# card_content3 = [
# ('subtitle','共发送动画表情 %d 次\n'%(messageImgEmojiNumber),PALETTE_SJTU_GREEN),
# ('separator',),
# ('illustration', time_dis3_path)
# ]
# if len(messageImgEmjMedal) > 0:
# card_content3.append(('subtitle', ' '.join(messageImgEmjMedal), PALETTE_SJTU_GREEN))

img_avatar = Image.open(BytesIO(get_avatar_pic(user_id)))
# 生成卡片图
Expand All @@ -298,9 +351,9 @@ def getMyActivity(user_id:int, group_id:int)->Optional[str]:
ResponseImage.RichContentCard(
raw_content = card_content2
),
ResponseImage.RichContentCard(
raw_content = card_content3
)
# ResponseImage.RichContentCard(
# raw_content = card_content3
# )
])
save_path = (os.path.join(SAVE_TMP_PATH, f'{user_id}_{group_id}_actReport.png'))
ActCards.generateImage(save_path)
Expand Down
16 changes: 8 additions & 8 deletions plugins/signIn_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from utils.accountOperation import get_user_coins, update_user_coins
from utils.responseImage_beta import *
try:
from resources.api.getMddCola import getTea
from resources.api.getMddTea24 import getTea
except ImportError:
raise NotPublishedException("Mdd Tea api not published")
FORTUNE_TXT = [['r',"大吉"],['r',"中吉"],['r',"小吉"],['g',"中平"],['h',"小赢"],['h',"中赢"],['h',"大赢"]]
Expand Down Expand Up @@ -83,33 +83,33 @@ def draw_signinbanner(qq_id:int, add_coins, now_coins, fortune):
)
)

# 第三段:雪碧
# 第三段:柠檬红茶
status, description = getTea(qq_id)
if status == False and description == '查询失败':
SignInCards.addCard(
ResponseImage.RichContentCard(
raw_content = [('subtitle', '* 绑定授权码以同步领取麦当劳每日免费雪碧\n发送命令【-icola】查看详情')],
raw_content = [('subtitle', '* 绑定授权码以同步领取麦当劳每日免费柠檬红茶\n发送命令【-icoke】查看详情')],
backColor = PALETTE_GREY_BACK
)
)
elif status == True or description=='当日已领取请明天再来':
SignInCards.addCard(
ResponseImage.RichContentCard(
raw_content = [
('title', f'已成功同步领取今日麦当劳【免费雪碧】!', (35,210,137,255)),
('title', f'已成功同步领取今日麦当劳【免费柠檬红茶】!', PALETTE_ORANGE),
('title','打开麦当劳APP或小程序, 即可看到优惠券~',PALETTE_GREY_SUBTITLE),
('separator',),
('subtitle','技术支持: Teruteru')
],
backColor = (214,255,238,255),
icon = os.path.join(IMAGES_PATH,'Sprite.png')
backColor = (253,243,214,255),
icon = os.path.join(IMAGES_PATH,'mddTea.png')
)
)
else:
SignInCards.addCard(
ResponseImage.RichContentCard(
raw_content = [
('subtitle', f'* 同步领取麦当劳每日免费雪碧失败\n原因: {description}'),
('subtitle', f'* 同步领取麦当劳每日免费柠檬红茶失败\n原因: {description}'),
],
backColor = PALETTE_GREY_BACK
)
Expand Down Expand Up @@ -139,7 +139,7 @@ def sign_in(qq_id:int):
update_user_coins(id, add_coins, '签到奖励')
try:
mycursor.execute("UPDATE accounts SET lastSign='%s', fortune=%d WHERE id=%d;"
%(escape_string(today_str), fortune, id))
%(today_str, fortune, id))
except mysql.connector.errors.DatabaseError as e:
warning("sql error in signin: {}".format(e))
return draw_signinbanner(id, add_coins, get_user_coins(id), fortune)
Expand Down
Loading

0 comments on commit d7335f8

Please sign in to comment.