Puregram
powerful and modern telegram bot api sdk for node.js and typescript π
Install / Use
/learn @nitreojs/PuregramREADME
introduction
first, what are telegram bots? telegram has their own bot accounts. bots are special telegram accounts that can be only accessed via code and were designed to handle messages, inline queries and callback queries automatically. users can interact with bots by sending them messages, commands and inline requests.
example
const { Telegram } = require('puregram')
const telegram = Telegram.fromToken(process.env.TOKEN)
telegram.updates.on('message', context => context.reply('hey!'))
telegram.updates.startPolling()
note you can find more examples here
MEMORANDUM Should the reader of this document experience difficulty in comprehending the informal style of presentation, said individual is directed to refer to the LEGAL.md file for further information.
table of contents
- why
puregram? (very important!) - getting started
- bot information
- what are contexts?
- action controller
Contextand its varieties- middlewares
- hooks
- typescript usage
- faq
- ecosystem
why puregram?
- written by starkΓ³w β
- powered by j++team β
- very cool package name
- package itself is cool (at least i think so)
- works (i guess)
- i understand only about 30% of my code
- because why not?
getting started
getting token
if you want to develop a bot, firstly you need to create it via @botfather and get token from it via /newbot command.
token looks like this: 123456:abc-def1234ghikl-zyx57w2v1u123ew11
installation
requirements
node.js version must be greater or equal than LTS (
16.15.0atm)
$ yarn add puregram
$ npm i -S puregram
usage
initializing Telegram instance
let's start with creating a Telegram instance:
const { Telegram } = require('puregram')
const bot = new Telegram({
token: '123456:abc-def1234ghikl-zyx57w2v1u123ew11'
})
You can also initialize it via Telegram.fromToken:
const bot = Telegram.fromToken('123456:abc-def1234ghikl-zyx57w2v1u123ew11')
now, we want to get updates from the bot. how can we do it?
getting updates
there are only two ways of getting updates right now:
- polling via
getUpdatesmethod... or just usingpuregram's built-in polling logic:
telegram.updates.startPolling()
- setting up a Webhook via
setWebhookmethod:
const { createServer } = require('http')
// you need to send this request only once
telegram.api.setWebhook({
url: 'https://www.example.com/'
})
const server = createServer(telegram.updates.getWebhookMiddleware())
server.listen(8443, () => console.log('started'))
remember that there are only four accepted ports for now: 443, 80, 88 and 8443. they are listed here under the notes section.
note more webhook examples are available here
handling updates
now with this setup we can catch updates like this:
telegram.updates.on('message', context => context.reply('yoo!'))
supported events are listed here
the mergeMediaEvents
if you've had to handle multiple attachments at once you'd know that in telegram every single attachment is a separate message. that makes it pretty hard for us to handle multiple attachs at once. here it comes - the mergeMediaEvents option in Telegram's constructor
const telegram = new Telegram({
token: process.env.TOKEN,
mergeMediaEvents: true
})
what's changed? if you'd set up a handler like this:
telegram.updates.on('message', (context) => {
console.log(context)
})
and then sent an album, you'd see that there will be some mediaGroup field in the MessageContext. that mediaGroup (instance of a MediaGroup class) contains some getters:
| getter | type | description |
| ------------- | ------------------ | --------------------------------------------------------------------- |
| id | string | media group's id |
| contexts | MessageContext[] | list of received (and processed) contexts which contain an attachment |
| attachments | Attachment[] | list of attachments mapped through contexts (described earlier) |
telegram.updates.on('message', (context) => {
if (context.isMediaGroup()) {
// INFO: all is* getters are methods in puregram@^2.9.0
// INFO: if you are using puregram < 2.9.0, consider using `isMediaGroup` as a getter
return context.reply(`this album contains ${context.mediaGroup.attachments.length} attachments!`)
}
})
manual updates handling
if you want to handle updates by yourself, you can use Updates.handleUpdate method, which takes one argument and this argument is raw Telegram update:
/** let's pretend i'm polling updates manually... */
const update = await getUpdate(...)
let context
try {
context = telegram.updates.handleUpdate(update)
} catch (error) {
console.log('update is not supported', update)
}
// voila! now you have the right context
// (or you don't if the event is not supported π’)
what is UpdatesFilter?
as mentioned in getUpdates documentation,
Specify an empty list to receive all update types except
chat_member(default). If not specified, the previous setting will be used.
as you can see, you have to specify chat_member in order to receive chat_member updates...
but you also will have to specify every single update type that you're going to handle like this:
{
allowedUpdates: ['chat_member', 'message', 'callback_query', 'channel_post', 'edited_message', 'edited_channel_post', ...]
}
not very convenient, is it? that's why we've createed UpdatesFilter: a class containing a few static methods
that will allow you to specify all update types or even exclude some!
const { Telegram, UpdatesFilter } = require('puregram')
const telegram = Telegram.fromToken(process.env.TOKEN, {
allowedUpdates: UpdatesFilter.all()
})
// puregram will now handle every single update including `chat_member` and others (if they're listed under the `UpdateType` enum)
const { Telegram, UpdatesFilter } = require('puregram')
const telegram = Telegram.fromToken(process.env.TOKEN)
telegram.updates.startPolling({
allowedUpdates: UpdatesFilter.except('callback_query')
})
telegram.updates.on('callback_query', (context) => {
// this will never be called.
return cry()
})
calling api methods
there are three ways of calling telegram bot api methods:
- using the
telegram.api.call(method, params?)(useful when new bot api update is released and the package is not updated yet):
const me = await telegram.api.call('getMe')
- using
telegram.api.method(params?):
const me = await telegram.api.getMe()
- using context methods:
telegram.updates.on('message', context => context.send('13Β² = 169! well, i mean "169", not "169!"... fuck.'))
suppressing errors
sometimes you dont want to deal with the errors sent by the api,
sometimes you just dont want to create an empty try/catch statement for that.
this is where suppress parameter in the api call params comes in!
you can pass suppress: true to any api method and in case the error happens
puregram will not throw an error, but will return json object with ok: false and error_code and description properties.
telegram.api usage
const result = await
Related Skills
node-connect
348.5kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
109.1kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Writing Hookify Rules
109.1kThis skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
review-duplication
100.3kUse this skill during code reviews to proactively investigate the codebase for duplicated functionality, reinvented wheels, or failure to reuse existing project best practices and shared utilities.
