I need to forward incoming calls to my Twilio number to a personal number. I need to do this by Java code because I have a few other Business logic executing when TwiMl App redirect the request and because of that, I can't use Twilio Studio.
I tried a few ways but didn't work and can't make the following method work. I think these are deprecated now,
Call call = Call.creator(
new PhoneNumber(TWILIO_NUMBER),
new PhoneNumber(FORWARD_TO),
new PhoneNumber(TWILIO_NUMBER)
).create();
And even following redirect()
method is also not there now.
Call.updater("call-sid")
.redirect(FORWARD_TO).update();
So what I need is when a call comes to my Twilio number then that call should be forwarded to my personal number. So how to do this? Can anybody help me? Thanks in advance.
The code block in your question triggers an outgoing call, which is why it doesn't work to handle incoming calls (and because the third parameter should contain TwiML and not a phone number).
To handle incoming calls with business logic, you need to implement a webhook that returns TwiML. Use the <Dial>
Tag in this TwiML response to initiate the call forwarding. Check out this tutorial to learn more about this.
The proper code should go like this:
import com.twilio.twiml.voice.Dial;
import com.twilio.twiml.VoiceResponse;
import com.twilio.twiml.voice.Say;
import com.twilio.twiml.TwiMLException;
public class Example {
public static void main(String[] args) {
Dial dial = new Dial.Builder("415-123-4567").build();
Say say = new Say.Builder("Goodbye").build();
VoiceResponse response = new VoiceResponse.Builder().dial(dial)
.say(say).build();
try {
System.out.println(response.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
}