68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package bot
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"matrix-gpt-bot/openai"
|
|
|
|
mautrix "maunium.net/go/mautrix"
|
|
"maunium.net/go/mautrix/event"
|
|
)
|
|
|
|
// RegisterHandler sets up the GPT message handler on the Matrix client.
|
|
func RegisterHandler(client *mautrix.Client) {
|
|
syncer := client.Syncer.(*mautrix.DefaultSyncer)
|
|
|
|
// Compute the bot's local name (without '@' or domain) for prefix matching
|
|
fullID := string(client.UserID) // e.g. "@gpt:ewnix.net"
|
|
local := strings.SplitN(fullID, ":", 2)[0] // "@gpt"
|
|
local = strings.TrimPrefix(local, "@") // "gpt"
|
|
|
|
syncer.OnEventType(event.EventMessage, func(ctx context.Context, evt *event.Event) {
|
|
msg := evt.Content.AsMessage()
|
|
if msg.MsgType != event.MsgText {
|
|
return
|
|
}
|
|
|
|
body := msg.Body
|
|
lcBody := strings.ToLower(body)
|
|
var content string
|
|
|
|
// Check for "gpt: message" prefix
|
|
if strings.HasPrefix(lcBody, local+":") {
|
|
content = strings.TrimSpace(body[len(local)+1:])
|
|
|
|
// Or for full Matrix mention
|
|
} else if strings.Contains(body, fullID) {
|
|
content = strings.TrimSpace(strings.ReplaceAll(body, fullID, ""))
|
|
} else {
|
|
// Not addressed to bot
|
|
return
|
|
}
|
|
|
|
// Nothing to send
|
|
if content == "" {
|
|
return
|
|
}
|
|
|
|
// Retrieve or initialize conversation history for this user
|
|
userID := string(evt.Sender)
|
|
history := GetHistory(userID)
|
|
history = append(history, openai.Message{Role: "user", Content: content})
|
|
|
|
// Ask OpenAI
|
|
resp, err := openai.Ask(history)
|
|
if err != nil {
|
|
client.SendText(context.Background(), evt.RoomID, "Error talking to ChatGPT: "+err.Error())
|
|
return
|
|
}
|
|
|
|
history = append(history, openai.Message{Role: "assistant", Content: resp})
|
|
SetHistory(userID, history)
|
|
|
|
// Send reply
|
|
client.SendText(context.Background(), evt.RoomID, resp)
|
|
})
|
|
}
|