nunbot/client.go
2022-07-13 15:20:59 -04:00

46 lines
1.1 KiB
Go

package main
import (
"fmt"
"log"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/id"
)
func newMatrixClient(config *botConfig) *mautrix.Client {
fmt.Println("Logging into", config.Homeserver, "as", config.Username)
var client *mautrix.Client
var err error
if config.Token == "" {
client, err = mautrix.NewClient(config.Homeserver, "", "")
if err != nil {
panic(err)
}
} else {
log.Println("using token login")
client, err = mautrix.NewClient(config.Homeserver, id.NewUserID(config.Username, config.Domain), config.Token)
if err != nil {
panic(err)
}
}
client.Store = NewLazyMemStore(config.Statefile)
if config.Token == "" {
loginRes, err := client.Login(&mautrix.ReqLogin{
Type: "m.login.password",
Identifier: mautrix.UserIdentifier{Type: mautrix.IdentifierTypeUser, User: config.Username},
Password: config.Password,
StoreCredentials: true,
})
if err != nil {
panic(err)
}
config.Token = loginRes.AccessToken
log.Println("Login succesful, saving access_token to config file")
writeConfig(config)
} else {
log.Println("skipping login since token provided")
}
return client
}