You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram Bot(Java):获取用户联系人并回显确认的实现问题

问题描述

我希望实现以下功能:用户向Telegram Bot发送联系人信息后,Bot获取该联系人信息并询问用户“这是你的电话号码吗?”。我尝试了如下代码写法,但仍无法解决该问题,不清楚如何正确获取联系人信息并回显给用户。

代码片段:

if(update.getMessage().getText().equals("SendContact"){
//Here user send contact when pressed button
}
// I`ve tried
if(update.getMessage().hasContact){
//recend contact to user
}
//and without if()
String phoneNum = update.getMessage().getContact().getPhoneNumber();
execute(phoneNum);
解决方案

你的代码存在语法错误和逻辑问题,修正后即可实现需求:

1. 修正语法错误

  • hasContact是方法,必须加括号调用:update.getMessage().hasContact()
  • 第一个if语句缺少闭合括号,应改为:if(update.getMessage().getText().equals("SendContact")){

2. 正确实现逻辑

先判断消息是否包含联系人信息,再提取号码并发送询问消息,完整示例代码如下:

// 处理用户发送的联系人消息
if (update.getMessage().hasContact()) {
    // 获取联系人的电话号码
    String phoneNum = update.getMessage().getContact().getPhoneNumber();
    
    // 构造询问消息
    SendMessage queryMsg = new SendMessage();
    queryMsg.setChatId(update.getMessage().getChatId());
    queryMsg.setText(String.format("这是你的电话号码吗?%s", phoneNum));
    
    // 发送消息
    try {
        execute(queryMsg);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

// 处理用户触发的"SendContact"文本消息(比如按钮点击)
if (update.getMessage().getText() != null && update.getMessage().getText().equals("SendContact")) {
    // 提示用户发送联系人
    SendMessage promptMsg = new SendMessage();
    promptMsg.setChatId(update.getMessage().getChatId());
    promptMsg.setText("请发送你的联系人信息");
    
    try {
        execute(promptMsg);
    } catch (TelegramApiException e) {
        e.printStackTrace();
    }
}

3. 关键注意事项

  • 必须先调用hasContact()判断消息是否包含联系人,否则直接调用getContact()会抛出空指针异常
  • execute()方法需要传入SendMessage对象,不能直接传字符串,你之前的execute(phoneNum)写法不符合API要求
  • 处理文本消息时,先判断getText()不为空,避免空指针异常

内容的提问来源于stack exchange,提问作者Сергій Ялинка

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:48:10