Implementing Chatbot Functionality with OpenIM
Brief Description
Implement chatbot functionality using the Webhook mechanism in OpenIM. After sending a text message or an image message to the chatbot, the bot will return the same message. Developers can replace this logic by calling the LLM interface to enable intelligent question-answering.
1. Modify the Configuration File
Refer to the template below to modify the config/webhooks.yml
configuration in open-im-server.
Tips:
url
is the callback URL.- Set
afterSendSingleMsg.enable
totrue
to enable this callback.
2. Create a Chatbot Account
- Log in to the admin console, refer to this document.
- Create a chatbot account in user management and note the userID of the account.
- For convenience, set this userID as a default friend.
3. Write the afterSendSingleMsg Interface
Refer to the example code below.
Tips:
- Replace robotics in the example with the userID obtained in step 2.
func (m *ChatApi) CallbackExample(c *gin.Context) {
// 1. Handling callbacks after sending a single chat message
msgInfo, err := handlingCallbackAfterSendMsg(c)
if err != nil {
apiresp.GinError(c, err)
return
}
// 2. If the user receiving the message is a customer service bot, return the message.
// 2.1 UserID of the robot account
robotics := "robotics"
// 2.2 ChatRobot account validation and determining if messages are text and images
if msgInfo.SendID == robotics || msgInfo.RecvID != robotics {
return
}
if msgInfo.ContentType != constant.Picture && msgInfo.ContentType != constant.Text {
return
}
// 2.3 Get administrator token
adminToken, err := getAdminToken(c)
if err != nil {
apiresp.GinError(c, err)
return
}
// 2.4 Get RobotAccount info
robUser, err := getRobotAccountInfo(c, adminToken.AdminToken, robotics)
if err != nil {
apiresp.GinError(c, err)
return
}
// 2.5 Constructing the contents of the message field or invoking an LLM to implement AI-driven question answering.
mapStruct, err := contextToMap(c, msgInfo)
if err != nil {
apiresp.GinError(c, err)
return
}
// 2.6 Send Message
err = sendMessage(c, adminToken.ImToken, robotics, msgInfo, robUser, mapStruct)
if err != nil {
apiresp.GinError(c, err)
return
}
}
For detailed code, refer to this link