Count Number of Messages Example

Prev Next

In this example, we are creating an app that records the number of messages sent on the server using the Persistence object. All messages sent are associated with one record. The app will save the number of messages, which can be viewed from the app logs.

To store the message count, we can write an executePostMessageSent event handler. The app’s main class looks something like this:

import {
    IAppAccessors,
    IConfigurationExtend,
    IEnvironmentRead,
    IHttp,
    ILogger,
    IModify,
    IPersistence,
    IRead,
} from '@rocket.chat/apps-engine/definition/accessors';
import { App } from '@rocket.chat/apps-engine/definition/App';
import { IMessage, IPostMessageSent } from '@rocket.chat/apps-engine/definition/messages';
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
import { IRoom } from '@rocket.chat/apps-engine/definition/rooms';
import { RocketChatAssociationModel, RocketChatAssociationRecord } from '@rocket.chat/apps-engine/definition/metadata';
import { MessagePersistence } from './MessagePersistence';

export class PersistenceSampleApp extends App implements IPostMessageSent {
    constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) {
        super(info, logger, accessors);
    }
public async executePostMessageSent(message: IMessage, read: IRead, http: IHttp, persistence: IPersistence, modify: IModify): Promise<void> {
    //create a new association to count messages
    const association = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, 'message-count');
    const persis = read.getPersistenceReader();
    interface RecordItem {
            count: number;
        }
    
    try {
        const record = await persis.readByAssociation(association) as RecordItem[];
        let count = 0;

        if (record.length > 0) {
            count = record[0].count;
            this.getLogger().log(`Current count: ${count}`);
        }
        count ++;
        await persistence.updateByAssociation(association, { count }, true);

        //log the number of messages
        this.getLogger().log(`Updated Message Sent Count: ${count}`);
    } catch (err) {
        this.getLogger().error(err);
    }
}}

Here,

  • MISC enumeration is used as the association model for the number of messages.

  • The count variable temporarily stores the number of messages sent. It is initialized to zero and updated based on data retrieved from persistent storage.

  • When the executePostMessageSent handler is called, it retrieves the current message count using the readByAssociation method. If a record exists, the count variable is updated accordingly. See the IPersistenceRead interface for details.

  • Next, the count is incremented by one to account for the newly sent message. Finally, the updated count is saved back to persistent storage using the updateByAssociation method, ensuring the count is preserved across different handler executions. See the IPersistence interface for details.

Deploy the app to your workspace and test it by sending some messages to any channel. Then, check the app logs. The app:executePostMessageSent tabs show the number of messages.

In this way, even in a cluster environment, your app in each Rocket.Chat instance can share data from a single data source, the Rocket.Chat persistence storage and maintain data consistency.