Skip to content

Commit

Permalink
broadcast refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ender-null committed May 6, 2024
1 parent 01f2db9 commit 2dc8121
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 60 deletions.
88 changes: 80 additions & 8 deletions src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
Parameter,
Translation,
User,
WSBroadcast,
WSCommand,
WSCommandPayload,
WSMessage,
Expand All @@ -32,7 +33,7 @@ import { WebSocket } from 'ws';
import * as plugins from './plugins/index';
import * as cron from 'node-cron';
import { Actions } from './actions';
import { db } from './main';
import { bots, db, wss } from './main';

export class Bot {
platform: string;
Expand Down Expand Up @@ -433,22 +434,81 @@ export class Bot {
this.sendMessage(msg.conversation, content, type, reply, extra);
}

sendBroadcast(json: WSBroadcast): void {
const broadcast: WSBroadcast = json;
const conversation = broadcast.message.conversation;
if (conversation.id === 'alerts') {
conversation.id = this.config.alertsConversationId;
conversation.title = 'Alerts';
} else if (conversation.id === 'admin') {
conversation.id = this.config.adminConversationId;
conversation.title = 'Admin';
} else if (conversation.id === 'owner') {
conversation.id = this.config.owner;
conversation.title = 'Owner';
}
const message: WSMessage = {
bot: broadcast.bot,
platform: broadcast.platform,
type: 'message',
message: new Message(
null,
conversation,
this.user,
broadcast.message.content,
broadcast.message.type,
now(),
null,
broadcast.message.extra,
),
};
if (Array.isArray(broadcast.target)) {
this.broadcastHandler(broadcast.message);
broadcast.target.forEach((target) => {
if (bots[target]) {
bots[target].send(JSON.stringify(message));
}
});
} else if (broadcast.target === '*' || broadcast.target === 'all') {
wss.clients.forEach((client) => {
//if (client !== ws) {
this.broadcastHandler(broadcast.message);
client.send(JSON.stringify(message));
//}
});
} else {
this.broadcastHandler(broadcast.message);
if (bots[broadcast.target]) {
bots[broadcast.target].send(JSON.stringify(message));
}
}
}

sendAlert(text: string, language = 'javascript'): void {
if (
this.config.alertsConversationId &&
!(text.includes(this.config.alertsConversationId) || text.includes('Chat not found'))
) {
const message = new Message(
null,
new Conversation(this.config.alertsConversationId, 'Alerts'),
new Conversation('alerts'),
this.user,
`<code class="language-${language}">${text}</code>`,
`${this.user.firstName} (@${this.user.username}) [${this.user.id}]\n<code class="language-${language}">${text}</code>`,
'text',
null,
null,
{ format: 'HTML', preview: false },
);
this.send(message);
const broadcast: WSBroadcast = {
bot: this.config.name,
target: this.config.alertsTarget,
platform: this.config.alertsPlatform,
type: 'broadcast',
message,
};

//this.send(message);
this.sendBroadcast(broadcast);
}
}

Expand All @@ -459,15 +519,27 @@ export class Bot {
) {
const message = new Message(
null,
new Conversation(this.config.adminConversationId, 'Admin'),
new Conversation('admin'),
this.user,
text,
`${this.user.firstName} (@${this.user.username}) [${this.user.id}]\n${text}`,
'text',
null,
null,
{ format: 'HTML', preview: false },
{
format: 'HTML',
preview: false,
},
);
this.send(message);
const broadcast: WSBroadcast = {
bot: this.config.name,
target: this.config.alertsTarget,
platform: this.config.alertsPlatform,
type: 'broadcast',
message,
};

//this.send(message);
this.sendBroadcast(broadcast);
}
}
}
8 changes: 6 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ export class Config {
plugins?: string | string[];
excludedPlugins?: string[];
translation?: string;
adminConversationId?: string;
alertsPlatform?: string;
alertsTarget?: string;
alertsConversationId?: string;
adminConversationId?: string;
apiKeys?: ApiKeys;

constructor() {
Expand All @@ -24,8 +26,10 @@ export class Config {
this.plugins = '*';
this.excludedPlugins = [];
this.translation = 'default';
this.adminConversationId = null;
this.alertsPlatform = null;
this.alertsTarget = null;
this.alertsConversationId = null;
this.adminConversationId = null;
this.apiKeys = {
telegramBotToken: null,
telegramPhoneNumber: null,
Expand Down
55 changes: 5 additions & 50 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { WebSocketServer, WebSocket } from 'ws';
import { BotSocket, Message, MongoDatabases, WSBroadcast, WSInit, WSMessage, WSPong } from './types';
import { catchException, logger, now } from './utils';
import { BotSocket, MongoDatabases, WSInit, WSMessage, WSPong } from './types';
import { catchException, logger } from './utils';
import { Bot } from './bot';
import { MongoClient } from 'mongodb';

let mongo: MongoClient;
const wss: WebSocketServer = new WebSocketServer({ port: 8080 });
export const wss: WebSocketServer = new WebSocketServer({ port: 8080 });

const close = () => {
logger.info(`🟡 Closing connection for ${wss.clients.size} client(s)...`);
Expand All @@ -30,7 +30,7 @@ process.on('exit', () => {
logger.info('❎ Exit process');
});

const bots: BotSocket = {};
export const bots: BotSocket = {};
export const db: MongoDatabases = {};

const start = () => {
Expand Down Expand Up @@ -83,42 +83,7 @@ const start = () => {
};
ws.send(JSON.stringify(pong));
} else if (json.type === 'broadcast') {
const broadcast: WSBroadcast = json;
const message: WSMessage = {
bot: broadcast.bot,
platform: broadcast.platform,
type: 'message',
message: new Message(
null,
broadcast.message.conversation,
bot.user,
broadcast.message.content,
broadcast.message.type,
now(),
null,
broadcast.message.extra,
),
};
if (Array.isArray(broadcast.target)) {
bot.broadcastHandler(broadcast.message);
broadcast.target.forEach((target) => {
if (bots[target]) {
bots[target].send(JSON.stringify(message));
}
});
} else if (broadcast.target === '*' || broadcast.target === 'all') {
wss.clients.forEach((client) => {
if (client !== ws) {
bot.broadcastHandler(broadcast.message);
client.send(JSON.stringify(message));
}
});
} else {
bot.broadcastHandler(broadcast.message);
if (bots[broadcast.target]) {
bots[broadcast.target].send(JSON.stringify(message));
}
}
bot.sendBroadcast(json);
} else {
logger.warning(`Unsupported data: ${data}`);
}
Expand All @@ -139,13 +104,3 @@ MongoClient.connect(process.env.MONGODB_URI, {

await start();
});

/*export const db = new Database();
db.events.once('loaded', async () => {
await start();
db.events.on('update:configs', async () => {
await start();
});
});
db.init();
*/

0 comments on commit 2dc8121

Please sign in to comment.