This repository has been archived by the owner on Dec 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
1635 lines (1607 loc) · 74 KB
/
bot.py
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from asyncio.tasks import wait
import random
import threading
import aiohttp
import math
from PIL import ImageFile
from aiohttp.client import ClientSession
from bs4 import BeautifulSoup
from graia.application import group
from graia.application.entities import UploadMethods
import imageio
from moviepy.video.VideoClip import ImageClip
ImageFile.LOAD_TRUNCATED_IMAGES = True
from random import randint
import requests
import hashlib
import json
import shutil
import cv2
import _thread
from PIL import ImageFont,ImageDraw
from graia.broadcast import Broadcast
from graia.application import GraiaMiraiApplication, Session, message
from graia.application.event.messages import GroupMessage
from graia.application.event.mirai import MemberJoinEvent, NewFriendRequestEvent
from graia.application.message.chain import MessageChain
from graia.saya import Saya
from graia.saya.builtins.broadcast import BroadcastBehaviour
import asyncio
import aiohttp
from graia.application.group import Group, Member
from graia.application.message.elements.internal import At, Image, Plain, Poke, Quote, Xml,Json,App,Source
from graia.broadcast.interrupt import InterruptControl
from graia.broadcast.interrupt.waiter import Waiter
from operator import eq
from datetime import datetime
import time as Time
from dateutil import rrule
from PIL import Image as Im
from pixivpy3 import *
import sys
import greenlet
import requests
import os
from os.path import join, getsize
from threading import Thread
import zipfile
from asyncio.subprocess import PIPE, STDOUT
from runtimetext import lolicon_key,saucenao_key,admin,hsomap,fl1,fl2,authKey,bot_qq,host_,aks_map,aks_map2,aks_map3,aki_map\
,helptext,refresh_token,maxx_img,infomap,maximgpass,xmlimg_group,oncesetuadd,setus,Search_map,Search_map2,stag,stag2,xmloffline
global is_run
global execout
api = AppPixivAPI()
loop = asyncio.get_event_loop()
is_run = False
def sdir(tdir): #新建目录
if not os.path.exists(tdir):
print('目标不存在,新建目录:',tdir)
os.makedirs(tdir)
try: #start
try:#初始化
if not os.path.exists('cfg.json'):
if not os.path.exists('./chace/mainbg.png'):print('错误:没有找到主界面背景')
cfg = {}
cfg['hsolvlist'] = {}
cfg['hsolv'] = {}
cfg['qd'] = {}
cfg['qdlist'] = {}
cfg['last_setu'] = {}
cfg['hsolvlist']['0'] = 0
cfg['hsolv']['0'] = 0
cfg['qd']['0'] = 0
cfg['qdlist']['0'] = 0
cfg['setu_group'] = [0]
cfg['r18_group'] = [0]
cfg['last_setu']['0'] = 0
cfg['time'] = math.floor( Time.time() / 60 / 60 / 24 )
cfg['cooling'] = math.floor( Time.time())
cfg['setu_l'] = 0
cfg['xml'] = 0
cfg['info'] = 0
cfg['revoke'] = 0
cfg['debug'] = 0
jsonfile=open("cfg.json","w")
json.dump(cfg,jsonfile,indent=4)
jsonfile.close()
print('初始化完成,你需要在群聊内输入akra来获取明日方舟的数据')
except Exception:print('初始化出现错误')
jsonfile = open("cfg.json","r")
cfg = json.load(jsonfile)
jsonfile.close()
try:#配置补全
for i in ['setu','chace','backups','listpiv','r18','setu','listpsh']:
sdir('./'+i)
for i in ['hsolvlist','hsolv','qd','qdlist','last_setu','plinfodata','setus','last_s']:
try:load = cfg[i]
except:cfg[i] = {}
for i in ['setu_l','xml','revoke','info','debug']:
try: load = cfg[i]
except: cfg[i] = 0
try: load = cfg['cooling']
except:cfg['cooling'] = math.floor(Time.time())
try:load = cfg['setus']['r18']
except:cfg['setus']['r18'] = []
try:load = cfg['setus']['setu']
except:cfg['setus']['setu'] = []
except:print('配置补全错误')
try:#时间转换
initDate = datetime.strptime(cfg['time'],'%Y-%m-%d %H:%M:%S')
cfg['time'] = math.floor( Time.time() / 60 / 60 / 24 )
print('更新时间配置')
except:pass
if type(cfg['time']) == float:
cfg['time'] = math.floor( Time.time() / 60 / 60 / 24 )
print('更新时间配置')
try:
hsolvlist_data = cfg['hsolvlist']
hsolv_data = cfg['hsolv']
qd_data = cfg['qd']
qdlist_data = cfg['qdlist']
setu_group = cfg['setu_group']
r18_group = cfg['r18_group']
last_setu = cfg['last_setu']
last_s = cfg['last_s']
except:print('严重错误,配置读取失败')
try:#方舟json读取
jsonfile = open("akm.json","r")
akm_data = json.load(jsonfile)
jsonfile.close()
jsonfile = open("aki.json","r")
aki_data = json.load(jsonfile)
jsonfile.close()
jsonfile = open("aks.json","r")
aks_data = json.load(jsonfile)
jsonfile.close()
except:print('错误,方舟数据读取失败')
except:print('err')
class DF(object): #下载
async def resize(path,mx=0,my=0):
onlyy = onlyx =False
inputimg = Im.open(path)
new_x = mmx = inputimg.size[0]
new_y = mmy = inputimg.size[1]
xyb = mmx / mmy
remove_x = mmx - mx
remove_y = mmy - my
if mx == 0: onlyy = True
if my == 0: onlyx = True
if remove_x >= remove_y or onlyx == True:
new_x = mx
rsize = mx / mmx
new_y = mmy * rsize
elif remove_y > remove_x or onlyy == True:
new_y = my
rsize = my / mmy
new_x = mmx * rsize
new_x = math.floor(new_x)
new_y = math.floor(new_y)
inputimg = inputimg.resize((new_x, new_y),Im.ANTIALIAS)
print('├新图片大小:',new_x,'|',new_y)
inputimg.save(path)
async def adf(url,path,resize=[],resize_r=False):#异步下载
debug(url ,">开始下载")
url = url.replace('i.pximg.net','i.pixiv.cat')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
async with aiohttp.ClientSession() as session:
response = await session.get(headers=headers, url=url)
content_img = await response.read()
tempf = open(path,'w')
tempf.close()
with open(path, 'wb') as f:
f.write(content_img)
await session.close()
if path.endswith('png') and resize == []:
await DF.resize(path,maxx_img)
print('└下载完毕' + path)
if resize_r == True:shutil.copyfile(path,path.replace('.png','_r.png'))
if resize != []:await DF.resize(path,resize[0],resize[1])
return path
class CHS(object): #数据初始化
def chs(id):
datas = [hsolv_data,hsolvlist_data,qd_data,qdlist_data]
for i in datas :
if id not in i:
i[id] = 0
#api = AppPixivAPI()
api = ByPassSniApi() # Same as AppPixivAPI, but bypass the GFW
api.require_appapi_hosts(hostname="public-api.secure.pixiv.net")
api.set_accept_language('en-us')
try:api.auth(refresh_token=refresh_token)
except:
try:api.auth(refresh_token=refresh_token)
except Exception as e:print('Pixiv登录错误: -\n└' + str(e))
bcc = Broadcast(loop=loop)
app = GraiaMiraiApplication(broadcast=bcc,connect_info=Session(host=host_,authKey=authKey,account=bot_qq,websocket=True,use_dispatcher_statistics = True,use_reference_optimization = True))
inc = InterruptControl(bcc)
###################################
#如果你想使用saya模块就去除下面的“#”
###################################
try:
saya = Saya(bcc)
saya.install_behaviours(BroadcastBehaviour(bcc))
with saya.module_context():
for module in os.listdir("modules"):
try:
if os.path.isdir(module):
saya.require(f"modules.{module}")
else:
saya.require(f"modules.{module.split('.')[0]}")
except ModuleNotFoundError:
pass
except Exception as e:
print('saya加载错误 不使用saya插件可无视:',e)
async def tlen(text): #文字宽度测量
lenTxt = len(text)
lenTxt_utf8 = len(text.encode('utf-8'))
size = int((lenTxt_utf8 - lenTxt)/2 + lenTxt)
return size
def debug(*nums):
if cfg['debug'] == 1:
print(*nums)
else: pass
async def aexec(code):
# Make an async function with the code and `exec` it
exec(
f'async def __ex(): ' +
''.join(f'\n {l}' for l in code.split('\n'))
)
# Get `__ex` from local variables, call it and return the result
return await locals()['__ex']()
class Ak:
async def m(): #明日方舟m数据获取
apiurl = 'https://penguin-stats.io/PenguinStats/api/v2/result/matrix'
print('与api沟通中...')
async with aiohttp.ClientSession() as session:
async with session.get(apiurl) as resp:
res_akm_json = await resp.json()
ak_m = res_akm_json['matrix']
akm = []
for i in ak_m:
end = False
print(i)
for item in i:
if 'end' in item:
print(i['stageId'],i['itemId'],'已录入')
end = True
if end == False:akm.append(i)
print('done')
jsonfile=open("akm.json","w")
json.dump(akm,jsonfile,indent=4)
jsonfile.close()
print('json save done')
async def i(): #明日方舟i数据获取
apiurl = 'https://penguin-stats.io/PenguinStats/api/v2/items'
print('与api沟通中...')
async with aiohttp.ClientSession() as session:
async with session.get(apiurl) as resp:
res_aki_json = await resp.json()
aki = []
for i in res_aki_json:
aki_jsoning = {}
aki_jsoning['itemId'] = i['itemId']
aki_jsoning['alias'] = i['alias']['zh']
aki_jsoning['rarity'] = i['rarity']
print(aki_jsoning['itemId'],aki_jsoning['alias'][0],'已录入')
aki.append(aki_jsoning)
print('done')
jsonfile=open("aki.json","w")
json.dump(aki,jsonfile,indent=4)
jsonfile.close()
print('json save done')
async def s(): #明日方舟s数据获取
apiurl = 'https://penguin-stats.io/PenguinStats/api/v2/stages'
print('与api沟通中...')
async with aiohttp.ClientSession() as session:
async with session.get(apiurl) as resp:
res_aks_json = await resp.json()
aks = []
for i in res_aks_json:
aks_jsoning = {}
aks_jsoning['stageId'] = i['stageId']
aks_jsoning['name'] = i['code_i18n']['zh']
aks_jsoning['stageType'] = i['stageType']
try:
aks_jsoning['apCost'] = i['apCost']
except:pass
try:
aks_jsoning['minClearTime'] = i['minClearTime']
except:pass
try:
aks_jsoning['dropInfos'] = i['dropInfos']
except:pass
print(aks_jsoning['stageId'],aks_jsoning['name'],'已录入')
aks.append(aks_jsoning)
print('done')
jsonfile=open("aks.json","w")
json.dump(aks,jsonfile,indent=4)
jsonfile.close()
print('json save done')
class Setu:
async def add(r18=0,just_get=True,s='-'): #为色图池增加色图
if r18 >= 2:
print('nom')
setudata = await pixiv.sh(s,20,r18=r18)
return setudata
ext_ing = ''
outmsg = []
p_ingdata = {}
setudata = {}
apiurl = 'https://api.lolicon.app/setu/?apikey=$APIKEY&r18=$R18'.replace('$APIKEY',lolicon_key).replace('$R18',str(r18)).replace('$NUM',str(1))
if s != '-':apiurl = apiurl + '&keyword=' + s
print('与api沟通中...','>',apiurl)
async with aiohttp.ClientSession() as session:
async with session.get(apiurl) as resp:
res_json = await resp.json()
print('└done')
code = str(res_json['code'])
codes = {
'-1' :'-1:api内部错误',
'0' :'none',
'401' :'401:APIKEY 不存在或被封禁',
'403' :'403:由于不规范的操作而被拒绝调用',
'404' :'404:找不到符合关键字的色图',
'429' :'429:达到色图调用上限,切换至本地色图'}
if code != '0':
setudata['img'] = ['.\chace\error.png']
setudata['info'] = code
if code == '404' :
setudata['info'] = '404找不到指定色图'
if s != '-':
setudata = await pixiv.sh(s,20,r18=r18)
return setudata
if code == '429':
cfg['setu_l'] = 1
setudata['img'] = ['.\chace\error.png']
setudata['info'] = '429色图调用上限'
return setudata
i = res_json['data'][0]
url_ing = i['url']
setudata['url'] = url_ing
pid_ing = i['pid']
if r18 == 1:path_ing = './r18/' + str(pid_ing) + '.png'
else:path_ing = './setu/' + str(pid_ing) + '.png'
p_ingdata['pid'] = pid_ing
if cfg['xml'] == 0 or xmloffline == True:
print('开始下载:',url_ing,pid_ing,)
try:await DF.adf(url_ing,path_ing)
except:
print('└连接错误,正在重试....')
try:await DF.adf(url_ing,path_ing)
except:
print(" └连接错误")
return
ext =" $title by $author |pid:$pid uid:$uid "\
.replace('$title',i['title'])\
.replace('$author',i['author'])\
.replace('$pid',str(pid_ing))\
.replace('$uid',str(i['uid']))
setudata['img'] = [path_ing]
setudata['ext'] = ext
tags = ''
for _ in i['tags']:
tags = tags +","+ _
setudata['raw'] = [i['title'],i['author'],str(pid_ing),str(i['uid']),tags]
outdata = ""
for item in i:
outdata = outdata + str(item) + str(i[str(item)])
outdata = outdata.replace('pid','pid:').replace('p0uid',' p0 - uid').replace('uid','uid:').replace('title','\n标题:').replace('author',' 作者:').replace('url','\n').replace('r18False','').replace('r18True','').replace('width','\n').replace('height','x').replace('tags','\n标签:')
setudata['info'] = outdata
if just_get == True:
if r18 == 1:fl = 'r18'
else:fl = 'setu'
cfg['setus'][fl].append(setudata)
print(' └色图数量+1, 目前色图总量为',len(cfg['setus'][fl]))
else:
return setudata
async def xml(setudata): #使用xml发出色图
print('intoxml')
print(setudata)
''.find('qaq')
if 'r18' in setudata['raw'][4]: stpath = 'R-18'
else: stpath = 'setu'
setu_num = len(cfg['setus'][stpath])
textxml = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><msg serviceID="1" templateID="1" action="web" brief="[有色图!!]" sourceMsgId="0" url="$url" flag="3" adverSign="0" multiMsgFlag="0"><item layout="0" mode="2" advertiser_id="0" aid="0"><title size="30" color="#D32F2F" style="3">$title</title><picture cover="$url" w="0" h="0" /><summary size="25" color="#EE9A00" style="1">$user</summary></item><item layout="6" advertiser_id="0" aid="0"><summary size="25" color="#EE9A00">$TEXT</summary><hr hidden="false" style="0" /></item><source name="$lost" icon="" action="-1" appid="0" /></msg>"""\
.replace('$title',setudata['raw'][0])\
.replace('$TEXT','tags:' + setudata['raw'][4])\
.replace('$user','by ' + setudata['raw'][1])\
.replace('$lost','pid:' + setudata['raw'][2] +' | uid:' + setudata['raw'][3] + ' -缓存:' + str(setu_num))
if type(setudata['url']) is list: textxml = textxml.replace('$url',str(setudata['url'][0]).replace('i.pixiv.net','i.pixiv.cat').replace('i.pixiv.cat','i.pximg.lolipoi.online'))
elif type(setudata['url']) is str: textxml = textxml.replace('$url',str(setudata['url']).replace('i.pixiv.ney','i.pixiv.cat').replace('i.pixiv.cat','i.pximg.lolipoi.online'))
outxml = [(Xml(textxml))]
return outxml
async def offline(r18): #发送离线色图
if r18 == 0: setu_ = './setu'
else: setu_ = './r18'
folder = os.listdir(setu_)
pach_chace = []
All_files_pach = []
for i in folder:
pach_chace=setu_ +'/' + i
All_files_pach.append(pach_chace)
setulen = len(All_files_pach)
if All_files_pach == []:print('没有找到色图')
else:print('色图载入成功')
x = randint(0,setulen)
filepach = str(All_files_pach[x])
filename = filepach.replace(setu_ + '/','')
print("选中色图" + filepach)
hsolv_data[id] = hsolv_data[id] - 1
hsolvlist_data[id] = hsolvlist_data[id] + 1
outmsg = [(Image.fromLocalFile(filepach))]
return outmsg
async def get(r18,qid=110,msg='',xml=cfg['xml']): #获取色图
isdigit = False
id = str(qid)
outmsg = []
if r18 == 1:fl = 'r18'
else:fl = 'setu'
if msg.isdigit() == True:
num = int(msg)
if 0 < num < 10:isdigit =True
else:
outmsg = [(Plain('色图数量不对劲!'))]
return outmsg
else:num = 1
if id not in hsolvlist_data: #初始化
print('初始化',id)
hsolv_data[id] = 0
hsolvlist_data[id] = 0
qd_data[id] = 0
qdlist_data[id] = 0
if qd_data[id] == 0: #签到
debug1 = hsolv_data[id]
if qdlist_data[id] == 0:
stadd = random.randint(20,56)
ext_ing = "这是你第一次获取色图,随机获取色图$张".replace('$',str(stadd))
else:
stadd = random.randint(15,30)
ext_ing = "今天第一次获取色图,随机获取色图$张".replace('$',str(stadd))
outmsg.append(Plain(ext_ing))
hsolv_data[id] += stadd
debug2 = hsolv_data[id]
qdlist_data[id] += 1
qd_data[id] = 1
if hsolv_data[id] > num: #有剩余色图并获取色图
if cfg['setu_l'] == 1: #离线色图
for i in range(num):
offline = await Setu.offline(r18)
outmsg.append(offline)
hsolvlist_data[id] += 1
hsolv_data[id] -= 1
return outmsg
if isdigit == True or msg == '': #普通和数量色图
global loop_ing
loop_ing = False
if num < len(cfg['setus'][fl]):
for _ in range(num):
lsetudata = cfg['setus'][fl]
setudata = lsetudata[0]
print(xml)
if xml == 1:
setudata['ext'] = setudata['ext'] + '色图缓存:' + str(len(cfg['setus'][fl]))
outxml = await Setu.xml(setudata)
outmsg = outxml
else:
outmsg.append(Image.fromLocalFile(setudata['img'][0]))
del lsetudata[0]
print('┌色图库 -1')
cfg['setus'][fl] = lsetudata
if cfg["info"] == 1:outmsg.append(Plain(setudata['info']))
hsolvlist_data[id] += 1
hsolv_data[id] -= 1
print('└色图人剩余色图',hsolv_data[id])
cfg['last_setu'][id] = setudata
else:
if is_run == True: outmsg.append(Plain('下载可能卡住了|'))
outmsg.append(Plain('色图获取的太多啦,补不上货啦'))
return outmsg
else : #搜索色图
setudata = await Setu.add(r18,False,s=msg)
print('joinsetudata')
xml = 1
if xml == 1:
outxml = await Setu.xml(setudata)
outmsg = outxml
else:
if r18 >= 2:
for _ in setudata['img']:
outmsg.append(Image.fromLocalFile(_))
else:outmsg.append(Image.fromLocalFile(setudata['img'][0]))
if cfg["info"] == 1:outmsg.append(Plain(setudata['info']))
hsolvlist_data[id] += 1
hsolv_data[id] -= 1
return outmsg
else:
outmsg.append(Plain('你没色图啦'))
debug(cfg['hsolv'][id],'>',hsolv_data[id],'| id:',id)
return outmsg
async def reget(r18 ): #重新补充色图
global is_run
if is_run == True: return
is_run = True
if r18 == 1:fl = 'r18'
else:fl = 'setu'
tasks = []
setu_ix = len(cfg['setus'][fl])
for _ in range(10):
if setu_ix < setus:
task = asyncio.ensure_future(Setu.add(r18=r18))
tasks.append(task)
setu_ix = setu_ix + 1
try:await asyncio.gather(*tasks)
except:is_run = False
is_run = False
async def tdf(url,path): #
await DF.adf(url,path)
shutil.copyfile(path,path.replace('.png','_r.png'))
await DF.resize(path,240,120)
async def rm(rmsg,c=False,set=0): #撤回色图
if cfg['xml'] == 1:return
if c == False :rtime = cfg['revoke']
if c == True: rtime = set
if rtime > 0:
await asyncio.sleep(rtime)
await app.revokeMessage(rmsg)
else:return
async def gif(path):
frames = []
image_list = ["chace/none.png",path]
for image_name in image_list:
frames.append(imageio.imread(image_name))
imageio.mimsave(path.replace('.png','.gif').replace('.jpg','.gif'), frames, 'GIF', duration=200)
path = path.replace('.png','.gif').replace('.jpg','.gif')
return path
async def setudata(pid,uid,pname,uname,w,h,tags):
pid = str(pid)
uid = str(uid)
w = str(w)
h = str(h)
setudatatext = '''pid:$pid p0 - uid:$uid\n标题:$pname 作者:$uname\n$url\n$xy\n标签:$tags'''\
.replace('$pid',pid)\
.replace('$uid',uid)\
.replace('$pname',pname)\
.replace('$uname',uname)\
.replace('$url',"pixiv.net/artworks/"+pid)\
.replace('$xy',w + '|' + h)\
.replace('$tags',''.join(tags))
return setudatatext
class pixiv:
async def sh(msg,num,r18=2):
setudata = {}
print(math.floor(Time.time()),'|',cfg['cooling'])
if math.floor(Time.time()) - cfg['cooling'] < 15 :
setudata['img'] = ['.\chace\error.png']
setudata['info'] = 'pixiv冷却中'
return setudata
cfg['cooling'] = math.floor(Time.time())
debug('开始搜图:',msg,'r18:',r18)
shlist = []
for i in stag:
if len(shlist) > num:break
word = msg + ' ' + i
raw = api.search_illust(search_target='partial_match_for_tags',word=word)
try:
for _ in raw['illusts']:
print(len(shlist),'/',num,'|',_['tags'][0]['name'])
if len(shlist) > num:break
if _['tags'][0]['name'] == 'R-18' and r18 >= 1 :shlist.append(_)
if _['tags'][0]['name'] != 'R-18' and r18 == 2 :shlist.append(_)
if _['tags'][0]['name'] != 'R-18' and r18 <= 0 :shlist.append(_)
except:
print('error:',raw)
if len(shlist) > num:break
await asyncio.sleep(3)
cfg['cooling'] = math.floor(Time.time())
debug('搜图完成,处理数据中')
data = shlist[random.randint(0,num)]
raw_tags = data['tags']
tags = []
for tag in raw_tags:tags.append(tag['name'])
setudata['info'] = await Setu.setudata(
data['id'],
data['user']['id'],
data['caption'],
data['user']['name'],
data['width'],data['height'],
tags
)
for _ in tags : tags_str = ','.join(_)
setudata['raw'] = [data['caption'],data['user']['name'],str(data['id']),str(data['user']['id']),tags_str]
outdata = ""
try:
print(data['meta_single_page']['original_image_url'],'>>>>')
url = data['meta_single_page']['original_image_url']
urls = [url]
print('-done')
except:
n = 0
urls = []
for _ in data['meta_pages']:
n += 1
print(_['image_urls']['original'],'>>>>')
urls.append(_['image_urls']['original'])
if n > 3:break
n = 0
print(urls)
setudata['img'] = []
n = 0
setudata['url'] = urls
cfg['cooling'] = math.floor(Time.time())
return setudata
async def rep(l,text): #文字占位处理
strnone = ' '
text=text.replace(' ',' ')
len_ing = await tlen(text)
if len_ing > l:
remove = (len_ing - l) + 2
for _ in range(100):
if remove > 0:
i = text[-1:]
if i >= u'\u4e00' and i <= u'\u9fa5' or i >= u'\u3040' and i <= u'\u31FF':
remove -=2
text = text[:-1]
else:
remove -=1
text = text[:-1]
else:
if remove < 0:
text = text + ' '
break
out = text + '..'
else:
add = strnone * ( l - len_ing)
out = text + add
return out
async def settime(time): #时间格式化
atime = ''
time_h = math.floor((time/1000)/60/60)
if time_h != 0:atime = atime + str(time_h) + ':'
time_m = math.floor((time/1000)/60) - time_h *60
if time_m != 0:atime = atime + str(time_m) + ':'
time_s = (math.floor(time/1000) -time_m *60 ) - time_h*60*60
if time_s != 0:atime = atime + str(time_s)
return atime
def restart_program(): #重启
python = sys.executable
os.execl(python, python, * sys.argv)
def savecfg(): #保存cfg.json
try:
jsonfile=open("cfg.json","w")
json.dump(cfg,jsonfile,indent=4)
jsonfile.close()
except Exception:
print(cfg)
print('保存cfg出现错误,已打印cfg内容')
def toimg(msg,imgpath='./chace/mainbg.png',f1=fl1,f2=fl2,PZ=False,savepath='./chace/out.png',SIZE=30,COLOR = "#ffffff"): #文字转图片
'''
input:
msg:str 输入文字
imgpath:str 图片路径
f1:str 字体1路径
f2:str 字体2路径
'''
msg = msg.replace('\n','').replace('\r','')
img = Im.open(imgpath).convert('RGBA')
global x,y,mx,my,mmx,mmy,size,color,pz,function_time,for_time,text_time,text_list,function_list,for_list,lispuimg,functionlist
for i in ['text_list' , 'function_list' , 'for_list' , 'lispuimg' , 'functionlist']:exec(i+'=[]',globals())
for i in ['y' , 'x' , 'my' , 'mx','function_time','for_time','text_time']:exec(i+'=0',globals())
pz = PZ
size = SIZE
color = COLOR
mmx = img.size[0]
mmy = img.size[1]
textmmy = mmy
efunction = False
f = ''
img = Im.open(imgpath)
textimg = Im.new('RGBA', img.size, (0,0,0,0))
for i in msg: # 遍历所有文字,探测\指令,输出所有文字占图片最大宽 高
function_s = Time.time()
if efunction == False and eq(i,"\\"): #探测到 \ 则进入功能模式
efunction=True
functionlist=[]
continue
elif efunction == True: #功能模式
if eq(i,"\\"): #在功能模式下再次探测到 \ 则退出功能模式
efunction = False
text = ''.join(functionlist)
if text.startswith("n"): #n:换行
if x + size > mx: mx = x + size
if y + size > my: my = y + size
text = text[1:]
if text.isdigit():x = int(text) #n<int> 换行并使x = int
if text.startswith('s'):x = x #ns 换行并保持x
else: x = 0
y += size
if x + size > mx: mx = x + size
if y + size > my: my = y + size
elif text.startswith("b"):size = int(text[1:]) #b<int>:文字大小
elif text.startswith('#'):color = text ##<16进制颜色>:文字颜色
elif text.startswith('x'):#x<x/y>(-/>)<int> : xy 绝对/相对值修改
text = text[1:]
if text.startswith('x'):
text = text[1:]
if text.startswith('-'):x -= int(text[1:])
elif text.startswith('>'):x = int(text[1:])
else: x += int(text)
elif text.startswith('y'):
text = text[1:]
if text.startswith('-'):y -= int(text[1:])
elif text.startswith('>'):y = int(text[1:])
else: x += int(text)
if x + size > mx: mx = x + size
if y + size > my: my = y + size
elif text.startswith('p'): #p<图片路径>: 添加图片
print(x,y)
putpath = text[1:]
putimg = Im.open(putpath).convert('RGBA')
putmx = putimg.size[0]
putmy = putimg.size[1]
layer = Im.new('RGBA', textimg.size, (0,0,0,0)) #空图层 原图大小
layer.paste(putimg,(math.floor(x),math.floor(y))) #空图层插入putimg
textimg = Im.composite(layer, textimg, layer) #图层与原图合并
if pz == True:
putpath = text[1:]
xin = x
xout = x + putmx
yin = y
yout = y + putmy
if yout > my: my = yout + size
if xout > mx: mx = xout + size
x = x + putmx + 1
putdata = {"xin":xin,"xout":xout,"yin":yin,"yout":yout} #因为该图片而产生的文字禁区:(xin,yin),(xout,yout)
print(putdata,x,y)
lispuimg.append(putdata) #所有图片的文字禁区
elif text.startswith('d'): #p<字典>: 变量修改(可用该功能一次性修改 x y color size 等等)
if x + size > mx: mx = x + size
if y + size > my: my = y + size
testx = 0
text = text[1:]
print(text)
dict_ing = json.loads(text)
print('修改:',dict_ing)
globals().update(dict_ing)
print(testx)
functionlist=[]
continue
functionlist.append(i) #退出后保存功能模式下所探测的文字到 functionlist
continue
function_e = Time.time()
function_list.append(function_e - function_s)
text_s = Time.time()
if i >= u'\u4e00' and i <= u'\u9fa5' or i >= u'\u3040' and i <= u'\u31FF':#中文
fx = size
f = f1
else: #如果是英文,使用英文字体,并每次x跃进时只会跃进半个文字大小
fx = size / 2
f = f2
ImageDraw.Draw(textimg).text((x+2, y-6),i,font=ImageFont.truetype(f,size),fill="#000000",direction=None)
ImageDraw.Draw(textimg).text((x, y-8),i,font=ImageFont.truetype(f,size),fill=color,direction=None) #文字
x += fx
text_e = Time.time()
text_list.append(text_e - text_s)
for_s = Time.time()
for r in range(maximgpass): #在 单个文字能跨过(图片中的)图片的最多次数 内循环
code = False
if pz == True:
for i in lispuimg: #文字撞到(图片中的)图片则跃进图片宽度
if i['xin'] <= x < i['xout'] and i['yin'] <= y < i['yout']:
print('撞到图片啦:',x,y,i['xin'],i['xout'])
x = i['xout'] + size
code = True
break
if i['xin'] <= x + size < i['xout'] and i['yin'] <= y < i['yout']:
print('撞到图片啦:',x,y,i['xin'],i['xout'])
x = i['xout'] + size
code = True
break
if i['xin'] <= x < i['xout'] and i['yin'] <= y + size < i['yout']:
print('撞到图片啦:',x,y,i['xin'],i['xout'])
x = i['xout'] + size
code = True
break
if i['xin'] <= x + size < i['xout'] and i['yin'] <= y + size < i['yout']:
print('撞到图片啦:',x,y,i['xin'],i['xout'])
x = i['xout'] + size
code = True
break
if x + size / 2 > mmx : #文字撞到边缘则换行
if x + size > mx: mx = x + size
if y + size > my: my = y + size
x = 0
y += size
code = True
if code == False : break #跳出循环
if my + 2*size > textmmy :
textmmy += 4 * size
textimg = textimg.crop((0,0,mmx,textmmy))
for_e = Time.time()
for_list.append(for_e - for_s)
if x > mx: mx = x + size
if y > my: my = y + size
if my == 0:mx = x + size
if my == 0:my += size
print('mx:' + str(mx) + "|my:" + str(my))
ly = (mmy - my) / 2
img = img.crop((0,ly,mx,ly+my))
layer = Im.new('RGBA', img.size, (0,0,0,0)) #空图层 原图大小
layer.paste(textimg,(0,0)) #空图层插入putimg
img = Im.composite(layer, img, layer) #图层与原图合并
img.save(savepath)
for i in for_list:for_time += i
for i in function_list:function_time += i
for i in text_list:text_time += i
print('function用时:',function_time)
print('写入文字用时:',text_time)
print('碰撞箱用时:',for_time)
loop.create_future()
@bcc.receiver("GroupMessage")
async def group_listener(app: GraiaMiraiApplication, message:MessageChain, group: Group, member:Member ): #群聊监听
msg = message.asDisplay()
if message.has(Xml):
txml = str(message.get(Xml))
print(txml)
if message.has(Json):
tjson = str(message.get(Json))
print(tjson)
if message.has(App):
tapp = str(message.get(App))
print(tapp)
if message.has(Plain):
tmsg = str(message.get(Plain)[0].text)
if msg.startswith('#bot'):
sendgroup=xmlimg_group
msg = msg.replace('#bot','')
else : sendgroup = group.id
#图片
if message.has(Image):
timg = message.get(Image)[0].url
print(timg)
if message.has(At):
# at机器人功能
if message.get(At)[0].target == bot_qq and group.id in setu_group:
#├<@机器人> <Img> |以图搜图
await app.sendGroupMessage(sendgroup, MessageChain.create([At(member.id), Plain("选择搜索源:\n1.saucenao\n2.ascii2d.net")]))
@Waiter.create_using_function([GroupMessage])
def waiter(
event: GroupMessage, waiter_group: Group,
waiter_member: Member, waiter_message: MessageChain
):
msg = waiter_message.asDisplay()
mode = 0
if all([
waiter_group.id == group.id,
waiter_member.id == member.id,
msg != ''
]):
if all([ len(msg) == 1 , msg.isdigit() ]):
mode = int(msg)
elif msg.startswith('sau'): mode = 1
elif msg.startswith('asc'): mode = 2
if mode != 0:
return mode
global stime
stime = Time.time()
mode = await inc.wait(waiter)
imgpath = './sh.png'
debug('WITE:',timg)
await DF.adf(timg,imgpath)
image = Im.open(imgpath)
mmx = image.size[0]
mmy = image.size[1]
await DF.resize(imgpath,360,180)
fromt = 'none'
ilist = []
if mode == 1:
fromt = 'saucenao'
print('以图搜图sau')
url = "https://saucenao.com/search.php?output_type=2&api_key=$key&testmode=1&db=999&numres=5&url=$url".replace('$url',timg).replace('$key',saucenao_key)
print(url)
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.json()
except:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.json()
data = data['results']
ilist = []
n = 0
for i in data:
idata = {}
n += 1
outlinks = []
linkdata = {}
try:linkdata['str'] = i['data']['title']
except:linkdata['str'] = 'none'
try:linkdata['url'] = i['data']['ext_urls'][0]
except:linkdata['url'] = 'none'
outlinks.append(linkdata)
linkdata = {}
try:linkdata['str'] = i['data']['member_name']
except:linkdata['str'] = 'none'
try:linkdata['url'] = 'https://www.pixiv.net/users/uid'.replace('uid',i['data']['member_id'])
except:linkdata['url'] = 'none'
outlinks.append(linkdata)
idata['from'] = i['header']['index_name'][10:]
idata['links'] = outlinks
idata['img'] = i['header']['thumbnail']
ilist.append(idata)
elif mode == 2:
fromt = 'ascii2d'
url = 'https://ascii2d.net/search/url/$url'.replace('$url',timg)
print('请求api:',url)
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
data = await resp.text()
soup = BeautifulSoup(data,'html.parser') #html.parser是解析器,也可是lxml
a = soup.find_all('div',attrs={"class": "row item-box"},limit=10)
ilist = []
n = 0
for i in a:
if n == 0 :
n += 1
continue
idata = {}
outlinks = []
try:outi = i.find_all('img',attrs={"loading": "eager"})[0]['src']
except:outi = i.find_all('img',attrs={"loading": "lazy"})[0]['src']
try:outlink = i.find_all('a',attrs={'target':"_blank"})
except:outlink = 'none'
try:small = i.find_all('small')[-1].string
except:small = 'none'
small = small.replace('\n','').replace('\r','').replace(' ','')
for _ in outlink:
linkdata = {}
linkdata['str'] = _.string
linkdata['url'] = _['href']
if linkdata == {} : linkdata['str'] = '详情不存在'
outlinks.append(linkdata)
idata['img'] = outi
idata['links'] = outlinks
idata['from'] = small
ilist.append(idata)
startmap = Search_map\
.replace('$from(17)////////',await rep(17,fromt))\
.replace('$s180x360', imgpath)
n = 0
outmsg = startmap
n = 0
tasks = []
for i in ilist:
n += 1
url = i['img']
if url.startswith('/thumbnail/'):url = 'https://ascii2d.net' + url
img_ing = './chace/' + str(n) + '.png'
task = asyncio.ensure_future(DF.adf(url,img_ing,resize=[240,120],resize_r=True))
tasks.append(task)
try:title = await rep(13,i['links'][0]['str'])
except:title =await rep(13,'None')
try:user = await rep(13,i['links'][1]['str'])
except:user =await rep(13,'None')
try:fromi = await rep(9,i['from'])
except:fromi =await rep(9,'None')
map_ing = Search_map2\
.replace('$i120x240',img_ing + '\\' + str(n) + '.')\
.replace('$title(13)///','\\xx>300\\'+ title)\
.replace('$user(13)///','\\xx>510\\'+ user)\
.replace('$from(9)/','\\xx>720\\'+fromi)
outmsg = outmsg + map_ing
outmsg = outmsg + aks_map3
path = './chace/bg_l.png'
path2 ='./chace/bg_d.png'
await asyncio.gather(*tasks)
await DF.resize(path,915,1560)
img = cv2.imread(path, -1)
fx = fy = 1
img = cv2.resize(img, (0, 0), fx=fx, fy=fy, interpolation=cv2.INTER_CUBIC)
img = cv2.GaussianBlur(img,(13,13),0)
cv2.imwrite(path2, img)
cv2.waitKey(0)
toimg(outmsg,path2)
#if cfg['xml'] == 1:
# setudata = {}
# setudata['img'] = './chace/out.png'