matrixbotlib/client.go

45 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-07-17 17:22:28 -04:00
package matrixbotlib
import (
"fmt"
"strings"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/id"
)
//NewMatrixClient returns a new logged in Mautrix Client struct
func NewMatrixClient(config *MatrixClientConfig, store mautrix.Storer) (*mautrix.Client, error) {
fmt.Println("Logging into", config.Homeserver, "as", config.Username)
var client *mautrix.Client
var err error
//make sure username is lower case otherwise token login breaks
uname := strings.ToLower(config.Username)
if config.Token == "" {
client, err = mautrix.NewClient(config.Homeserver, "", "")
if err != nil {
return client, err
}
} else {
client, err = mautrix.NewClient(config.Homeserver, id.NewUserID(uname, config.Domain), config.Token)
if err != nil {
return client, err
}
}
client.Store = store
if config.Token == "" {
loginRes, err := client.Login(&mautrix.ReqLogin{
Type: "m.login.password",
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: uname},
Password: config.Password,
StoreCredentials: true,
})
if err != nil {
return client, err
}
config.Token = loginRes.AccessToken
WriteMatrixClientConfig(config)
}
return client, err
}