First commit
This commit is contained in:
67
bot/bot.go
Normal file
67
bot/bot.go
Normal file
@ -0,0 +1,67 @@
|
||||
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)
|
||||
})
|
||||
}
|
18
bot/memory.go
Normal file
18
bot/memory.go
Normal file
@ -0,0 +1,18 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"matrix-gpt-bot/openai"
|
||||
)
|
||||
|
||||
// conversations stores per-user message history.
|
||||
var conversations = map[string][]openai.Message{}
|
||||
|
||||
// GetHistory retrieves the conversation history for a given user.
|
||||
func GetHistory(userID string) []openai.Message {
|
||||
return conversations[userID]
|
||||
}
|
||||
|
||||
// SetHistory saves the conversation history for a given user.
|
||||
func SetHistory(userID string, history []openai.Message) {
|
||||
conversations[userID] = history
|
||||
}
|
Reference in New Issue
Block a user