From a3b0b8ce2197aa52e32c1a514dc21fcb15b24aeb Mon Sep 17 00:00:00 2001
From: linghaihui <75124771@qq.com>
Date: Thu, 23 Mar 2023 10:37:56 +0800
Subject: [PATCH] Fix some issues
---
README.md | 2 +-
bingchat/app.js | 18 ++++++---
bingchat/components/chatbox/index.wxss | 4 +-
bingchat/config.js | 2 +-
bingchat/pages/index/index.js | 8 ++--
bingchat/pages/index/index.wxml | 5 ++-
bingchat/pages/index/index.wxss | 3 ++
bingchat/project.config.json | 52 ++++++++++++-------------
bingchat/project.private.config.json | 16 ++++----
new-bing/EdgeGPT.py | 2 +-
new-bing/app.py | 19 ++++-----
wechatbot/README.md | 4 +-
wechatbot/gpt/bing.go | 38 ++++++++++--------
wechatbot/gpt/gpt.go | 20 ++++++++--
wechatbot/handlers/group_msg_handler.go | 15 ++++---
wechatbot/handlers/user_msg_handler.go | 6 +--
16 files changed, 125 insertions(+), 89 deletions(-)
diff --git a/README.md b/README.md
index f19ec99..82e2fa2 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-本项目实现了[New Bing 聊天的接口](./new-bing),并做了一个简单的[小程序](./bingchat),同时将`chatgpt 3.5`和`New Bing`集成到[微信](./wechatbot)。
+本项目实现了[New Bing 聊天的接口](./new-bing),并做了一个简单的[小程序](./bingchat),同时将`chatGPT`和`New Bing`集成到[微信](./wechatbot)。
diff --git a/bingchat/app.js b/bingchat/app.js
index 2c8b352..037920c 100644
--- a/bingchat/app.js
+++ b/bingchat/app.js
@@ -1,4 +1,4 @@
-import SERVER_HOST from '../../config';
+import { SERVER_HOST } from "config";
App({
onShow: function () {},
@@ -9,27 +9,33 @@ App({
getSid: function () {
var that = this;
if (!this.globalData.sid) {
- var sid = wx.getStorageSync('sid1');
+ var sid = wx.getStorageSync("sid1");
if (!sid) {
wx.login({
success: (res) => {
wx.request({
- url: SERVER_HOST + '/bing/openid',
+ url: SERVER_HOST + "/bing/openid",
data: {
code: res.code,
},
success: (res) => {
+ if (res.statusCode != 200) {
+ wx.showToast({
+ title: "接口异常",
+ });
+ return;
+ }
that.globalData.sid = res.data.data.openid;
- wx.setStorageSync('sid1', that.globalData.sid);
+ wx.setStorageSync("sid1", that.globalData.sid);
},
});
},
});
} else {
this.globalData.sid = sid;
- wx.setStorageSync('sid1', this.globalData.sid);
+ wx.setStorageSync("sid1", this.globalData.sid);
}
}
- return this.globalData.sid ? this.globalData.sid : '';
+ return this.globalData.sid ? this.globalData.sid : "";
},
});
diff --git a/bingchat/components/chatbox/index.wxss b/bingchat/components/chatbox/index.wxss
index b98de25..7ddccf3 100644
--- a/bingchat/components/chatbox/index.wxss
+++ b/bingchat/components/chatbox/index.wxss
@@ -21,12 +21,12 @@
width: 80rpx;
height: 80rpx;
border-radius: 50%;
- background-color: rgb(224, 226, 232)
+ background-color: #e0e2e8;
}
.dt {
font-size: 24rpx;
- color: rgb(180, 187, 196)
+ color: #b4bbc4;
}
.content {
diff --git a/bingchat/config.js b/bingchat/config.js
index b742d7e..0b63ddc 100644
--- a/bingchat/config.js
+++ b/bingchat/config.js
@@ -1 +1 @@
-export default SERVER_HOST = 'https://example.com';
+export const SERVER_HOST = "https://example.com";
diff --git a/bingchat/pages/index/index.js b/bingchat/pages/index/index.js
index 4d1967f..01ad859 100644
--- a/bingchat/pages/index/index.js
+++ b/bingchat/pages/index/index.js
@@ -1,4 +1,4 @@
-import SERVER_HOST from "../../config";
+import { SERVER_HOST } from "../../config";
Date.prototype.format = function (fmt) {
var o = {
@@ -42,7 +42,7 @@ Page({
},
InputFocus(e) {
this.setData({
- InputBottom: e.detail.height + 2,
+ InputBottom: e.detail.height,
});
},
InputBlur(e) {
@@ -116,7 +116,7 @@ Page({
}
wx.request({
url: SERVER_HOST + "/bing/chat",
- method: "GET",
+ method: "POST",
data: {
q: content,
t: new Date().getTime(),
@@ -204,7 +204,7 @@ Page({
},
submit() {
var content = this.data.content;
- if (content.length == 0 || content == null || content.trim().length == 0) {
+ if (content.length == 0 || content.trim().length == 0) {
return;
}
this.submitContent(content);
diff --git a/bingchat/pages/index/index.wxml b/bingchat/pages/index/index.wxml
index fe97059..420ae49 100644
--- a/bingchat/pages/index/index.wxml
+++ b/bingchat/pages/index/index.wxml
@@ -1,4 +1,5 @@
-
-
+
+
+
\ No newline at end of file
diff --git a/bingchat/pages/index/index.wxss b/bingchat/pages/index/index.wxss
index e69de29..6863741 100644
--- a/bingchat/pages/index/index.wxss
+++ b/bingchat/pages/index/index.wxss
@@ -0,0 +1,3 @@
+button::after {
+ border: none;
+}
\ No newline at end of file
diff --git a/bingchat/project.config.json b/bingchat/project.config.json
index 0a6d485..5acc0ff 100644
--- a/bingchat/project.config.json
+++ b/bingchat/project.config.json
@@ -1,27 +1,27 @@
{
- "appid": "wxee7496be5b68b740",
- "compileType": "miniprogram",
- "libVersion": "2.12.3",
- "packOptions": {
- "ignore": [],
- "include": []
- },
- "setting": {
- "es6": true,
- "postcss": true,
- "minified": true,
- "enhance": true,
- "packNpmRelationList": [],
- "babelSetting": {
- "ignore": [],
- "disablePlugins": [],
- "outputPath": ""
- },
- "uglifyFileName": false
- },
- "condition": {},
- "editorSetting": {
- "tabIndent": "tab",
- "tabSize": 2
- }
-}
+ "appid": "wxee7496be5b68b740",
+ "compileType": "miniprogram",
+ "libVersion": "2.12.3",
+ "packOptions": {
+ "ignore": [],
+ "include": []
+ },
+ "setting": {
+ "es6": true,
+ "postcss": true,
+ "minified": true,
+ "enhance": true,
+ "packNpmRelationList": [],
+ "babelSetting": {
+ "ignore": [],
+ "disablePlugins": [],
+ "outputPath": ""
+ },
+ "uglifyFileName": false
+ },
+ "condition": {},
+ "editorSetting": {
+ "tabIndent": "tab",
+ "tabSize": 2
+ }
+}
\ No newline at end of file
diff --git a/bingchat/project.private.config.json b/bingchat/project.private.config.json
index 3d11a51..2422f01 100644
--- a/bingchat/project.private.config.json
+++ b/bingchat/project.private.config.json
@@ -1,9 +1,9 @@
{
- "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
- "projectname": "bingchat",
- "setting": {
- "compileHotReLoad": true,
- "urlCheck": false
- },
- "libVersion": "2.15.0"
-}
+ "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档:https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
+ "projectname": "bingchat",
+ "setting": {
+ "compileHotReLoad": true,
+ "urlCheck": false
+ },
+ "libVersion": "2.15.0"
+}
\ No newline at end of file
diff --git a/new-bing/EdgeGPT.py b/new-bing/EdgeGPT.py
index baef5bd..fad44eb 100644
--- a/new-bing/EdgeGPT.py
+++ b/new-bing/EdgeGPT.py
@@ -272,7 +272,7 @@ class ChatHub:
"protocol": "json",
"version": 1
}))
- await self.wss.recv()
+ # await self.wss.recv()
async def close(self):
"""
diff --git a/new-bing/app.py b/new-bing/app.py
index d1fda9d..24bfb6e 100644
--- a/new-bing/app.py
+++ b/new-bing/app.py
@@ -49,19 +49,20 @@ def get_bot(sid):
async def do_chat(request):
- return await get_bot(request.args.get('sid')).ask(
- request.args.get('q'), conversation_style=ConversationStyle.balanced
+ return await get_bot(request.json.get('sid')).ask(
+ request.json.get('q'), conversation_style=ConversationStyle.balanced
)
-@app.route('/chat')
+@app.post('/chat')
async def chat(request):
res = await do_chat(request)
- auto_reset = request.args.get('auto_reset', '')
+ auto_reset = request.json.get('auto_reset', '')
+ sid = request.json.get('sid')
status = res['item']['result']['value']
if status == 'Throttled':
reset_cookie()
- await get_bot(request.args.get('sid')).reset()
+ await get_bot(sid).reset()
res = await do_chat(request)
status = res['item']['result']['value']
text = ''
@@ -69,17 +70,17 @@ async def chat(request):
if status == 'Success':
if len(res['item']['messages']) >= 2:
text = res['item']['messages'][1]['text']
- if re.match(r'.*\[\^\d+\^\].*', text):
+ if re.search(r'\[\^\d+\^\]', text):
text = res['item']['messages'][1]['adaptiveCards'][0]['body'][0]['text']
- text = re.sub(r'\[\^\d+\^\]', '', text)
+ text = re.sub(r'\[\^\d+\^\]', '', text)
suggests = [x['text'] for x in res['item']['messages'][1]['suggestedResponses']]
else:
text = '抱歉,未搜索到结果,请重试。'
- suggests = [request.args.get('q')]
+ suggests = [request.json.get('q')]
msg = res['item']['result']['message'] if 'message' in res['item']['result'] else ''
# 自动reset
if auto_reset and ('New topic' in text or 'has expired' in msg):
- await get_bot(request.args.get('sid')).reset()
+ await get_bot(sid).reset()
return json({
'data': {
'status': status,
diff --git a/wechatbot/README.md b/wechatbot/README.md
index d68c46b..7466030 100644
--- a/wechatbot/README.md
+++ b/wechatbot/README.md
@@ -1,5 +1,5 @@
# wechatbot
-最近chatGPT异常火爆,想到将其接入到个人微信是件比较有趣的事,所以有了这个项目。项目基于[openwechat](https://github.com/eatmoreapple/openwechat)开发,支持chatGPT和New Bing[依赖于new-bing](../new-bing)
+最近chatGPT异常火爆,想到将其接入到个人微信是件比较有趣的事,所以有了这个项目。项目基于[openwechat](https://github.com/eatmoreapple/openwechat)开发,支持chatGPT和New Bing[依赖于new-bing项目](../new-bing)
### 目前实现了以下功能
+ 群聊@回复
@@ -26,6 +26,6 @@ go run main.go
```
-本项目fork至[https://github.com/djun/wechatbot](https://github.com/djun/wechatbot),在此致谢!
+本项目fork至[https://github.com/djun/wechatbot](https://github.com/djun/wechatbot),修改使之支持`chatGPT`和`New bing`,在此致谢!
**⚠️ 有一定的几率导致被微信封号,请谨慎使用,由此导致的封号,本人概不负责**
diff --git a/wechatbot/gpt/bing.go b/wechatbot/gpt/bing.go
index c9e4f08..81065ba 100644
--- a/wechatbot/gpt/bing.go
+++ b/wechatbot/gpt/bing.go
@@ -1,19 +1,22 @@
package gpt
import (
+ "bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
- "net/url"
"strings"
"github.com/bujnlc8/wechatbot/config"
)
-type BingQuery struct {
- Q string `json:"q"`
- SID string `json:"sid"`
+const Referer = "https://servicewechat.com/wxee7496be5b68b740"
+
+type BingQueryParam struct {
+ Q string `json:"q"`
+ SID string `json:"sid"`
+ AutoReset string `json:"auto_reset"`
}
type BingResponse struct {
@@ -28,22 +31,25 @@ type BingResponseData struct {
Message string `json:"message"`
}
-// const BingChatUrl = "http://127.0.0.1:8000/chat"
-
-const Referer = "https://servicewechat.com/wxee7496be5b68b740"
-
func BingSearch(msg string, nickName string) (string, error) {
- params := url.Values{}
- params.Add("q", msg)
- params.Add("sid", nickName)
- params.Add("auto_reset", "1")
- log.Printf("request bing query string : %v", params)
- BingChatUrl := config.LoadConfig().BingChatUrl
- req, err := http.NewRequest("GET", BingChatUrl+"?"+params.Encode(), nil)
+ requestBody := BingQueryParam{
+ Q: msg,
+ SID: nickName,
+ AutoReset: "1",
+ }
+ requestData, err := json.Marshal(requestBody)
+
if err != nil {
return "", err
}
- req.Header.Set("Referer", Referer)
+ log.Printf("request bing json string : %v", string(requestData))
+ BingChatUrl := config.LoadConfig().BingChatUrl
+ req, err := http.NewRequest("POST", BingChatUrl, bytes.NewBuffer(requestData))
+ if err != nil {
+ return "", err
+ }
+ req.Header.Set("Referer", Referer)
+ req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
diff --git a/wechatbot/gpt/gpt.go b/wechatbot/gpt/gpt.go
index 6308ee5..6cb02b0 100644
--- a/wechatbot/gpt/gpt.go
+++ b/wechatbot/gpt/gpt.go
@@ -40,13 +40,26 @@ type ChatGPTRequestBody struct {
Messages []Message `json:"messages"`
}
-func Completions(msg string) (string, error) {
+var MessageCacheRegistry = make(map[string][]Message)
+
+func Completions(msg string, nickName string) (string, error) {
+ messageCache := MessageCacheRegistry[nickName]
message := Message{Role: "user", Content: msg}
+ if messageCache == nil || len(messageCache) == 0 {
+ messageCache = []Message{message}
+ } else {
+ messageCache = append(messageCache, message)
+ // 只保留10条
+ if len(messageCache) > 10 {
+ messageCache = messageCache[(len(messageCache) - 10):]
+ }
+ }
+ MessageCacheRegistry[nickName] = messageCache
requestBody := ChatGPTRequestBody{
Model: "gpt-3.5-turbo",
MaxTokens: 2048,
Temperature: 0.2,
- Messages: []Message{message},
+ Messages: messageCache,
}
requestData, err := json.Marshal(requestBody)
@@ -73,7 +86,6 @@ func Completions(msg string) (string, error) {
if err != nil {
return "", err
}
-
gptResponseBody := &ChatGPTResponseBody{}
log.Println(string(body))
err = json.Unmarshal(body, gptResponseBody)
@@ -83,6 +95,8 @@ func Completions(msg string) (string, error) {
var reply string
if len(gptResponseBody.Choices) > 0 {
for _, v := range gptResponseBody.Choices {
+ messageCache = append(messageCache, v.Message)
+ MessageCacheRegistry[nickName] = messageCache
reply = v.Message.Content
break
}
diff --git a/wechatbot/handlers/group_msg_handler.go b/wechatbot/handlers/group_msg_handler.go
index 554e580..ce02552 100644
--- a/wechatbot/handlers/group_msg_handler.go
+++ b/wechatbot/handlers/group_msg_handler.go
@@ -18,8 +18,11 @@ type GroupMessageHandler struct {
func (g *GroupMessageHandler) handle(msg *openwechat.Message) error {
if msg.IsText() {
return g.ReplyText(msg)
+ } else {
+ if strings.Contains(msg.Content, "@GPTBot") || strings.Contains(msg.Content, "@bing") {
+ msg.ReplyText("目前我只支持文字哦~")
+ }
}
- msg.ReplyText("目前我只支持文字哦~")
return nil
}
@@ -34,7 +37,7 @@ func (g *GroupMessageHandler) ReplyText(msg *openwechat.Message) error {
group := openwechat.Group{User: sender}
log.Printf("Received Group %v Text Msg : %v", group.NickName, msg.Content)
- // @GPTBot 或者 @bing的消息才处理
+ // @GPTBot 或者 @bing的消息才处理
if !(strings.Contains(msg.Content, "@GPTBot") || strings.Contains(msg.Content, "@bing")) {
return nil
}
@@ -43,10 +46,12 @@ func (g *GroupMessageHandler) ReplyText(msg *openwechat.Message) error {
var reply = ""
if strings.Contains(msg.Content, "@bing") {
requestText = strings.TrimSpace(strings.ReplaceAll(msg.Content, "@bing", ""))
- reply, err = gpt.BingSearch(requestText, sender.NickName)
+ reply, err = gpt.BingSearch(requestText, group.UserName)
+ if reply != "" && strings.HasPrefix(reply, "[") {
+ reply = "\n" + reply
+ }
} else {
-
- reply, err = gpt.Completions(requestText)
+ reply, err = gpt.Completions(requestText, group.UserName)
}
if err != nil {
log.Printf("gpt request error: %v \n", err)
diff --git a/wechatbot/handlers/user_msg_handler.go b/wechatbot/handlers/user_msg_handler.go
index 6a31626..912f22d 100644
--- a/wechatbot/handlers/user_msg_handler.go
+++ b/wechatbot/handlers/user_msg_handler.go
@@ -32,7 +32,7 @@ func NewUserMessageHandler() MessageHandlerInterface {
func (g *UserMessageHandler) ReplyText(msg *openwechat.Message) error {
// 接收私聊消息
sender, err := msg.Sender()
- log.Printf("Received User %v Text Msg : %v", sender.NickName, msg.Content)
+ log.Printf("Received User %v Text Msg : %v", sender.UserName, msg.Content)
requestText := strings.TrimSpace(msg.Content)
requestText = strings.Trim(msg.Content, "\n")
@@ -40,9 +40,9 @@ func (g *UserMessageHandler) ReplyText(msg *openwechat.Message) error {
var reply = ""
if strings.Contains(msg.Content, "@bing") {
requestText = strings.TrimSpace(strings.ReplaceAll(msg.Content, "@bing", ""))
- reply, err = gpt.BingSearch(requestText, sender.NickName)
+ reply, err = gpt.BingSearch(requestText, sender.UserName)
} else {
- reply, err = gpt.Completions(requestText)
+ reply, err = gpt.Completions(requestText, sender.UserName)
}
if err != nil {
log.Printf("gpt request error: %v \n", err)