How to use the matrix-bot-sdk.LogService.warn function in matrix-bot-sdk

To help you get started, we’ve selected a few matrix-bot-sdk examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github matrix-org / mjolnir / src / protections / BasicFlooding.ts View on Github external
public async handleEvent(mjolnir: Mjolnir, roomId: string, event: any): Promise {
        if (!this.lastEvents[roomId]) this.lastEvents[roomId] = {};

        const forRoom = this.lastEvents[roomId];
        if (!forRoom[event['sender']]) forRoom[event['sender']] = [];
        let forUser = forRoom[event['sender']];

        if ((new Date()).getTime() - event['origin_server_ts'] > TIMESTAMP_THRESHOLD) {
            LogService.warn("BasicFlooding", `${event['event_id']} is more than ${TIMESTAMP_THRESHOLD}ms out of phase - rewriting event time to be 'now'`);
            event['origin_server_ts'] = (new Date()).getTime();
        }

        forUser.push({originServerTs: event['origin_server_ts'], eventId: event['event_id']});

        // Do some math to see if the user is spamming
        let messageCount = 0;
        for (const prevEvent of forUser) {
            if ((new Date()).getTime() - prevEvent.originServerTs > 60000) continue; // not important
            messageCount++;
        }

        if (messageCount >= MAX_PER_MINUTE) {
            // Prioritize redaction over ban - we can always keep redacting what the user said.

            if (this.recentlyBanned.includes(event['sender'])) return; // already handled (will be redacted)
github matrix-org / mjolnir / src / utils.ts View on Github external
processed++;

            if (stopProcessingMembers.includes(event['sender'])) continue;
            if (testUser(event['sender'])) messages.push(event);
            if (event['type'] === 'm.room.member' && testUser(event['state_key']) && isTrueJoinEvent(event)) {
                stopProcessingMembers.push(event['sender']);
                if (!isGlob) return messages; // done!
            }
        }

        if (token) {
            bfMessages = await backfill(token);
            let lastToken = token;
            token = bfMessages['end'];
            if (lastToken === token) {
                LogService.warn("utils", "Backfill returned same end token - returning");
                return messages;
            }
        }
    } while (token);

    return messages;
}
github matrix-org / mjolnir / src / commands / UnbanBanCommand.ts View on Github external
export async function parseArguments(roomId: string, event: any, mjolnir: Mjolnir, parts: string[]): Promise {
    let defaultShortcode = null;
    try {
        const data = await mjolnir.client.getAccountData(DEFAULT_LIST_EVENT_TYPE);
        defaultShortcode = data['shortcode'];
    } catch (e) {
        LogService.warn("UnbanBanCommand", "Non-fatal error getting default ban list");
        LogService.warn("UnbanBanCommand", e);

        // Assume no default.
    }

    let argumentIndex = 2;
    let ruleType = null;
    let entity = null;
    let list = null;
    while (argumentIndex < 6 && argumentIndex < parts.length) {
        const arg = parts[argumentIndex++];
        if (!arg) break;
        if (["user", "room", "server"].includes(arg.toLowerCase())) {
            if (arg.toLowerCase() === 'user') ruleType = RULE_USER;
            if (arg.toLowerCase() === 'room') ruleType = RULE_ROOM;
            if (arg.toLowerCase() === 'server') ruleType = RULE_SERVER;
        } else if (!entity && (arg[0] === '@' || arg[0] === '!' || arg[0] === '#' || arg.includes("*"))) {
github matrix-org / mjolnir / src / Mjolnir.ts View on Github external
private async getEnabledProtections() {
        let enabled: string[] = [];
        try {
            const protections = await this.client.getAccountData(ENABLED_PROTECTIONS_EVENT_TYPE);
            if (protections && protections['enabled']) {
                for (const protection of protections['enabled']) {
                    enabled.push(protection);
                }
            }
        } catch (e) {
            LogService.warn("Mjolnir", e);
        }

        return enabled;
    }
github turt2live / matrix-voyager-bot / src / mq / mq.ts View on Github external
private async onMessage(message: any): Promise {
        try {
            if (!message) return;
            if (!message.properties) {
                LogService.warn("mq#onMessage", "Received message without properties - ignoring");
                return;
            }
            if (message.properties.contentType !== "application/json") {
                LogService.warn("mq#onMessage", "Received non-JSON message - ignoring");
                return;
            }
            if (message.properties.contentEncoding !== "utf8") {
                LogService.warn("mq#onMessage", "Received non-UTF8 message - ignoring");
                return;
            }
            if (!message.fields || !this.listeners[message.fields.routingKey]) {
                LogService.warn("mq#onMessage", "Received unexpected routing key - ignoring");
                return;
            }

            LogService.info("mq#onMessage", `Delivering ${message.properties.type} message from ${message.fields.routingKey} to ${this.listeners[message.fields.routingKey].length} handlers...`);
            const payload = JSON.parse(message.content.toString());
            for (const handler of this.listeners[message.fields.routingKey]) {
                handler(message.properties.type, payload);
            }

            LogService.info("mq#onMessage", "Acknowledging message...");
            await this.channel.ack(message);
            LogService.info("mq#onMessage", "Acknowledged.");
github matrix-org / mjolnir / src / Mjolnir.ts View on Github external
private async printActionResult(errors: RoomUpdateError[], title: string = null, logAnyways = false) {
        if (errors.length <= 0) return false;

        if (!logAnyways) {
            errors = errors.filter(e => ErrorCache.triggerError(e.roomId, e.errorKind));
            if (errors.length <= 0) {
                LogService.warn("Mjolnir", "Multiple errors are happening, however they are muted. Please check the management room.");
                return true;
            }
        }

        let html = "";
        let text = "";

        const htmlTitle = title ? `${title}<br>` : '';
        const textTitle = title ? `${title}\n` : '';

        html += `<font color="#ff0000"><b>${htmlTitle}${errors.length} errors updating protected rooms!</b></font><br><ul>`;
        text += `${textTitle}${errors.length} errors updating protected rooms!\n`;
        for (const error of errors) {
            const url = this.protectedRooms[error.roomId] ? this.protectedRooms[error.roomId] : `https://matrix.to/#/${error.roomId}`;
            html += `<li><a href="${url}">${error.roomId}</a> - ${error.errorMessage}</li>`;
            text += `${url} - ${error.errorMessage}\n`;</ul>
github matrix-org / mjolnir / src / Mjolnir.ts View on Github external
private async enableProtections() {
        for (const protection of await this.getEnabledProtections()) {
            try {
                this.enableProtection(protection, false);
            } catch (e) {
                LogService.warn("Mjolnir", e);
            }
        }
    }
github matrix-org / mjolnir / src / queues / AutomaticRedactionQueue.ts View on Github external
public async handleEvent(roomId: string, event: any, mjolnirClient: MatrixClient) {
        if (this.isUserQueued(event['sender'])) {
            const permalink = Permalinks.forEvent(roomId, event['event_id']);
            try {
                LogService.info("AutomaticRedactionQueue", `Redacting event because the user is listed as bad: ${permalink}`)
                if (!config.noop) {
                    await mjolnirClient.redactEvent(roomId, event['event_id']);
                } else {
                    await logMessage(LogLevel.WARN, "AutomaticRedactionQueue", `Tried to redact ${permalink} but Mjolnir is running in no-op mode`);
                }
            } catch (e) {
                logMessage(LogLevel.WARN, "AutomaticRedactionQueue", `Unable to redact message: ${permalink}`);
                LogService.warn("AutomaticRedactionQueue", e);
            }
        }
    }
}