Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bot api, how i can get last message or chat history?

Tags:

telegram-bot

I want implement some functional like user send me a message and I reply to him with my (bot) latest message from chat history.

like image 881
row248 Avatar asked Oct 30 '22 18:10

row248


1 Answers

As you can see in the Telegram Bot API Documentation you can use sendMessage to send a message to the user.

When you receive a message, look for the chat or the from parameter in the JSON (depends if you want to answer to the person when it's a group chat or not). You can use the id parameter of the chat or from to send the message.

So the first parameter for your sendMessage would be chat_id=message.chat.id

You don't need the parse_mode, disable_web_page_preview and reply_markup for this example.

As you want to reply to the message of the user you may want to set the reply_to_message_id to the id of the received message.

reply_to_message_id = message.message_id

Last but not least, you want to set the text parameter. If I understand it correctly, your program will send the last received message.text to the user.

So what you want to do is, as soon as you get a message, save it.

Message oldMessage = message

And when you send the Message to the user use the old messages text property as the text.

text = oldMessage.text

Alright to sum it up here is the pseudocode of the function that will happen as soon as you receive a message:

Message oldMessage = null;

public void NewMessage(Message message){

    int chat_id = message.chat.id;
    int reply_to_message_id = message.message_id;

    String text = "There is no old Message"; //fallback value

    if(oldMessage != null){
        text = oldMessage.text;
    }

    //Send Message in this example only has 3 parameters, and ignores the 
    //not used ones
    SendMessage(chat_id,text,reply_to_message_id);

    oldMessage = message; //store the received message for future answering

}

As you store the whole message in oldMessage you could also set the text you will send to something like this:

String text = oldMessage.from.first_name+": "+oldMessage.text;
like image 183
Loki Avatar answered Nov 08 '22 05:11

Loki