Getting Familiar with the Telegram API and Deleting Messages
The Telegram API is one of the powerful tools that allows developers to create various chatbots and different interactions. One of the interesting features offered by this API is the ability to delete messages. This feature can be useful in situations where there is a need to delete sent messages in chats, which can be very practical. For example, there might be a mistakenly sent message or a message that needs to be deleted from a group.
Deleting messages is accomplished through the function deleteMessage
. This function allows you to delete specific messages by using their identifier (ID) from chats. To use this function, you need to know what message you want to delete and in which chat it is located.
To use the Telegram API and send a request to delete a message, you will need a valid access token. This token authorizes you to interact with the API and carry out various operations. If you haven't received your token yet, you can create a new bot in Telegram and obtain its token.
Now that we are familiar with the concept of deleting messages in Telegram, let’s use a simple code to see how to perform this action. We will use HTTP POST to send the request and with the help of the token and identifiers of the message and chat, we will delete the intended message.
Sample Code for Deleting Messages
const https = require('https');
const token = 'YOUR_BOT_TOKEN';
const chatId = 'CHAT_ID';
const messageId = 'MESSAGE_ID';
const url = `https://api.telegram.org/bot${token}/deleteMessage?chat_id=${chatId}&message_id=${messageId}`;
https.get(url, (resp) => {
let data = '';
// A good data has been received
resp.on('data', (chunk) => {
data += chunk;
});
// All data has been received
resp.on('end', () => {
console.log(`Message with identifier ${messageId} has been deleted.`);
});
}).on('error', (err) => {
console.log('Error: ' + err.message);
});
Line-by-Line Explanation of the Code
Line 1:
const https = require('https');
Here, we import HTTPS to facilitate sending HTTP requests to the Telegram API.
Line 2:
const token = 'YOUR_BOT_TOKEN';
This line defines the access token for your bot. This token should be obtained from Telegram.
Line 3:
const chatId = 'CHAT_ID';
This line identifies the chat in which the message was sent that we want to delete.
Line 4:
const messageId = 'MESSAGE_ID';
This line identifies the message that we wish to delete.
Line 5:
const url = `${ ... }`;
This line constructs the URL for the delete message request, including the token, chat identifier, and message identifier.
Lines 6-14:
https.get(url, (resp) => { ... });
Here, we send a GET request to the Telegram API to delete the message and handle the response accordingly. If the message is successfully deleted, we log a success message to the console.
Last Line:
console.log('Error: ' + err.message);
If an error occurs during the request, we log the error message to the console.