@tasolutions/express-core
Version:
All libs for express
95 lines (79 loc) • 3.65 kB
JavaScript
;
const { Client, GatewayIntentBits, TextChannel } = require('discord.js');
const _ = require('lodash');
const { discordInfo } = require('../../config');
const config = require('../../config');
module.exports = {
init: async () => {
// Kiểm tra nếu Discord bot được kích hoạt
if (discordInfo.enable !== 'true') {
console.log('[DiscordService] Discord bot is disabled; will not initialize.');
return; // Ngăn không cho khởi tạo nếu không được kích hoạt
}
const token = discordInfo.bot_token;
this.client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
this.client.login(token).then(() => {
console.log('[DiscordService] Discord bot logged in');
}).catch((error) => {
console.error('[DiscordService] Error logging in:', error);
});
},
sendMessage: async (title, message, channelInit = false) => {
if (!this.client) {
console.warn('[DiscordService] Discord bot is not initialized; cannot send message.');
return; // Ngăn không cho gửi tin nhắn nếu bot không được khởi tạo
}
try {
const channelId = channelInit ? channelInit : discordInfo.channel_id;
const channel = await this.client.channels.fetch(channelId);
if (channel && channel instanceof TextChannel) {
const appName = `${config.env}-${config.applicationName}` || 'Unknown Application Service';
// Hàm kiểm tra xem chuỗi có phải là JSON hợp lệ hay không
const isValidJson = (str) => {
try {
JSON.parse(str);
return true;
} catch {
return false;
}
};
const formattedMessage = isValidJson(message)
? `**${appName}**\n${title}\n\`\`\`json\n${message}\n\`\`\``
: `**${appName}**\n${title}\n${_.escape(message)}`;
await channel.send(formattedMessage);
console.log('[DiscordService] Message sent:', formattedMessage);
} else {
console.error('[DiscordService] Channel not found or not a text channel');
}
} catch (error) {
console.error('[DiscordService] Error sending message:', error);
return false;
}
},
disconnect: async () => {
if (this.client) {
await this.client.destroy();
console.log('[DiscordService] Discord bot disconnected');
}
},
formatObjectToMessage: (object) => {
if (!object || typeof object !== 'object') return '';
// Hàm để format key cho đẹp (có thể cải tiến với custom mapping)
const formatKey = (key) => {
return key
.replace(/_/g, ' ') // Thay thế dấu gạch dưới bằng khoảng trắng
.replace(/\b\w/g, char => char.toUpperCase()); // Viết hoa chữ cái đầu mỗi từ
};
let message = '';
for (let [key, value] of Object.entries(object)) {
// Kiểm tra và format ngày nếu cần
if (key.toLowerCase().includes('date') && !isNaN(Date.parse(value))) {
value = new Date(value).toLocaleString();
}
message += `🔹 **${formatKey(key)}:** ${value || 'Chưa cập nhật'}\n`;
}
return message;
},
};