Back to Blog
Language How-Tos

How to Forward Calls to Another Number in Twilio Using Python

Build a Twilio call forwarding system in Python that routes inbound calls to different numbers based on time, input, or business logic.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
8 min read
Twilio
Python
How-To
Code
How to Forward Calls to Another Number in Twilio Using Python

This tutorial builds a call forwarding system in Python using Flask and Twilio TwiML that routes inbound calls to different phone numbers based on time of day, business hours, or configurable rules. It targets developers who need intelligent call routing without expensive PBX hardware, such as forwarding to a mobile number after hours or distributing calls among a team. You will build a Flask webhook that applies business hours logic and returns a TwiML Dial verb pointing to the correct forwarding destination.

Prerequisites and Setup

You need Python 3.7 or higher, Flask, and the Twilio SDK installed with pip install twilio flask python-dotenv pytz. Configure your Twilio number's voice webhook in the Console to POST inbound calls to your Flask route. Define your forwarding numbers and business hours in environment variables or a configuration dictionary so they can be updated without changing application code. The pytz library ensures your business hours comparison uses the correct local timezone regardless of where the server is hosted.

pip install twilio flask python-dotenv pytz

# .env
TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
TWILIO_AUTH_TOKEN=your_auth_token_here
TWILIO_PHONE_NUMBER=+15551234567
OFFICE_NUMBER=+15550001111
MOBILE_NUMBER=+15550002222
VOICEMAIL_URL=https://yourdomain.com/voicemail

The Complete Code

The forwarding webhook uses Python's datetime module with a pytz timezone to determine whether the current time falls within configured business hours. During business hours, the Dial verb forwards to the office number with a 20-second timeout before falling through to voicemail. Outside business hours, the call goes directly to the mobile number for after-hours coverage. The action attribute on the Dial verb points to a fallback route that plays a voicemail prompt if the forwarded number is unanswered.

import os
from datetime import datetime
import pytz
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse, Dial
from dotenv import load_dotenv

load_dotenv()

app = Flask(__name__)

TIMEZONE       = pytz.timezone("America/New_York")
BUSINESS_HOURS = {"start": 9, "end": 18}
DAYS_OPEN      = {0, 1, 2, 3, 4}  # Monday to Friday

OFFICE_NUMBER  = os.environ.get("OFFICE_NUMBER", "+15550001111")
MOBILE_NUMBER  = os.environ.get("MOBILE_NUMBER", "+15550002222")

def is_business_hours() -> bool:
    now = datetime.now(TIMEZONE)
    return now.weekday() in DAYS_OPEN and BUSINESS_HOURS["start"] <= now.hour < BUSINESS_HOURS["end"]

@app.route("/forward", methods=["POST"])
def forward_call():
    resp = VoiceResponse()

    if is_business_hours():
        dial = Dial(timeout=20, action="/no-answer", method="POST", callerId=os.environ["TWILIO_PHONE_NUMBER"])
        dial.number(OFFICE_NUMBER)
    else:
        resp.say("Our office is currently closed. Forwarding you to our after-hours line.", voice="alice")
        dial = Dial(timeout=30, action="/no-answer", method="POST", callerId=os.environ["TWILIO_PHONE_NUMBER"])
        dial.number(MOBILE_NUMBER)

    resp.append(dial)
    return str(resp), 200, {"Content-Type": "text/xml"}

@app.route("/no-answer", methods=["POST"])
def no_answer():
    dial_status = request.form.get("DialCallStatus", "")
    resp = VoiceResponse()
    if dial_status in ("no-answer", "busy", "failed"):
        resp.say("We are unable to take your call right now. Please leave a message after the tone.", voice="alice")
        resp.record(timeout=10, transcribe=True, transcribe_callback="/transcription")
    resp.hangup()
    return str(resp), 200, {"Content-Type": "text/xml"}

@app.route("/transcription", methods=["POST"])
def transcription():
    text = request.form.get("TranscriptionText", "")
    sid  = request.form.get("RecordingSid", "")
    print(f"Voicemail transcript [{sid}]: {text}")
    return "", 204

if __name__ == "__main__":
    app.run(port=5000, debug=True)

Testing and Debugging

Call your Twilio number during business hours and verify the call forwards to your office number; call again outside business hours and verify it routes to the mobile number. Temporarily change the BUSINESS_HOURS hours to include or exclude the current time to test each branch without waiting for the actual time to change. If the forwarded call is not ringing the destination, check that your Twilio number's voice webhook is set to your Flask route and that ngrok is still tunneling. Test the no-answer fallback by having the forwarded number reject the call or let it ring until timeout, then verify the voicemail prompt plays.

Taking It Further

Add a round-robin or simultaneous ring pattern by placing multiple Number elements inside the Dial verb, which rings all numbers at once and connects to whoever answers first. Build a holiday schedule by loading closed dates from a database and checking the current date against that list before the business hours check. Implement skills-based routing that reads the caller's history from a CRM and forwards to the appropriate team member based on their previous interactions. Add a Gather verb before the Dial to ask callers to press a digit for different departments before forwarding, combining this tutorial with the IVR tutorial patterns.

Contact Telphi Consulting to design an intelligent call routing system with CRM integration and real-time analytics.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.