main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. from flask import Flask, request, abort, send_file
  2. import pandas as pd
  3. from openai import OpenAI
  4. import requests
  5. import time
  6. import re
  7. from wakeonlan import send_magic_packet
  8. from ai_pic import story_start, story_start_p2p, story_start_p2p_sese, story_start2
  9. from msg_send_save import (send_private_message_word,save_group_message,send_group_message_pic,send_group_message_word,
  10. send_group_poke,del_group_message,send_group_vioce)
  11. from chat_model import AI_chat,AI_get_picprompt,AI_lora_getpic_prompt,AI_sendphoto_ornot,get_ja_trans
  12. from special_date import get_week,get_v50,get_holidays
  13. from tts import get_free_tts,get_gpu_tts
  14. from config import config_get
  15. import random
  16. import os
  17. app = Flask(__name__)
  18. # 读取王石列表,存为stones数据df文件
  19. stones = pd.read_csv('other/stone.csv')
  20. if 'Unnamed: 0' in stones.columns:
  21. stones = stones.drop('Unnamed: 0', axis=1)
  22. for i in range(len(stones)):
  23. final_stat = "\n"
  24. abilities = stones.loc[i, 'stats'].split("&")
  25. for j in range(len(abilities)):
  26. ability = abilities[j].split("#")
  27. if ability[2] != "Nan":
  28. final_stat += ability[2]+":"
  29. if ability[0].endswith("%"):
  30. final_stat += ability[0].split("%")[0] + ability[1] +"% "
  31. else:
  32. final_stat += ability[0] + ability[1] + " "
  33. stones.loc[i,"stat"] = final_stat
  34. # QQ机器人基础板块,包括人格,绘图风格和名称自我意识
  35. my_name = config_get("my_name")
  36. prompt_max = config_get("prompt_max")
  37. prompt_less = config_get("prompt_less")
  38. # 一个比较没用的变量,用来限制绘画cd的,现在默认是0就是无cd
  39. last_request_time = 0
  40. # 最近一次的心跳上报时间,用来记录服务状态
  41. last_heartbeat_time = time.time()
  42. def on_my_message(group_id, user_id, user_name, raw_message, message):
  43. """
  44. 每次触发猫猫关键词,收到@使用这个方法来进行回应
  45. """
  46. global last_request_time
  47. # 先对解码后消息进行判断,如果第一个解码消息为@,则触发命令模式,遍历完成若没有命令触发则再触发人格对话
  48. if message[0]['type'] == "at" and message[1]['type'] == "text":
  49. command = message[1]['data']['text'].strip(" ")
  50. if str(command).startswith("/"):
  51. on_command(group_id, user_id, command)
  52. elif command=="v你50":
  53. print(send_group_message_pic(group_id, user_id, 'v50.png'))
  54. else:
  55. AI_ans = AI_chat(group_id, user_name+":"+raw_message, prompt_less)
  56. send_group_message_word(group_id, AI_ans)
  57. save_group_message(group_id, my_name, AI_ans)
  58. # 根据条件触发AI绘画
  59. if AI_sendphoto_ornot("猫猫:"+AI_ans) == "是":
  60. current_time = time.time()
  61. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  62. if current_time-last_request_time >= 0:
  63. last_request_time = current_time
  64. send_group_message_pic(group_id, user_id, story_start(AI_get_picprompt(group_id)))
  65. else:
  66. AI_ans = AI_chat(group_id, user_name + ":" + raw_message, prompt_less)
  67. send_group_message_word(group_id, AI_ans)
  68. save_group_message(group_id, my_name, AI_ans)
  69. # 根据条件触发AI绘画
  70. if AI_sendphoto_ornot(AI_ans) == "是":
  71. current_time = time.time()
  72. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  73. if current_time - last_request_time >= 0:
  74. last_request_time = current_time
  75. send_group_message_pic(group_id, user_id, story_start(AI_get_picprompt(group_id)))
  76. def on_command(group_id, user_id,command):
  77. """
  78. 每当接到命令符号时,开启这个功能进行回应
  79. """
  80. global last_request_time
  81. if command == "/菜单":
  82. home = """欢迎使用命令功能:
  83. /菜单:显示功能介绍
  84. /王石:查询王石效果
  85. /猫猫画画:调用自定义AI绘画功能
  86. /整点瑟瑟:不用我多说了吧
  87. /语音合成+角色名称:合成AI语音(测试用,目前支持诺艾尔,芙宁娜,神里绫华,迪卢克
  88. 所有命令均需要@猫猫触发"""
  89. send_group_message_word(group_id, home)
  90. save_group_message(group_id, my_name, home)
  91. elif str(command).startswith("/王石"):
  92. stone_stat = ch_stone(command)
  93. send_group_message_word(group_id, stone_stat)
  94. save_group_message(group_id, my_name, stone_stat)
  95. elif str(command).startswith("/猫猫画画2"):
  96. pic_word = str(command)[len("/猫猫画画2"):]
  97. current_time = time.time()
  98. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  99. if current_time - last_request_time >= 0:
  100. send_group_message_word(group_id, "图片正在生成中...")
  101. last_request_time = current_time
  102. send_group_message_pic(group_id, user_id, story_start2(AI_lora_getpic_prompt(pic_word)))
  103. elif str(command).startswith("/整点瑟瑟2"):
  104. pic_word = str(command)[len("/整点瑟瑟2"):]
  105. current_time = time.time()
  106. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  107. if group_id == 637612718:
  108. send_group_message_word(group_id, "本群该功能已被禁用!")
  109. else:
  110. if current_time - last_request_time >= 0:
  111. send_group_message_word(group_id, "图片正在生成中...")
  112. last_request_time = current_time
  113. message_id = send_group_message_pic(group_id, user_id, story_start2("nsfw,best quality,masterpiece," + AI_lora_getpic_prompt(pic_word)))[
  114. 'data']['message_id']
  115. time.sleep(18)
  116. del_group_message(message_id)
  117. elif str(command).startswith("/猫猫画画"):
  118. pic_word = str(command)[len("/猫猫画画"):]
  119. current_time = time.time()
  120. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  121. if current_time - last_request_time >= 0:
  122. send_group_message_word(group_id, "图片正在生成中...")
  123. last_request_time = current_time
  124. send_group_message_pic(group_id, user_id, story_start(AI_lora_getpic_prompt(pic_word)))
  125. elif str(command).startswith("/整点瑟瑟"):
  126. pic_word = str(command)[len("/整点瑟瑟"):]
  127. current_time = time.time()
  128. # 判断距离上次请求图片的时间间隔是否小于60秒(1分钟)
  129. if group_id == 637612718:
  130. send_group_message_word(group_id, "本群该功能已被禁用!")
  131. else:
  132. if current_time - last_request_time >= 0:
  133. send_group_message_word(group_id, "图片正在生成中...")
  134. last_request_time = current_time
  135. message_id = send_group_message_pic(group_id, user_id, story_start("nsfw,"+AI_lora_getpic_prompt(pic_word)))['data']['message_id']
  136. time.sleep(10)
  137. del_group_message(message_id)
  138. elif str(command).startswith("/语音合成"):
  139. send_group_message_word(group_id, "语音合成开始")
  140. name = "xxx"
  141. text = "xxx"
  142. if str(command).startswith("/语音合成诺艾尔"):
  143. name = "诺艾尔"
  144. text = str(command)[len("/语音合成诺艾尔"):]
  145. elif str(command).startswith("/语音合成芙宁娜"):
  146. name = "芙宁娜"
  147. text = str(command)[len("/语音合成芙宁娜"):]
  148. elif str(command).startswith("/语音合成神里绫华"):
  149. name = "神里绫华"
  150. text = str(command)[len("/语音合成神里绫华"):]
  151. elif str(command).startswith("/语音合成迪卢克"):
  152. name = "迪卢克"
  153. text = str(command)[len("/语音合成迪卢克"):]
  154. result = get_free_tts(name, text)
  155. if result.startswith("https"):
  156. send_group_vioce(group_id, result)
  157. else:
  158. send_group_message_word(group_id, result)
  159. else:
  160. error = "抱歉没有找到你所输入的命令!如有关于命令的问题请@猫猫输入/菜单进行查询\n示例:\n@猫猫 /菜单"
  161. send_group_message_word(group_id, error)
  162. save_group_message(group_id, my_name, error)
  163. def ch_stone(name):
  164. """
  165. 根据关键词搜索王石,返回具体介绍
  166. """
  167. word = name.lstrip("/王石")
  168. for i in range(len(stones)):
  169. if stones.loc[i, 'name'] == word:
  170. stone_up_on = stones.loc[i, 'up_on']
  171. if stone_up_on == "Nan":
  172. stone_up_on = ""
  173. else:
  174. stone_up_on = "\n可强化:" + stone_up_on
  175. return stones.loc[i, 'type'] +" " + stones.loc[i, 'name'] + stone_up_on + stones.loc[i, 'stat']
  176. return "这里似乎没有你想找的东西喵~\n如果要查找王石,请使用/王石查询正确的王石名称,示例:\n@猫猫 /王石科隆老大\n如果不清楚王石全名,可以在[掌上波多姆]中进行模糊搜索喵"
  177. def change2setu(raw_message,group_id,user_id, model=1):
  178. """
  179. 进入变瑟图命令
  180. """
  181. message = str(raw_message)
  182. # 提取 QQ 号
  183. pattern = r'\[CQ:at,qq=(\d+),name=[^]]+\]'
  184. match = re.search(pattern, message)
  185. if match:
  186. qq = match.group(1)
  187. try:
  188. img_url = f'https://q1.qlogo.cn/g?b=qq&nk={qq}&s=640'
  189. # 创建 user 文件夹
  190. on_file_path = os.path.join('user', qq)
  191. if not os.path.exists(on_file_path):
  192. os.makedirs(on_file_path)
  193. # 下载图片
  194. img_response = requests.get(img_url)
  195. img_response.raise_for_status()
  196. file_path = os.path.join('user', qq, f'{qq}.jpg')
  197. with open(file_path, 'wb') as file:
  198. file.write(img_response.content)
  199. print(f'图片已保存到 {file_path}')
  200. send_group_message_word(group_id, "开始变身!")
  201. message_id = send_group_message_pic(group_id, user_id, story_start_p2p_sese(qq, model))
  202. print(message_id)
  203. time.sleep(10)
  204. del_group_message(message_id['data']['message_id'])
  205. except Exception as e:
  206. print(f'发生未知错误: {e}')
  207. send_group_message_word(group_id, "变身失败!")
  208. else:
  209. print('未找到 QQ 号')
  210. def change2girl(raw_message,group_id,user_id, model=1):
  211. """
  212. 进入变美少女命令
  213. """
  214. message = str(raw_message)
  215. # 提取 QQ 号
  216. pattern = r'\[CQ:at,qq=(\d+),name=[^]]+\]'
  217. match = re.search(pattern, message)
  218. if match:
  219. qq = match.group(1)
  220. try:
  221. img_url = f'https://q1.qlogo.cn/g?b=qq&nk={qq}&s=640'
  222. # 创建 user 文件夹
  223. on_file_path = os.path.join('user', qq)
  224. if not os.path.exists(on_file_path):
  225. os.makedirs(on_file_path)
  226. # 下载图片
  227. img_response = requests.get(img_url)
  228. img_response.raise_for_status()
  229. file_path = os.path.join('user', qq, f'{qq}.jpg')
  230. with open(file_path, 'wb') as file:
  231. file.write(img_response.content)
  232. print(f'图片已保存到 {file_path}')
  233. send_group_message_word(group_id, "开始变身!")
  234. send_group_message_pic(group_id, user_id, story_start_p2p(qq,model))
  235. except Exception as e:
  236. print(f'发生未知错误: {e}')
  237. send_group_message_word(group_id, "变身失败!")
  238. else:
  239. print('未找到 QQ 号')
  240. @app.route('/stat', methods=['GET'])
  241. def stat_get():
  242. return {"heartbeat": last_heartbeat_time}
  243. @app.route('/cat', methods=['POST'])
  244. def chat():
  245. global last_heartbeat_time
  246. data = request.json
  247. data_type = data['post_type']
  248. # 管理员模式,目前只有开启主机功能
  249. if 'message_type' in data:
  250. if data['message_type'] == 'private':
  251. # 进入管理员模式
  252. if data['raw_message'] == "原神启动" and data['user_id'] == 3494084267:
  253. send_magic_packet("22-43-4D-05-34-B2")
  254. send_private_message_word(data['user_id'], "主机3B0IJ2U已启动!")
  255. print(data)
  256. # 进入群聊模式
  257. if data_type == "message" and data['message_type'] == "group":
  258. group_id = data['group_id']
  259. user_id = data['user_id']
  260. message = data['message']
  261. raw_message = data['raw_message']
  262. time_now = data['time']
  263. user_name = data['sender']['nickname']
  264. # 首先判断消息类型,如果为图片类型则存入url,否则存入csv文件中
  265. if message[0].get('type')=='image':
  266. image_data = message[0].get('data', {})
  267. url = image_data.get('url')
  268. save_group_message(group_id, user_name, f"图片内容:{url}")
  269. else:
  270. save_group_message(group_id, user_name, raw_message)
  271. # 然后根据命令优先级进入AI对话模式,在这里写入AI模块
  272. if str(raw_message).startswith("变美少女[CQ:at"):
  273. change2girl(raw_message, group_id, user_id)
  274. elif str(raw_message).startswith("变美少女2[CQ:at"):
  275. change2setu(raw_message, group_id, user_id, 2)
  276. elif str(raw_message).startswith("变瑟图[CQ:at"):
  277. if group_id == 637612718:
  278. send_group_message_word(group_id,"本群该功能已被禁用!")
  279. else:
  280. change2setu(raw_message, group_id, user_id)
  281. elif str(raw_message).startswith("变瑟图2[CQ:at"):
  282. if group_id == 637612718:
  283. send_group_message_word(group_id, "本群该功能已被禁用!")
  284. else:
  285. change2setu(raw_message, group_id, user_id, 2)
  286. elif str(raw_message) == "看不懂中文":
  287. print("开始日语语音合成")
  288. ja_text = get_ja_trans(group_id)
  289. bs64 = get_gpu_tts(ja_text)
  290. if bs64 == "获取失败":
  291. print(bs64)
  292. send_group_message_word(group_id, "转写失败")
  293. else:
  294. print("发送语音开始!")
  295. send_group_vioce(group_id, "base64://"+bs64)
  296. elif my_name in raw_message:
  297. on_my_message(group_id, user_id, user_name, raw_message, message)
  298. print(
  299. f"收到message!群号:{group_id},发送人:{user_id},时间{time_now}\n"
  300. f"消息内容:{message}\n原始消息内容:{raw_message}")
  301. else:
  302. print(f"群聊{group_id}已记录新消息!")
  303. # 进入提示消息模式
  304. elif data_type == "notice":
  305. notice_type = data['notice_type']
  306. group_id = data['group_id']
  307. if notice_type == "group_increase":
  308. user_id = data['user_id']
  309. print(f"群成员增加!群号:{group_id},加入者:{user_id}")
  310. requests.post('http://127.0.0.1:3000/send_group_msg', json={
  311. 'group_id': group_id,
  312. 'message': [{
  313. "type": "at",
  314. "data": {
  315. "qq": f"{user_id}"
  316. }
  317. }, {
  318. 'type': 'text',
  319. 'data': {
  320. 'text': "欢迎新成员加入群聊喵~"
  321. }
  322. }]
  323. })
  324. elif notice_type == "notify" and data['target_id'] == data['self_id']:
  325. user_id = data['user_id']
  326. print(f"我被{user_id}戳了一下!")
  327. if get_week()=="星期四":
  328. # 触发疯狂星期四文案
  329. # 生成一个0到99之间的随机整数,控制特殊文案概率为40%
  330. rand_num = random.randint(0, 99)
  331. print(rand_num)
  332. send_group_message_word(group_id,get_v50()) if rand_num < 30 else send_group_message_word(group_id,"₍^ >ヮ<^₎")
  333. else:
  334. send_group_message_word(group_id,"₍^ >ヮ<^₎")
  335. send_group_poke(group_id, user_id)
  336. elif data_type == "meta_event":
  337. if data["meta_event_type"] == "heartbeat" and data["status"]['online'] == True:
  338. last_heartbeat_time = data['time']
  339. return ""
  340. # 允许的图片文件扩展名
  341. ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}
  342. @app.route('/pic', methods=['GET'])
  343. def pic_send():
  344. # 获取URL参数中的path
  345. image_path = request.args.get('path')
  346. # 检查path参数是否存在
  347. if not image_path:
  348. abort(400, description="缺少path参数")
  349. # 检查文件是否存在
  350. if not os.path.exists(image_path):
  351. abort(404, description="图片文件不存在")
  352. # 检查文件是否为图片类型
  353. file_ext = os.path.splitext(image_path)[1].lower()
  354. if file_ext not in ALLOWED_EXTENSIONS:
  355. abort(400, description="不支持的文件类型,仅允许图片文件")
  356. # 检查是否为文件(不是目录)
  357. if not os.path.isfile(image_path):
  358. abort(400, description="指定路径不是文件")
  359. try:
  360. # 返回图片文件
  361. return send_file(image_path)
  362. except Exception as e:
  363. abort(500, description=f"服务器错误:{str(e)}")
  364. if __name__ == '__main__':
  365. app.run(host='0.0.0.0', port=3100)