概述
基于前一篇文章https://mp.csdn.net/mp_blog/creation/editor/new/128808067
继续开发QQ机器人的一些功能, 基于chatgpt可CSDN开发,具体功能有查询博客、问答、和写代码功能,后续还可以自己添加更多代码, 注意,go-cqhttp要的位置需要放在指定位置(~/go-cqhttp),或者可以自己该写代码
代码
main.py
#!/usr/bin/python
from flask import Flask, request
import threading, os
from Api import Api
Api = Api(manager=2919465681)
app = Flask(__name__)
@app.route('/', methods=["POST", "GET"])
def post_data():
'request.get_json().get获取数据'
res = request.get_json()
print(res)
if res.get('message_type') == 'private':
uid = res.get('sender').get('user_id')
message = res.get('raw_message')
Api.send(message, uid)
if res.get('message_type') == 'group':
uid = res.get('sender').get('user_id')
gid = res.get('group_id')
message = res.get('raw_message')
message_seq = res.get('message_seq')
message_id = res.get('message_id')
Api.send(message, uid, gid, message_id, message_seq)
return 'ok'
def run_QQ():
os.system('cd ~/go-cqhttp && ./go-cqhttp')
def run_app():
app.run(debug=False, host='127.0.0.1', port=5701)
if __name__ == '__main__':
threading.Thread(target=run_QQ).start()
threading.Thread(target=run_app).start()
Api.py
#!/usr/bin/python
import requests
from utils.tool import Tool
def send_group(msg, gid):
url = "http://127.0.0.1:5700/send_group_msg"
data = {
"group_id": gid,
"message": msg,
"auto_escape": False
}
resp = requests.post(url, data=data)
print("successful sending" if resp.status_code == 200 else "failed sending")
def send_private(msg, uid, gid):
url = 'http://127.0.0.1:5700/send_private_msg'
data = {
"user_id": uid,
"group_id": gid,
"message": msg,
"auto_escape": False
}
resp = requests.post(url, data=data)
print("successful sending" if resp.status_code == 200 else "failed sending")
def isRepeate(uid, *args):
for usr in args:
if uid in usr:
return False
return True
class Api():
def __init__(self, manager=None, manager_group=None):
self.manager = manager
self.manager_group = manager_group
self.tool = Tool()
self.mode1_usr = []
self.mode2_usr = []
self.mode3_usr = []
self.mode4_usr = []
def send(self, message, uid, gid=None, message_id=None, message_seq=None):
if self.manager_group == None:
self.manager_group = gid
if gid: # group message
if message == '#0' and not isRepeate(uid, self.mode1_usr, self.mode2_usr, self.mode3_usr, self.mode4_usr): # exit mode
try:
self.mode1_usr.remove(uid)
except:
pass
try:
self.mode2_usr.remove(uid)
except:
pass
try:
self.mode3_usr.remove(uid)
except:
pass
try:
self.mode4_usr.remove(uid)
except:
pass
msg = f'''number:\n#1:{len(self.mode1_usr)} people\n#2:{len(self.mode2_usr)} people\n#3:{len(self.mode3_usr)} people\n#4:{len(self.mode4_usr)} people'''
msg = f'[CQ:reply,id={message_id},qq={uid},time=3376656000,seq=5123]{msg}'
send_group(msg=msg, gid=gid)
if message == '#1' and uid not in self.mode1_usr: # start mode1
msg = ""
if isRepeate(uid, self.mode2_usr, self.mode3_usr, self.mode4_usr) and len(self.mode1_usr) <= 4:
self.mode1_usr.append(uid)
msg = "sucessful start #1"
else:
msg = "failed start,number is full or please exit other mode"
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif message == '#2': # start mode2
msg = ""
if isRepeate(uid, self.mode1_usr, self.mode3_usr, self.mode4_usr) and len(self.mode2_usr) <= 4:
self.mode2_usr.append(uid)
msg = "sucessful start #2"
else:
msg = "failed start,number is full or please exit other mode"
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif message == '#3': # start mode3
msg = ""
if isRepeate(uid, self.mode2_usr, self.mode1_usr, self.mode4_usr) and len(self.mode3_usr) <= 4:
self.mode3_usr.append(uid)
msg = "sucessful start #3"
else:
msg = "failed start! \nnumber is full or please exit other mode"
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif message == '#4': # start mode4
msg = ""
if isRepeate(uid, self.mode2_usr, self.mode3_usr, self.mode1_usr) and len(self.mode4_usr) <= 4:
self.mode4_usr.append(uid)
msg = "sucessful start #4"
else:
msg = "failed start! \nnumber is full or please exit other mode"
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif uid in self.mode1_usr:
msg = self.tool.openai_code(content=message)
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif uid in self.mode2_usr:
msg = self.tool.openai_QA(content=message)
msg = f'[CQ:reply,id={message_id},qq={uid},seq={message_seq}]{msg}'
send_group(msg, gid)
elif uid in self.mode3_usr:
item = self.tool.get_csdn(content=message)
for title, url in item.items():
msg = f'{title}[CQ:share,url={url},title={title}]'
send_private(msg, uid, gid)
else: # private message
if '博客查询' in message:
message = message.replace('博客查询', '')
item = self.tool.get_csdn(content=message)
for title, url in item.items():
msg = f'{title}[CQ:share,url={url},title={title}]'
send_private(msg, uid, gid)
utils.tool
#!/usr/bin/python
import openai
import requests
import cv2
class Tool():
def __init__(self):
self.openai = openai
self.openai.api_key = '' # 此处填写自己chatgpt的key
self.csdn_url = 'https://so.csdn.net/api/v3/search'
def openai_code(self, content="python写1到100累加和"):
response = self.openai.Completion.create(
model="code-davinci-002",
prompt=f"\"\"\"\n{content}\n\"\"\"\n",
temperature=0.0,
max_tokens=1000,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["\"\"\""]
)
return response.choices[0].text
def openai_QA(self, content="你会干什么"):
response = self.openai.Completion.create(
model="text-davinci-003",
prompt=f"{content}\nA:",
temperature=0.5,
max_tokens=300,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=["\n"]
)
return response.choices[0].text
def get_csdn(self, content='python'):
param = {
'q': content
}
res = {}
resp = requests.get(self.csdn_url, param).json()["result_vos"]
num = 5
for i in resp:
url = i['url']
title = i['title'].replace('<em>', '').replace('</em>', '')
if num <= 0:
break
if title == 'python技能树' or title == 'C技能树':
pass
else:
num -= 1
res[title] = url
return res
总结
这个代码还有一些功能没有实现,可以自己去填写一些功能