add sync message from eco server
This commit is contained in:
parent
c98fc6f00c
commit
5ef45db864
@ -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
|
||||
|
36
src/commands/setChatChannelId.ts
Normal file
36
src/commands/setChatChannelId.ts
Normal 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)
|
||||
}
|
||||
},
|
||||
};
|
34
src/commands/syncMessages.ts
Normal file
34
src/commands/syncMessages.ts
Normal 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)
|
||||
}
|
||||
},
|
||||
};
|
@ -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<MessageI[]>(`${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<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,
|
||||
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
|
||||
}
|
||||
}
|
@ -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)
|
||||
}
|
||||
|
13
src/index.ts
13
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<boolean>;
|
||||
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: `Сервер офлайн`,
|
||||
|
@ -1,5 +1,5 @@
|
||||
export default interface MessageI {
|
||||
Timestamp: Number;
|
||||
Timestamp: number;
|
||||
Sender: string;
|
||||
Receiver: string;
|
||||
Text: string;
|
||||
|
Loading…
x
Reference in New Issue
Block a user