switched to mautrix example

This commit is contained in:
Erik Winter 2023-05-12 15:07:16 +02:00
parent 363d72c560
commit a9751511e3
3 changed files with 245 additions and 29 deletions

19
go.mod
View File

@ -3,8 +3,23 @@ module ewintr.nl/matrix-bots
go 1.20
require (
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530
github.com/russross/blackfriday/v2 v2.1.0
github.com/chzyer/readline v1.5.1
github.com/rs/zerolog v1.29.1
github.com/sashabaranov/go-openai v1.9.4
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea
maunium.net/go/mautrix v0.15.1
)
require (
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/tidwall/gjson v1.14.4 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/yuin/goldmark v1.5.4 // indirect
golang.org/x/crypto v0.8.0 // indirect
golang.org/x/net v0.9.0 // indirect
golang.org/x/sys v0.7.0 // indirect
maunium.net/go/maulogger/v2 v2.4.1 // indirect
)

48
go.sum
View File

@ -1,8 +1,48 @@
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 h1:kHKxCOLcHH8r4Fzarl4+Y3K5hjothkVW5z7T1dUM11U=
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530/go.mod h1:/gBX06Kw0exX1HrwmoBibFA98yBk/jxKpGVeyQbff+s=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/chzyer/logex v1.2.1 h1:XHDu3E6q+gdHgsdTPH6ImJMIp436vR6MPtH8gP05QzM=
github.com/chzyer/logex v1.2.1/go.mod h1:JLbx6lG2kDbNRFnfkgvh4eRJRPX1QCoOIWomwysCBrQ=
github.com/chzyer/readline v1.5.1 h1:upd/6fQk4src78LMRzh5vItIt361/o4uq553V8B5sGI=
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/chzyer/test v1.0.0 h1:p3BQDXSxOhOG0P9z6/hGnII4LGiEPOYBhs8asl/fC04=
github.com/chzyer/test v1.0.0/go.mod h1:2JlltgoNkt4TW/z9V/IzDdFaMTM2JPIi26O1pF38GC8=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc=
github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU=
github.com/sashabaranov/go-openai v1.9.4 h1:KanoCEoowAI45jVXlenMCckutSRr39qOmSi9MyPBfZM=
github.com/sashabaranov/go-openai v1.9.4/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM=
github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
github.com/yuin/goldmark v1.5.4 h1:2uY/xC0roWy8IBEGLgB1ywIoEJFGmRrX21YQcvGZzjU=
github.com/yuin/goldmark v1.5.4/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ=
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE=
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea h1:vLCWI/yYrdEHyN2JzIzPO3aaQJHQdp89IZBA/+azVC4=
golang.org/x/exp v0.0.0-20230510235704-dd950f8aeaea/go.mod h1:V1LtkGg67GoY2N1AnLN78QLrzxkLyJw7RJb1gzOOz9w=
golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
maunium.net/go/maulogger/v2 v2.4.1 h1:N7zSdd0mZkB2m2JtFUsiGTQQAdP0YeFWT7YMc80yAL8=
maunium.net/go/maulogger/v2 v2.4.1/go.mod h1:omPuYwYBILeVQobz8uO3XC8DIRuEb5rXYlQSuqrbCho=
maunium.net/go/mautrix v0.15.1 h1:pmCtMjYRpd83+2UL+KTRFYQo5to0373yulimvLK+1k0=
maunium.net/go/mautrix v0.15.1/go.mod h1:icQIrvz2NldkRLTuzSGzmaeuMUmw+fzO7UVycPeauN8=

203
main.go
View File

