-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin_deer.py
More file actions
818 lines (692 loc) · 29.4 KB
/
plugin_deer.py
File metadata and controls
818 lines (692 loc) · 29.4 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
import base64
import calendar
import datetime
import json, os, math, random
import threading
from enum import Enum
from io import BytesIO
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import requests
import websocket
from sqlalchemy import func
from deer_db import db
from deer_db.db import UserDeer, UserDeerAdmin, UserBans
class WakeUpCommand(Enum):
none = ''
point = '.'
slash = '/'
# 测试
DEBUG = False
# 命令
WAKEUP = WakeUpCommand.point.value
CMD = WAKEUP + '🦌'
# 签到冷却
SIGNIN_CD = 1440 # 分钟
N_GAP = 30 # 分钟,随机种子变化间隔
M_SIGNIN_LIMIT = 50 # 每月签到上限
ADMIN_ROW = ['admin', 'owner']
# 使用区间,只有在区间内才可唤起
is_server_interval = True
SERVICE_INTERVAL = [
{"start": '00:00', "end": '08:00'},
{"start": '10:00', "end": '13:00'},
{"start": '18:00', "end": '19:30'},
{"start": '21:30', "end": '01:00'},
]
class API:
@staticmethod
def send(data, message):
message_type = data['message_type']
if 'group' == message_type:
group_id = data['group_id']
params = {
"group_id": int(group_id),
"message": message
}
else:
user_id = data['user_id']
params = {
"user_id": int(user_id),
"message": message
}
url = "http://127.0.0.1:5700/send_msg"
requests.get(url, params=params)
# Main
def main_function(ws, data):
data = json.loads(data)
post_main_data = data
content = data.get('raw_message')
if content is not None and f'{CMD}补' in content:
# .🦌补11月2日*3
try:
index_bu = content.index('补')
index_month = content.index('月')
index_day = content.index('日')
index_multiplier = content.index('*')
if index_multiplier > index_day > index_month > index_bu:
input_month = int(content[index_bu + 1:index_month])
input_day = int(content[index_month + 1:index_day])
input_multiplier = int(content[index_multiplier + 1:])
if input_month > 12 or input_day > 31 or input_month < 1 or input_day < 1:
content = f'日期格式错误'
else:
content = supplementary_signin(data, input_month, input_day, input_multiplier)
else:
content = f'日期格式错误'
except Exception as e:
content = f'日期格式错误'
API.send(post_main_data, content)
return
elif content == f'{CMD}详情':
content = user_deer_signin_logs(data)
API.send(post_main_data, content)
return
elif content == f'{CMD}排行':
content = ranking(post_main_data, 'LOCAL')
API.send(post_main_data, content)
return
elif content == f'{CMD}全局排行':
content = ranking(post_main_data, 'ALL')
API.send(post_main_data, content)
return
elif content is not None and f'{CMD}封禁' in content:
# .🦌封禁1214617226
index_qq_id = content.index('封禁')
if index_qq_id >= 0:
input_qq = str(content[index_qq_id + 2:])
content = deer_ban(post_main_data, input_qq, 1)
else:
content = "操作失败"
API.send(post_main_data, content)
return
elif content is not None and f'{CMD}解禁' in content:
index_qq_id = content.index('解禁')
if index_qq_id >= 0:
input_qq = str(content[index_qq_id + 2:])
content = deer_ban(post_main_data, input_qq, 0)
else:
content = "操作失败"
API.send(post_main_data, content)
return
elif content == f'{CMD}帮助':
content = f"""指令:\n
{CMD}\n
{CMD}详情 ,查询自己所有记录.
{CMD}排行 ,看看你和其他人排行.
{CMD}全局排行 ,列车所有参与者,不在限制本群.
{CMD}补11月12日*2 ,补签 注意时间格式和次数,范围是1-4.
{CMD}准备 ,🦌前健康检查,确认自己是否成功🦌.
{CMD}管理开启 / {CMD}管理关闭 ,管理开启或关闭.
{CMD}封禁 / {CMD}解禁 ,管理封禁用户,封禁QQ号码 例子:{CMD}封禁100 / {CMD}解禁100
"""
API.send(post_main_data, content)
elif content == f'{CMD}准备': # 查看冷却、成功率
content = prepare(data)
API.send(post_main_data, content)
return
elif content == f'{CMD}管理开启':
content = deer_switch(data, 1)
API.send(post_main_data, content)
elif content == f'{CMD}管理关闭':
content = deer_switch(data, 0)
API.send(post_main_data, content)
elif content == f'{CMD}':
content = signin(data)
API.send(post_main_data, content)
return
# 查看本群排行
def ranking(data, type):
try:
ranking_content = ""
## 返回本月记录
start_date, end_date = get_start_time_the_month()
rank_query = db.session.query(
UserDeer.user_qq_id,
UserDeer.user_qq_name,
func.count(UserDeer.user_qq_id).label('sign_in_count')
).filter(
UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
)
if type == 'ALL':
rank_query = rank_query.filter(UserDeer.by_group_id == str(data.get("group_id")))
else:
rank_query = rank_query.filter(
UserDeer.by_platform == 'qq',
UserDeer.by_group_id == str(data.get("group_id"))
)
rank_query = rank_query.group_by(
UserDeer.user_qq_id,
).order_by(
func.count(UserDeer.user_qq_id).desc()
)
rank_list_data = rank_query.limit(20).all()
if len(rank_list_data) <= 0:
raise Exception("未有🦌记录")
# 生成排名结果字符串
for i, (user_qq_id, user_qq_name, count) in enumerate(rank_list_data, start=1):
ranking_content += f"{i}.{user_qq_name} {count}次\n"
return f"本群本月排行(前20):\n{ranking_content}"
except Exception as e:
return f"本群本月查询失败 {e}"
# 查询自己本月签到日志
def user_deer_signin_logs(data):
## 返回本月记录
start_date, end_date = get_start_time_the_month()
## 查询用户本月所有记录
user_deer_log = db.session.query(UserDeer).filter(UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
UserDeer.user_qq_id == data.get('user_id'))
log_count = user_deer_log.count()
if log_count <= 0:
return "[CQ:at,qq={data.get('user_id')}] 暂无🦌记录"
# 将查询结果转换为 JSON 列表
json_data = []
for result in user_deer_log:
j_data = {
'id': result.id,
'creation_time': str(result.creation_time.strftime("%Y-%m-%d %H:%M:%S.%f")),
}
json_data.append(j_data)
return f"[CQ:at,qq={data.get('user_id')}] 🦌记录(本月总计{log_count}):\n{generate_calendar(json_data, data.get('user_id'))}"
# 准备
def prepare(data):
content = ''
response = check_signin_feasibility(data)
# print(response)
# temp = {
# 'signin_available': False,
# 'log_count_today': log_count,
# 'signin_possibility': 0,
# 'minute_passed_last_signin': minute_passed
# }
log_count_today = response.get('log_count_today', 0)
content += f'今日已成功🦌了 {log_count_today} 次\n\n'
if response.get('signin_available', False):
signin_possibility = response.get('signin_possibility', 0)
content += f'准备就绪\n'
content += f'成功率为: {int(signin_possibility * 100)} %'
else: # 'signin_available': False
content += f'目前还在贤者时间内\n'
time_remain = SIGNIN_CD - response.get('minute_passed_last_signin', 0)
if time_remain < 1:
content += f'还剩 {int(time_remain * 60)} 秒可再次🦌'
else:
content += f'还剩 {int(time_remain)} 分钟可再次🦌'
return f"[CQ:at,qq={data.get('user_id')}] {content}"
# 签到
def signin(data):
try:
## 前置条件检查
if check_service_interval() is False:
return f"群组已开启指定时间可🦌: {format_intervals()}\n请各位节制使用🦌,并在无人聊天时使用,谢谢(鞠躬"
if check_group_status(data) is None or check_group_status(data) == 0:
return "群组未开启🦌"
check_user_ban_status_result = check_user_ban_status(data)
if check_user_ban_status_result is not None and check_user_ban_status_result.status == 1:
return "小笨蛋,你在黑名单里"
## 返回本月记录
start_date, end_date = get_start_time_the_month()
## 查询签到用户最新一条 以及 用户本月总签到数量
query = db.session.query(
UserDeer,
func.count(UserDeer.id).label('count')
).filter(
UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
UserDeer.user_qq_id == data.get('user_id'),
UserDeer.by_platform == "qq",
UserDeer.by_group_id == str(data.get("group_id"))
)
user_deer_first_log, user_deer_day_log_count = query.first()
# 检查冷却时间
response = check_signin_feasibility(data)
# response = {
# 'signin_available': False,
# 'log_count_today': log_count,
# 'signin_possibility': 0,
# 'minute_passed_last_signin': minute_passed
# }
if user_deer_day_log_count > 1 and user_deer_first_log is not None:
if user_deer_day_log_count >= M_SIGNIN_LIMIT:
print(f"info.>{M_SIGNIN_LIMIT}")
return f"[CQ:at,qq={data.get('user_id')}] 本月已🦌{user_deer_day_log_count}次,适当🦌,已强制阻止"
elif not response['signin_available']:
content = ''
content += f'目前还在贤者时间内\n'
time_remain = SIGNIN_CD - response.get('minute_passed_last_signin', 0)
if time_remain < 1:
content += f'还剩 {int(time_remain * 60)} 秒可再次🦌'
else:
content += f'还剩 {int(time_remain)} 分钟可再次🦌'
return f"[CQ:at,qq={data.get('user_id')}] {content}"
else: # response['signin_available'] == True
# 可🦌
possibility = response.get('signin_possibility', 0)
# 用epoch int来设定随机种子,60*10等于每10分钟换一次随机种子,避免一直随机导致通过
seed_int = int(datetime.datetime.now().timestamp() / (60 * N_GAP))
random.seed(seed_int)
num = random.random()
print(f'random seed: {seed_int}, num: {num}') # for debugging
if num > possibility:
# 失败
content = ''
content += f'🦌成功率为: {int(possibility * 100)} %\n'
content += f'但是你失败了!!!'
content += f'重复尝试并不会改变你的结果,请于 {N_GAP} 分钟后再试。'
return f"[CQ:at,qq={data.get('user_id')}] {content}"
## 插入记录
new_user_deer = UserDeer(user_qq_id=data.get('user_id'), user_qq_name=data.get("sender").get("nickname"),
creation_time=datetime.datetime.now(), by_platform="qq",
by_group_id=data.get("group_id"))
db.session.add(new_user_deer)
db.session.commit()
## 查询符合数据
user_deer_log = query_month_signin(data.get("user_id")).all()
# 将查询结果转换为 JSON 列表
json_data = []
for result in user_deer_log:
j_data = {
'id': result.id,
'creation_time': str(result.creation_time.strftime("%Y-%m-%d %H:%M:%S.%f")),
}
json_data.append(j_data)
# 生成日历
content = generate_calendar(json_data, data.get('user_id'))
return f"[CQ:at,qq={data.get('user_id')}] 成功🦌了{content}"
except Exception as e:
print(e)
return f"[CQ:at,qq={data.get('user_id')}] 🦌失败 {e}"
# 补卡
def supplementary_signin(data, input_month, input_day, input_multiplier):
try:
## 前置条件检查
if check_service_interval() is False:
return f"组组已开启指定时间可🦌: {format_intervals()}"
if check_group_status(data) is None or check_group_status(data) == 0:
return "群组未开启🦌"
check_user_ban_status_result = check_user_ban_status(data)
if check_user_ban_status_result is not None and check_user_ban_status_result.status == 1:
return "小笨蛋,你在黑名单里"
## 检查是否穿越补卡
check_time = datetime.datetime.strptime(f'{datetime.datetime.now().year}-{input_month}-{input_day}',
'%Y-%m-%d')
if check_time >= datetime.datetime.now():
return f"[CQ:at,qq={data.get('user_id')}] 不可以穿越🦌哦"
## 检查CD
## 返回本月记录
start_date, end_date = get_start_time_the_month()
## 查询签到用户最新一条 以及 用户本月总签到数量
query = db.session.query(
UserDeer,
func.count(UserDeer.id).label('count')
).filter(
UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
UserDeer.user_qq_id == data.get('user_id'),
UserDeer.by_platform == "qq",
UserDeer.by_group_id == str(data.get("group_id"))
)
user_deer_first_log, user_deer_day_log_count = query.first()
# 检查冷却时间
response = check_signin_feasibility(data)
# response = {
# 'signin_available': False,
# 'log_count_today': log_count,
# 'signin_possibility': 0,
# 'minute_passed_last_signin': minute_passed
# }
if user_deer_day_log_count > 1 and user_deer_first_log is not None:
if user_deer_day_log_count >= M_SIGNIN_LIMIT:
print(f"info.>{M_SIGNIN_LIMIT}")
return f"[CQ:at,qq={data.get('user_id')}] 本月已🦌{user_deer_day_log_count}次,适当🦌,已强制阻止"
elif not response['signin_available']:
content = ''
content += f'目前还在贤者时间内\n'
time_remain = SIGNIN_CD - response.get('minute_passed_last_signin', 0)
if time_remain < 1:
content += f'还剩 {int(time_remain * 60)} 秒可再次🦌'
else:
content += f'还剩 {int(time_remain)} 分钟可再次🦌'
return f"[CQ:at,qq={data.get('user_id')}] {content}"
else: # response['signin_available'] == True
# 可🦌
possibility = response.get('signin_possibility', 0)
# 用epoch int来设定随机种子,60*10等于每10分钟换一次随机种子,避免一直随机导致通过
seed_int = int(datetime.datetime.now().timestamp() / (60 * N_GAP))
random.seed(seed_int)
num = random.random()
print(f'random seed: {seed_int}, num: {num}') # for debugging
if num > possibility:
# 失败
content = ''
content += f'🦌成功率为: {int(possibility * 100)} %\n'
content += f'但是你失败了!!!'
content += f'重复尝试并不会改变你的结果,请于 {N_GAP} 分钟后再试。'
return f"[CQ:at,qq={data.get('user_id')}] {content}"
input_multiplier = int(input_multiplier)
# 补签记录
if 1 <= input_multiplier <= 4:
deer_logs = []
for i in range(input_multiplier):
time = datetime.datetime.strptime(f'{datetime.datetime.now().year}-{input_month}-{input_day}',
'%Y-%m-%d')
deer_logs.append(
UserDeer(
user_qq_id=data.get('user_id'),
user_qq_name=data.get("sender").get("nickname"),
creation_time=time,
by_platform="qq",
by_group_id=data.get("group_id")
),
)
db.session.add_all(deer_logs)
db.session.commit()
## 查询符合数据
user_deer_log = query_month_signin(data.get("user_id")).all()
# 将查询结果转换为 JSON 列表
json_data = []
for result in user_deer_log:
j_data = {
'id': result.id,
'creation_time': str(result.creation_time.strftime("%Y-%m-%d %H:%M:%S.%f")),
}
json_data.append(j_data)
content = generate_calendar(json_data, data.get('user_id'))
return f"[CQ:at,qq={data.get('user_id')}] 补🦌成功\n{content}"
else:
return f"[CQ:at,qq={data.get('user_id')}] 🦌数范围: 1-4"
except Exception as e:
return f"[CQ:at,qq={data.get('user_id')}] 补🦌失败, {e}"
# 查询当天签到次数以及成功概率
def check_signin_feasibility(data):
user_deer_day_log = query_today_signin(data.get('user_id'), data.get('group_id')).all()
# print(user_deer_day_log)
log_count = len(user_deer_day_log)
if log_count > 0:
latest_signin = user_deer_day_log[-1].creation_time
minute_passed = (datetime.datetime.now() - latest_signin).total_seconds() / 60
else:
minute_passed = 1e+16
temp = {
'signin_available': False,
'log_count_today': log_count,
'signin_possibility': 0,
'minute_passed_last_signin': minute_passed
}
if log_count < 1:
temp['signin_available'] = True
temp['signin_possibility'] = 1
elif minute_passed < SIGNIN_CD:
# 贤者时间,不给签到
dummy = 1
elif minute_passed >= SIGNIN_CD:
# 基础概率曲线,可随意选择,但是必须越来越小
base_possibility = 1 / math.sqrt(log_count + 1)
# 恢复曲线,可随意选择,但必须 < 1
ratio = minute_passed / SIGNIN_CD
possibility = base_possibility * (0.5 + 0.5 * math.erf(ratio)) # as t->inf, base_possibility * 1
temp['signin_available'] = True
temp['signin_possibility'] = possibility
else:
raise Exception('Unplanned option!!!')
return temp
# 查询当天签到次数和最新签到时间
def query_today_signin(user_id, group_id):
try:
## 返回本月记录
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
start_date = datetime.date(year, month, day)
tomorrow = now + datetime.timedelta(days=1)
year = tomorrow.year
month = tomorrow.month
day = tomorrow.day
end_date = datetime.date(year, month, day)
## 查询符合数据
data = db.session.query(UserDeer).filter(UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
UserDeer.by_group_id == group_id,
UserDeer.user_qq_id == user_id)
return data
except Exception as e:
return f"失败🦌, {e}"
# 管理员🦌开关
# 0关 1开,管理操作只能是当前群组
def deer_switch(data, status):
try:
if data.get("sender").get("role") in ADMIN_ROW:
admin_group = db.session.query(UserDeerAdmin).filter(
UserDeerAdmin.by_group_id == str(data.get('group_id'))
).first()
if admin_group is None:
new_user_deer_admin = UserDeerAdmin(by_group_id=data.get('group_id'), status=int(status))
db.session.add(new_user_deer_admin)
db.session.commit()
else:
user_admin = db.session.query(UserDeerAdmin).filter_by(by_group_id=data.get('group_id')).first()
user_admin.status = int(status)
db.session.commit()
else:
return "非管理身份"
return "操作成功"
except Exception as e:
return "操作失败"
# 管理员封禁
# 0解除 1封禁
def deer_ban(data, id, status):
try:
if data.get("sender").get("role") in ADMIN_ROW:
user_ban_group = db.session.query(UserBans).filter(
UserBans.by_user_id == str(id),
UserBans.by_group_id == str(data.get('group_id'))
).first()
if user_ban_group is None:
new_user_ban = UserBans(by_user_id=id, by_group_id=data.get('group_id'),
status=int(status))
db.session.add(new_user_ban)
db.session.commit()
else:
update_user_ban = db.session.query(UserBans).filter(UserBans.by_user_id == id).first()
update_user_ban.status = int(status)
db.session.commit()
else:
return "非管理身份"
return "操作成功"
except Exception as e:
return f"操作失败 {e}"
##
# 🦌工具类def
##
# 查询本月签到
# 注意返回的是结构体,需要获取数据,则query_month_signin(data).all() or query_month_signin(data).count()
def query_month_signin(user_id):
try:
start_date, end_date = get_start_time_the_month()
## 查询符合数据
data = db.session.query(UserDeer).filter(UserDeer.creation_time >= start_date,
UserDeer.creation_time <= end_date,
UserDeer.user_qq_id == user_id)
return data
except Exception as e:
return f"失败🦌, {e}"
# 对数字字符串进行脱敏
def desensitize_number(num_str, start, end):
"""
Args:
num_str: 需要脱敏的数字字符串
start: 开始脱敏的位置
end: 结束脱敏的位置
Returns:
脱敏后的字符串
"""
return num_str[:start] + '*' * (end - start) + num_str[end:]
# plt转base64
def plot_to_base64(fig):
"""将 Matplotlib 图形转换为 Base64 字符串
Args:
fig: Matplotlib 图形对象
Returns:
Base64 字符串
"""
img = BytesIO()
fig.savefig(img, format='png')
img.seek(0)
return base64.b64encode(img.getvalue()).decode('utf-8')
# 生成日历
def generate_calendar(user_data, id):
# 获取系统当前年月
now = datetime.datetime.now()
year = now.year
month = now.month
# 获取指定年月的一月日历
cal = calendar.monthcalendar(year, month)
# 创建一个空的矩阵来存储日历数据和签到次数
data = np.zeros((6, 7))
sign_in_counts = np.zeros((6, 7), dtype=int)
# 将日历数据填充到矩阵中
for i in range(len(cal)):
for j in range(len(cal[i])):
if cal[i][j] != 0:
data[5 - i][j] = cal[i][j]
# 统计签到次数
for user_sign_in in user_data:
# 将签到时间转换为datetime对象
sign_in_time = datetime.datetime.strptime(user_sign_in['creation_time'], "%Y-%m-%d %H:%M:%S.%f") # 请根据实际时间格式调整
sign_in_day = sign_in_time.day
for i in range(len(cal)):
for j in range(len(cal[i])):
if cal[i][j] == sign_in_day:
sign_in_counts[5 - i][j] += 1
# 加载要显示的图片
img = mpimg.imread('deer.png')
img_done = mpimg.imread('deer_done.png')
# 创建图形
fig, ax = plt.subplots(figsize=(4, 3)) # 调整图形大小
ax.text(3.5, 3, f"{month}", ha='center', va='center', fontsize=170, alpha=0.1)
# 显示图片,并根据日历数据和签到次数设置透明度
for i in range(6):
for j in range(7):
if data[i][j] != 0:
# 调整图片大小和位置
ax.imshow(img, extent=[j, j + 0.8, i, i + 0.8], alpha=.95 if sign_in_counts[i][j] > 0 else 0.5)
# 在图片上显示日期
ax.text(j, i + .8, f"{int(data[i][j])}", ha='center', va='center', fontsize=8, family='Arial')
# 显示签到次数
if sign_in_counts[i][j] > 0:
# ax.imshow(img_done, extent=[j, j + 0.8, i, i + 0.8], aspect="auto")
ax.text(
j + 0.65,
i + 0.75,
f"{sign_in_counts[i][j]}",
fontsize=8, ha='center',
horizontalalignment='right',
color='red'
)
# 设置图片配置
ax.set_xticks(np.arange(7) + 0) # 将刻度线移到单元格中心
ax.set_yticks(np.arange(6) + 0)
ax.set_yticklabels([])
ax.axis('off')
ax.fill()
# 设置标题
ax.set_title("")
# img = BytesIO()
save_path = "C:/Users/user_DTh9D37zP/Desktop/BFBAN-BOTDeer/deer_png/"
save_file_name = f"{year}-{month}.{id}.{datetime.datetime.now().timestamp()}.png"
delete_old_png(save_path, 60) # file older than 60 sec to delete
if DEBUG:
plt.show() # 显示图形
plt.savefig(f'{save_path}{save_file_name}', format='jpeg')
# plt.savefig(img, format='jpeg')
# img.seek(0)
return f"[CQ:image,file=file://{save_path}{save_file_name}]"
# return f"[CQ:image,file=base64://{plot_to_base64(plt.gcf())}]"
def delete_old_png(save_path, how_old_to_delete):
# save_path, 图片储存路径
# how_old_to_delete: 超过多久的图片可以删除 [sec]
thistime = int(datetime.datetime.now().timestamp())
# List all files in the directory
files = [f for f in os.listdir(save_path) if os.path.isfile(os.path.join(save_path, f))]
for file in files:
file_path = save_path + file
# print(file_path)
if '.png' in file_path:
creation_time = os.path.getctime(file_path)
if thistime - how_old_to_delete > creation_time:
# Check if the file exists before deleting
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} has been deleted.")
else:
print(f"{file_path} does not exist.")
def format_intervals():
"""将时间区间列表格式化为字符串
Returns:
str: 格式化后的字符串
"""
formatted_intervals = []
for interval in SERVICE_INTERVAL:
formatted_intervals.append(f"{interval['start']}-{interval['end']}")
return ', '.join(formatted_intervals)
# 检查是否在使用区间
def check_service_interval():
"""
判断当前时间是否在服务区间内
Returns:
bool: True表示在区间内,False表示不在区间内
"""
if is_server_interval is False: return True
current_time = datetime.datetime.now()
for interval in SERVICE_INTERVAL:
start_time = datetime.datetime.strptime(interval['start'], '%H:%M').time()
end_time = datetime.datetime.strptime(interval['end'], '%H:%M').time()
# 处理跨天的情况,例如23:00-0:00
if end_time < start_time:
if current_time.time() >= start_time or current_time.time() <= end_time:
return True
else:
if start_time <= current_time.time() <= end_time:
return True
return False
# 检查群组是否可用
# 决定是否签到、补签、查询等功能
def check_group_status(data):
status = db.session.query(UserDeerAdmin).filter(
UserDeerAdmin.by_group_id == str(data.get('group_id'))
).first()
return status
# 检查用户是否封禁
def check_user_ban_status(data):
status = db.session.query(UserBans).filter(
UserBans.by_user_id == str(data.get('user_id')),
).first()
return status
# 获取本月的开始和结束日期
# 如11月,11月1日-11月30日
# 使用例子: start_date, end_date = get_start_time_the_month()
def get_start_time_the_month():
now = datetime.datetime.now()
year = now.year
month = now.month
first_day = datetime.date(year, month, 1)
last_day = datetime.date(year, month, calendar.monthrange(year, month)[1])
return first_day, last_day
## 单例测试用 (^U^)ノ~YO
# generate_calendar([
# {"id": 1, "creation_time": "2024-11-14 11:16:53.412898"},
# {"id": 2, "creation_time": "2024-11-14 11:16:55.838954"}
# ], 1)
# ranking()
# supplementary_signin({"user_id": "1214617226", "user_name": "可爱"}, ".🦌补11月2日*3")
# signin({"user_id": "1214617226", "user_name": "可爱", "group_id": "1214617226"})
def main_function_threading(ws, data):
thread = threading.Thread(target=main_function, args=(ws, data))
thread.start()
if __name__ == '__main__':
ws = websocket.WebSocketApp("ws://127.0.0.1:5800", on_message=main_function_threading)
ws.run_forever()