ussd-tg-proxy/src/bot.js

95 lines
2.4 KiB
JavaScript

const crypto = require("crypto");
const { Bot, Keyboard } = require("grammy");
const log = require("./log");
const util = require("./util");
const cache = require("./cache");
const config = require("./config");
const request = require("./request");
const bot = new Bot(config.get("TELEGRAM_TOKEN"));
log.debug("bot initialized");
bot.command("start", async (ctx) => {
log.debug(ctx.update, "/start cmd executed");
const tgLinked = await cache.get(ctx.msg.from.id);
log.debug({ cache: tgLinked }, "cache request:tgLinked");
if (tgLinked) {
const localSessionId = crypto.randomBytes(16).toString("hex");
await cache.set(tgLinked, localSessionId);
const res = util.parseUssdResponse(
await request.proxy(localSessionId, tgLinked)
);
return ctx.reply(res.text, {
reply_markup: {
resize_keyboard: true,
keyboard: res.keyboard,
},
});
}
const keyboard = new Keyboard();
return await ctx.reply(
"Click on the button below to link your phone number.",
{
reply_markup: keyboard.requestContact("Link Phone"),
}
);
});
bot.on("message:text", async (ctx) => {
log.debug(ctx.update, "msg:text received");
const tgLinked = await cache.get(ctx.msg.from.id);
const localSessionId = await cache.get(tgLinked);
log.debug({ cache: localSessionId }, "cache request:localSessionId");
if (tgLinked && localSessionId) {
const res = util.parseUssdResponse(
await request.proxy(localSessionId, tgLinked, ctx.msg.text)
);
if (res.code === "END") {
await cache.del(tgLinked);
return await ctx.reply(res.text, {
reply_markup: { remove_keyboard: true },
});
}
return await ctx.reply(res.text, {
reply_markup: {
resize_keyboard: true,
keyboard: res.keyboard,
},
});
}
return await ctx.reply(
"Session expired or account not linked. /start the bot again to access your Sarafu account."
);
});
bot.on("msg:contact", async (ctx) => {
log.debug(ctx.update, "msg:contact received");
const contact = ctx.msg.contact;
if (
ctx.from.id === contact.user_id &&
util.isKenyanNumber(contact.phone_number)
) {
await cache.set(contact.user_id, contact.phone_number);
return ctx.reply(
"Phone number successfully linked. /start the bot again to access your Sarafu account."
);
}
return ctx.reply("Could not verify sent contact.");
});
module.exports = bot;