@ -2,12 +2,20 @@ package main
import (
"context"
"errors"
"fmt"
"github.com/matrix-org/gomatrix"
"github.com/russross/blackfriday/v2"
"github.com/chzyer/readline"
"github.com/rs/zerolog"
"github.com/sashabaranov/go-openai"
"golang.org/x/exp/slog"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/format"
"maunium.net/go/mautrix/id"
"os"
"os/signal"
"sync"
"time"
)
func main() {
@ -16,11 +24,12 @@ func main() {
slog.Error("MATRIX_HOME_SERVER is not set")
os.Exit(1)
}
MatrixUserID, ok := os.LookupEnv("MATRIX_USER_ID")
MatrixUserIDStr, ok := os.LookupEnv("MATRIX_USER_ID")
if !ok {
slog.Error("MATRIX_USER_ID is not set")
os.Exit(1)
}
MatrixUserID := id.UserID(MatrixUserIDStr)
MatrixAccessKey, ok := os.LookupEnv("MATRIX_ACCESS_KEY")
if !ok {
slog.Error("MATRIX_ACCESS_KEY is not set")
@ -35,21 +44,96 @@ func main() {
// Create new OpenAI client
openaiClient := openai.NewClient(OpenaiAPIKey)
matrixClient, _ := gomatrix.NewClient(MatrixHomeserver, MatrixUserID, MatrixAccessKey)
//matrixClient, _ := mautrix.NewClient(MatrixHomeserver, MatrixUserID, MatrixAccessKey)
//
//syncer := matrixClient.Syncer.(*mautrix.DefaultSyncer)
//syncer.OnEventType(event.StateMember, func(source mautrix.EventSource, evt *event.Event) {
// if evt.Content["membership"] == "invite" && *ev.StateKey == MatrixUserID {
// _, err := matrixClient.JoinRoom(ev.RoomID, "", nil)
// if err != nil {
// fmt.Println("Failed to join room:", err)
// }
// }
//})
//
//syncer.OnEventType("m.room.message", func(ev *gomatrix.Event) {
// if ev.Sender != MatrixUserID {
// msgBody, _ := ev.Body()
//
// // Generate a message with OpenAI API
// openAiResp, err := openaiClient.CreateChatCompletion(
// context.Background(),
// openai.ChatCompletionRequest{
// Model: openai.GPT4,
// Messages: []openai.ChatCompletionMessage{
// {
// Role: openai.ChatMessageRoleSystem,
// Content: "You are a chatbot that helps people by responding to their questions with short messages.",
// },
//
// {
// Role: openai.ChatMessageRoleUser,
// Content: msgBody,
// },
// },
// })
//
// if err != nil {
// fmt.Println("OpenAI API returned with ", err)
// return
// }
//
// // Send the OpenAI response back to the chat
// responseText := openAiResp.Choices[len(openAiResp.Choices)-1].Message.Content
// formattedResponse := blackfriday.Run([]byte(responseText))
// _, _ = matrixClient.SendFormattedText(ev.RoomID, responseText, string(formattedResponse))
// }
//})
//
//for {
// if err := matrixClient.Sync(); err != nil {
// fmt.Println("Sync() returned with ", err)
// }
//}
syncer := matrixClient.Syncer.(*gomatrix.DefaultSyncer)
syncer.OnEventType("m.room.member", func(ev *gomatrix.Event) {
if ev.Content["membership"] == "invite" && *ev.StateKey == MatrixUserID {
_, err := matrixClient.JoinRoom(ev.RoomID, "", nil)
client, err := mautrix.NewClient(MatrixHomeserver, MatrixUserID, MatrixAccessKey)
if err != nil {
fmt.Println("Failed to join room:", err)
panic(err)
}
}
})
syncer.OnEventType("m.room.message", func(ev *gomatrix.Event) {
if ev.Sender != MatrixUserID {
msgBody, _ := ev.Body()
var oei mautrix.OldEventIgnorer
oei.Register(client.Syncer.(mautrix.ExtensibleSyncer))
rl, err := readline.New("[no room]> ")
if err != nil {
panic(err)
}
defer rl.Close()
log := zerolog.New(zerolog.NewConsoleWriter(func(w *zerolog.ConsoleWriter) {
w.Out = rl.Stdout()
w.TimeFormat = time.Stamp
})).With().Timestamp().Logger()
//if !*debug {
// log = log.Level(zerolog.InfoLevel)
//}
client.Log = log
var lastRoomID id.RoomID
syncer := client.Syncer.(*mautrix.DefaultSyncer)
syncer.OnEventType(event.EventMessage, func(source mautrix.EventSource, evt *event.Event) {
lastRoomID = evt.RoomID
rl.SetPrompt(fmt.Sprintf("%s> ", lastRoomID))
log.Info().
Str("sender", evt.Sender.String()).
Str("type", evt.Type.String()).
Str("id", evt.ID.String()).
Str("body", evt.Content.AsMessage().Body).
Msg("Received message")
if evt.Sender != MatrixUserID {
msgBody := evt.Content.AsMessage().Body
// Generate a message with OpenAI API
openAiResp, err := openaiClient.CreateChatCompletion(
@ -75,15 +159,92 @@ func main() {
}
// Send the OpenAI response back to the chat
responseText := openAiResp.Choices[len(openAiResp.Choices)-1].Message.Content
formattedResponse := blackfriday.Run([]byte(responseText))
_, _ = matrixClient.SendFormattedText(ev.RoomID, responseText, string(formattedResponse))
responseMarkdown := openAiResp.Choices[len(openAiResp.Choices)-1].Message.Content
responseMessage := format.RenderMarkdown(responseMarkdown, true, false)
client.SendMessageEvent(lastRoomID, event.EventMessage, &responseMessage)
}
})
syncer.OnEventType(event.StateMember, func(source mautrix.EventSource, evt *event.Event) {
if evt.GetStateKey() == client.UserID.String() && evt.Content.AsMember().Membership == event.MembershipInvite {
_, err := client.JoinRoomByID(evt.RoomID)
if err == nil {
lastRoomID = evt.RoomID
rl.SetPrompt(fmt.Sprintf("%s> ", lastRoomID))
log.Info().
Str("room_id", evt.RoomID.String()).
Str("inviter", evt.Sender.String()).
Msg("Joined room after invite")
} else {
log.Error().Err(err).
Str("room_id", evt.RoomID.String()).
Str("inviter", evt.Sender.String()).
Msg("Failed to join room after invite")
}
}
})
for {
if err := matrixClient.Sync(); err != nil {
fmt.Println("Sync() returned with ", err)
}
//cryptoHelper, err := cryptohelper.NewCryptoHelper(client, []byte("meow"), "mautrix-example.db")
//if err != nil {
// panic(err)
//}
//
//// You can also store the user/device IDs and access token and put them in the client beforehand instead of using LoginAs.
////client.UserID = "..."
////client.DeviceID = "..."
////client.AccessToken = "..."
//// You don't need to set a device ID in LoginAs because the crypto helper will set it for you if necessary.
////cryptoHelper.LoginAs = &mautrix.ReqLogin{
//// Type: mautrix.AuthTypePassword,
//// Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: *username},
//// Password: *password,
////}
//// If you want to use multiple clients with the same DB, you should set a distinct database account ID for each one.
////cryptoHelper.DBAccountID = ""
//err = cryptoHelper.Init()
//if err != nil {
// panic(err)
//}
//// Set the client crypto helper in order to automatically encrypt outgoing messages
//client.Crypto = cryptoHelper
log.Info().Msg("Now running")
syncCtx, cancelSync := context.WithCancel(context.Background())
var syncStopWait sync.WaitGroup
syncStopWait.Add(1)
go func() {
err = client.SyncWithContext(syncCtx)
defer syncStopWait.Done()
if err != nil && !errors.Is(err, context.Canceled) {
panic(err)
}
}()
done := make(chan os.Signal)
signal.Notify(done, os.Interrupt)
<-done
//for {
// line, err := rl.Readline()
// if err != nil { // io.EOF
// break
// }
// if lastRoomID == "" {
// log.Error().Msg("Wait for an incoming message before sending messages")
// continue
// }
// resp, err := client.SendText(lastRoomID, line)
// if err != nil {
// log.Error().Err(err).Msg("Failed to send event")
// } else {
// log.Info().Str("event_id", resp.EventID.String()).Msg("Event sent")
// }
//}
cancelSync()
syncStopWait.Wait()
//err = cryptoHelper.Close()
//if err != nil {
// log.Error().Err(err).Msg("Error closing database")
//}
}