add sync message from eco server

This commit is contained in:
The Foxon 2023-07-01 05:38:23 +12:00
parent c98fc6f00c
commit 5ef45db864
8 changed files with 162 additions and 21 deletions

View File

@ -3,12 +3,16 @@ import syncUsers from './syncUsers'
import Alert from './Alert' import Alert from './Alert'
import Message from './Message' import Message from './Message'
import Exec from './Exec' import Exec from './Exec'
import syncMessages from './syncMessages'
import setChatChannelId from './setChatChannelId'
const commands = new Collection const commands = new Collection
commands.set('sync_users', syncUsers) commands.set(syncUsers.data.name, syncUsers)
commands.set('alert', Alert) commands.set(Alert.data.name, Alert)
commands.set('message', Message) commands.set(Message.data.name, Message)
commands.set('exec', Exec) commands.set(Exec.data.name, Exec)
commands.set(syncMessages.data.name, syncMessages)
commands.set(setChatChannelId.data.name, setChatChannelId)
export default commands export default commands

View File

@ -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<CacheType>, 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)
}
},
};

View File

@ -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<CacheType>, 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)
}
},
};

View File

@ -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 ConfigManager from "./ConfigManager";
import axios from "axios"; import axios from "axios";
import UserI from "../types/UserI"; import UserI from "../types/UserI";
import MessageI from "../types/MessageI"; import MessageI from "../types/MessageI";
import { channel } from "diagnostics_channel";
export default class UserManager { var isSyncing = false
config: ConfigManager
public constructor(config: ConfigManager) { export default class ChatController {
this.config = config public constructor() { }
}
public async getMessages() { public async getMessages() {
try { try {
const { data, status } = await axios.get<MessageI[]>(`${process.env.ECO_API_BASE || "https://eco.kamgames.xyz"}/api/v1/chat`, { const { data, status } = await axios.get<MessageI[]>(`${process.env.ECO_API_BASE || "https://eco.kamgames.xyz"}/api/v1/chat`, {
@ -29,25 +29,67 @@ export default class UserManager {
return false return false
} }
public async syncMessageWithDiscord() { 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 { try {
const { data, status } = await axios.get<MessageI[]>(`${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<MessageI[]>(
`${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, timeout: 5000,
headers: { headers: {
"X-API-Key": process.env.ECO_API_KEY "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 return true
} catch (error) { } catch (error) {
console.log(error) console.log(error)
} }
isSyncing = false
return false return false
} }
} }

View File

@ -11,6 +11,7 @@ interface ConfigManagerI {
}; };
messages?: MessageI[]; messages?: MessageI[];
serverInfo?: ServerInfoI; serverInfo?: ServerInfoI;
chatChannelId?: string;
} }
export default class ConfigManager { export default class ConfigManager {
@ -23,18 +24,29 @@ export default class ConfigManager {
authCodes: [], authCodes: [],
} }
public messages: MessageI[] = [] public messages: MessageI[] = []
public serverInfo?: ServerInfoI = undefined // public serverInfo?: ServerInfoI = undefined
public chatChannelId: string = ""
constructor() { constructor() {
this.load() this.load()
setInterval(() => this.save(), 10000) setInterval(() => this.save(), 10000)
} }
save() { 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)) fs.writeFileSync(this.configPath, JSON.stringify(r))
} }
load() { 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)) { if (!fs.existsSync(this.configPath)) {
fs.writeFileSync(this.configPath, JSON.stringify(r)) fs.writeFileSync(this.configPath, JSON.stringify(r))
} }
@ -44,8 +56,10 @@ export default class ConfigManager {
this.userManager = { ...this.userManager, ...t.userManager } this.userManager = { ...this.userManager, ...t.userManager }
if (!!t?.messages) if (!!t?.messages)
this.messages = t.messages this.messages = t.messages
if (!!t?.serverInfo) // if (!!t?.serverInfo)
this.serverInfo = t.serverInfo // this.serverInfo = t.serverInfo
if (!!t?.chatChannelId)
this.chatChannelId = t.chatChannelId
} catch (error) { } catch (error) {
console.log(error) console.log(error)
} }

View File

@ -5,6 +5,7 @@ import ConfigManager from './controller/ConfigManager';
import updateCommands from './updateCommands'; import updateCommands from './updateCommands';
import commands from './commands'; import commands from './commands';
import { ServerInfoI } from './types/ServerInfoI'; import { ServerInfoI } from './types/ServerInfoI';
import ChatController from './controller/ChatController';
dotenv.config() dotenv.config()
@ -22,12 +23,22 @@ const client = new Client({
], ],
}); });
declare global {
var client: Client<boolean>;
var config: ConfigManager;
}
const config = new ConfigManager() const config = new ConfigManager()
const chatController = new ChatController()
global.client = client
global.config = config
client.on('ready', () => { client.on('ready', () => {
console.log(`Logged in as ${client.user?.tag}!`); console.log(`Logged in as ${client.user?.tag}!`);
updateServerData(); updateServerData();
setInterval(updateServerData, 10000) setInterval(updateServerData, 10000)
setInterval(() => { chatController.syncMessageWithDiscord() }, 2000)
}); });
async function updateServerData() { async function updateServerData() {
@ -39,7 +50,7 @@ async function updateServerData() {
name: `${data.OnlinePlayers}/${data.TotalPlayers}`, name: `${data.OnlinePlayers}/${data.TotalPlayers}`,
type: ActivityType.Playing type: ActivityType.Playing
}) })
config.serverInfo = data // config.serverInfo = data
} catch (e) { } catch (e) {
client.user?.setActivity({ client.user?.setActivity({
name: `Сервер офлайн`, name: `Сервер офлайн`,

View File

@ -1,5 +1,5 @@
export default interface MessageI { export default interface MessageI {
Timestamp: Number; Timestamp: number;
Sender: string; Sender: string;
Receiver: string; Receiver: string;
Text: string; Text: string;