You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Python通过Twilio API从文本文件读取号码发起多目标呼叫

How to Make Bulk Outgoing Calls with Twilio API in Python (Reading Numbers from a Text File)

Got it, let's walk through how to set up bulk calls using Twilio's Python SDK, including pulling target numbers from a text file. I'll fix the small issue in your original code and break this down into actionable steps with working examples.

Prerequisites First

Before diving in, make sure you have these ready:

  • Install the Twilio Python SDK: pip install twilio
  • Your Twilio Account SID and Auth Token (grab these from your Twilio dashboard)
  • A Twilio phone number that can make outgoing calls
  • A text file (let's call it phone_numbers.txt) with one phone number per line—each number needs a country code (e.g., +1234567890 for US numbers)

Step 1: Read Numbers from Your Text File

First, we'll write a simple function to load and clean up the numbers from your file. This handles empty lines and extra whitespace automatically.

Step 2: Bulk Call Implementation

Your original code tried passing lists to to and from_—that won't work, since Twilio's calls.create() expects single strings for individual calls. Instead, we'll loop through each number from the file and initiate a call for each one.

Here's the full working code:

import os
from twilio.rest import Client

def read_phone_numbers(file_path):
    """Read and clean phone numbers from a text file (one per line)"""
    with open(file_path, 'r') as f:
        # Strip whitespace and skip empty lines
        numbers = [line.strip() for line in f if line.strip()]
    return numbers

# Replace these with your actual Twilio credentials
TWILIO_ACCOUNT_SID = 'AXXXXXXXXXXXXXXXXXXxx'
TWILIO_AUTH_TOKEN = '1XXXXXXXXXXXXXXXXXXX'
TWILIO_FROM_NUMBER = '+17123XXX'  # Your Twilio phone number
# TwiML URL tells Twilio what to do when the call connects (demo URL included)
TWIML_CALL_URL = "http://demo.twilio.com/docs/voice.xml"

# Path to your numbers file
NUMBERS_FILE_PATH = 'phone_numbers.txt'

def main():
    # Initialize Twilio client
    client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
    # Load target numbers
    target_numbers = read_phone_numbers(NUMBERS_FILE_PATH)
    
    # Loop through each number and initiate a call
    for number in target_numbers:
        try:
            call = client.calls.create(
                to=number,
                from_=TWILIO_FROM_NUMBER,
                url=TWIML_CALL_URL
            )
            print(f"✅ Call started to {number} | Call SID: {call.sid}")
        except Exception as e:
            print(f"❌ Failed to call {number}: {str(e)}")

if __name__ == "__main__":
    main()

Key Notes to Keep in Mind

  • Error Handling: The try/except block ensures that if one call fails (e.g., invalid number, Twilio quota hit), the rest of the calls still go through.
  • TwiML Customization: The demo URL plays a sample message, but you can replace it with your own TwiML. For example, you can generate custom TwiML directly in code:
    from twilio.twiml.voice_response import VoiceResponse
    
    def get_custom_twiml():
        response = VoiceResponse()
        response.say("Hi there! This is your custom bulk call message. Thanks for listening!")
        return str(response)
    
    You'd then host this TwiML (using Twilio Functions, a simple web server, etc.) and update the TWIML_CALL_URL to point to it.
  • Rate Limits: Twilio has limits on how many calls you can initiate per minute—check Twilio's docs to avoid hitting these limits (you might need to add small delays if you're calling a huge list).
  • Number Formatting: Always include the country code for every number—this is critical for Twilio to route the call correctly.

内容的提问来源于stack exchange,提问作者Said

火山引擎 最新活动