When I pull ChatGPT into the group chat, my friends are crazy

foreword

Recently, ChatGPT can be said to be too hot. Questions and answers, writing papers, writing poems, and writing codes, as long as you enter the precise prompt, his performance is always surprising. In line with the principle of joining if you can't beat it. What would happen if ChatGPT was pulled into the group chat? Just do what you say, and spent a night tinkering with a small Demo [ChatGPT group chat assistant]. With its "intelligence", it should be able to solve the questions of my netizens, girlfriends, and mothers...

Reminder: If you have never experienced ChatGPT, we have prepared a novice experience demo for you, no registration! No login! No proxy!!!, you can quickly check it at the end of the article.

Effect

The effect can be seen in the figure below

insert image description here

Application prospects

Although Demo is only tested in a small group chat, ChatGPT has powerful semantic understanding and interaction capabilities. It can not only connect the context of the conversation, but also correct code bugs in a timely manner. It makes people think that if ChatGPT can be applied to chat robot software to complete the tasks of answering questions, providing services, and even solving problems, helping people solve repetitive or a large amount of manual work, replacing traditional chat robots in customer service and e-commerce , education and finance industries.

Compared with traditional chatbots, ChatGPT can timely adjust the answering strategy according to the user's requirements and characteristics in order to answer questions more accurately and have a more humanized experience. The smart customer service that is widely used now is not smart enough. The capabilities of ChatGPT are exactly what the customer service field needs.

1 Preparations

It is not possible to register a ChatGPT account in China, so you need to prepare as follows:

Foreign mobile phone numbers that can receive text messages: Receive text messages online with a foreign virtual number for only a few dollars. You can go to some third-party platforms such as: http://sms-activate.org/cn .

It should be noted here that when sms-activate.org selects the country of the mobile phone number, it is recommended to choose India. If you choose Indonesia, the following error will be reported in openAI:

You’ve made too many phone verification requests. Please try again later or contact us through our help center at help.openai.com

insert image description here

The above are the necessary prerequisites. After the above preparations, you can go to https://chat.openai.com/auth/login to register an account.

2 Implementation Ideas

2.1 Technology Status

chatGPTProvides Weba version-based interactive interface, which is not convenient for programmatic calls. Therefore, we can log in by simulating a browser, and then encapsulate the interaction process into APIan interface.

2.2 Implementation process

ChatGPTTo join a group chat as a robot character, you need to forward the Q&A on the PC side ChatGPT. Therefore, we can complete the encapsulation of the ChatGPT interface on the PC and join the group chat. Then the data is transmitted in real time through instant IMChatGPT (group chat) to realize group chat and chat.

insert image description here

3 PC end package code implementation

3.1 Encapsulate chatGPT call

We use the chatgpt-api library to package and call chatGPT, so we need to install the dependent library first:

npm install chatgpt

After installing the chtgpt library, it is very simple to use:

var ChatGPT, ConversationId, ParentMessageId;
var API_KEY = ;//这里填写KEY
(async () => {
    
    
    const {
    
     ChatGPTAPI } = await import('chatgpt');
    ChatGPT = new ChatGPTAPI({
    
     apiKey: API_KEY})
})();
//向ChatGPT发出提问
function chat(text, cb) {
    
    
    console.log("正在向ChatGPT发送提问:",text)
    ChatGPT.sendMessage(text, {
    
    
        conversationId: ConversationId,
        parentMessageId: ParentMessageId
    }).then(
        function (res) {
    
    
            ConversationId = res.conversationId
            ParentMessageId = res.id
            cb && cb(true, res.text)
            console.log(res)
        }
    ).catch(function (err) {
    
    
        cb && cb(false, err);
    });
}

Note that the second line needs to be filled in API_KEY. After logging in to OpenAI, open the link https://platform.openai.com/account/api-keys to get it, as shown in the figure below

insert image description here

3.2 Send and receive group chat messages

About Zego IM, if you are interested, you can go to the official website https://doc-zh.zego.im to learn more. As we all know, in terms of instant chat and real-time audio and video, Instant IM is the first choice for individual developers or small and medium-sized enterprises. Because we only focus on one-to-one private chat or group chat, we have made a second package on the basis of the official SDK. Please refer to the attachment for the specific package code, only the packaged usage code is posted here:

const Zego = require('./zego/Zego.js');

var zim;
function onError(err) {
    
    
    console.log("on error", err);
} 
//发送消息
function sendZegoMsg(isToGroup, text, toID){
    
    
    Zego.sendMsg(zim, isToGroup, text, toID, function (succ, err) {
    
    
        if (!succ) {
    
    
            console.log("回复即构消息发送失败:", msg, err);
        }
    }) 
}
//收到消息回调
function onRcvZegoMsg(isFromGroup, msg, fromUID) {
    
     
    var rcvText = msg.message ;
    
}
function main() {
    
    
    let zegoChatGPTUID = "chatgpt"
    zim = Zego.initZego(onError, onRcvZegoMsg, zegoChatGPTUID);

}
main();

When receiving a message, judge whether there are @chatgptkeywords, and if so, extract the content of the message, then call chatGPTthe encapsulated interface to wait for ChatGPTa reply, and send the reply content to the chat group.

4 Join the group chat on the mobile phone and chat with ChatGPT

