Skip to content

Commit

Permalink
chore: bot rework
Browse files Browse the repository at this point in the history
  • Loading branch information
hmbanan666 committed Jan 22, 2025
1 parent b8c024d commit 76eea63
Show file tree
Hide file tree
Showing 9 changed files with 192 additions and 157 deletions.
2 changes: 1 addition & 1 deletion apps/telegram-game/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"unplugin-auto-import": "^19.0.0",
"unplugin-icons": "^22.0.0",
"unplugin-vue-components": "^28.0.0",
"vite": "^6.0.7",
"vite": "^6.0.11",
"vite-plugin-terminal": "^1.2.0",
"vite-plugin-vue-devtools": "^7.7.0",
"vue-tsc": "^2.2.0"
Expand Down
96 changes: 4 additions & 92 deletions apps/website/server/core/telegram/bot.ts
Original file line number Diff line number Diff line change
@@ -1,100 +1,18 @@
import { Bot } from 'grammy'
import { activateProduct } from '../product/activate'
import { dictionary } from './locale'
import { notifyAdmin } from './oldBot'

const logger = useLogger('telegram')
const { telegramBotToken, telegramGameBotToken, telegramAdminId } = useRuntimeConfig()
const { telegramGameBotToken } = useRuntimeConfig()

const startAppData = 'new'
const gameUrl = `tg://resolve?domain=woodlandsgamebot&appname=game&startapp=${startAppData}`
const gameChannelUrl = 'https://t.me/chatgamespace'

const woodlandsBotUrl = 'https://t.me/WoodlandsGameBot'
const twitchUrl = 'https://twitch.tv/hmbanan666'
const chatgameUrl = 'https://chatgame.space'

const ru: typeof en = {
chatgame: {
welcomeMessage: `Добро пожаловать в ChatGame! 🥳
Выбери игру или действие 👇`,
playingOnTwitch: '👾 Играем на Twitch',
},
woodland: {
welcomeMessage: `Добро пожаловать в Woodlands! 🥳
Одна из задач - сопровождать Машину из точки А в точку Б. По пути могут встречаться препятствия. Тапай их! 👆💪
Участвуй в событиях, приглашай друзей, добывай Монеты и разблокируй вручную созданных персонажей. 🤴🎅🐶`,
title: '🌲 Woodlands: Онлайн-игра',
play: '🎮 Играть',
developingGameOnTwitch: '👾 Улучшаем игру на Twitch',
website: '👨‍💻 Веб-сайт проекта',
},
subscribeToChannel: '📢 Подпишись на канал',
defaultBotReply: 'Я пока не умею отвечать на сообщения. Свяжись с @hmbanan666, если есть вопросы.',
}

const en = {
chatgame: {
welcomeMessage: `Welcome to ChatGame! 🥳
Choose the game or action 👇`,
playingOnTwitch: '👾 Playing on Twitch',
},
woodland: {
welcomeMessage: `Welcome to Woodlands! 🥳
One of the tasks is to accompany the Machine from point A to point B. Along the way, obstacles may appear. Tap them! 👆💪
Participate in events, invite friends, collect Coins and unlock manually created characters. 🤴🎅🐶`,
title: '🌲 Woodlands: Online Game',
play: '🎮 Play',
developingGameOnTwitch: '👾 Developing game on Twitch',
website: '👨‍💻 Project website',
},
subscribeToChannel: '📢 Subscribe to the channel',
defaultBotReply: 'I dont know how to reply to messages yet. Contact @hmbanan666 if you have any questions.',
}

function dictionary(locale: string | undefined = 'en') {
switch (locale) {
case 'ru':
return ru
default:
return en
}
}

const bot = new Bot(telegramBotToken)
const gameBot = new Bot(telegramGameBotToken)

// Old bot
bot.on('message:text', async (ctx) => {
const locale = ctx.message.from.language_code

if (ctx.hasCommand('start')) {
// Welcome message with buttons
await ctx.reply(
dictionary(locale).chatgame.welcomeMessage,
{
reply_markup: {
inline_keyboard: [
[{ text: dictionary(locale).woodland.title, url: woodlandsBotUrl }],
[{ text: dictionary(locale).subscribeToChannel, url: gameChannelUrl }],
[{ text: dictionary(locale).chatgame.playingOnTwitch, url: twitchUrl }],
],
},
},
)

return
}

logger.log(ctx.message.from.id, ctx.message.text)
ctx.reply(dictionary(locale).defaultBotReply)
})

