Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ส่ง SMS อัปเดตไปยังโทรศัพท์มือถือด้วย Python

ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีส่ง SMS ใน Python เราจะใช้ Twilio สำหรับส่ง SMS

ก่อนอื่น ไปที่ Twilio สร้างบัญชี จะได้ free trial account ทำการตั้งค่าเสร็จสิ้น

เราต้องติดตั้งโมดูล twilio เพื่อทำงานกับ Twilio client ติดตั้งด้วยคำสั่ง

pip install twilio

ไปที่ Twilio Documentation เกี่ยวกับการส่ง SMS หรือทำตามขั้นตอน

  • นำเข้า Client จาก twilio.rest
  • ดึงและเก็บ account_sid และ auth_token จากบัญชี Twilio
  • สร้าง instance ของ Client ส่ง account_sid และ auth_token
  • ดึงหมายเลข from จากบัญชี Twilio
  • ส่งข้อความด้วย client.messages.create(body=message, from_=from_number, to=verified_number)
  • จะได้รับข้อความ

ตัวอย่าง

# นำเข้า Client จาก twilio
from twilio.rest import Client
# Account SID และ Auth Token จาก Twilio
account_sid = '[ACCOUNT_SID]'
auth_token = '[AUTH_TOKEN]'
# สร้าง Client instance
client = Client(account_sid, auth_token)
# ส่งข้อความ
message = client.messages.create(
    body='Hi there! How are you?',
    from_='[FROM_NUMBER]',
    to='[VERIFIED_NUMBER]'
)
# พิมพ์ SID หลังส่งสำเร็จ
print(message.sid)

หากส่งสำเร็จ จะได้ hash code ดังนี้โดยไม่มี error

SMd954e170ca2545248075c3bc2623aabd

สรุป

ใช้ Twilio Python SDK ส่ง SMS ต้องมี Account SID, Auth Token, และเบอร์ verified หากมีข้อสงสัย กรุณาแจ้งในส่วนความคิดเห็น