gomatrix package - github.com/matrix-org/gomatrix - Go Packages (original) (raw)
Package gomatrix implements the Matrix Client-Server API.
Specification can be found at http://matrix.org/docs/spec/client_server/r0.2.0.html
// Custom interfaces must be set prior to calling functions on the client. cli, _ := NewClient("https://matrix.org", "@example:matrix.org", "MDAefhiuwehfuiwe")
// anything which implements the Storer interface customStore := NewInMemoryStore() cli.Store = customStore
// anything which implements the Syncer interface customSyncer := NewDefaultSyncer("@example:matrix.org", customStore) cli.Syncer = customSyncer
// any http.Client cli.Client = http.DefaultClient
// Once you call a function, you can't safely change the interfaces. _, _ = cli.SendText("!foo:bar", "Down the rabbit hole")
cli, _ := NewClient("https://matrix.org", "@example:matrix.org", "MDAefhiuwehfuiwe") cli.Store.SaveFilterID("@example:matrix.org", "2") // Optional: if you know it already cli.Store.SaveNextBatch("@example:matrix.org", "111_222_333_444") // Optional: if you know it already syncer := cli.Syncer.(*DefaultSyncer) syncer.OnEventType("m.room.message", func(ev *Event) { fmt.Println("Message: ", ev) })
// Blocking version if err := cli.Sync(); err != nil { fmt.Println("Sync() returned ", err) }
// Non-blocking version go func() { for { if err := cli.Sync(); err != nil { fmt.Println("Sync() returned ", err) } // Optional: Wait a period of time before trying to sync again. } }()
- func (cli *Client) BanUser(roomID string, req *ReqBanUser) (resp *RespBanUser, err error)
- func (cli *Client) BuildBaseURL(urlPath ...string) string
- func (cli *Client) BuildURL(urlPath ...string) string
- func (cli *Client) BuildURLWithQuery(urlPath []string, urlQuery map[string]string) string
- func (cli *Client) ClearCredentials()
- func (cli *Client) CreateFilter(filter json.RawMessage) (resp *RespCreateFilter, err error)
- func (cli *Client) CreateRoom(req *ReqCreateRoom) (resp *RespCreateRoom, err error)
- func (cli *Client) ForgetRoom(roomID string) (resp *RespForgetRoom, err error)
- func (cli *Client) GetAvatarURL() (string, error)
- func (cli *Client) GetDisplayName(mxid string) (resp *RespUserDisplayName, err error)
- func (cli *Client) GetOwnDisplayName() (resp *RespUserDisplayName, err error)
- func (cli *Client) GetOwnStatus() (resp *RespUserStatus, err error)
- func (cli *Client) GetStatus(mxid string) (resp *RespUserStatus, err error)
- func (cli *Client) InviteUser(roomID string, req *ReqInviteUser) (resp *RespInviteUser, err error)
- func (cli *Client) InviteUserByThirdParty(roomID string, req *ReqInvite3PID) (resp *RespInviteUser, err error)
- func (cli *Client) JoinRoom(roomIDorAlias, serverName string, content interface{}) (resp *RespJoinRoom, err error)
- func (cli *Client) JoinedMembers(roomID string) (resp *RespJoinedMembers, err error)
- func (cli *Client) JoinedRooms() (resp *RespJoinedRooms, err error)
- func (cli *Client) KickUser(roomID string, req *ReqKickUser) (resp *RespKickUser, err error)
- func (cli *Client) LeaveRoom(roomID string) (resp *RespLeaveRoom, err error)
- func (cli *Client) Login(req *ReqLogin) (resp *RespLogin, err error)
- func (cli *Client) Logout() (resp *RespLogout, err error)
- func (cli *Client) LogoutAll() (resp *RespLogoutAll, err error)
- func (cli *Client) MakeRequest(method string, httpURL string, reqBody interface{}, resBody interface{}) error
- func (cli *Client) MarkRead(roomID, eventID string) error
- func (cli *Client) Messages(roomID, from, to string, dir rune, limit int) (resp *RespMessages, err error)
- func (cli *Client) PublicRooms(limit int, since string, server string) (resp *RespPublicRooms, err error)
- func (cli *Client) PublicRoomsFiltered(limit int, since string, server string, filter string) (resp *RespPublicRooms, err error)
- func (cli *Client) RedactEvent(roomID, eventID string, req *ReqRedact) (resp *RespSendEvent, err error)
- func (cli *Client) Register(req *ReqRegister) (*RespRegister, *RespUserInteractive, error)
- func (cli *Client) RegisterDummy(req *ReqRegister) (*RespRegister, error)
- func (cli *Client) RegisterGuest(req *ReqRegister) (*RespRegister, *RespUserInteractive, error)
- func (cli *Client) SendFormattedText(roomID, text, formattedText string) (*RespSendEvent, error)
- func (cli *Client) SendImage(roomID, body, url string) (*RespSendEvent, error)
- func (cli *Client) SendMessageEvent(roomID string, eventType string, contentJSON interface{}) (resp *RespSendEvent, err error)
- func (cli *Client) SendNotice(roomID, text string) (*RespSendEvent, error)
- func (cli *Client) SendStateEvent(roomID, eventType, stateKey string, contentJSON interface{}) (resp *RespSendEvent, err error)
- func (cli *Client) SendText(roomID, text string) (*RespSendEvent, error)
- func (cli *Client) SendVideo(roomID, body, url string) (*RespSendEvent, error)
- func (cli *Client) SetAvatarURL(url string) error
- func (cli *Client) SetCredentials(userID, accessToken string)
- func (cli *Client) SetDisplayName(displayName string) (err error)
- func (cli *Client) SetStatus(presence, status string) (err error)
- func (cli *Client) StateEvent(roomID, eventType, stateKey string, outContent interface{}) (err error)
- func (cli *Client) StopSync()
- func (cli *Client) Sync() error
- func (cli *Client) SyncRequest(timeout int, since, filterID string, fullState bool, setPresence string) (resp *RespSync, err error)
- func (cli *Client) TurnServer() (resp *RespTurnServer, err error)
- func (cli *Client) UnbanUser(roomID string, req *ReqUnbanUser) (resp *RespUnbanUser, err error)
- func (cli *Client) UploadLink(link string) (*RespMediaUpload, error)
- func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (*RespMediaUpload, error)
- func (cli *Client) UserTyping(roomID string, typing bool, timeout int64) (resp *RespTyping, err error)
- func (cli *Client) Versions() (resp *RespVersions, err error)
- func (s *DefaultSyncer) GetFilterJSON(userID string) json.RawMessage
- func (s *DefaultSyncer) OnEventType(eventType string, callback OnEventListener)
- func (s *DefaultSyncer) OnFailedSync(res *RespSync, err error) (time.Duration, error)
- func (s *DefaultSyncer) ProcessResponse(res *RespSync, since string) (err error)
- func (s *InMemoryStore) LoadFilterID(userID string) string
- func (s *InMemoryStore) LoadNextBatch(userID string) string
- func (s *InMemoryStore) LoadRoom(roomID string) *Room
- func (s *InMemoryStore) SaveFilterID(userID, filterID string)
- func (s *InMemoryStore) SaveNextBatch(userID, nextBatchToken string)
- func (s *InMemoryStore) SaveRoom(room *Room)
This section is empty.
This section is empty.
DecodeUserLocalpart decodes the given string back into the original input string. Returns an error if the given string is not a valid user ID localpart encoding. See http://matrix.org/docs/spec/intro.html#mapping-from-other-character-sets
This decodes quoted-printable bytes back into UTF8, and unescapes casing. For example:
_alph=40_bet=5f50up => Alph@Bet_50up
Returns an error if the input string contains characters outside the range "a-z0-9._=-", has an invalid quote-printable byte (e.g. not hex), or has an invalid _ escaped byte (e.g. "_5").
localpart, err := DecodeUserLocalpart("_alph=40_bet__50up") if err != nil { panic(err) } fmt.Println(localpart)
Output: Alph@Bet_50up
EncodeUserLocalpart encodes the given string into Matrix-compliant user ID localpart form. See http://matrix.org/docs/spec/intro.html#mapping-from-other-character-sets
This returns a string with only the characters "a-z0-9._=-". The uppercase range A-Z are encoded using leading underscores ("_"). Characters outside the aforementioned ranges (including literal underscores ("_") and equals ("=")) are encoded as UTF8 code points (NOT NCRs) and converted to lower-case hex with a leading "=". For example:
Alph@Bet_50up => _alph=40_bet=5f50up
localpart := EncodeUserLocalpart("Alph@Bet_50up") fmt.Println(localpart)
Output: _alph=40_bet__50up
Client represents a Matrix client.
func NewClient(homeserverURL, userID, accessToken string) (*Client, error)
NewClient creates a new Matrix Client ready for syncing
BuildBaseURL builds a URL with the Client's homeserver set already. You must supply the prefix in the path.
userID := "@example:matrix.org" cli, _ := NewClient("https://matrix.org", userID, "abcdef123456") out := cli.BuildBaseURL("_matrix", "client", "r0", "directory", "room", "#matrix:matrix.org") fmt.Println(out)
Output: https://matrix.org/_matrix/client/r0/directory/room/%23matrix:matrix.org
BuildURL builds a URL with the Client's homeserver/prefix set already.
userID := "@example:matrix.org" cli, _ := NewClient("https://matrix.org", userID, "abcdef123456") out := cli.BuildURL("user", userID, "filter") fmt.Println(out)
Output: https://matrix.org/_matrix/client/r0/user/@example:matrix.org/filter
BuildURLWithQuery builds a URL with query parameters in addition to the Client's homeserver/prefix set already.
cli, _ := NewClient("https://matrix.org", "@example:matrix.org", "abcdef123456") out := cli.BuildURLWithQuery([]string{"sync"}, map[string]string{ "filter_id": "5", }) fmt.Println(out)
Output: https://matrix.org/_matrix/client/r0/sync?filter_id=5
func (cli *Client) ClearCredentials()
ClearCredentials removes the user ID and access token on this client instance.
func (cli *Client) JoinRoom(roomIDorAlias, serverName string, content interface{}) (resp *RespJoinRoom, err error)
JoinRoom joins the client to a room ID or alias. See http://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-join-roomidoralias
If serverName is specified, this will be added as a query param to instruct the homeserver to join via that server. If content is specified, it will be JSON encoded and used as the request body.
Join a room by alias.
cli, _ := NewClient("http://localhost:8008", "@example:localhost", "abcdef123456") if resp, err := cli.JoinRoom("#test:localhost", "", nil); err != nil { panic(err) } else { // Use room ID for something. _ = resp.RoomID }
Join a room by ID.
cli, _ := NewClient("http://localhost:8008", "@example:localhost", "abcdef123456") if _, err := cli.JoinRoom("!uOILRrqxnsYgQdUzar:localhost", "", nil); err != nil { panic(err) }
JoinedMembers returns a map of joined room members. See TODO-SPEC. https://github.com/matrix-org/synapse/pull/1680
In general, usage of this API is discouraged in favour of /sync, as calling this API can race with incoming membership changes. This API is primarily designed for application services which may want to efficiently look up joined members in a room.
func (cli *Client) JoinedRooms() (resp *RespJoinedRooms, err error)
JoinedRooms returns a list of rooms which the client is joined to. See TODO-SPEC. https://github.com/matrix-org/synapse/pull/1680
In general, usage of this API is discouraged in favour of /sync, as calling this API can race with incoming membership changes. This API is primarily designed for application services which may want to efficiently look up joined rooms.
func (cli *Client) Login(req *ReqLogin) (resp *RespLogin, err error)
Login a user to the homeserver according to http://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-loginThis does not set credentials on this client instance. See SetCredentials() instead.
Login to a local homeserver and set the user ID and access token on success.
cli, _ := NewClient("http://localhost:8008", "", "") resp, err := cli.Login(&ReqLogin{ Type: "m.login.password", User: "alice", Password: "wonderland", }) if err != nil { panic(err) } cli.SetCredentials(resp.UserID, resp.AccessToken)
func (cli *Client) MakeRequest(method string, httpURL string, reqBody interface{}, resBody interface{}) error
MakeRequest makes a JSON HTTP request to the given URL. The response body will be stream decoded into an interface. This will automatically stop if the response body is nil.
Returns an error if the response is not 2xx along with the HTTP body bytes if it got that far. This error is an HTTPError which includes the returned HTTP status code, byte contents of the response body and possibly a RespError as the WrappedError, if the HTTP body could be decoded as a RespError.
func (cli *Client) RegisterDummy(req ReqRegister) (RespRegister, error)
RegisterDummy performs m.login.dummy registration according to https://matrix.org/docs/spec/client_server/r0.2.0.html#dummy-auth
Only a username and password need to be provided on the ReqRegister struct. Most local/developer homeservers will allow registration this way. If the homeserver does not, an error is returned.
This does not set credentials on the client instance. See SetCredentials() instead.
res, err := cli.RegisterDummy(&gomatrix.ReqRegister{
Username: "alice",
Password: "wonderland",
})if err != nil { panic(err) } token := res.AccessToken
func (cli *Client) SetCredentials(userID, accessToken string)
SetCredentials sets the user ID and access token on this client instance.
func (cli *Client) StateEvent(roomID, eventType, stateKey string, outContent interface{}) (err error)
StateEvent gets a single state event in a room. It will attempt to JSON unmarshal into the given "outContent" struct with the HTTP response body, or return an error. See http://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-client-r0-rooms-roomid-state-eventtype-statekey
Retrieve the content of a m.room.name state event.
content := struct {
Name string json:"name"
}{}
cli, _ := NewClient("https://matrix.org", "@example:matrix.org", "abcdef123456")
if err := cli.StateEvent("!foo:bar", "m.room.name", "", &content); err != nil {
panic(err)
}
func (cli *Client) StopSync()
StopSync stops the ongoing sync started by Sync.
Sync starts syncing with the provided Homeserver. If Sync() is called twice then the first sync will be stopped and the error will be nil.
This function will block until a fatal /sync error occurs, so it should almost always be started as a new goroutine. Fatal sync errors can be caused by:
- The failure to create a filter.
- Client.Syncer.OnFailedSync returning an error in response to a failed sync.
- Client.Syncer.ProcessResponse returning an error.
If you wish to continue retrying in spite of these fatal errors, call Sync() again.
UploadLink uploads an HTTP URL and then returns an MXC URI.
type DefaultSyncer struct { UserID string Store Storer
}
DefaultSyncer is the default syncing implementation. You can either write your own syncer, or selectively replace parts of this default syncer (e.g. the ProcessResponse method). The default syncer uses the observer pattern to notify callers about incoming events. See DefaultSyncer.OnEventType for more information.
func NewDefaultSyncer(userID string, store Storer) *DefaultSyncer
NewDefaultSyncer returns an instantiated DefaultSyncer
GetFilterJSON returns a filter with a timeline limit of 50.
func (s *DefaultSyncer) OnEventType(eventType string, callback OnEventListener)
OnEventType allows callers to be notified when there are new events for the given event type. There are no duplicate checks.
OnFailedSync always returns a 10 second wait period between failed /syncs, never a fatal error.
ProcessResponse processes the /sync response in a way suitable for bots. "Suitable for bots" means a stream of unrepeating events. Returns a fatal error if a listener panics.
type Event struct {
StateKey *string json:"state_key,omitempty"
Sender string json:"sender"
Type string json:"type"
Timestamp int64 json:"origin_server_ts"
ID string json:"event_id"
RoomID string json:"room_id"
Redacts string json:"redacts,omitempty"
Unsigned map[string]interface{} json:"unsigned"
Content map[string]interface{} json:"content"
PrevContent map[string]interface{} json:"prev_content,omitempty"
}
Event represents a single Matrix event.
func (*Event) Body ¶
Body returns the value of the "body" key in the event content if it is present and is a string.
func (event *Event) MessageType() (msgtype string, ok bool)
MessageType returns the value of the "msgtype" key in the event content if it is present and is a string.
type Filter struct {
AccountData FilterPart json:"account_data,omitempty"
EventFields []string json:"event_fields,omitempty"
EventFormat string json:"event_format,omitempty"
Presence FilterPart json:"presence,omitempty"
Room RoomFilter json:"room,omitempty"
}
Filter is used by clients to specify how the server should filter responses to e.g. sync requests Specified by: https://matrix.org/docs/spec/client_server/r0.2.0.html#filtering
func DefaultFilter() Filter
DefaultFilter returns the default filter used by the Matrix server if no filter is provided in the request
func (filter *Filter) Validate() error
Validate checks if the filter contains valid property values
type FilterPart struct {
NotRooms []string json:"not_rooms,omitempty"
Rooms []string json:"rooms,omitempty"
Limit int json:"limit,omitempty"
NotSenders []string json:"not_senders,omitempty"
NotTypes []string json:"not_types,omitempty"
Senders []string json:"senders,omitempty"
Types []string json:"types,omitempty"
ContainsURL *bool json:"contains_url,omitempty"
}
FilterPart is used to define filtering rules for specific categories of events
func DefaultFilterPart() FilterPart
DefaultFilterPart returns the default filter part used by the Matrix server if no filter is provided in the request
type HTMLMessage struct {
Body string json:"body"
MsgType string json:"msgtype"
Format string json:"format"
FormattedBody string json:"formatted_body"
}
An HTMLMessage is the contents of a Matrix HTML formated message event.
func GetHTMLMessage(msgtype, htmlText string) HTMLMessage
GetHTMLMessage returns an HTMLMessage with the body set to a stripped version of the provided HTML, in addition to the provided HTML.
HTTPError An HTTP Error response, which may wrap an underlying native Go Error.
type ImageMessage struct {
MsgType string json:"msgtype"
Body string json:"body"
URL string json:"url"
Info ImageInfo json:"info"
}
ImageMessage is an m.image event
InMemoryStore implements the Storer interface.
Everything is persisted in-memory as maps. It is not safe to load/save filter IDs or next batch tokens on any goroutine other than the syncing goroutine: the one which called Client.Sync().
func NewInMemoryStore() *InMemoryStore
NewInMemoryStore constructs a new InMemoryStore.
LoadFilterID from memory.
LoadNextBatch from memory.
func (s *InMemoryStore) SaveFilterID(userID, filterID string)
SaveFilterID to memory.
func (s *InMemoryStore) SaveNextBatch(userID, nextBatchToken string)
SaveNextBatch to memory.
func (s *InMemoryStore) SaveRoom(room *Room)
SaveRoom to memory.
type OnEventListener func(*Event)
OnEventListener can be used with DefaultSyncer.OnEventType to be informed of incoming events.
type PublicRoom struct {
CanonicalAlias string json:"canonical_alias"
Name string json:"name"
WorldReadable bool json:"world_readable"
Topic string json:"topic"
NumJoinedMembers int json:"num_joined_members"
AvatarURL string json:"avatar_url"
RoomID string json:"room_id"
GuestCanJoin bool json:"guest_can_join"
Aliases []string json:"aliases"
}
PublicRoom represents the information about a public room obtainable from the room directory
type ReqCreateRoom struct {
Visibility string json:"visibility,omitempty"
RoomAliasName string json:"room_alias_name,omitempty"
Name string json:"name,omitempty"
Topic string json:"topic,omitempty"
Invite []string json:"invite,omitempty"
Invite3PID []ReqInvite3PID json:"invite_3pid,omitempty"
CreationContent map[string]interface{} json:"creation_content,omitempty"
InitialState []Event json:"initial_state,omitempty"
Preset string json:"preset,omitempty"
IsDirect bool json:"is_direct,omitempty"
}
ReqCreateRoom is the JSON request for https://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-createroom
type RespSync struct {
NextBatch string json:"next_batch"
AccountData struct {
Events []Event json:"events"
} json:"account_data"
Presence struct {
Events []Event json:"events"
} json:"presence"
Rooms struct {
Leave map[string]struct {
State struct {
Events []Event json:"events"
} json:"state"
Timeline struct {
Events []Event json:"events"
Limited bool json:"limited"
PrevBatch string json:"prev_batch"
} json:"timeline"
} json:"leave"
Join map[string]struct {
State struct {
Events []Event json:"events"
} json:"state"
Timeline struct {
Events []Event json:"events"
Limited bool json:"limited"
PrevBatch string json:"prev_batch"
} json:"timeline"
Ephemeral struct {
Events []Event json:"events"
} json:"ephemeral"
} json:"join"
Invite map[string]struct {
State struct {
Events []Event
} json:"invite_state"
} json:"invite"
} json:"rooms"
}
RespSync is the JSON response for http://matrix.org/docs/spec/client_server/r0.2.0.html#get-matrix-client-r0-sync
type RespTurnServer struct {
Username string json:"username"
Password string json:"password"
TTL int json:"ttl"
URIs []string json:"uris"
}
RespTurnServer is the JSON response from a Turn Server
Room represents a single Matrix room.
NewRoom creates a new Room with the given ID
GetMembershipState returns the membership state of the given user ID in this room. If there is no entry for this member, 'leave' is returned for consistency with left users.
GetStateEvent returns the state event for the given type/state_key combo, or nil.
func (room Room) UpdateState(event *Event)
UpdateState updates the room's current state with the given Event. This will clobber events based on the type/state_key combination.
type RoomFilter struct {
AccountData FilterPart json:"account_data,omitempty"
Ephemeral FilterPart json:"ephemeral,omitempty"
IncludeLeave bool json:"include_leave,omitempty"
NotRooms []string json:"not_rooms,omitempty"
Rooms []string json:"rooms,omitempty"
State FilterPart json:"state,omitempty"
Timeline FilterPart json:"timeline,omitempty"
}
RoomFilter is used to define filtering rules for room events
type Storer interface { SaveFilterID(userID, filterID string) LoadFilterID(userID string) string SaveNextBatch(userID, nextBatchToken string) LoadNextBatch(userID string) string SaveRoom(room *Room) LoadRoom(roomID string) *Room }
Storer is an interface which must be satisfied to store client data.
You can either write a struct which persists this data to disk, or you can use the provided "InMemoryStore" which just keeps data around in-memory which is lost on restarts.
Syncer represents an interface that must be satisfied in order to do /sync requests on a client.
type TagProperties struct {
Order float32 json:"order,omitempty"
}
TagProperties contains the properties of a Tag
type TextMessage struct {
MsgType string json:"msgtype"
Body string json:"body"
FormattedBody string json:"formatted_body"
Format string json:"format"
}
TextMessage is the contents of a Matrix formated message event.