如何使用Python通过Twilio API从文本文件读取号码发起多目标呼叫
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.,+1234567890for 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:
You'd then host this TwiML (using Twilio Functions, a simple web server, etc.) and update thefrom 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)TWIML_CALL_URLto 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




