78 lines
2.9 KiB
JavaScript
78 lines
2.9 KiB
JavaScript
import Telegraf from 'telegraf'
|
|
import { saveChat, getChats, saveLogoutTime, getLastLogoutTime, saveKillCount, getKillCount,
|
|
saveLevelUp, getLevelUpCount, saveLevel, setOnlineState, setOfflineState, getPlayersData
|
|
} 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.command(
|
|
'players',
|
|
({ replyWithMarkdown }) => getPlayersData()
|
|
.then(getPlayersData => replyWithMarkdown(
|
|
getPlayersData
|
|
.map(({ displayName, level, online }) => `:bust_in_silhouette: *${displayName}* уровень ${level} ${online ? '*онлайн*' : 'оффлайн'}`)
|
|
.join('\n')
|
|
))
|
|
)
|
|
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, displayName, ...payload }) => {
|
|
switch (type) {
|
|
case EVENT_TYPE_JOIN:
|
|
setOnlineState(displayName)
|
|
getLastLogoutTime(displayName)
|
|
.then(lastLogoutTime => lastLogoutTime < currentTime() - JOIN_NOTIFICATION_TIME_DELTA &&
|
|
sendMessageToAll(`Игрок ${displayName} присоединился!`))
|
|
break
|
|
case EVENT_TYPE_QUIT:
|
|
setOfflineState(displayName)
|
|
saveLogoutTime(displayName)
|
|
break
|
|
case EVENT_TYPE_DEATH:
|
|
sendMessageToAll(`Игрок ${displayName} ${getEntityDeathMessage(payload)} :(`)
|
|
break
|
|
case EVENT_TYPE_PLAYER_LEVEL_CHANGE:
|
|
const { newLevel, oldLevel } = payload
|
|
saveLevel(displayName, newLevel)
|
|
if (oldLevel && newLevel < oldLevel) {
|
|
return
|
|
}
|
|
const levelUpCount = getLevelUpCount(displayName)
|
|
if (newLevel % LEVEL_NOFIFICATION_EACH_LEVELS === 0 &&
|
|
levelUpCount >= LEVEL_NOFIFICATION_EACH_LEVELS
|
|
) {
|
|
sendMessageToAll(`Игрок ${displayName} прокачался до уровня ${newLevel}!`)
|
|
saveLevelUp(displayName, 0)
|
|
} else {
|
|
saveLevelUp(displayName, levelUpCount + 1)
|
|
}
|
|
break
|
|
case EVENT_TYPE_PLAYER_KILLED_ENTITY:
|
|
getKillCount(displayName, payload.entityName)
|
|
.then(killCount => {
|
|
const newKillCount = killCount + 1
|
|
saveKillCount(displayName, payload.entityName, newKillCount)
|
|
if (newKillCount % KILL_NOTIFICATION_EACH_KILLS === 0) {
|
|
sendMessageToAll(`${getEntityName(payload)} повержен(а) игроком ${displayName}. Убито ещё ${KILL_NOTIFICATION_EACH_KILLS}! Всего: ${newKillCount}`)
|
|
}
|
|
})
|
|
break
|
|
}
|
|
}
|