Install
npm i telefaith
Complete Guide
- Quick View
- Creating new bot with BotFather
- Working with Faith
- Messages
- Order with Async Await (Important⚠️⚠️)
- Sending Methods
- Replying Methods
- replyWithText
- replyWithPhoto
- replyWithAnimation
- replyWithSticker
- replyWithLocation
- replyWithVenue
- and so on... all sending methods are available as reply methods in
Message
class
- Editing Methods
- Chat Methods
- Creating StickerSet
- Missing Methods
Quick View
const teleBot = ;const BOT_TOKEN = 'your_bot_token'; const bot = BOT_TOKEN; { const botInfo = await bot; console; for { if ctxcontent === 'message' ; if ctxcontent === 'inlineQuery' ; if ctxcontent === 'callbackQuery' ; } } ; { bot } { try if inlineQueryquery === '#Tracks:dhFjs74Y5r' const killEmAllAlbumCover = 'https://upload.wikimedia.org/wikipedia/en/5/5c/Metallica_-_Kill_%27Em_All_cover.jpg'; inlineQuery; catch err console; } { try if callbackQuerydata callbackQuery; else if callbackQuerydata callbackQuery; else if callbackQuerydata await bot; const sentMsg = await bot; sentMsg; catch err console }
Creating new bot with BotFather
The following steps describe how to create a new bot:
- Contact @BotFather in your Telegram messenger
- To get a token, send BotFather a message that says
/newbot
- When asked for a name for your new bot choose something that ends with the word
bot
. For example,my_test_bot
- If your chosen name is available, BotFather will send you a token
- Save the token
you can see your created bots using /mybots
command.
if you wanna change your bots settings and infos, just click on your bot name.
Working with Faith
Ok, you created the bot, now we need Faith. First create a node project and install telefaith:
npm i telefaith
Create a file index.js (or any other name) and inside the file require telefaith:
const teleBot = ;
then store your token in a variable or something...
const BOT_TOKEN = 'your_bot_token';
Now, create a bot
const bot = BOT_TOKEN;
OK, we need a async function for getting message, because comming message(messages, edited messages, inline queries, polls and ...) came throw the "async iterator", and we need for await
and it works in async function.
if you don't know what the heck is "async iterator", dont worry just follow the syntax:
{ for { ifctxcontent === 'message' console; ctxmessage; } }
finally call the function!
;
Full vision:
const teleBot = ;const BOT_TOKEN = 'your_bot_token'; const bot = BOT_TOKEN; { for { ifctxcontent === 'message' console; ctxmessage; } } ;
To make sure BOT_TOKEN
is correct and we can connect to our bot we can use getMe
method at the Beginning of the start function.
If token wasn't correct its gonna throw error and catch()
method runs.
const teleBot = ;const BOT_TOKEN = 'your_bot_token'; const bot = BOT_TOKEN; { //check bot Correctness 👇👇👇👇👇 const botInfo = await bot; console; for { ifctxcontent === 'message' console; ctxmessage; } } ;
ctx
?
what the hell is Telegram bot doesn't limited to messages only, bots can answer inline queries, resive poll answers and ...
So, all of these things(messages, polls, inline queries,...) came throw ctx
. you can check the ctx
type with ctx.content
.
ifctxcontent === 'message' //do something console; ifctxcontent === 'inlineQuery' //do something console; ifctxcontent === 'poll' //do something console; ifctxcontent === 'editedMessage' //do something console; ifctxcontent === 'callbackQuery' //do something console; ifctxcontent === 'chosenInlineResult' //do something console;
check these types at Comming updates.
Mesages
What can we do with messages🤔? well, we can answer them😜.
Every user or better to say "chat" in telegram has an unique id. you can get this id from comming messages using this command: ctx.message.chat.id
.
yes! yes! why i need to know that😒? well, bot should know who do you want to send a message to, sooo! pass the chat id to it like example bellow! And one more thing, if sending was successfull the sent message gonna return.
if ctxcontent === 'message' bot ; bot ; bot ; bot ; bot ;
RESULT:
- first: these methods are all async, so there is no guarantee that these messages sent in order. see this chapter for having order : Order with Async Await.
- second: these methods are all async, sooooooo, use
.catch()
on them or put try catch or something to prevent error and crash in thefor await
loop. - third: logging is an expensive process and takes a lot of time! so do not log
sentMessage
in production app. logging is for testing and learning purposes. just log errors and important things!
Replying
If you don't like this whole "chat id" thing, well! you can use replying methods that are Embedded in message
object but its gonna have this replying mark on the message.
if replying was successfull the sent message gonna return.
ifctxcontent === 'message' ctxmessage ctxmessage ctxmessage ctxmessage ctxmessage;
RESULT:
Some Tricks with sent messages
These "send methods" on success, returns the sent message and we can do some cool things with it:
if ctxcontent === 'message' bot ;
RESULT:
Order with Async Await
huh! why is this important🤔? well im gonna tell you!
⛔ Do not use await
directly to achive order! Like:
for { if ctxcontent === 'message' await bot await bot await bot await bot }
Why?
Because it's gonna pause the whole for await
loop for each await
and other users must wait in the queue till one user gets all these messages. For example:
200 people send message to the bot at the same time and bot gonna answer them like this:
- send text to USER_1
- send photo to USER_1
- send poll to USER_1
- send animation to USER_1
THEN - send text to USER_2
- send photo to USER_2
- send poll to USER_2
- send animation to USER_2
THEN - USER_3 , USER_4 , ...... USER_199
THEN - send text to USER_200
- send photo to USER_200
- send poll to USER_200
- send animation to USER_200
Well, as you can see, the 200th user must wait till other 199 users recive message😨😱😱😳!!!
another Example:
Let's say you need some delay between sending messages(I don't know why, but let's just say we need it 🙄). with async await we probebly gonna write something like this:
const delay = ; for { if ctxcontent === 'message' const msg = await bot; //10 second delay await ; await msg; }
Well, It's gonna be a disaster😑, the whole for await
loop gonna blocked for 10 second for Each Message 🤦♂️😵.
OK, What do we do now😰?
Well, we just need an async handler:
{ const botInfo = await bot; console; for { if ctxcontent === 'message' ; } } ; { await bot; await bot; await bot; await bot; }
In this way for await
loop is not gonna pause anymore and messageHandler
gonna invoke for users Immediately. Now no ones gonna wait in queue anymore and you achived the order that you wanted 🥳🥳🎈🎉🎊.
Oh, and as always, add .catch()
or use try catch
to prevent Errors!
Reply and Async Await
With this async handler we can work with replying and prevent .then()
chains.
{ try const sentMessage = await bot; const sentPoll = await sentMessage; console; catch err console }
RESULT:
Sending Methods
OK, Here's some examples for sending methods that exists on Bot
class, im gonna write code inside the messageHandler functions:
const teleBot = ;const BOT_TOKEN = 'your_bot_token'; const bot = BOT_TOKEN; { const botInfo = await bot; console; for { if ctxcontent === 'message' ; }} ; { //for the bellow examples im gonna write codes here}
sendText
Use this method to send text messages. On success, the sent Message is returned.
{ try await bot; await bot; // visit this link for formating syntaxes: https://core.telegram.org/bots/api#formatting-options await bot; await bot; catcherr console; }
RESULT:
sendPhoto
Use this method to send photos. On success, the sent Message is returned.
{ try //send local file (NOT Recommended at all, it's so slow) await bot; //send image by link await bot; //send image by file id await bot; catch err console; }
RESULT:
sendAnimation
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
{ try //send local file (NOT Recommended at all, it's so slow) await bot; //send with Gif link await bot; //send with gif file id await bot; catch err console; }
RESULT:
sendSticker
Use this method to send static .WEBP or animated .TGS stickers. On success, the sent Message is returned.
const fs = ; { try //get some sticker Some stickerSet name: 'MrCat' , 'Miss_Bunny', 'FroggoInLove', 'ValentineCat' const stickerSet = await bot; //send them to user for const sticker of stickerSetstickers await bot; //download them all for const sticker of stickerSetstickers const file = await sticker; await fspromises ; //send downloaded ones to user again🤨🤨. you know, i'm doing these stuff to show you some different patterns and codes const downloadedStickers = await fspromises; for const fileName of downloadedStickers await bot; catch err console; }
RESULT:
sendLocation
Use this method to send point on the map. On success, the sent Message is returned.
{ try //bot.sendLocation(chatId, latitude, longitude) const sentMsg = await bot; sentMsg; catch err console; }
RESULT:
sendVenue
Use this method to send information about a venue. On success, the sent Message is returned.
{ try //bot.sendLocation(chatId, latitude, longitude, title, address) const sentMsg = await bot; sentMsg catch err console; }
RESULT:
sendContact
Use this method to send phone contacts. On success, the sent Message is returned.
{ try //bot.sendContact(chatId, phone_number, name, options) const sentMsg = await bot; sentMsg; catch err console; }
RESULT:
sendDice
Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned.
{ try if msgtext === 'Dice' //bot.sendDice(chatId, options) well, it's kinda useful for games and chances const sentMsg = await bot; //get the value of dice like this: console; catch err console; }
RESULT:
April 24, 2020 UPDATE: You can set emoji “🎲” or “🎯” to be send as Dice. Defaults to “🎲”.
const delay = ; { try if msgtext === 'Dart' //you can set emoji to either “🎲” or “🎯”. Defaults to “🎲” const sentMsg = await bot; //get the value of dice like this: console; if sentMsgdicevalue === 6 await ; sentMsg; else if msgtext === 'Dice' //Defaults to 🎲 const sentMsg = await bot; console; catch err console; }
sendPoll
Use this method to send a native poll. On success, the sent Message is returned.
{ try //answer items must be 2-10 strings 1-100 characters each await bot; //quiz kind await bot; catch err console; }
RESULT:
sendAudio
Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
const fs = ; { try await bot; await bot; await bot; await bot; catch err console; }
RESULT:
sendVideo
Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
const fs = ; { try //send local file await bot; //send by file_id await bot; //send by url await bot; catch err console; }
RESULT:
sendDocument
Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
const fs = ; { try // Any file can be sent as document 📂 //send local file await bot; //send by file_id await bot; //send by url await bot; //add thumb for files await bot; await bot; catch err console; }
RESULT:
sendMediaGroup
Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.
const fs = ; { try const sentMsges = await bot; sentMsges; catch err console; }
RESULT:
Another example:
const fs = ; { try const sentMsges = await bot; sentMsges; catch err console; }
RESULT:
you can send video and photos together
const fs = ; { try const sentMsges = await bot; sentMsges; catch err console; }
RESULT:
sendVoice
Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
const fs = ; { try await bot; //send by file_id await bot; await bot; //send by url await bot; catch err console; }
RESULT:
sendVideoNote
As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
const fs = ;const delay = ; { try //donwload videoNote if msgvideoNote const file = await msgvideoNote; await fspromises; //send by fileId await bot; //send local videoNote await bot; //send by url await bot; catch err console; }
RESULT:
Replying Methods
replying methods are embeded in Message
class, so, comming messages and returned messages have these methods
{ await msg; await msg; await msg // ... const sentMsg = await bot; await sentMsg; await sentMsg; await sentMsg // ... }
replyWithText
Use this method to reply with text messages. On success, the sent Message is returned.
const fs = ; { try const sentMsg = await bot; await sentMsg; catch err console; }
RESULT:
replyWithPhoto
Use this method to reply with photos. On success, the sent Message is returned.
const fs = ; { try if msgtext await msg; const sentMsg = await bot; sentMsg catch err console; }
RESULT:
replyWithAnimation
Use this method to reply with animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
{ try if msgtext await msg; else if msgtext msg catch err console; }
RESULT:
replyWithSticker
Use this method to reply with static .WEBP or animated .TGS stickers. On success, the sent Message is returned.
{ try if msgtext await msg; else if msgtext const stickerSetName = msgtext1; //get sticker set Some stickerSet name: 'MrCat' , 'Miss_Bunny', 'FroggoInLove', 'ValentineCat' const set = await bot; for const sticker of setstickers await msg; catch err console; }
RESULT:
replyWithLocation
Use this method to reply with point on the map. On success, the sent Message is returned.
{ try const sentMsg = await msg; sentMsg; catch err console; }
RESULT:
replyWithVenue
Use this method to reply with information about a venue. On success, the sent Message is returned.
{ try const sentMsg = await msg; sentMsg; catch err console; }
RESULT:
Editing-Methods
Use these methods to edit sent message. these methods are available one bot instance and Message
class(returned messages from send or reply methods).
editMessageText
Use this method to edit text and game messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
Timer example⏱:
const delay = ; { try let time = 0; const sentMsg = await bot; // await ; await bot; //easy solution: embeded method await ; await sentMsg; catch err console; }
I Love You Example😍:
const delay = ; { try const sentMsg = await bot; let txt = 'I' await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; catch err console; }
editMessageCaption
Use this method to edit captions of messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
Sneeze Example 🤧:
const delay = ; { try const sentMsg = await bot; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; await ; await sentMsg; //or this hard way //bot.editMessageCaption(sentMsg.chat.id, sentMsg.messageId, 'you just sneezed 😂'); catch err console; }
Another Example:
{ const botInfo = await bot; console; for { if ctxcontent === 'message' ; else if ctxcontent === 'callbackQuery' ; }} ; { try bot; catch err console; } { try if querydata querymessage; catch err console }
editMessageMedia
Use this method to edit animation, audio, document, photo, or video messages. If a message is a part of a message album, then it can be edited only to a photo or a video. Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded. Use previously uploaded file via its fileId or specify a URL. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
Example:
const fs = ;const delay = ; { try const sentMsg = await bot; await ; await bot; await ; //easy way await sentMsg; catch err console; }
editMessageCaption
Use this method to edit captions of messages. On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
const delay = ; { try const sentMsg = await bot; await ; bot; await ; sentMsg; await ; sentMsg; catch err console; }
deleteMessage
Use this method to delete a message, including service messages, with the following limitations:
- A message can only be deleted if it was sent less than 48 hours ago.
- A dice message in a private chat can only be deleted if it was sent more than 24 hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
- Bots can delete incoming messages in private chats.
- Bots granted can_post_messages permissions can delete outgoing messages in channels.
- If the bot is an administrator of a group, it can delete any message there.
- If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success.
const delay = ; { try const sentMsg1 = await bot; await ; bot; const sentMsg2 = await bot; await ; //easy way sentMsg2; //you can even delete the user's message msg; catch err console; }
Chat Methods
const delay = ; { try if msgtext == 'hi' await msgchat; //await bot.exportChatInviteLink(msg.chat.id).then(link => console.log(link)); await msgchat; //await bot.setChatPhoto(msg.chat.id, fs.createReadStream('./public/image.jpg')); await msgchat; //await bot.deleteChatPhoto(msg.chat.id); await msgchat; //await bot.setChatTitle(msg.chat.id, 'CATHARSIS'); await msgchat; //await bot.setChatDescription(msg.chat.id, `Whenever I fall\nIf ever at all\nYou're there to watch me crumble`); await msgchat; //await bot.pinChatMessage(msg.chat.id, msg.messageId); await ; await msgchat; //await bot.unpinChatMessage(msg.chat.id); await msgchat; // await bot.setChatPermissions(msg.chat.id, { // can_send_polls: true, // can_pin_messages: false, // can_invite_users: true, // can_send_messages: true // }); await msgchat; //await bot.getChatAdministrators(msg.chat.id).then(admins => console.log(admins)); await msgchat; //await bot.getChatMembersCount(msg.chat.id, msg.messageId).then(count => console.log(count)); await msgchat; //await bot.getChatMember(msg.chat.id, msg.from.id).then(member => console.log(member)); await msgchat; //await bot.setChatStickerSet('RickAndMorty').catch(err => console.log(err)); await msgchat; //await bot.deleteChatStickerSet(msg.chat.id).catch(err => console.log(err)); catch err console; }
Creating StickerSet
Learn more about creating sticker set: Learn About StickerSet
- images for stickers must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
- image for thumbnail must be up to 128 kilobytes in size and have width and height exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size
- Here's some images that i used to create sticker set https://github.com/tashimato/tf-images/tree/master/images
const fs = ; { try if msgtext === 'create' const username: botUsername = await bot; //create a set await bot; //add more stickers to set await bot; await bot; //set thumbnail for set await bot; const set = await bot; for const sticker of setstickers await bot; //change the position of the last sticker to first sticker //await bot.setStickerPositionInSet(set.stickers.pop().fileId, 0); //delete the last sticker //await bot.deleteStickerFromSet(set.stickers.pop().fileId); catch err console; }