Created
January 29, 2019 10:18
-
-
Save technix/b7e8263c40090c98e19dae57c8b09b0a to your computer and use it in GitHub Desktop.
Telegram bot for choice-based games
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const TelegramBot = require('node-telegram-bot-api'); | |
const atrament = require('./atrament'); | |
const token = 'SECRET-TOKEN-HERE'; | |
const bot = new TelegramBot(token, {polling: true}); | |
let chatId; | |
const kbdMessage = {}; | |
const gameConfig = { | |
episodes: [ | |
'capsule.ink.json' | |
] | |
}; | |
function fileLoader(filename) { | |
return new Promise((resolve) => { | |
fs.readFile(filename, (err, data) => { | |
resolve(data); | |
}); | |
}); | |
} | |
function sendMessageWithKbd (chatId, text, inline_keyboard) { | |
bot.sendMessage(chatId, text, { parse_mode: 'Markdown' }) | |
.then(() => bot.sendMessage(chatId, '-', { | |
parse_mode: 'Markdown', | |
one_time_keyboard: true, | |
reply_markup: { | |
inline_keyboard | |
} | |
})).then((msg) => { | |
kbdMessage[chatId] = msg.message_id; | |
}); | |
} | |
atrament.init(gameConfig); | |
atrament.on('loadStory', fileLoader); | |
atrament.on('error', (e) => console.error(e)); | |
atrament.registerCommand( | |
'CLEAR', | |
() => { return false; } | |
); | |
function renderScene() { | |
const scene = atrament.renderScene(); | |
let sceneText = scene.text.join(''); | |
if (!sceneText) { | |
sceneText = '.'; | |
} | |
if (!scene.choices.length) { | |
// game over | |
return; | |
} | |
const choices = scene.choices.map( | |
(t) => ([{text:t.choice, callback_data:t.id}]) | |
); | |
sendMessageWithKbd(chatId, sceneText, choices); | |
} | |
bot.on('message', (msg) => { | |
chatId = msg.chat.id; | |
if (msg.text === '/start') { | |
atrament.startGame().then(renderScene); | |
} else { | |
bot.sendMessage(chatId, 'Say "/start" to start game.') | |
} | |
}); | |
bot.on('callback_query', (res) => { | |
chatId = res.message.chat.id; | |
if (kbdMessage[chatId]) { | |
bot.deleteMessage(chatId, kbdMessage[chatId]).then(() => kbdMessage[chatId] = null); | |
} | |
atrament.makeChoice(res.data); | |
renderScene(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment