【发布时间】:2015-12-28 04:52:56
【问题描述】:
我想实现一些功能,例如用户向我发送消息,然后我用聊天记录中的(机器人)最新消息回复他。
【问题讨论】:
标签: telegram-bot
我想实现一些功能,例如用户向我发送消息,然后我用聊天记录中的(机器人)最新消息回复他。
【问题讨论】:
标签: telegram-bot
正如您在Telegram Bot API Documentation 中看到的,您可以使用sendMessage 向用户发送消息。
当您收到消息时,在 JSON 中查找 chat 或 from 参数(取决于您是否想在群聊时回复此人)。您可以使用chat或from的id参数发送消息。
所以你的 sendMessage 的第一个参数是chat_id=message.chat.id
对于此示例,您不需要 parse_mode、disable_web_page_preview 和 reply_markup。
当您想回复用户的消息时,您可能需要将reply_to_message_id 设置为收到消息的 id。
reply_to_message_id = message.message_id
最后但同样重要的是,您要设置text 参数。如果我理解正确,您的程序会将最后收到的message.text 发送给用户。
所以你想做的是,一旦你收到一条消息,就保存它。
Message oldMessage = message
当您向用户发送消息时,请使用旧消息 text 属性作为文本。
text = oldMessage.text
好了,这里总结一下就是一收到消息就会发生的函数的伪代码:
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
}
当您将整个消息存储在oldMessage 中时,您还可以将要发送的文本设置为:
String text = oldMessage.from.first_name+": "+oldMessage.text;
【讨论】:
oldMsg = newMsg,如果第二个用户向机器人发送消息,它将显示“好像”最后一个用户发送了这两个消息。使用数组或对象来存储每个 user_id 和他的 last_message。
如果你只是想回复用户的消息,你需要这个功能:
public void sendMsg(Message message, String text){
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try{
setButtons(sendMessage);
sendMessage(sendMessage);
}catch (TelegramApiException e){
e.printStackTrace();
}
}
【讨论】: