teletype-telegram-bot-api

A Telegram bot API written with TypeScript.

Usage no npm install needed!

<script type="module">
  import teletypeTelegramBotApi from 'https://cdn.skypack.dev/teletype-telegram-bot-api';
</script>

README

Teletype - A Telegrm Bot API

An easy way to use Telegram bot with Typescript.

Features

  • Long Polling mode
  • Webhook mode
  • Subscribe events
  • Send message
  • Send sticker
  • Send media (files, photos, videos...etc)
  • Send keyboard
  • Inline mode event

Dependency package

  • Axios
  • Telegram-typings

How to use it

1. Install package

npm i teletype-telegram-bot-api

2. Create object

Import Teletype and TgEvents from the package.

import { Teletype, TgEvents } from 'teletype-telegram-bot-api'

Then create a Teletype object with a token of your bot.

const bot = new Teletype(botToken)

3. Subscribe event

Use these functions to subscribe events.

  • on(TgEvents, EventId, Triggered function)
    If user send a sticker to bot, you can subscribe a sticker event like this (See more events in TgEvents.ts):

    bot.on(TgEvents.STICKER, "name of event", async (update) => {
        // Do something here...
    })
    
  • onText(RegExStr, Triggered function)
    If the text sent by user matches with the regular expression, then the function you send in will be called.

    bot.onText("[h|H][i|I]", async (message, update) => {
        // Do something here...
    })
    
  • onCommand(RegExStr, Triggered function)
    If the command sent by user matches with the regular expression, then the function you send in will be called.

    bot.onCommand("start", async (message, update) => {
        // Do something here...
    })
    
  • always(Triggered function)
    Whatever user send, always call this function.

    bot.always(async (update) => {
        // Do something here...
    })
    

4. Process Update

Webhook

If you did not set webhook yet, call setWebhook(url) to set it.

Call processUpdate and pass whole body of request.

bot.processUpdate(request.body)

Long Polling

If you have already set webhook, please delete it first by calling deleteWebhook.

Use getUpdates() to get the latest updates and pass each Update object to processUpdate.

const updates = await bot.getUpdates()
updates.forEach(update=>{
        bot.processUpdate(update)
})

5. Send something

  • sendMessage(ChatId, Text)
    Send a message to a chat room.
await bot.sendMessage(chatId, "Hello~")
  • sendSticker(ChatId, StickerFileId)
    Send a sticker to a chat room.
await bot.sendSticker(chatId, "Sticker file_id")