Skip to content

Instantly share code, notes, and snippets.

@technix
Created January 29, 2019 10:18
Show Gist options
  • Save technix/b7e8263c40090c98e19dae57c8b09b0a to your computer and use it in GitHub Desktop.
Save technix/b7e8263c40090c98e19dae57c8b09b0a to your computer and use it in GitHub Desktop.
Telegram bot for choice-based games
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