There can be situations when it will be useful not to read every message in Telegram channel, but just be notified on some message. To handle this, we can do the following.
There are several libraries available that make it easy to interact with Telegram’s API. One popular library is “dart-telegram-bot” which is an unofficial Telegram Bot API client library for Dart.
To get started, you’ll need to create a new bot on Telegram by talking to the BotFather. Once you have your bot’s API token, you can use it to interact with the Telegram API using the dart-telegram-bot library.
Here is an example of how to use the library to send a message to a user:
import 'package:dart_telegram_bot/dart_telegram_bot.dart';
void main() {
TelegramBot bot = TelegramBot(apiToken);
bot.sendMessage(chatId: 123456, text: "Hello, World!");
}
To receive updates from Telegram, you can use the onUpdate method to register a callback function that will be called whenever a new update is received. For example:
bot.onUpdate.listen((Update update) {
if (update.message.text == '/start') {
bot.sendMessage(chatId: update.message.chat.id, text: "Hello, I'm your bot!");
}
});
You can also use the setWebhook method to set a URL that Telegram will send updates to, rather than polling for updates.
It is important to keep in mind that creating a bot requires you to follow Telegram’s Bot API rules, which include not using the bot to spam or harass users, not sharing the bot’s token, and not using the bot to engage in illegal activities.
Here is an example of how to use the library to listen for messages on a channel:
import 'package:dart_telegram_bot/dart_telegram_bot.dart';
void main() {
TelegramBot bot = TelegramBot(apiToken);
bot.setWebhook(url: 'https://your-server.com/your-webhook-path');
bot.onUpdate.listen((Update update) {
if (update.message.chat.type == "channel") {
print(update.message.text);
}
});
}
Webhook or direct message?
A webhook is a way for an app to provide other applications with real-time information. It allows an app to send a message or event to another app, when a specific event or trigger occurs within the app.
In the context of Telegram, a webhook is a way for Telegram to send updates to a server that you control, rather than your application having to poll Telegram’s servers for updates. When Telegram sends an update to your server, it is referred to as a “webhook callback”.
When you set a webhook for your Telegram bot, you need to provide Telegram with a callback URL, which is the endpoint on your server that Telegram will send updates to. When Telegram receives a message for your bot, it will send the message to the callback URL as a JSON object. Your server can then handle the message, for example by sending a reply to the user.
Webhooks have an advantage over polling because they push information to your application, rather than your application having to pull the information. This can be more efficient and less resource-intensive, especially if your bot handles a high volume of messages.
It’s important to note that when you set a webhook, Telegram will send a “ping” to your server when you set the webhook, and every time the webhook is reset to confirm that the URL is valid and the server is up.
Whether to use a webhook or to send messages directly to a user depends on the specific use case and requirements of your Telegram bot. Both options have their own advantages and disadvantages.
Webhooks are generally more efficient and less resource-intensive than sending messages directly to a user, especially if your bot handles a high volume of messages. When you set a webhook, Telegram sends updates to your server, rather than your application having to poll Telegram’s servers for updates. This can help reduce the load on Telegram’s servers, and also reduce the amount of data and resources that your application needs to handle.
On the other hand, sending messages directly to a user can be simpler and more flexible, especially if your bot only needs to send a small number of messages. In this case, you can use the Telegram Bot API to send messages directly to a user, without needing to set up a webhook.
It’s also worth noting that when you set a webhook, Telegram will send a “ping” to your server when you set the webhook, and every time the webhook is reset to confirm that the URL is valid and the server is up. This can be beneficial in terms of keeping the webhook up and running, but it also means that you need to have a server running to receive those pings.
Ultimately, whether to use a webhook or to send messages directly to a user will depend on the specific requirements of your Telegram bot and how it will be used. If your bot will handle a high volume of messages, using a webhook may be the more efficient and scalable option, while if your bot will only send a small number of messages, sending messages directly to a user may be the simpler and more flexible option.
Channel listening
Here’s an example of a method in Dart that listens for messages on a Telegram channel using the Telegram Bot API and the http package:
import 'package:http/http.dart' as http;
import 'dart:convert';
Future<void> listenToChannel({String botToken, String channelId}) async {
var offset = 0;
while (true) {
// Send a request to Telegram's API to get updates
var response = await http.get(
'https://api.telegram.org/bot$botToken/getUpdates?offset=$offset&timeout=60');
if (response.statusCode != 200) {
// Handle error
print('Error: ${response.statusCode}');
} else {
// Parse the response as a JSON object
var jsonResponse = json.decode(response.body);
// Iterate through the updates
for (var update in jsonResponse['result']) {
// Check if the update is from the specified channel
if (update['message']['chat']['id'] == int.parse(channelId)) {
// Print the message text
print(update['message']['text']);
// Update the offset
offset = update['update_id'] + 1;
}
}
}
}
}
This method takes in two parameters: botToken and channelId. botToken is the token of your Telegram bot, which you can get from the BotFather. channelId is the ID of the Telegram channel that you want to listen to.
The method uses an infinite loop to repeatedly send requests to Telegram’s API to get updates, using the http.get method. It then parses the response as a JSON object and iterates through the updates, checking if the update is from the specified channel. If it is, it prints the message text and updates the offset so that it doesn’t receive the same message again.
It’s important to note that this code is just an example and this method is not fully functional. You should handle the errors and implement more functionalities as needed.
Also, this method uses the “long polling” technique to receive updates from Telegram, which means that it makes a request to Telegram’s server, and Telegram’s server holds the request open for a certain period of time (up to 60 seconds in this example) waiting for updates. If there are no updates during that time, Telegram’s server sends an empty response. This technique is less efficient than webhooks, but it is simpler to implement and does not require a publicly accessible server to receive updates.
Add bot to the channel
To add a Telegram bot to a channel, you will first need to create the bot and get its token. You can do this by talking to the BotFather on Telegram.
Once you have the token, you can add the bot to the channel using the following steps:
- Open Telegram and go to the channel that you want to add the bot to.
- Tap on the channel’s name at the top of the screen to open the channel’s settings.
- Select “Add administrator” from the menu.
- Search for the bot by its username or paste the bot token you received from the BotFather into the “Username or ID” field.
- Select the bot from the search results and tap on “Add.”
- Give the bot the “Post Messages” permission and tap on “Save.”
- The bot will now be added to the channel, and you can start using it to post messages or moderate the channel.
Alternatively, you can also add bot to your channel by using the Telegram’s Bot API with a script that sends request to Telegram’s server.
Here’s an example of a method in Dart that sends a request to join a Telegram channel using the Telegram Bot API and the http package with addChatMember endpoint:
import ‘package:http/http.dart’ as http;
import ‘dart:convert’;
// This method takes in three parameters:
// botToken, channelUsername and botUserId.
// botToken is the token of your Telegram bot,
// which you can get from the BotFather.
// channelUsername is the username of the
// channel that you want the bot to join.
// botUserId is the user_id of the bot which
// you can get by sending a message to the bot
// and then using the getUpdates endpoint to
// get the recent updates and find the bot’s
// user_id in the response.
//
// The method sends a request to Telegram’s
// API to join the channel using the http.post
// method and addChatMember endpoint. Then it
// parses the response as a JSON object and
// print out the bot joined which channel or
// the error.
Future<void> joinChannel({String botToken, String channelUsername, int botUserId}) async {
// Send a request to Telegram's API to join channel
var response = await http.post(
'https://api.telegram.org/bot$botToken/addChatMember',
body: {
'chat_id': "@$channelUsername",
'user_id': botUserId
});
if (response.statusCode != 200) {
// Handle error
print('Error: ${response.statusCode}');
} else {
// Parse the response as a JSON object
var jsonResponse = json.decode(response.body);
if(jsonResponse["ok"])
print("Bot joined the ${jsonResponse['result']['title']} channel");
else
print("Error Occured: ${jsonResponse["description"]}")
}
}
Please note that the bot needs to be an admin of the channel to post messages.
Also, the bot can only be added to channels, not to groups.