From 5ef45db8646d98abc341fda80eccc254bb4ab20c Mon Sep 17 00:00:00 2001 From: The-Foxon Date: Sat, 1 Jul 2023 05:38:23 +1200 Subject: [PATCH] add sync message from eco server --- src/commands/index.ts | 12 ++++--- src/commands/setChatChannelId.ts | 36 +++++++++++++++++++ src/commands/syncMessages.ts | 34 ++++++++++++++++++ src/controller/ChatController.ts | 62 ++++++++++++++++++++++++++------ src/controller/ConfigManager.ts | 24 ++++++++++--- src/controller/MessageManager.ts | 0 src/index.ts | 13 ++++++- src/types/MessageI.ts | 2 +- 8 files changed, 162 insertions(+), 21 deletions(-) create mode 100644 src/commands/setChatChannelId.ts create mode 100644 src/commands/syncMessages.ts delete mode 100644 src/controller/MessageManager.ts diff --git a/src/commands/index.ts b/src/commands/index.ts index 92297f3..ae5c129 100644 --- a/src/commands/index.ts +++ b/src/commands/index.ts @@ -3,12 +3,16 @@ import syncUsers from './syncUsers' import Alert from './Alert' import Message from './Message' import Exec from './Exec' +import syncMessages from './syncMessages' +import setChatChannelId from './setChatChannelId' const commands = new Collection -commands.set('sync_users', syncUsers) -commands.set('alert', Alert) -commands.set('message', Message) -commands.set('exec', Exec) +commands.set(syncUsers.data.name, syncUsers) +commands.set(Alert.data.name, Alert) +commands.set(Message.data.name, Message) +commands.set(Exec.data.name, Exec) +commands.set(syncMessages.data.name, syncMessages) +commands.set(setChatChannelId.data.name, setChatChannelId) export default commands diff --git a/src/commands/setChatChannelId.ts b/src/commands/setChatChannelId.ts new file mode 100644 index 0000000..f0ae20d --- /dev/null +++ b/src/commands/setChatChannelId.ts @@ -0,0 +1,36 @@ +import { CacheType, ChatInputCommandInteraction, Message, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import ConfigManager from '../controller/ConfigManager'; +import ChatController from '../controller/ChatController'; +import { error } from 'console'; + +// const adminPermissions = new PermissionsBitField('Administrator'); + +export default { + data: new SlashCommandBuilder() + .setName('set_chat_channel') + .setDescription('set chat channel') + .setDefaultMemberPermissions(PermissionFlagsBits.Administrator), + async execute(interaction: ChatInputCommandInteraction, config: ConfigManager) { + + await interaction.deferReply({ ephemeral: true }) + + try { + if (!interaction.channel?.isTextBased()) throw new Error() + + global.config.chatChannelId = interaction.channelId + + if (!!global.config.chatChannelId) { + await interaction.followUp("Успешно") + } else { + await interaction.followUp("Ошибка синхронизации") + } + return + } catch (error) { + if (interaction.replied) + await interaction.editReply("Ошибка синхронизации") + else + await interaction.followUp("Ошибка синхронизации") + console.log(error) + } + }, +}; diff --git a/src/commands/syncMessages.ts b/src/commands/syncMessages.ts new file mode 100644 index 0000000..d05cacf --- /dev/null +++ b/src/commands/syncMessages.ts @@ -0,0 +1,34 @@ +import { CacheType, ChatInputCommandInteraction, Message, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js'; +import ConfigManager from '../controller/ConfigManager'; +import ChatController from '../controller/ChatController'; + + +// const adminPermissions = new PermissionsBitField('Administrator'); + +export default { + data: new SlashCommandBuilder() + .setName('sync_messages') + .setDescription('Sync all messages') + .setDefaultMemberPermissions(PermissionFlagsBits.Administrator), + async execute(interaction: ChatInputCommandInteraction, config: ConfigManager) { + const chatController = new ChatController(config) + + await interaction.deferReply({ ephemeral: true }) + + try { + const sync = await chatController.syncMessageWithDiscord() + if (sync) { + await interaction.followUp("Успешно") + } else { + await interaction.followUp("Ошибка синхронизации") + } + return + } catch (error) { + if (interaction.replied) + await interaction.editReply("Ошибка синхронизации") + else + await interaction.followUp("Ошибка синхронизации") + console.log(error) + } + }, +}; diff --git a/src/controller/ChatController.ts b/src/controller/ChatController.ts index 9da024e..5d3f0ed 100644 --- a/src/controller/ChatController.ts +++ b/src/controller/ChatController.ts @@ -1,14 +1,14 @@ -import { ActionRowBuilder, ButtonBuilder, ButtonStyle, CacheType, ChatInputCommandInteraction, Message } from "discord.js"; +import { ActionRowBuilder, ButtonBuilder, ButtonStyle, CacheType, ChatInputCommandInteraction, EmbedBuilder, Message } from "discord.js"; import ConfigManager from "./ConfigManager"; import axios from "axios"; import UserI from "../types/UserI"; import MessageI from "../types/MessageI"; +import { channel } from "diagnostics_channel"; -export default class UserManager { - config: ConfigManager - public constructor(config: ConfigManager) { - this.config = config - } +var isSyncing = false + +export default class ChatController { + public constructor() { } public async getMessages() { try { const { data, status } = await axios.get(`${process.env.ECO_API_BASE || "https://eco.kamgames.xyz"}/api/v1/chat`, { @@ -29,25 +29,67 @@ export default class UserManager { return false } public async syncMessageWithDiscord() { - if (!process.env.CHAT_CHANNEL_ID || !this.config.serverInfo) return false + if (isSyncing) return + + isSyncing = true + + if (!global.config.chatChannelId) { + isSyncing = false + return false + } try { - const { data, status } = await axios.get(`${process.env.ECO_API_BASE || "https://eco.kamgames.xyz"}/api/v1/chat?startDay=${(this.config.serverInfo.TimeSinceStart / 3600 - 10).toFixed(5)}`, { + const { data, status } = await axios.get( + `${process.env.ECO_API_BASE || "https://eco.kamgames.xyz"}/api/v1/chat?startDay=${global.config.messages.length > 0 ? (global.config.messages[global.config.messages.length - 1].Timestamp / 3600 - 60).toFixed(10) : 0}`, { timeout: 5000, headers: { "X-API-Key": process.env.ECO_API_KEY } }); - if (status !== 200) return false + if (status !== 200) { + isSyncing = false + return false + } - console.log(data) + if (data.length === 0) { + isSyncing = false + return true + } + const messages = data + + const ch = await global.client.channels.fetch(config.chatChannelId) + if (!ch || !ch.isTextBased()) { + isSyncing = false + return false + } + + messages.forEach(async m => { + if (global.config.messages.filter(v => + m.Timestamp === v.Timestamp && + m.Text === v.Text && + m.Sender === v.Sender && + m.Receiver === v.Receiver + ).length > 0) return + else { + // const me = new EmbedBuilder() + // me.setDescription(m.Text) + // me.setAuthor({ name: m.Sender }) + // ch.send({ embeds: [me] }) + await ch.send(`**${m.Sender}**: ${m.Text}`) + + global.config.messages.push(m) + } + }) + + isSyncing = false return true } catch (error) { console.log(error) } + isSyncing = false return false } } \ No newline at end of file diff --git a/src/controller/ConfigManager.ts b/src/controller/ConfigManager.ts index 7d533c7..f93e034 100644 --- a/src/controller/ConfigManager.ts +++ b/src/controller/ConfigManager.ts @@ -11,6 +11,7 @@ interface ConfigManagerI { }; messages?: MessageI[]; serverInfo?: ServerInfoI; + chatChannelId?: string; } export default class ConfigManager { @@ -23,18 +24,29 @@ export default class ConfigManager { authCodes: [], } public messages: MessageI[] = [] - public serverInfo?: ServerInfoI = undefined + // public serverInfo?: ServerInfoI = undefined + public chatChannelId: string = "" constructor() { this.load() setInterval(() => this.save(), 10000) } save() { - const r: ConfigManagerI = { userManager: this.userManager, messages: this.messages, serverInfo: this.serverInfo } + const r: ConfigManagerI = { + userManager: this.userManager, + messages: this.messages, + // serverInfo: this.serverInfo, + chatChannelId: this.chatChannelId, + } fs.writeFileSync(this.configPath, JSON.stringify(r)) } load() { - const r = { userManager: this.userManager, serverInfo: this.serverInfo, messages: this.messages } + const r = { + userManager: this.userManager, + // serverInfo: this.serverInfo, + messages: this.messages, + chatChannelId: this.chatChannelId, + } if (!fs.existsSync(this.configPath)) { fs.writeFileSync(this.configPath, JSON.stringify(r)) } @@ -44,8 +56,10 @@ export default class ConfigManager { this.userManager = { ...this.userManager, ...t.userManager } if (!!t?.messages) this.messages = t.messages - if (!!t?.serverInfo) - this.serverInfo = t.serverInfo + // if (!!t?.serverInfo) + // this.serverInfo = t.serverInfo + if (!!t?.chatChannelId) + this.chatChannelId = t.chatChannelId } catch (error) { console.log(error) } diff --git a/src/controller/MessageManager.ts b/src/controller/MessageManager.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/index.ts b/src/index.ts index 760a6de..6feb062 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,6 +5,7 @@ import ConfigManager from './controller/ConfigManager'; import updateCommands from './updateCommands'; import commands from './commands'; import { ServerInfoI } from './types/ServerInfoI'; +import ChatController from './controller/ChatController'; dotenv.config() @@ -22,12 +23,22 @@ const client = new Client({ ], }); +declare global { + var client: Client; + var config: ConfigManager; +} + const config = new ConfigManager() +const chatController = new ChatController() + +global.client = client +global.config = config client.on('ready', () => { console.log(`Logged in as ${client.user?.tag}!`); updateServerData(); setInterval(updateServerData, 10000) + setInterval(() => { chatController.syncMessageWithDiscord() }, 2000) }); async function updateServerData() { @@ -39,7 +50,7 @@ async function updateServerData() { name: `${data.OnlinePlayers}/${data.TotalPlayers}`, type: ActivityType.Playing }) - config.serverInfo = data + // config.serverInfo = data } catch (e) { client.user?.setActivity({ name: `Сервер офлайн`, diff --git a/src/types/MessageI.ts b/src/types/MessageI.ts index 0b3aa15..5af29e3 100644 --- a/src/types/MessageI.ts +++ b/src/types/MessageI.ts @@ -1,5 +1,5 @@ export default interface MessageI { - Timestamp: Number; + Timestamp: number; Sender: string; Receiver: string; Text: string;