sendMessage method
This endpoint is used to send a message event to a room. Message events allow access to historical events and pagination, making them suited for "once-off" activity in a room.
The body of the request should be the content object of the event; the
fields in this object will vary depending on the type of event. See
Room Events for the m. event specification.
Homeservers MUST allow clients to send m.room.redaction events with this
endpoint for all room versions. In rooms with a version older than 11 they
MUST move the redacts property inside the content to the top level of
the event.
roomId The room to send the event to.
eventType The type of event to send.
txnId The transaction ID for this event. Clients should generate an
ID unique across requests with the same access token; it will be
used by the server to ensure idempotency of requests.
body
returns event_id:
A unique identifier for the event.
Implementation
Future<String> sendMessage(
String roomId,
String eventType,
String txnId,
Map<String, Object?> body,
) async {
final requestUri = Uri(
path:
'_matrix/client/v3/rooms/${Uri.encodeComponent(roomId)}/send/${Uri.encodeComponent(eventType)}/${Uri.encodeComponent(txnId)}',
);
final request = Request('PUT', baseUri!.resolveUri(requestUri));
request.headers['authorization'] = 'Bearer ${bearerToken!}';
request.headers['content-type'] = 'application/json';
request.bodyBytes = utf8.encode(jsonEncode(body));
const maxBodySize = 60000;
if (request.bodyBytes.length > maxBodySize) {
bodySizeExceeded(maxBodySize, request.bodyBytes.length);
}
final response = await httpClient.send(request);
final responseBody = await response.stream.toBytes();
if (response.statusCode != 200) unexpectedResponse(response, responseBody);
final responseString = utf8.decode(responseBody);
final json = jsonDecode(responseString);
return json['event_id'] as String;
}