Skip to content

Inline Bots

Carlos Meneses edited this page Jan 17, 2021 · 8 revisions

These type of bots were introduced in January 2016 and extend the capabilities current bots have. With this type of bots you can basically just invoke a bot in whatever conversation you have with somebody and then some quick search results will appear so that you can choose from one.

This class implements those type of bots and the usage is pretty simple, set up a webhook and put the $_POST request into an update class. This will fill out any details you may have.

What's different from normal updates however is that you are now required to check the Update object: in an inline bot message will not be set, but inline_query will be. (Or optionally chosen_inline_result). You will also get an ID which you are required to send back (so that Telegram knows what to display to which user).

The following example code should help you a lot with this:

use unreal4u\TelegramAPI\Telegram\Types\Inline\Query\Result\Article;
use unreal4u\TelegramAPI\Telegram\Types\InputMessageContent\Text;
use unreal4u\TelegramAPI\Telegram\Methods\AnswerInlineQuery;
use unreal4u\TelegramAPI\TgLog;

$update = new Update($_POST);

if (!empty($update->inline_query)) {
    $inlineQueryResultArticle = new Article();
    $inlineQueryResultArticle->title = 'Hello world';

    $inputMessageContentText = new Text();
    $inputMessageContentText->message_text = 'This should be an interesting comment';

    $inlineQueryResultArticle->input_message_content = $inputMessageContentText;
    $inlineQueryResultArticle->id = md5('something unique that you can query on later');

    $answerInlineQuery = new AnswerInlineQuery();
    $answerInlineQuery->inline_query_id = $update->inline_query->id;
    $answerInlineQuery->addResult($inlineQueryResultArticle);

    try {
        $tgLog = new TgLog(BOT_TOKEN);
        $result = $tgLog->performApiRequest($answerInlineQuery);
    } catch (\Exception $e) {
        echo '[EXCEPT] '.$e->getMessage().PHP_EOL;
    }
}

A functional example can be found in a working implementation.

Getting a chosen_inline_result back

This can be tricky because when you set up a bot with the botfather, you must also set the option to be able to receive the chosen inline result. So, all you have to do to begin receiving the chosen_inline_result back, is set /setinlinefeedback to any value except disabled in a conversation with the BotFather. Now you're ready to go!