The next important feature that needed to be implemented was the ability to send photos.
Sending photos in a Telegram bot with BotFire
There are three ways to send a photo.
Send via link
For example, we have a picture that can be downloaded from the address https://download.samplelib.com/png/sample-bumblebee-400x300.png
. Using the link, the file can be sent to the bot.
Example:
$link = 'https://download.samplelib.com/png/sample-bumblebee-400x300.png';
Bot::new()->photo($link)->send();
Send photo contents
In this method, our file does not need to be accessible via a link. Our file exists somewhere on the server and can be sent using Bot::inputFile
.
Example:
$file = Bot::inputFile(__DIR__.'/assets/test.png');
Bot::new()->photo($file)->send();
How to add a caption to a photo?
Bot::new()->photo($file)->caption('Hello caption 😃')->send();
Receive a photo from the client in the bot
To find out whether the type of message the client sent to the bot is a photo or not, we can do the following:
if(Bot::message()->type() == Message::TYPE_PHOTO){
// ...
}
If the client has sent a photo, we can access its information through the photo
method.
Telegram sends us a file_id
which contains a unuque identifier and if you save this identifier you can send the photo later without having to upload it again (more information)
if(Bot::message()->type() == Message::TYPE_PHOTO){
$file_id = Bot::message()->photo()->first()->fileId();
}
Telegram sends us an array of images of different sizes, the first one being the lowest and the last one being the highest resolution and size.
In the example above, we received the first one. Other methods are also available.
Method | Description |
---|---|
first | Returns the first value |
last | Reterns the last value |
count | Number of arrays |
indexOf | Returns the value based on its index. |
asArray | Returns the entire array in its entirety. |
If the photo has a caption, you can get it like this:
$caption = Bot::message()->caption();
If there is no caption, it returns null
.
Now, if you have access to the file_id, you can resend that image in the same way as explained:
$file_id = $file_id = Bot::message()->photo()->last()->fileId();
bot::new()->photo($file_id)->caption('New Caption ...')->send();
Top comments (0)