如何在不发送自动回复的情况下阅读传入的短信

时间:2017-07-11 02:39:09

标签: java twilio twilio-api

我想阅读来自Twilio的传入消息。我已经按照他们网站上的建议与ngrok建立了隧道。

我可以使用以下

发送消息

SendMessage.java

Twilio.init(SendAndReceiveController.ACCOUNT_SID, SendAndReceiveController.AUTH_TOKEN);
    Message message = Message.creator(new PhoneNumber(receiver),
            new PhoneNumber(sender),smsContent).create();

我尝试了4种不同的方法来接收/阅读。

ReceiveMessage.java

MessageFetcher mf = new MessageFetcher("SM2ccd0dc43cea07bcc3f522b3e571eb79");
    System.out.println("message is " + mf.fetch().getBody());   <-- Method 1

    Body body = new Body("Something here");                     <-- Method 2
    Message message = new Message.Builder().action("/receive-sms")
            .method(Method.POST).body(body).build();
    MessagingResponse response = new MessagingResponse.Builder().message(message).build();

    ResourceSet<Message> messages = Message.reader().read();    <-- Method 3

    for(Message message : messages){
        System.out.println(message);
    }

    try {
        System.out.println(response.toXml());
    } catch (TwiMLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    post("/receive-sms", (req, res)-> {                         <-- Method 4
        // This gets the message content
        System.out.println(req.queryParams("Body"));            
        // GOT CONTENT
        // Must parse the format and get the content value
        // Must be able to get the latest message

        Message sms = new Message.Builder()
                .body(new Body(""))
                .build();

        MessagingResponse twiml = new MessagingResponse.Builder()
                .message(sms)
                .build();

        return twiml.toXml();
    });

我目前正在使用方法4.当它工作时,我被迫发回消息,因为它是一个帖子[这是使用sparkjava库]。我通过Twilio的技术帮助来回发送电子邮件,他们一直建议我在Twilio的REST api中使用回调函数。我相信我使用的post方法是一个回调函数。

有没有办法让我在没有发送回复的情况下阅读用户的最新消息?如果是这样,你能否在代码中解释一下如何做到这一点?我很难理解如何将其翻译成Java,因为他们网站上的大部分代码都是HTML格式。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

Twilio开发者传道者在这里。

使用方法4是正确的。您正在收到传入消息作为对/receive-sms端点的POST请求。

但是,你不想回复!谢天谢地,这很好,很容易。 MessagingResponse构建Message,你可以把它留空。

post("/receive-sms", (req, res)-> {                         <-- Method 4
    // This gets the message content
    System.out.println(req.queryParams("Body"));            
    // GOT CONTENT
    // Must parse the format and get the content value
    // Must be able to get the latest message

    // do something with the content

    MessagingResponse twiml = new MessagingResponse.Builder().build();
    return twiml.toXml();
});

这将产生以下TwiML:

<Response />

并且不会发送回复邮件。

让我知道这是否有帮助。

相关问题