Home >Backend Development >Python Tutorial >How to use Python to connect to OpenAi API to implement intelligent QQ robot
TheseSDK
can not only be used to develop robots, but can also be used to freely develop the effects you want. As you think, it is a toolkit , help you chuanchuan build a ChatGPT
service and session.
Recently OpenAi
has installed a CDN
service of Cloudflare
on him. This service will intercept non-real machine requests. It's now crackable.
Looking for a suitable reverse SDK
The original author used this.
There are not many files in the whole package. If you like Python
, you can check it out. I don’t understand Java
. .
The revChatGPT used in the code relies on the source code library:
https://github.com/acheong08/ChatGPT
Our Python version requires >=3.8
, and then pip
directly upgrade to the latest version.
The purpose of the following code is to interact with the official interface of ChatGPT. Please pay attention to installing the dependencies used in it
chat-gpt-qbot.py:
import flask, json from flask import request from revChatGPT.revChatGPT import Chatbot config = { "session_token": "换成你自己的token" } # 创建一个服务,把当前这个python文件当做一个服务 server = flask.Flask(__name__) chatbot = Chatbot(config, conversation_id=None) def chat(msg): message = chatbot.get_chat_response(msg)['message'] print(message) return message @server.route('/chat', methods=['post']) def chatapi(): requestJson = request.get_data() if requestJson is None or requestJson == "" or requestJson == {}: resu = {'code': 1, 'msg': '请求内容不能为空'} return json.dumps(resu, ensure_ascii=False) data = json.loads(requestJson) print(data) try: msg = chat(data['msg']) except Exception as error: print("接口报错") resu = {'code': 1, 'msg': '请求异常: ' + str(error)} return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 0, 'data': msg} return json.dumps(resu, ensure_ascii=False) if __name__ == '__main__': server.run(port=7777, host='0.0.0.0')
We import our reverse package.
from revChatGPT.revChatGPT import Chatbot
This is the source code in the reverse package, which is used to initialize a service. We just called this package in the class.
Then create an interface that throws this service so that it can be easily called.
We only need to run the above code to interact directly with ChatGPT on port 7777.
We use the interface tool to test it. The results are as shown below. You can see that the interface works normally and the conversation results are obtained from ChatGPT.
The message body:
{"msg": "你会数学吗"}
The message body is our customized content. You can add fields by yourself to extend the function of the interface
This example The msg in is the content of our speech
and the interface returns:
{ "code": 0, "data": "是的,我会数学。我是一个大型语言模型,我可以回答各种问题,包括数学问题。你有什么数学问题需要我帮助你解决吗?"}
This is also defined by ourselves. When code=0
, it means ChatGPT
The interaction is successful. At this time, data
is the conversation content fed back to us by ChatGPT
. When code=1
, it means an error occurred. There is no data
, but the error message is returned in msg
.
At this point we have an interface that can interact with ChatGPT. Through this interface, we can have a conversation with ChatGPT
Since we have a conversation, we need With an input box and a button, you can make a web page to call this interface. This is very simple, so we won’t go into details here.
What we really want to do is a QQ robot. The principle is to let the QQ robot listen to the message, forward the message to ChatGPT through our interface, and then send the conversation content returned by ChatGPT to the QQ user. Such a robot that can talk is ready. The specific method will be explained below.
Above we implemented an interface and successfully obtained the ChatGPT conversation content using code. Next we will continue to improve the QQ robot related logic. Pay attention to the comments in the code.
In order to more conveniently compare the optimized code (connected to QQ robot) with the previous code, I opened a local comparison and The code that has not changed has been put away.
You may not understand the robot interaction implementation logic, because we are using a robot framework. In fact, we should not limit our thinking. We can try to modify and use other robot frameworks ourselves, such as Yunzai Robot. Implement the logic yourself.
We are using go-cqhttp
.
go-cqhttp Help Center
So, you have to understand this change go-cqhttp
before you can understand it, but we need to learn flexibly. We just need to understand the idea, and then go to the official documentation to find how to use it.
At this point, these codes already have the functions of processing friend requests, group requests, and replying to messages.
As you can see, compared to the previous article, we have added a lot of code and added comments
Of course, it doesn’t matter if you don’t understand these codes, you can follow mine Change the corresponding part of the article and use it directly.
Everyone come to the original author Q group to play, I am also in it: 206867743
.
In the first two articles, we have solved the problem of communicating with ChatGPT and the problem of QQ processing messages. Now we need to deal with how to monitor QQ News.
In the updates and problems encountered, the original author and many authors of the reverse package have updated a lot of content. Let’s take a look at the update record of the original author:
2022-12-12 23:52 Add a Windows-specific version, which can only be used on Windows computers or servers, and can automatically obtain cloudflare Cookie 2022-12-12 12:38 Update contentAdd CloudFlare Configuration, update dependencies, account passwords are not supported for the time being. I don’t know how often the CloudFlare configuration needs to be changed. Now it seems that I have to circumvent the firewall 2022-12-10 17:42 Update content adds account password support, you can not use tokens , directly use the account password 2022-12-10 00:23 The updated content distinguishes each QQ private chat, and each person's private chat robot is an independent session. Differentiates each QQ group, and each QQ group is an independent session. Increase the word limit for replies. If the limit exceeds the limit, it will be converted into a picture reply (see configuration file). If you want to reset the session, send the robot: Reset session
Listen to QQ messages and We don’t need to write code, because there are already many open source QQ robot frameworks on the market. Here we use go-cqhttp
Official documentation: go-cqhttp
If you are interested, you can read the official documentation , if you don’t want to read it, just read my article directly.
Prerequisites You need to prepare a QQ account. Do not use your own large account. You need to prepare an OpenAi account to obtain a Token server (optional, if you want the robot to be online 24/7, please Prepare one, 1 core and 1G is enough, external server is best)
Note: There are a bunch of videos on the registration method of OpenAi (ChatGPT) at Station B, just refer to any one.
If you don’t know how to register, you can also read the article on my blog: One article teaches you how to quickly register OpenAi (ChatGPT)
(old version) I also wrote a tutorial on how to build a robot: use OpenGPT (ChatGPT) builds QQ robot
But! Note, as mentioned before, the current ChatGPT
is equipped with a CF
's CDN
, which will intercept human-computer interaction requests.
Now, in addition to getting the session-token
of OpenAi
, we also need to get cf_clearance
.
At the same time, we also need to obtain user-agent
.
Go to the network tab of the console and check it. If it is blank, just send a message.
Copy and write it into the configuration file, which is the py/config.js
file.
Currently the original author has packaged two versions, one for Linux. The trouble is that the CDN
interaction token of cf
will expire within 2H
, we need to obtain and update manually, which is troublesome.
The other is the window
version, which has automatically obtained CloudflareCookie
.
Configuration Guide
This version can only be used on Windows, any Windows computer or server will work.
Still only supports token.
The system will automatically open Google Chrome to obtain Cloufflare related cookies. Manual verification may be required when running for the first time, so please click carefully.
Note that the script can only open Google Chrome and does not configure other browsers.
Other description
In the author’s latest version of the code, some new functions have also been added.
Do your own research.
Then many reverse package authors are also thinking of a perfect solution, let’s wait slowly!
Then, please look at this sentence:
The above is the detailed content of How to use Python to connect to OpenAi API to implement intelligent QQ robot. For more information, please follow other related articles on the PHP Chinese website!