43 lines
1.1 KiB
Go
43 lines
1.1 KiB
Go
|
package matrixbotlib
|
||
|
|
||
|
import (
|
||
|
"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) {
|
||
|
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
|
||
|
}
|