mcTelegramBot/bot.js
2019-02-10 00:51:30 +03:00

54 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Telegraf from 'telegraf'
import { saveChat, getChats, saveLogout, getLastLogoutTime, saveKillCount, getKillCount } from './database'
import {
EVENT_TYPE_JOIN, EVENT_TYPE_DEATH, EVENT_TYPE_QUIT, EVENT_TYPE_PLAYER_LEVEL_CHANGE, EVENT_TYPE_PLAYER_KILLED_ENTITY
} from './types'
import { currentTime } from './utility'
import { getEntityDeathMessage, getEntityName } from './ru'
const bot = new Telegraf('643297173:AAGuqfZx3GhiiARwvY7AtWTTFw1T-2FiwCM')
bot.start(({ message: { chat: { id } } }) => saveChat(id))
bot.launch()
const sendMessageToAll = text => getChats()
.then(chats => chats.map(({ chatId }) => chatId)
.forEach(chatId => bot.telegram.sendMessage(chatId, text))
)
const JOIN_NOTIFICATION_TIME_DELTA = 60 * 60 // 1h
const LEVEL_NOFIFICATION_EACH_LEVELS = 5
const KILL_NOTIFICATION_EACH_KILLS = 50
export const sendEvent = ({ type, ...payload }) => {
switch (type) {
case EVENT_TYPE_JOIN:
getLastLogoutTime(payload.displayName)
.then(lastLogoutTime => lastLogoutTime < currentTime() - JOIN_NOTIFICATION_TIME_DELTA &&
sendMessageToAll(`Игрок ${payload.displayName} присоединился!`))
break
case EVENT_TYPE_QUIT:
saveLogout(payload.displayName)
break
case EVENT_TYPE_DEATH:
sendMessageToAll(`Игрок ${payload.displayName} ${getEntityDeathMessage(payload)} :(`)
break
case EVENT_TYPE_PLAYER_LEVEL_CHANGE:
const { newLevel } = payload
if (parseInt(newLevel) % LEVEL_NOFIFICATION_EACH_LEVELS === 0) {
sendMessageToAll(`Игрок ${payload.displayName} прокачался до уровня ${newLevel}!`)
}
break
case EVENT_TYPE_PLAYER_KILLED_ENTITY:
getKillCount(payload.displayName, payload.entityName)
.then(killCount => {
const newKillCount = killCount + 1
saveKillCount(payload.displayName, payload.entityName, newKillCount)
if (newKillCount % KILL_NOTIFICATION_EACH_KILLS === 0) {
sendMessageToAll(`${getEntityName(payload)} повержен(а) игроком ${payload.displayName}. Он убил ещё ${KILL_NOTIFICATION_EACH_KILLS}! Всего: ${newKillCount}`)
}
})
break
}
}