How to use telegraf - 10 common examples

To help you get started, we’ve selected a few telegraf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github EdJoPaTo / telegraf-inline-menu / test / javascript-user-hints.ts View on Github external
test('menu.middleware fails with .init() hint', t => {
  const menu: any = new TelegrafInlineMenu('yaay')

  const bot = new Telegraf('')
  // Normally user would use bot.use.
  // But telegraf will later use .middleware() on it. in order to check this faster, trigger this directly
  t.throws(() => bot.use(menu.middleware()), /bot\.use\(menu\.init/)
})
github EdJoPaTo / telegraf-inline-menu / test / toggle.ts View on Github external
test('isSetFunc falsy is like false', async t => {
  const menu = new TelegrafInlineMenu('yaay')
  menu.toggle('toggle me', 'c', {
    setFunc: async () => Promise.reject(new Error('Nothing has to be set when only showing the menu')),
    // Returning undefined is not possible from TypeScript but from JavaScript
    isSetFunc: () => undefined as any
  })

  const bot = new Telegraf('')
  bot.use(menu.init({actionCode: 'a'}))

  bot.context.answerCbQuery = async () => true
  bot.context.editMessageText = async (_text, extra: InlineExtra) => {
    t.deepEqual(extra.reply_markup.inline_keyboard, [[{
      text: emojiFalse + ' toggle me',
      callback_data: 'a:c-true'
    }]])
    return true
  }

  await bot.handleUpdate({callback_query: {data: 'a'}} as Update)
})
github EdJoPaTo / telegraf-inline-menu / source / index.js View on Github external
const hitQuestionButton = async ctx => {
      const extra = Extra.markup(Markup.forceReply())
      await Promise.all([
        ctx.reply(questionText, extra),
        ctx.answerCbQuery(),
        ctx.deleteMessage()
          .catch(error => {
            if (/can't be deleted/.test(error)) {
              // Looks like message is to old to be deleted
              return
            }

            console.error('deleteMessage on question button failed', error)
          })
      ])
    }
github EdJoPaTo / telegraf-inline-menu / source / index.ts View on Github external
const actualParts = ctx.callbackQuery.data.split(':')
      // Go up to the menu that shall be opened
      while (actualParts.length > expectedPartCount) {
        actualParts.pop()
      }

      const menuAction = actualParts.join(':')
      actualActionCode = new ActionCode(menuAction).getString()
      options.log('generate with actualActionCode', actualActionCode, actionCode.get(), ctx.callbackQuery.data)
    } else {
      actualActionCode = actionCode.getString()
    }

    const keyboardMarkup = await this.buttons.generateKeyboardMarkup(ctx, actualActionCode, options)
    options.log('buttons', keyboardMarkup.inline_keyboard)
    const extra = Extra.markdown().markup(keyboardMarkup) as Extra
    return {text, extra}
  }
github EdJoPaTo / telegraf-inline-menu / source / index.js View on Github external
const actualParts = ctx.callbackQuery.data.split(':')
      // Go up to the menu that shall be opened
      while (actualParts.length > expectedPartCount) {
        actualParts.pop()
      }

      const menuAction = actualParts.join(':')
      actualActionCode = new ActionCode(menuAction)
      options.log('generate with actualActionCode', actualActionCode.get(), actionCode.get(), ctx.callbackQuery.data)
    } else {
      actualActionCode = actionCode
    }

    const keyboardMarkup = await this.buttons.generateKeyboardMarkup(ctx, actualActionCode, options)
    options.log('buttons', keyboardMarkup.inline_keyboard)
    const extra = Extra.markdown().markup(keyboardMarkup)
    return {text, extra}
  }
