Thursday, 18 April 2024

python code to Twilio SMS

Here's an example of a TwilioSMS class that you can use to send SMS messages using the Twilio Python helper library:



import os

from twilio.rest import Client


class TwilioSMS:

    def __init__(self, account_sid: str, auth_token: str, from_number: str):

        self.account_sid = account_sid

        self.auth_token = auth_token

        self.from_number = from_number

        self.client = Client(account_sid, auth_token)


    def send_sms(self, to_number: str, message: str):

        try:

            # Send an SMS

            message = self.client.messages.create(

                body=message,

                from_=self.from_number,

                to=to_number

            )


            # Print the message SID

            print(message.sid)

            return True


        except Exception as e:

            # Print the error message

            print(e)

            return False




You can use this class as follows:

# Initialize the TwilioSMS class

twilio_sms = TwilioSMS(

    account_sid=os.environ['TWILIO_ACCOUNT_SID'],

    auth_token=os.environ['TWILIO_AUTH_TOKEN'],

    from_number='+12345678901'  # Your Twilio number

)


# Send an SMS

success = twilio_sms.send_sms('+09876543210', 'Hello from Python!')

print(f'SMS sent successfully: {success}')

Make sure to replace TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN with your actual Twilio account SID and auth token, and replace +12345678901 and +09876543210 with your actual Twilio number and the phone number you want to send the SMS to, respectively.


The TwilioSMS class takes the Twilio account SID, auth token, and from number as arguments in its constructor. It then initializes a Client object using these credentials, which you can use to send SMS messages.


The send_sms method takes the phone number to send the SMS to and the message as arguments. It then sends the SMS using the Client object and prints the message SID if the SMS is sent successfully. If there is an error sending the SMS, it prints the error message.


You can add more methods to the TwilioSMS class to add more functionality, such as checking the status of a message or sending an SMS to multiple phone numbers.

No comments:

Post a Comment

python code to Twilio SMS

Here's an example of a TwilioSMS class that you can use to send SMS messages using the Twilio Python helper library: import os from twil...