-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1219 lines (1027 loc) · 46.5 KB
/
main.py
File metadata and controls
1219 lines (1027 loc) · 46.5 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
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
import asyncio
import botpy
from botpy import BotAPI
from botpy.ext.command_util import Commands
from botpy.manage import GroupManageEvent
from botpy.message import GroupMessage
import IPy
import time
import sqlite3
from datetime import datetime
import aiohttp
import random
import requests
import json
from mcrcon import MCRcon
from openai import OpenAI
import re
import socket
import r
_log = botpy.logging.get_logger()
session: aiohttp.ClientSession
async def on_ecustmc_backend_error(message: GroupMessage):
await message.reply(content=f"服务无响应,请稍后再试,若此问题依然存在,请联系机器人管理员")
@Commands("/校园天气")
async def query_weather(api: BotAPI, message: GroupMessage, params=None):
async with aiohttp.ClientSession() as session:
fx_res, xh_res = await asyncio.gather(
session.get(f"https://restapi.amap.com/v3/weather/weatherInfo?city=310120&key=" + r.weather_api_token),
session.get(f"https://restapi.amap.com/v3/weather/weatherInfo?city=310104&key=" + r.weather_api_token)
)
if fx_res.ok:
fx_result = await fx_res.json()
xh_result = await xh_res.json()
if fx_result.get("status") == "1" and "lives" in fx_result and len(fx_result["lives"]) > 0:
fx_live_data = fx_result["lives"][0]
xh_live_data = xh_result["lives"][0]
fx_weather = fx_live_data.get("weather", "N/A")
fx_temperature = fx_live_data.get("temperature", "N/A")
fx_winddirection = fx_live_data.get("winddirection", "N/A")
fx_windpower = fx_live_data.get("windpower", "N/A")
fx_humidity = fx_live_data.get("humidity", "N/A")
xh_weather = xh_live_data.get("weather", "N/A")
xh_temperature = xh_live_data.get("temperature", "N/A")
xh_winddirection = xh_live_data.get("winddirection", "N/A")
xh_windpower = xh_live_data.get("windpower", "N/A")
xh_humidity = xh_live_data.get("humidity", "N/A")
reporttime = fx_live_data.get("reporttime", "N/A")
reply_content = (
f"\n"
f"奉贤校区:\n"
f"天气:{fx_weather}\n"
f"温度:{fx_temperature}\n"
f"风向:{fx_winddirection}\n"
f"风力:{fx_windpower}\n"
f"湿度:{fx_humidity}\n"
f"\n"
f"徐汇校区:\n"
f"天气:{xh_weather}\n"
f"温度:{xh_temperature}\n"
f"风向:{xh_winddirection}\n"
f"风力:{xh_windpower}\n"
f"湿度:{xh_humidity}\n"
f"更新时间:{reporttime}"
)
await message.reply(content=reply_content)
else:
error_content = "查询失败,响应数据不正确"
await message.reply(content=error_content)
else:
error_content = "查询失败,无法连接到天气服务"
await message.reply(content=error_content)
return True
@Commands("/服务器状态")
async def query_ecustmc_server(api: BotAPI, message: GroupMessage, params=None):
# 假设 r.mc_servers 包含了服务器列表,用逗号分隔
server_list = r.mc_servers.split(",")
reply_content = ""
# 遍历每个服务器并查询状态
for server in server_list:
server = server.strip() # 去除两端的空格
if not server:
continue
if server == "mcmod.ecustvr.top":
headers = {'User-Agent': 'ecustmc-qqbot/1.0 (https://cnb.cool/ecustmc/ecustmc-qqbot)'}
async with session.get(f"https://api.mcsrvstat.us/2/{server}", headers=headers) as res:
server_info = await res.json()
server=server.replace('.', '-')
if server_info.get('online'):
players_online = server_info['players']['online']
players_max = server_info['players']['max']
description = server_info['motd']['raw'][0]
sample_players = server_info.get('players', {}).get('list', [])
version = server_info.get('version', 'N/A')
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 拼接每个服务器的状态信息
reply_content += (
f"\n"
f"服务器地址: {server}\n"
f"描述: {description}\n"
f"在线玩家: {players_online}/{players_max}\n"
f"版本: {version}\n"
f"查询时间: {timestamp}\n"
)
# 如果有在线玩家,显示他们的名字
if players_online > 0 and sample_players:
reply_content += "正在游玩:\n"
for player in sample_players:
player_name = player
reply_content += f"- {player_name}\n"
reply_content += "-----------------------------\n"
else:
reply_content += (
f"\n查询 {server} 服务器信息失败,1分钟后再试\n"
f"状态码: {res.status}\n"
)
else:
async with session.post(f"https://mc.sjtu.cn/custom/serverlist/?query={server}") as res:
result = await res.json()
if res.ok:
server_info = result
server=server.replace('.', '-')
description_raw = server_info.get('description_raw', {})
if isinstance(description_raw, str):
description_raw = {"text": description_raw}
description = description_raw.get('text', description_raw.get('translate', server_info.get('description', {}).get('text', '无描述')))
if "服务器已离线..." in description:
description = description.replace("...", "或查询失败")
players_max = server_info.get('players', {}).get('max', '未知')
players_online = server_info.get('players', {}).get('online', '未知')
sample_players = server_info.get('players', {}).get('sample', [])
version = server_info.get('version', '未知')
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 拼接每个服务器的状态信息
reply_content += (
f"\n"
f"服务器地址: {server}\n"
f"描述: {description}\n"
f"在线玩家: {players_online}/{players_max}\n"
f"版本: {version}\n"
f"查询时间: {timestamp}\n"
)
# 如果有在线玩家,显示他们的名字
if players_online > 0 and sample_players:
reply_content += "正在游玩:\n"
for player in sample_players:
player_name = player.get('name', '未知')
reply_content += f"- {player_name}\n"
reply_content += "-----------------------------\n"
else:
reply_content += (
f"\n查询 {server} 服务器信息失败\n"
f"状态码: {res.status}\n"
)
# 发送回复
if not reply_content:
reply_content = "未查询到任何服务器信息"
reply_content += "⚠️由于QQAPI限制,服务器地址中间的“-”请自行换成“.”!"
await message.reply(
content=reply_content,
msg_type=0
)
return True
@Commands("/一言")
async def daily_word(api: BotAPI, message: GroupMessage, params=None):
daily_word = f"https://v1.hitokoto.cn/"
async with session.post(daily_word) as res:
result = await res.json()
if res.ok:
content = result['hitokoto']
author_from = result['from']
author = result['from_who']
if author != author_from and author != None:
author_from = f"{author}《{author_from}》"
reply_content = (
f"\n"
f"{content}"
f"\n"
f"——{author_from}"
)
await message.reply(content=reply_content)
else:
error_content = (
f"获取一言失败"
)
await message.reply(content=error_content)
return True
@Commands("/今日黄历")
async def daily_huangli(api: BotAPI, message: GroupMessage, params=None):
# 获取当前日期
current_date = time.strftime("%Y%m%d", time.localtime())
# 构建 API 请求 URL
daily_huangli = f"https://www.mxnzp.com/api/holiday/single/{current_date}?ignoreHoliday=false&app_id={r.api_app_id}&app_secret={r.api_app_secret}"
# 发送请求
async with aiohttp.ClientSession() as session:
async with session.get(daily_huangli) as res:
# 解析响应 JSON 数据
result = await res.json()
if res.ok and result['code'] == 1: # 检查响应是否成功
# 获取所需的黄历内容
data = result['data']
date = data.get('date', '未知')
type_des = data.get('typeDes', '未知')
chinese_zodiac = data.get('chineseZodiac', '未知')
lunar_calendar = data.get('lunarCalendar', '未知')
suit = data.get('suit', '无宜')
avoid = data.get('avoid', '无忌')
constellation = data.get('constellation', '未知')
solar_terms = data.get('solarTerms', '未知')
# 拼接黄历内容
reply_content = (
f"\n"
f"📅 日期: {date}\n"
f"🀄 农历: {lunar_calendar}\n"
f"💫 星座: {constellation}\n"
f"🌞 节气: {solar_terms}\n"
f"🐉 生肖: {chinese_zodiac}\n"
f"📌 类型: {type_des}\n"
f"✅ 宜: {suit}\n"
f"❌ 忌: {avoid}\n"
)
# 发送回复
await message.reply(content=reply_content)
else:
# 错误处理
await message.reply(content="获取黄历失败")
return True
@Commands("/今日运势")
async def jrys(api: BotAPI, message: GroupMessage, params=None):
conn = sqlite3.connect('user_numbers.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_numbers (
user_id TEXT PRIMARY KEY,
random_number INTEGER,
number INTEGER,
date TEXT
)
''')
conn.commit()
with open('jrys.json', 'r', encoding='utf-8') as file:
jrys_data = json.load(file)
def get_fortune_number(lucky_star):
star_count = lucky_star.count('★')
if star_count == 0:
return random.randint(0, 10)
elif star_count == 1:
return random.randint(5, 15)
elif star_count == 2:
return random.randint(10, 25)
elif star_count == 3:
return random.randint(25, 40)
elif star_count == 4:
return random.randint(40, 55)
elif star_count == 5:
return random.randint(55, 70)
elif star_count == 6:
return random.randint(70, 85)
elif star_count == 7:
return random.randint(85, 100)
else:
return None
def get_user_number(user):
today_date = datetime.now().strftime('%Y-%m-%d')
cursor.execute('SELECT random_number, number FROM user_numbers WHERE user_id = ? AND date = ?',
(user, today_date))
row = cursor.fetchone()
if row:
random_number = row[0]
number = row[1]
fortune_data = jrys_data[str(random_number)][0]
else:
while True:
random_number = random.randint(1, 1433)
fortune_data = jrys_data.get(str(random_number))
if fortune_data:
fortune_data = fortune_data[0]
lucky_star = fortune_data['luckyStar']
number = get_fortune_number(lucky_star)
if number is not None:
break
cursor.execute('''
INSERT OR REPLACE INTO user_numbers (user_id, random_number, number, date)
VALUES (?, ?, ?, ?)
''', (user, random_number, number, today_date))
conn.commit()
return random_number, number, fortune_data
user = f"{message.author.member_openid}"
random_number, assigned_number, fortune_data = get_user_number(user)
reply = (
f"\n"
f"今日运势:{fortune_data['fortuneSummary']}\n"
f"幸运星象:{fortune_data['luckyStar']}\n"
f"运势评述:{fortune_data['signText']}\n"
f"评述解读:{fortune_data['unSignText']}"
)
await message.reply(content=reply)
return True
@Commands("/今日人品")
async def jrrp(api: BotAPI, message: GroupMessage, params=None):
conn = sqlite3.connect('user_numbers.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_numbers (
user_id TEXT PRIMARY KEY,
random_number INTEGER,
number INTEGER,
date TEXT
)
''')
conn.commit()
with open('jrys.json', 'r', encoding='utf-8') as file:
jrys_data = json.load(file)
def get_fortune_number(lucky_star):
star_count = lucky_star.count('★')
if star_count == 0:
return random.randint(0, 10)
elif star_count == 1:
return random.randint(5, 15)
elif star_count == 2:
return random.randint(10, 25)
elif star_count == 3:
return random.randint(25, 40)
elif star_count == 4:
return random.randint(40, 55)
elif star_count == 5:
return random.randint(55, 70)
elif star_count == 6:
return random.randint(70, 85)
elif star_count == 7:
return random.randint(85, 100)
else:
return None
def GetRangeDescription(score:int) -> str :
if score==0:
return "这运气也太差了吧???该不会是。。。。"
if score==66:
return "恭喜哦,抽到了隐藏彩蛋,六六大顺,666666666"
if score==88:
return "恭喜哦,抽到了隐藏彩蛋,发发发发,888888888"
if score==69:
return "这是什么意思啊,69696969696969696,哈哈哈哈哈哈哈哈哈"
if score==100:
return ""
if score>0 and score<10:
return "好烂的运气啊,大概率你今天买泡面没调料没叉子,点外卖没餐具。"
if score>=10 and score<20:
return "好烂的运气啊,大概率你今天买泡面没调料没叉子,点外卖没餐具。"
if score>=20 and score<30:
return "也许今天更适合摆烂。"
if score>=30 and score<40:
return "运气一般般啊,平平淡淡没什么新奇。"
if score>=40 and score<50:
return "运气不好不差,钻石矿可能比较难挖到。"
if score>=50 and score<60:
return "运气处于正态分布的中部,今天适合玩MC服。"
if score>=60 and score<70:
return "运气不好不差,今天就别开箱子了。"
if score>=70 and score<80:
return "今天你将会拥有非凡的一天。"
if score>=80 and score<90:
return "运气还不错,看起来一切都很顺利。"
if score>=90 and score<100:
return "运气真不错,今天适合抽卡。"
def get_user_number(user):
today_date = datetime.now().strftime('%Y-%m-%d')
cursor.execute('SELECT random_number, number FROM user_numbers WHERE user_id = ? AND date = ?',
(user, today_date))
row = cursor.fetchone()
if row:
random_number = row[0]
number = row[1]
fortune_data = jrys_data[str(random_number)][0]
else:
while True:
random_number = random.randint(1, 100)
fortune_data = jrys_data.get(str(random_number))
if fortune_data:
fortune_data = fortune_data[0]
lucky_star = fortune_data['luckyStar']
number = get_fortune_number(lucky_star)
if number is not None:
break
cursor.execute('''
INSERT OR REPLACE INTO user_numbers (user_id, random_number, number, date)
VALUES (?, ?, ?, ?)
''', (user, random_number, number, today_date))
conn.commit()
return number
user = f"{message.author.member_openid}"
assigned_number = get_user_number(user)
reply = f"今日人品值:{assigned_number},{GetRangeDescription(int(assigned_number))}"
await message.reply(content=reply)
return True
import urllib.parse
@Commands("/wiki")
async def wiki(api: BotAPI, message: GroupMessage, params=None):
if params:
# 获取指令后的关键字
query = ''.join(params)
# 对查询关键词进行URL编码
encoded_query = urllib.parse.quote(query)
# 生成Wiki链接
wiki_link = f"https://mc.ecustvr.top/wiki/{encoded_query}"
reply_content = f"\n📚 你可以查看相关信息: \n🔗点击访问Wiki:{wiki_link}"
await message.reply(content=reply_content)
else:
await message.reply(content="⚠️ 请提供要查询的Wiki页面关键字!例如 /wiki 门")
return True
@Commands("/添加服务器")
async def add_server(api: BotAPI, message: GroupMessage, params=None):
if params:
new_server = ''.join(params).strip()
# 获取当前服务器列表
current_servers = r.mc_servers.split(",")
# 检查服务器是否已经存在
if new_server in current_servers:
await message.reply(content=f"服务器已存在")
return True
# 添加新服务器并更新 .env 文件
current_servers.append(new_server)
updated_servers = ','.join(current_servers)
r.update_env_variable("MC_SERVERS", updated_servers)
# 更新 r.py 中的 mc_servers
r.mc_servers = updated_servers
new_server = new_server.replace('.', '-')
await message.reply(content=f"服务器 {new_server} 已添加")
else:
await message.reply(content="⚠️ 请提供要添加的服务器地址!")
return True
@Commands("/移除服务器")
async def remove_server(api: BotAPI, message: GroupMessage, params=None):
if params:
server_to_remove = ''.join(params).strip()
# 获取当前服务器列表
current_servers = r.mc_servers.split(",")
# 检查服务器是否存在
if server_to_remove not in current_servers:
await message.reply(content=f"服务器不存在")
return True
# 删除服务器并更新 .env 文件
current_servers.remove(server_to_remove)
updated_servers = ','.join(current_servers)
r.update_env_variable("MC_SERVERS", updated_servers)
# 更新 r.py 中的 mc_servers
r.mc_servers = updated_servers
server_to_remove = server_to_remove.replace('.','-')
await message.reply(content=f"服务器 {server_to_remove} 已删除")
else:
await message.reply(content="⚠️ 请提供要删除的服务器地址!")
return True
@Commands("/塔罗牌")
async def query_tarot(api: BotAPI, message: GroupMessage, params=None):
# 加载塔罗牌数据
with open('Tarots.json', 'r', encoding='utf-8') as file:
tarots = json.load(file)
# 从塔罗牌列表中随机选择一张塔罗牌
card_number = random.choice(list(tarots.keys()))
tarot_card = tarots[card_number]
# 获取塔罗牌信息
name = tarot_card['name']
description = tarot_card['info']['description']
reverse_description = tarot_card['info']['reverseDescription']
img_url = "http://www.ecustvr.top/"
img_url += tarot_card['info']['imgUrl']
# 随机决定正位还是逆位
is_reverse = random.choice([True, False])
if is_reverse:
description_to_use = f"逆位:{reverse_description}"
else:
description_to_use = f"正位:{description}"
# 上传图片
uploadmedia = await api.post_group_file(
group_openid=message.group_openid,
file_type=1,
url=img_url
)
# 构建回复内容
reply_content = (
f"\n"
f"塔罗牌:{name}\n"
f"{description_to_use}"
)
# 发送消息
await message.reply(
content=reply_content,
msg_type=7,
media=uploadmedia
)
return True
@Commands("vv")
async def query_vv(api: BotAPI, message: GroupMessage, params=None):
# 如果没有提供查询参数,读取vv.txt文件获取表情名
if not params:
with open('vv.txt', 'r', encoding='utf-8') as file:
emote_list = file.readlines()
emote_name = random.choice(emote_list).strip()
# 拼接完整的URL
encoded_emote_name = urllib.parse.quote(emote_name)
emote_url = f"https://cn-nb1.rains3.com/vvq/images/{encoded_emote_name}"
else:
# 有查询参数,构建请求负载
query = params
encoded_query = urllib.parse.quote(query) # 对查询参数进行URL编码
async with aiohttp.ClientSession() as session:
url = f'https://api.zvv.quest/search?q={encoded_query}&n=5'
async with session.get(url) as response:
# 解析返回的JSON数据
result = await response.json()
emote_url = random.choice(result["data"]) # 从返回的列表中随机选择一个表情包文件名
emote_name = urllib.parse.unquote(emote_url.split('/')[-1].rstrip('.png')) # 获取表情包文件名
# 上传表情包图片
uploadmedia = await api.post_group_file(
group_openid=message.group_openid,
file_type=1,
url=emote_url
)
# 构建回复内容
reply_content = (
f"\n"
f"{emote_name.rstrip('.png')}"
)
# 发送消息
await message.reply(
content=reply_content,
msg_type=7,
media=uploadmedia
)
return True
@Commands("/求签")
async def query_divinatory_symbol(api: BotAPI, message: GroupMessage, params=None):
# 加载卦象数据
with open('DivinatorySymbols.json', 'r', encoding='utf-8') as file:
divinatory_symbols = json.load(file)
# 从卦象列表中随机选择一个卦象
symbol_number = random.choice(list(divinatory_symbols.keys()))
divinatory_symbol = divinatory_symbols[symbol_number]
# 获取卦象信息
name = divinatory_symbol['name']
description = divinatory_symbol['info']['description']
level = divinatory_symbol['info']['level']
# 构建回复内容
reply_content = (
f"\n"
f"卦象: {name}\n"
f"等级: {level}\n"
f"解读: \n{description}"
)
# 发送消息
await message.reply(content=reply_content)
return True
@Commands("/帮助")
async def help(api: BotAPI, message: GroupMessage, params=None):
help_content = (
"\n👋 欢迎新人!\n"
"为了享受更好的游戏体验,请先注册皮肤站账号。\n"
"🔗 访问链接: https://mcskin.ecustvr.top/auth/register\n"
"通过这个站点,你可以自定义和上传你的皮肤,使用联合认证账号登录游戏,便可进入使用 Union 联合认证的其他高校的 Minecraft 服务器游玩,或登录到支持 Union OAuth 登录的网站。\n"
"更多关于游戏、启动器及账号配置等,欢迎访问 🔗萌新指南:https://mc.ecustvr.top/tutorial/\n"
"更多关于bot指令的帮助,欢迎访问 🔗QQBot:https://mc.ecustvr.top/qqbot/,祝游戏愉快!"
)
await message.reply(content=help_content)
return True
@Commands("/ip")
async def query_ip_info(api: BotAPI, message: GroupMessage, params=None):
ip = "".join(params).strip() if params else None
def is_ipv4(ip):
pattern = re.compile(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
return pattern.match(ip) is not None
def checkip(address):
try:
version = IPy.IP(address).version()
if version == 4 or version == 6:
return True
else:
return False
except Exception as e:
return False
def resolve_domain(domain):
try:
# 获取所有地址信息
addresses = socket.getaddrinfo(domain, None)
# 提取所有IP地址
ip_addresses = list(set(addr[4][0] for addr in addresses)) # 去重
return ip_addresses
except socket.gaierror:
return None
def query_ipv4(ip):
api_url = f"https://ip.ecust.icu/find?ip={ip}"
response = requests.get(api_url)
if response.status_code == 200:
result = response.json()
if result.get("code") == 200:
query = result["data"]["query"]
isp = query.get("isp", "未知ISP")
locale = query.get("locale", "未知地区")
return f"IPv4 地址 {ip} 的查询结果:\nISP: {isp}\n地区: {locale}\nPowered by Eric"
else:
return f"查询 IPv4 地址 {ip} 失败:{result.get('msg', '未知错误')}"
else:
return f"调用 IPv4 查询接口失败,状态码: {response.status_code}"
def query_ipv6(ip):
api_url = f"https://ip.zxinc.org/api.php?type=json&ip={ip}"
response = requests.get(api_url)
if response.status_code == 200:
result = response.json()
if result.get("code") == 0:
location = result["data"].get("location", "未知地区")
return f"IPv6 地址 {ip} 的查询结果:\n位置: {location}"
else:
return f"查询 IPv6 地址 {ip} 失败:{result.get('msg', '未知错误')}"
else:
return f"调用 IPv6 查询接口失败,状态码: {response.status_code}"
try:
if not ip:
model_response = "请输入要查询的IP地址或域名"
else:
if not checkip(ip):
ips = resolve_domain(ip)
if not ips:
model_response = "输入的 IP地址/域名 格式不正确或无法解析,请输入有效的 IPv4/IPv6 地址或域名。"
else:
results = []
for current_ip in ips:
if is_ipv4(current_ip):
results.append(query_ipv4(current_ip))
else:
results.append(query_ipv6(current_ip))
model_response = "\n\n".join(results)
else:
if is_ipv4(ip):
model_response = query_ipv4(ip)
else:
model_response = query_ipv6(ip)
await message.reply(content=model_response)
except Exception as e:
await message.reply(content=f"查询 IP 信息时发生错误: {str(e)}")
return True
@Commands("/nslookup")
async def query_domain_info(api: BotAPI, message: GroupMessage, params=None):
ip = "".join(params).strip() if params else None
if not ip:
await message.reply(content="请输入有效的域名或 IP 地址。")
return True
try:
# 获取所有地址信息
addresses = socket.getaddrinfo(ip, None)
# 提取 IP 地址
ip_addresses = list(set([addr[4][0] for addr in addresses]))
ip_addresses_str = ", ".join(ip_addresses)
await message.reply(content="查询到的 IP 地址有:" + ip_addresses_str)
except socket.gaierror:
await message.reply(content="无效的域名或 IP 地址,请检查后重试。")
return True
@Commands("/ping")
async def ping_info(api: BotAPI, message: GroupMessage, params=None):
domain = "".join(params).strip() if params else None
if not domain:
await message.reply(content="请输入有效的域名或 IP 地址。")
else:
# 设置url
url = 'https://api.tjit.net/api/ping/v2?key='+r.tjit_key+'&type=node'
# 发送post请求
response = requests.post(url)
# 获取响应内容
result = response.json()["data"][-1]["node"]
random_node = random.sample(range(1, result), 6)
ping_content = '\nping测试结果为(随机6节点):\n'
for i in random_node:
url = 'https://api.tjit.net/api/ping/v2?key='+r.tjit_key+'&node='+str(i)+'&host='+domain
response = requests.post(url)
result = response.json()
if 'time' in result['data']:
ping_content += f"{result['data']['node_name']}-{result['data']['node_isp']}:{result['data']['time']}\n"
else:
ping_content += f"{result['data']['node_name']}-{result['data']['node_isp']}:{result['data']['msg']}\n"
await message.reply(content=ping_content)
return True
@Commands("/mc")
async def query_mc_command(api: BotAPI, message: GroupMessage, params=None):
# 通过 r 获取 RCON 密码
rcon_password = r.mc_rcon_password
rcon_host = r.mc_server
rcon_port = int(r.mc_rcon_port)
if not params:
await message.reply(content="请提供 Minecraft 服务器命令(say/list/永昼机/关闭永昼机)")
else:
# 直接使用 params 作为 Minecraft 命令
mc_command = params
if mc_command == "永昼机":
# 特殊处理命令为“永昼机”的情况
try:
with MCRcon(rcon_host, rcon_password, port=rcon_port) as mcr:
# 执行多个命令
mcr.command("player bot_sleep spawn at -3200 55 9370 facing -90 0 in minecraft:overworld")
mcr.command("player bot_sleep use interval 20")
await message.reply(content="永昼机已启动")
except Exception as e:
await message.reply(content=f"连接 Minecraft 服务器时发生错误: {str(e)}")
return True
if mc_command == "关闭永昼机":
# 特殊处理命令为“关闭永昼机”的情况
try:
with MCRcon(rcon_host, rcon_password, port=rcon_port) as mcr:
# 执行多个命令
mcr.command("player bot_sleep kill")
await message.reply(content="永昼机已关闭")
except Exception as e:
await message.reply(content=f"连接 Minecraft 服务器时发生错误: {str(e)}")
return True
if mc_command not in {"list"} and not any(mc_command.startswith(prefix) for prefix in ["say", "tp"]):
await message.reply(content="请提供合法的 Minecraft 服务器命令(say/list/永昼机/关闭永昼机)")
else:
try:
# 连接到 RCON 服务器
with MCRcon(rcon_host, rcon_password, port=rcon_port) as mcr:
# 发送命令并获取响应
response = mcr.command(mc_command)
# 回复命令执行的结果
await message.reply(content=f"消息已送达服务器\n{response}")
except Exception as e:
await message.reply(content=f"连接 Minecraft 服务器时发生错误: {str(e)}")
return True
@Commands("/status")
async def query_server_status(api: BotAPI, message: GroupMessage, params=None):
# API 地址
api_url = "http://mcsm.ecustvr.top/" # 替换为实际 API 地址
try:
# 获取服务器状态数据
response = requests.get(api_url)
if response.status_code != 200:
await message.reply(content=f"无法获取服务器状态,状态码: {response.status_code}")
return
data = response.json()
if data.get("status") != 200:
await message.reply(content="服务器返回了非正常状态的数据")
return
# 提取所需数据
system_info = data["data"][0]["system"]
# 系统信息展示
uptime = system_info["uptime"] / 3600
loadavg = system_info["loadavg"]
total_mem = system_info["totalmem"] / (1024 ** 3) # 转换为 GB
free_mem = system_info["freemem"] / (1024 ** 3) # 转换为 GB
cpu_usage_percent = system_info["cpuUsage"] * 100
mem_usage_percent = system_info["memUsage"] * 100
# 构建信息内容
info_message = (
f"服务器状态:\n"
f"运行时间: {uptime:.2f} 小时\n"
f"近期负载: {loadavg}\n"
f"总内存: {total_mem:.2f} GB\n"
f"可用内存: {free_mem:.2f} GB\n"
f"CPU 使用率: {cpu_usage_percent:.2f}%\n"
f"内存使用率: {mem_usage_percent:.2f}%"
)
# 回复状态信息
await message.reply(content=info_message)
except Exception as e:
await message.reply(content=f"查询服务器状态时发生错误: {str(e)}")
return True
@Commands("/dsr")
async def query_deepseek_r1(api: BotAPI, message: GroupMessage, params=None):
user_input = "".join(params) if params else "Hello world!"
try:
# 使用 OpenAI 类初始化客户端
client = OpenAI(api_key=r.baidu_api_key, base_url="http://oneapi.ecustvr.top/v1/")
# 调用大模型
completion = client.chat.completions.create(
model="deepseek-r1",
messages=[
{
"role": "user",
"content": user_input,
},
],
temperature=0.3,
)
# 提取并发送模型响应
model_reasoning_content = completion.choices[0].message.reasoning_content
model_response = completion.choices[0].message.content
await message.reply(content=f"Deepseek-R1:\n推理:\n{model_reasoning_content}\n回复:\n{model_response}")
except Exception as e:
# 错误处理
await message.reply(content=f"调用 Deepseek-R1 大模型时出错: {str(e)}")
return True
async def get_tenant_access_token(app_id: str, app_secret: str) -> str:
"""获取飞书访问令牌"""
url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
headers = {"Content-Type": "application/json"}
payload = {"app_id": app_id, "app_secret": app_secret}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=payload) as response:
data = await response.json()
if data.get("code") == 0:
return data["tenant_access_token"]
else:
print(f"获取飞书访问令牌失败: {data}")
return None
except Exception as e:
print(f"获取飞书访问令牌出错: {e}")
return None
async def fetch_groups_from_feishu(app_id: str, app_secret: str) -> list:
"""从飞书获取群组数据"""
token = await get_tenant_access_token(app_id, app_secret)
if not token:
return []
all_groups = []
page_token = None
has_more = True
try:
while has_more:
url = "https://open.feishu.cn/open-apis/bitable/v1/apps/Y9HBbtQoxawALxs3XK8cOY9pn8g/tables/tblVq51wR2ZPVax4/records/search?page_size=100"
if page_token:
url += f"&page_token={page_token}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
payload = {
"sort": [{"field_name": "类别", "desc": False}],
"filter": {
"conjunction": "and",
"conditions": [{
"field_name": "是否可信",
"operator": "is",
"value": ["true"]
}]
}
}
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=payload) as response:
data = await response.json()
if data.get("code") == 0:
for item in data["data"]["items"]:
fields = item["fields"]
# 处理群号
group_id = str(fields.get("QQ群号", ""))
# 处理加群链接