// Game bot
gameBot.on('message:text', async (ctx) => {
try {
const locale = ctx.message.from.language_code
Expand All @@ -117,8 +35,6 @@ gameBot.on('message:text', async (ctx) => {
},
)

// await notifyAdmin(`[Woodlands] Команда старт от пользователя ${ctx.message.from.id} ${ctx.message.from.first_name}, locale: ${ctx.message.from.language_code}`)

return
}

Expand Down Expand Up @@ -181,8 +97,4 @@ gameBot.on('message:successful_payment', async (ctx) => {
}
})

async function notifyAdmin(message: string) {
return bot.api.sendMessage(telegramAdminId, message)
}

export { bot, gameBot, notifyAdmin }
export { gameBot }
21 changes: 21 additions & 0 deletions apps/website/server/core/telegram/locale/en.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const en = {
chatgame: {
welcomeMessage: `Welcome to ChatGame! 🥳
Choose the game or action 👇`,
playingOnTwitch: '👾 Playing on Twitch',
},
woodland: {
welcomeMessage: `Welcome to Woodlands! 🥳
One of the tasks is to accompany the Machine from point A to point B. Along the way, obstacles may appear. Tap them! 👆💪
Participate in events, invite friends, collect Coins and unlock manually created characters. 🤴🎅🐶`,
title: '🌲 Woodlands: Online Game',
play: '🎮 Play',
developingGameOnTwitch: '👾 Developing game on Twitch',
website: '👨‍💻 Project website',
},
subscribeToChannel: '📢 Subscribe to the channel',
defaultBotReply: 'I dont know how to reply to messages yet. Contact @hmbanan666 if you have any questions.',
}
13 changes: 13 additions & 0 deletions apps/website/server/core/telegram/locale/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { en } from './en'
import { ru } from './ru'

export type Dictionary = typeof en

export function dictionary(locale: string | undefined = 'en'): Dictionary {
switch (locale) {
case 'ru':
return ru
default:
return en
}
}
23 changes: 23 additions & 0 deletions apps/website/server/core/telegram/locale/ru.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { Dictionary } from '.'

export const ru: Dictionary = {
chatgame: {
welcomeMessage: `Добро пожаловать в ChatGame! 🥳
Выбери игру или действие 👇`,
playingOnTwitch: '👾 Играем на Twitch',
},
woodland: {
welcomeMessage: `Добро пожаловать в Woodlands! 🥳
Одна из задач - сопровождать Машину из точки А в точку Б. По пути могут встречаться препятствия. Тапай их! 👆💪
Участвуй в событиях, приглашай друзей, добывай Монеты и разблокируй вручную созданных персонажей. 🤴🎅🐶`,
title: '🌲 Woodlands: Онлайн-игра',
play: '🎮 Играть',
developingGameOnTwitch: '👾 Улучшаем игру на Twitch',
website: '👨‍💻 Веб-сайт проекта',
},
subscribeToChannel: '📢 Подпишись на канал',
defaultBotReply: 'Я пока не умею отвечать на сообщения. Свяжись с @hmbanan666, если есть вопросы.',
}
23 changes: 23 additions & 0 deletions apps/website/server/core/telegram/notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { gameBot } from './bot'

export async function sendNotificationToAllPlayers() {
const telegramProfiles = await prisma.telegramProfile.findMany()

for (const telegramProfile of telegramProfiles) {
try {
await gameBot.api.sendMessage(telegramProfile.telegramId, `Появилась возможность активировать предметы в Инвентаре! 🎉
Кладу тебе в Инвентарь Банан 🍌 Можешь его съесть и получить награду.`, {
reply_markup: {
inline_keyboard: [
[{ text: '🎮 Открыть игру', url: `tg://resolve?domain=woodlandsgamebot&appname=game&startapp=banana` }],
],
},
})
} catch (error) {
console.error(error)
}
}

return true
}
42 changes: 42 additions & 0 deletions apps/website/server/core/telegram/oldBot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Bot } from 'grammy'
import { dictionary } from './locale'

const logger = useLogger('telegram')
const { telegramBotToken, telegramAdminId } = useRuntimeConfig()

const gameChannelUrl = 'https://t.me/chatgamespace'
const woodlandsBotUrl = 'https://t.me/WoodlandsGameBot'
const twitchUrl = 'https://twitch.tv/hmbanan666'

const bot = new Bot(telegramBotToken)

bot.on('message:text', async (ctx) => {
const locale = ctx.message.from.language_code

if (ctx.hasCommand('start')) {
// Welcome message with buttons
await ctx.reply(
dictionary(locale).chatgame.welcomeMessage,
{
reply_markup: {
inline_keyboard: [
[{ text: dictionary(locale).woodland.title, url: woodlandsBotUrl }],
[{ text: dictionary(locale).subscribeToChannel, url: gameChannelUrl }],
[{ text: dictionary(locale).chatgame.playingOnTwitch, url: twitchUrl }],
],
},
},
)

return
}

logger.log(ctx.message.from.id, ctx.message.text)
ctx.reply(dictionary(locale).defaultBotReply)
})

async function notifyAdmin(message: string) {
return bot.api.sendMessage(telegramAdminId, message)
}

export { bot, notifyAdmin }
3 changes: 2 additions & 1 deletion apps/website/server/plugins/03.startTelegram.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import process from 'node:process'
import { bot, gameBot } from '../core/telegram/bot'
import { gameBot } from '../core/telegram/bot'
import { bot } from '../core/telegram/oldBot'

export default defineNitroPlugin(() => {
if (process.env.NODE_ENV !== 'production') {
Expand Down
Loading

0 comments on commit 76eea63

Please sign in to comment.