用python调用chatgtp接口实现聊天
时间: 2023-06-02 22:01:40 浏览: 215
首先,需要安装`requests`库和`websocket`库:
```
pip install requests
pip install websocket
```
然后,按照以下步骤实现:
1. 导入库和设置参数:
```python
import requests
import websocket
import json
url = "http://127.0.0.1:5000/gtp"
ws_url = "ws://127.0.0.1:5000/ws"
```
其中,`url`为chatgtp接口的地址,`ws_url`为websocket接口的地址,根据实际情况进行修改。
2. 定义函数发送请求:
```python
def send_request(command):
data = {'command': command}
response = requests.post(url, data=json.dumps(data))
result = response.json()
return result['result']
```
通过`requests`库向chatgtp接口发送请求,获取返回的结果。
3. 定义函数进行聊天:
```python
def chat():
ws = websocket.create_connection(ws_url)
print("请开始聊天:")
while True:
message = input("你:")
ws.send(message)
if message == 'exit':
break
response = ws.recv()
print("机器人:", response)
ws.close()
```
通过`websocket`库连接websocket接口,不断地进行聊天交互,直到输入`exit`退出。
4. 实现调用:
```python
print(send_request('boardsize 19'))
print(send_request('clear_board'))
print(send_request('komi 7.5'))
print(send_request('play black q16'))
print(send_request('genmove white'))
chat()
```
先通过`send_request`函数调用chatgtp接口实现下棋操作,然后通过`chat`函数进行聊天交互。
完整代码如下:
```python
import requests
import websocket
import json
url = "http://127.0.0.1:5000/gtp"
ws_url = "ws://127.0.0.1:5000/ws"
def send_request(command):
data = {'command': command}
response = requests.post(url, data=json.dumps(data))
result = response.json()
return result['result']
def chat():
ws = websocket.create_connection(ws_url)
print("请开始聊天:")
while True:
message = input("你:")
ws.send(message)
if message == 'exit':
break
response = ws.recv()
print("机器人:", response)
ws.close()
print(send_request('boardsize 19'))
print(send_request('clear_board'))
print(send_request('komi 7.5'))
print(send_request('play black q16'))
print(send_request('genmove white'))
chat()
```
阅读全文