After a user has started a conversation with your bot, you can send the user messages using the Telegram Bot API. You can not only send text messages to the user, but also you can send other types of messages including images, videos, audio, documents and any other type of file.
In this article, we will see the parameters that you need to pass to the API to send these messages. I will assume that you already know the basic message sending code that we used in the previous article of this series.
API Overview
Before we dive into looking this, you need to know that the Telegram API supports four ways of passing parameters:
- URL Query String (GET)
- application/x-www-form-urlencoded(POST)
- application/json (except for uploading files, in raw body)
- multipart/form-data (mainly for file uploads, POST)
If your request contains a file then you should use the fourth method, otherwise you can choose any of the other methods for making requests.
Note: The example we saw in previous article only showed the URL Query String and application/json method.
It is also noteworthy that the respone to API request will always contain a ok
field. If this field is true, then there was no error, otherwise it means that some error occurred and an optional description
along with error_code
field may be returned with the response for further inspection.
sendMessage
We already saw previously how to send simple text messages to user in the hellobot example. Here we will explore the parse_mode
to send text messages to user but using a little formatting.
There are three parse modes available for text messages (other than the default plain text message), which we will see individually.
HTML
Using this parsing mode, you can send HTML text to user that will be rendered and displayed to user. But you should note that, only a few tags are supported, other tags will be ignored. The supported tags include b
, strong
, i
, em
, u
, ins
, s
, strike
, del
, a
, code
and pre
.
All ther symbols that are not part of the above mentioned tags must be replaced with their entities part (only <, >, & and " are supported, others need to be passed using numeric codes).
MarkdownV2
This is the markdown parse mode. However, the syntax differs than the standard markdown as:
- to make the text bold, use
*
- to make the text italic, use
_
- to underline the text, use
__
(double underscores) - to strikethrough the text, use
~
- For URLs, standard format can be used
[text](link)
- single back ticks and triple back ticks for inline and code block respectively
Besides, above rules, you need to make sure that:
- Inside pre and code entities, all back ticks and back slashes need to be escaped with a preceeding back slash
- Inside link part of URLs, closing parenthesis and back slash need to be escaped wit a preceeding back slash
- And in all other cases (
_*[]()~>#+-=|{}.!
, back tick and back slash itself) needs to be escaped using a back slash
Markdown
This mode is purely kept for backward compatibility, and has no usage for us. So, I won't go into its details.
Now, you need to know that getting the syntax right will be difficult for you and you may have to do a lot of hit and trials. You should make sure before deploying your code to production that it correctly sends the proper text that is renderable.
If everything went right, you will receive the sent Message as a JSON object in the output of API call. Or you will get an error message.
Sending files
The other methods to send photos, audio, media etc all come under this category. You can send the files in three ways:
- Use
file_id
of exisiting file on Telegram servers: If the file is already on the servers, and you have a handle for this file (by receiving it from some user), then simply use this handle to send as you wouldn't need to upload it again. - Using HTTP URL of file that needs to be sent (with public access)
- Upload the photo from your script using
multipart/form-data
MIME type in your POST request
The difference between above methods is that of file size limits: the first method has no special limit (any file already on Telegram servers could be sent using this method), the second method has limits of 5 MB for photos and 20 MB for other type of files (including photo being sent as a file); while the last method allows you to upload photos of up to 10 MB and 50 MB for other files. (More here)
So, basically if your bot needs to upload files greater than 50 MB, you'll need a work around to do so.
sendPhoto
This method accepts two essential parameters: chat_id
and photo
. The parameter photo can be a file id, HTTP URL or InputFile object (uploaded using multipart/form-data MIME type with name photo
).
This method also accepts optional arguments: caption, parse_mode (for caption), reply_to_message_id (when replying to a specific message id in that chat) etc.
sendVideo
This method is also similar to sendPhoto with essential parameter of video
. But, here an additional (optional) parameter thumb
is also present which can be used to upload a thumbnail of the video.
The thumbnail has to be uploaded every time (if there is need to) and cannot be reused. This file also has limitations: maximum file size of 200 kB and max height/width of 320px.
Also, note that only video of type mp4 can be uploaded as Video. For other formats, you will have to use sendDocument method. And also keep in mind the upload limits applied to bots for sending files.
sendAnimation
This method is similar to sendVideo with essential parameter of animation
. The other details are almost similar, except one small detail: the video cannot have audio.
sendAudio
This method has essential parameter of audio
instead of video in sendVideo method. The audio file can be of MP3 format or M4A format. Other formats need to be sent using sendDocument method.
sendVoice
Similar to sendAudio, voice can sent using this method. The file must be encoded in OPUS format (OGG File) for this. Otherwise, the sendAudio or sendDocument method may be used.
sendDocument
This method is similar to above methods with optional parameter of document
. This accepts file of any type (including images, video and audio) under the file size limitations imposed for bots.
All the above methods return the Message object that is sent to the target chat_id, if everything goes as planned.
All the above methods have support for following parameters:
Parameter | Description |
---|---|
chat_id | The unique identifier of the chat where the bot has to send the message (Required) |
photo/ video/ animation/ audio/ voice/ document.. | The second essential parameter for each method (Required using multipart/form-data) |
duration | For media, this will tell Telegram about duration of the uploaded media file |
caption | Text representing the sent object |
parse_mode | Parse mode for caption: MarkdownV2/HTML/Markdown |
disable_notification | Optionally send the message silently |
reply_to_message_id | The message id in whose reply this is being sent |
thumb | (Except for sendPhoto) Optional thumbnail sent as multipart/form-data |
reply_markup | Additional interface options |
So, now that you know about these methods, try sending them to your user.
Tip: If you want to send with existing file_id, use the following script for debugging, and send a message to your bot with the file:
function random_string($length) {$key = '';$keys = array_merge(range(0, 9), range('a', 'z'));for ($i = 0; $i < $length; $i++) $key .= $keys[array_rand($keys)];return $key;}
file_put_contents(random_string(8).".json", $content);
With each request, you will see a new JSON file being created. Check it out and try to figure what happens when you send some file to your bot.
To send a file for all the above methods, you need to define additional function that will take arguments as method, parameters, file(path to file being uploaded), param(name of parameter like photo, video), thumb(optional thumbnail file):
function apiSend($method, $parameters, $file, $param, $thumb="") {
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!$parameters) {
$parameters = array();
} else if (!is_array($parameters)) {
error_log("Parameters must be an array\n");
return false;
}
if (!is_string($file)) {
error_log("File name must be a string\n");
}
if (!is_string($param)) {
error_log("Parama name must be a string\n");
}
foreach ($parameters as $key => &$val) {
// encoding to JSON array parameters, for example reply_markup
if (!is_numeric($val) && !is_string($val)) {
$val = json_encode($val);
}
}
$url = API_URL.$method;
$parameters[$param] = new CURLFile(realpath($file));
if ($thumb != "") $parameters['thumb'] = new CURLFile(realpath($thumb));
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data"));
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_POSTFIELDS, $parameters);
return exec_curl_request($handle);
}
So, now that you have learned about the sending methods for your bot, now you need to gear up the process and set up a database for saving the data.
These articles are a part of Telegram bot series and will be using PHP as their coding language. But if you read through the code, you can easily adapt the code to be used in any language.