import {ask_gpt, initiate_gpt} from 'backend/openai.js'; import wixChatBackend from 'wix-chat-backend'; import wixData from 'wix-data'; export function wixChat_onMessage(event) { if(event.direction === 'VisitorToBusiness') { console.log('Chat was commenced'); commence(event); } } const commence = (event) => { wixData.query('gpt_chat').eq('channelId', event.channelId).find() .then( async(res) => { console.log('Query comepleted'); if(res.items.length > 0) { //Existing Chat let gpt_res = await ask_gpt(event.payload.text, event.sender.id) gpt_response(gpt_res, event.channelId, event.payload.text); } else { //New Chat let obj = { channelId: event.channelId, userId: event.sender.id }; wixData.insert('gpt_chat', obj); let gpt_res = await initiate_gpt(event.sender.id) let gpt_res2 = await ask_gpt(event.payload.text, event.sender.id) gpt_response(gpt_res2, event.channelId, event.payload.text); } }); } const gpt_response = (gpt, chid, prev) => { let obj = { "messageText": gpt.choices[0].text, "channelId": chid, "sendAsVisitor": false }; console.log(obj); wixChatBackend.sendMessage(obj) .then( () => { console.log("Chat message sent"); }) .catch( (error) => { console.log(error); }); } //Sample event VisitorToBusiness: // { // "channelId":"0379888f-e5cb-30c4-86fc-4d0e1ce6a827", // "sequence":1676742002559626, // "type":"TEXT", // "summary":"Testing Again", // "participantId":"e2a75cd0-a60b-4d0a-abb5-279fc64a9f10", // "createdDate":"2023-02-18T17:40:02.559Z", // "metadata":{}, // "payload":{ // "text":"Testing Again" // }, // "direction":"VisitorToBusiness", // "sender":{ // "role":"Visitor", // "id":"e2a75cd0-a60b-4d0a-abb5-279fc64a9f10" // } // } BLOG | kc39jewelry
top of page
Search
bottom of page