Search code examples
telegramtelegram-bot

How to use setMessageReaction(Telegram Bot API)?


Telegram recently added a new API function to set reactions:

setMessageReaction

Use this method to change the chosen reactions on a message
...


I've created a bot, added it to the channel as an administrator, and now I want to add a reaction to the publication on its behalf.


I've tried the following PHP code:

function sendToTelegram($token, $method, $response)
{
    $ch = curl_init('https://api.telegram.org/bot' . $token . '/' . $method);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $response);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

$result = sendToTelegram('BOT_KEY', 'setMessageReaction', ['chat_id' => -1001493310237, 'message_id' => 27, 'reaction[]' => "👍"]);

In the response I'm getting:

{"ok":true,"result":true}

But the publication doesn’t get a reaction.

What am I doing wrong?


Solution

  • You passing the emoji as the wrong data format.

    The reaction parameter of setMessageReaction needs to be an array of ReactionType.

    So instead off passing "👍" as a reaction, you'll need something like:

    [
        [ 'type' => 'emoji', 'emoji' => '👍' ]
    ]
    

    I've used the following PHP code to succesfully set a Reaction:

    <?php
    
    
    $token = '859163076:....';
    $chat = 1;
    $message = 2;
    
    $data = http_build_query([
        'chat_id' => $chat,
        'message_id' => $message
    ]);
    
    $reactions = json_encode([
        [ 'type' => 'emoji', 'emoji' => '👍' ]
    ]);
    
    $re = @file_get_contents("https://api.telegram.org/bot$token/setMessageReaction?{$data}&reaction={$reactions}");
    var_dump($re);
    

    enter image description here