github KrauseFx / FxLifeSheet / worker.ts View on Github external
function triggerNextQuestionFromQueue(ctx) {
  let keyboard = Extra.markup(m => m.removeKeyboard()); // default keyboard
  let questionAppendix = "";

  currentlyAskedQuestionObject = currentlyAskedQuestionQueue.shift();

  if (currentlyAskedQuestionObject == null) {
    ctx.reply("All done for now, let's do this 💪", keyboard);
    // Finished
    return;
  }

  if (currentlyAskedQuestionObject.question == null) {
    console.error("No text defined for");
    console.error(currentlyAskedQuestionObject);
  }

  if (currentlyAskedQuestionObject.type == "header") {
github KrauseFx / FxLifeSheet / worker.ts View on Github external
// user entered a command to start the survey
    let command = ctx.match[1];
    let matchingCommandObject = config.userConfig[command];

    if (matchingCommandObject && matchingCommandObject.questions) {
      console.log("User wants to run:");
      console.log(matchingCommandObject);
      saveLastRun(command);
      if (
        currentlyAskedQuestionQueue.length > 0 &&
        currentlyAskedQuestionMessageId
      ) {
        // Happens when the user triggers another survey, without having completed the first one yet
        ctx.reply(
          "^ Okay, but please answer my previous question also, thanks ^",
          Extra.inReplyTo(currentlyAskedQuestionMessageId)
        );
      }

      currentlyAskedQuestionQueue = currentlyAskedQuestionQueue.concat(
        matchingCommandObject.questions.slice(0)
      ); // slice is a poor human's .clone basically

      if (currentlyAskedQuestionObject == null) {
        triggerNextQuestionFromQueue(ctx);
      }
    } else {
      ctx
        .reply("Sorry, I don't know how to run `/" + command)
        .then(({ message_id }) => {
          sendAvailableCommands(ctx);
        });
github ironsoul0 / headhunter / src / bot / scenes / askMessageForHunter.js View on Github external
const hunter = await User.findOne({
    // eslint-disable-next-line no-underscore-dangle
    target: user._id,
    killed: false,
  });

  const content = [
    "Your aim has left message for you 😏",
    `<b>${message}</b>`,
  ].join("\n\n");

  try {
    ctx.telegram.sendMessage(
      hunter.chatId,
      content,
      Extra.HTML().markup(m =&gt;
        m.inlineKeyboard([m.callbackButton("Reply 🤫", "Reply to Aim")])
      )
    );
  } catch (err) {
    console.log(err);
  }

  ctx.scene.leave();
  return ctx.reply(messageRecieved, ctx.mainMenu);
});
github qlik-bots / QlikBotNode / app / server / routes / api / sense-bot / telegram.js View on Github external
catch (error) {
		site.logger.info(`error: ${error}`, { route: `api/sense-bot/telegram::cioCustomerService()` });
	}
});

/***************
 * HELPDESK
 **************/
// BUTTONS
const keyboardHelpdesk = Markup.inlineKeyboard([
	[
		Markup.urlButton('View Demo', 'https://demos.qlik.com/qliksense/HelpdeskManagement'),
		Markup.callbackButton(config.text[lang].helpdesk.highPriorityCases.button, 'helpdeskHighPriorityCases')
	],
	[
		Markup.callbackButton(config.text[lang].helpdesk.mediumPriorityCases.button, 'helpdeskMediumPriorityCases'),
		Markup.callbackButton(config.text[lang].helpdesk.lowPriorityCases.button, 'helpdeskLowPriorityCases')
	]
]);
// COMMANDS - ACTIONS
bot.command('helpdesk', (ctx) => {
	try {
		site.logger.info(`helpdesk-main`, { route: `api/sense-bot/telegram` });
		ctx.reply(config.text[lang].helpdesk.welcome);
		ctx.replyWithPhoto({ url: 'https://sense-demo-staging.qlik.com/appcontent/133dab5d-8f56-4d40-b3e0-a6b401391bde/helpdesk_management.jpg' });
		ctx.telegram.sendCopy(ctx.from.id, ctx.message, Extra.markup(keyboardHelpdesk));
	}
	catch (error) {
		site.logger.info(`error: ${error}`, { route: `api/sense-bot/telegram::helpdesk()` });
	}
});
bot.action('helpdeskHighPriorityCases', (ctx) => {
github qlik-bots / QlikBotNode / app / server / routes / api / sense-bot / telegram.js View on Github external
})
			.catch(error => ctx.reply(`Error: ${error}`));
	}
	catch (error) {
		site.logger.info(`error: ${error}`, { route: `api/sense-bot/telegram::helpdeskLowPriorityCases()` });
	}
});

/***************
 * LANGUAGE SELECTOR
 **************/
// BUTTONS
const keyboardLang = Markup.inlineKeyboard([
	[
		Markup.callbackButton(config.text.en.title, 'langEn'),
		Markup.callbackButton(config.text.el.title, 'langGr')
	]
]);
// COMMANDS - ACTIONS
bot.command('lang', (ctx) => {
	try {
		site.logger.info(`lang-main`, { route: `api/sense-bot/telegram` });
		ctx.reply("Select Language");
		ctx.telegram.sendCopy(ctx.from.id, ctx.message, Extra.markup(keyboardLang));
	}
	catch (error) {
		site.logger.info(`error: ${error}`, { route: `api/sense-bot/telegram::lang()` });
	}
});
bot.action('langEn', (ctx) => {
	try {
		lang = 'en';