Fix some issues
This commit is contained in:
parent
f173af8104
commit
a3b0b8ce21
@ -1 +1 @@
|
||||
本项目实现了[New Bing 聊天的接口](./new-bing),并做了一个简单的[小程序](./bingchat),同时将`chatgpt 3.5`和`New Bing`集成到[微信](./wechatbot)。
|
||||
本项目实现了[New Bing 聊天的接口](./new-bing),并做了一个简单的[小程序](./bingchat),同时将`chatGPT`和`New Bing`集成到[微信](./wechatbot)。
|
||||
|
||||
@ -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 : "";
|
||||
},
|
||||
});
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -1 +1 @@
|
||||
export default SERVER_HOST = 'https://example.com';
|
||||
export const SERVER_HOST = "https://example.com";
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
<chat-box bindsuggestSubmit="onSuggestSubmit"></chat-box>
|
||||
<view style="bottom:{{InputBottom}}px; border-radius: 20rpx;margin-left: 1.5%;width: 97%;min-height: 88rpx;position: fixed;background-color: #f4f6f8;">
|
||||
<textarea bindfocus="InputFocus" bindblur="InputBlur" model:value="{{content}}" adjust-position="{{false}}" focus="{{false}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="请输入问题..." style="padding: 10rpx;width: 98%;" disable-default-padding="{{true}}"></textarea>
|
||||
<view style="bottom:{{InputBottom}}px; border-radius: 20rpx;margin-left: 1.5%;width: 97%;min-height: 88rpx;position: fixed;background-color: #f4f6f8;display: flex;">
|
||||
<textarea bindfocus="InputFocus" bindblur="InputBlur" model:value="{{content}}" adjust-position="{{false}}" focus="{{false}}" maxlength="2000" auto-height="{{true}}" cursor-spacing="10" bindconfirm="submit" fixed="{{true}}" show-confirm-bar="{{false}}" confirm-type="send" placeholder="请输入问题..." style="padding: 10rpx;flex: 8;" disable-default-padding="{{true}}" placeholder-style="color: #b4bbc4"></textarea>
|
||||
<!-- <button style="flex: 1;background-color: #f4f6f8;color: {{content ? black : '#b4bbc4'}};border-left: 1px dashed #b4bbc4;border-radius: 0 20rpx 20rpx 0;" bindtap="submit">发送</button> -->
|
||||
</view>
|
||||
@ -0,0 +1,3 @@
|
||||
button::after {
|
||||
border: none;
|
||||
}
|
||||
@ -272,7 +272,7 @@ class ChatHub:
|
||||
"protocol": "json",
|
||||
"version": 1
|
||||
}))
|
||||
await self.wss.recv()
|
||||
# await self.wss.recv()
|
||||
|
||||
async def close(self):
|
||||
"""
|
||||
|
||||
@ -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)
|
||||
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,
|
||||
|
||||
@ -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`,在此致谢!
|
||||
|
||||
**⚠️ 有一定的几率导致被微信封号,请谨慎使用,由此导致的封号,本人概不负责**
|
||||
|
||||
@ -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 {
|
||||
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)
|
||||
requestBody := BingQueryParam{
|
||||
Q: msg,
|
||||
SID: nickName,
|
||||
AutoReset: "1",
|
||||
}
|
||||
requestData, err := json.Marshal(requestBody)
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
log.Printf("request bing json string : %v", string(requestData))
|
||||
BingChatUrl := config.LoadConfig().BingChatUrl
|
||||
req, err := http.NewRequest("GET", BingChatUrl+"?"+params.Encode(), nil)
|
||||
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 {
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
@ -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("目前我只支持文字哦~")
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
@ -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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user