After PCthe terminal is implemented, then on the mobile terminal, you only need to send a question message to @chatgpt in the group through the instant IM SDK . Of course, you can also call @chatgpt and then call the chatGPT interface during one-on-one private chat. These can be customized and developed according to actual needs. For reasons of space, here we only talk about group chats.

Similarly, we only focus on sending and receiving messages, so we made a second package for the official SDK provided by Jigou . If you want to know more details, you can go to the official documentation to read.

The codes for logging in to ZIM and creating Token are not described in detail here. Interested readers can check the code attachment. The code is very simple and easy to understand.

First encapsulate the Msg object, representing the message entity class:

public class Msg {
    
    
    public String msg;
    public long time;
    public String toUID;
    public String fromUID;
    public MsgType type;

    public enum MsgType {
    
    
        P2P,
        GROUP
    }
}

Secondary encapsulation of sending messages, the same group chat and one-to-one chat interface:

public static void sendMsg(ZIM zim, Msg msg, ZIMMessageSentCallback cb) {
    
    
    // 发送“单聊”通信的信息

    ZIMTextMessage zimMessage = new ZIMTextMessage();
    zimMessage.message = msg.msg;

    ZIMMessageSendConfig config = new ZIMMessageSendConfig();
    // 消息优先级,取值为 低:1 默认,中:2,高:3
    config.priority = ZIMMessagePriority.LOW;
    // 设置消息的离线推送配置
    ZIMPushConfig pushConfig = new ZIMPushConfig();
    pushConfig.title = "离线推送的标题";
    pushConfig.content = "离线推送的内容";
    pushConfig.extendedData = "离线推送的扩展信息";
    config.pushConfig = pushConfig;
    if (msg.type == Msg.MsgType.P2P)
        zim.sendPeerMessage(zimMessage, msg.toUID, config, cb);
    else
        zim.sendGroupMessage(zimMessage, msg.toUID, config, cb);
}

Secondary encapsulation to receive messages, and uniformly onRcvMsgreceive messages through functions.

private void onRcvMsg(ArrayList<ZIMMessage> messageList) {
    
    
    if (lsArr == null) return;
    for (ZIMMessage zimMessage : messageList) {
    
    
        if (zimMessage instanceof ZIMTextMessage) {
    
    
            ZIMTextMessage zimTextMessage = (ZIMTextMessage) zimMessage;
            if (zimMessage.getTimestamp() < this.startTime)
                continue;
            String fromUID = zimTextMessage.getSenderUserID();
            ZIMConversationType ztype = zimTextMessage.getConversationType();
            String toUID = zimTextMessage.getConversationID();
            Msg.MsgType type = Msg.MsgType.P2P;
            if (ztype == ZIMConversationType.PEER) type = Msg.MsgType.P2P;
            else if (ztype == ZIMConversationType.GROUP) type = Msg.MsgType.GROUP;
            String data = zimTextMessage.message;
            Msg msg = new Msg(type, data, zimMessage.getTimestamp(), fromUID, toUID);
            for (MsgCenterListener l : lsArr) l.onRcvMsg(msg);
        }
    }
}
private ZIMEventHandler handler = new ZIMEventHandler() {
    
    

    @Override
    public void onReceivePeerMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromUserID) {
    
    
        onRcvMsg(messageList);
    }



    @Override
    public void onReceiveGroupMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromGroupID) {
    
    
        onRcvMsg(messageList);
    }

    @Override
    public void onTokenWillExpire(ZIM zim, int second) {
    
    
        onRenewToken();
    }
};

It should be noted that because our current scenario only needs to focus on text messages, there is no need to think too much about messages such as pictures and files. Readers with similar needs can further encapsulate it according to the official documents.

In addition, in order to simplify and avoid every time users actively pull chatgptinto a new group, we first make an appointment with a super large group ID: group_chatgpt. Just join this large group every time a new user logs in. If there is a more fine-grained control requirement, you can create different groups according to different users, then chatgptsend the group ID to the robot, and develop the corresponding automatic joining corresponding group function on the PC side.

For the logic of adding groups, a second package is also done:

public void joinGroup(String groupId) {
    
    
    zim.joinGroup(groupId, new ZIMGroupJoinedCallback() {
    
    
        @Override
        public void onGroupJoined(ZIMGroupFullInfo groupInfo, ZIMError errorInfo) {
    
    
            for (MsgCenterListener l : lsArr)
                l.onJoinGroup(groupId);
        }
});

At this point, the entire process development is complete, enjoy ChatGPT to the fullest.

5 Developer Experience

In addition to ChatGPT, the developer tool ZIM SDK used in the demo is also a powerful tool to improve work efficiency. ZIM SDK provides comprehensive IM capabilities to meet various message types such as text, pictures, and voice. There is no upper limit on the number of online users and supports hundreds of millions of messages. Level message concurrency. At the same time, it supports a security audit mechanism to ensure message security compliance.

ZIM SDK provides a mature instant messaging solution with rapid integration and rich interfaces. It meets the communication needs of various business scenarios, and is suitable for creating large-scale live broadcasts, chat rooms, customer service systems and other scenarios. Instant messaging product IM is as low as 1,200 yuan https://www.zego.im/activity/zegoland , and can also be used in combination with other products in the Metaverse and live broadcast room. Interested developers can go to Zego official website to register and experience https://doc-zh.zego.im/article/11591

6 complete code

Guess you like

Origin blog.csdn.net/RTC_SDK_220704/article/details/129406187