Home > database >  How to clear chat NODE JS telegram bot (node-telegram-bot-api.)
How to clear chat NODE JS telegram bot (node-telegram-bot-api.)

Time:11-06

Hi guys i'm junior nodejs developper!

my question: How to clear chat on write text == cls

my code

const { chat, message_id } = message
const chatId = message.chat.id
const name = message.from.first_name
const text = message.text
// ================== on write "cls" clear chat
else if (text == 'cls') {
    bot.deleteMessage(chatId, chat.id)
    var msg = message;
}

CodePudding user response:

I think currently there isn't any method to clear whole chat using bot but you can use simple loop to delete last 100 messages(only work for group chats and bot should have admin permission to delete messages). Like this,

const Telegram = require('node-telegram-bot-api')
const TOKEN = process.env.TOKEN || "<YOUR BOT TOKEN>";
const bot = new Telegram(TOKEN,{polling:true})
    
bot.onText(/\/start/,(msg)=>{
    bot.sendMessage(msg.chat.id,'Hello World!')
})
    //I use bot command regex to prevent bot from miss understanding any user messages contain 'cls'
bot.onText(/\/cls/,(msg)=>{for (let i = 0; i < 101; i  ) {
    bot.deleteMessage(msg.chat.id,msg.message_id-i).catch(er=>{return})
//if there isn't any messages to delete bot simply return
}
}
)

Hopefully this might help you :D

Refer: https://core.telegram.org/bots/api#deletemessage

Note: I'm a beginner, so if there are any mistakes, please excuse me.

  • Related