def delete_sms(request, message_sid): client = Client(shmeys.ACCOUNT_SID, shmeys.AUTH_TOKEN) message = client.messages(message_sid).fetch() if request.method == 'POST': client.messages(message_sid).delete() return redirect('sms:index') return render(request, 'index.html', {'message': message})
def StartSMS(): global mobile, note, tot_fail current = int(datetime.now().strftime("%H")) if (current >= 21 and current <= 9): return mobile = mobile account_sid = "AC1dbcae0e435ef98c73e01cb49e0a5e35" auth_token = "4c195142b9173861838bbd2abb98fae3" client = Client(account_sid, auth_token) message = client.messages.create(to=mobile, from_="+13862109616", body="Hello World!") time.sleep(10) sms_status = message.sid message = client.messages(sms_status).fetch() sms_status = message.status fail = 0 while (not (sms_status == 'delivered' or sms_status == 'received')) and (fail < 5): message = client.messages.create(to=mobile, from_="+13862109616", body=note) fail += 1 sms_status = message.sid time.sleep(10) message = client.messages(sms_status).fetch() sms_status = message.status tot_fail += fail print("Message failed for ", tot_fail, " times")
class TwilioHelper(object): def __init__(self): #read config from twilio.config file self.config = configparser.RawConfigParser() self.config.read('twilio.config') self.tw_sid = self.config.get('twilio_sms', 'sid') self.tw_token = self.config.get('twilio_sms', 'auth') self.tw_from_ = self.config.get('twilio_sms', 'from') self.phone_validate_api_key = self.config.get('abstract_api', 'key') self.phone_validate_api_url = self.config.get('abstract_api', 'api_url') self._client = Client(self.tw_sid, self.tw_token) def sendsms(self, send_to, send_text): """Send SMS""" self.to = send_to self.valid = self.validatephone(send_to) if self.valid: self.body = send_text self.message = self._client.messages.create(to=self.to, from_=self.tw_from_, body=self.body) self.sid = self.message.sid self.message_status = self._client.messages( self.sid).fetch().status while (self.message_status == 'sent'): self.message_status = self._client.messages( self.sid).fetch().status else: self.message_status = self._client.messages( self.sid).fetch().status return self.message_status else: self.message_status = 'Destination Phone Number ' self.message_status += send_to self.message_status += ' is invalid. Please Try again' return self.message_status def validatephone(self, send_to): """Validate Phone Number Using Abstract Phone Validation API https://app.abstractapi.com/api/phone-validation """ self.send_to = send_to.lstrip('+') self.params = { 'api_key': self.phone_validate_api_key, 'phone': self.send_to } response = requests.get(self.phone_validate_api_url, params=self.params) decoded_content = json.loads(response.content.decode('UTF-8')) is_phonenumber_valid = decoded_content['valid'] return is_phonenumber_valid
def send_recovery_message(to, id): client = Client(account_sid, auth_token) message = client.messages \ .create( body="Ihre ID ist: " + str(id) + " - An einem sicheren Ort aufbewahren! - Privacy: https://stei.ml/privacy - Info: https://stei.ml/info", from_="IDPRO", to=to ) messages = client.messages.list(limit=20) for record in messages: if record.sid != message.sid: client.messages(record.sid).delete()
def twilio_second_sms_status_check_task(): ''' after time specified in call parameter checks msg status with sms provider for messages which had not "delivered" status ''' logger.info("second sms status check") undelivered_msgs = SMS.objects.filter(checked_once=True, checked_twice=False, delivered=False) ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) for msg in undelivered_msgs: fetched = client.messages(msg.twilio_message_sid).fetch() msg.checked_twice = True msg.save() if fetched.status == 'delivered': msg.twilio_message_status = 'delivered' msg.delivered = True msg.save() else: msg.twilio_message_status = fetched.status mail_title = 'SMS undelivered to %s' % msg.addressee.username mail_body = 'SMS to {parent_name} was undelivered. Message details:\n\ phone_number: {phone_number}\n\ service: Twilio\n\ message: {msg_body}\n\ message sid: {msg_sid}\n\ message status: {msg_status}'.format( parent_name=msg.addressee.username, phone_number=msg.to, msg_body=msg.body, msg_sid=msg.sid, msg_status=msg.status) admin_email(mail_title, mail_body)
def get_message(message_sid): #Wrapper to get message from Twilio API logger.info("Getting Message {}".format(message_sid)) client = Client(account_access, account_secret) message = client.messages(message_sid) return message
def twilioSMS(k,msg, count): # To check for country code pn = phonenumbers.parse(k) print pn.country_code country = pycountry.countries.get(alpha_2=region_code_for_number(pn)) yo = region_code_for_country_code(pn.country_code) # To get timezone for the specified country url = "http://api.timezonedb.com/v2/list-time-zone?key=" + API_Key + "&format=json&country=" + yo json_obj_places = urllib2.urlopen(url) places = json.load(json_obj_places) print places["zones"][0]["zoneName"] local_date = datetime.now(pytz.timezone(places["zones"][0]["zoneName"])) print local_date.time() hour = local_date.time().hour try: # To check whether the time is the night time or not if hour in range(7, 23): client = Client(account_sid, auth_token) message = client.messages.create(to=k, from_=my_twilio, body=msg) time.sleep( 60 ) print message.sid bappa = client.messages(message.sid).fetch() print(bappa.body) print(bappa.status) # Checking the status of the Message after 1 minute if not delivered or sent, sending again if bappa.status not in ["delivered", "sent"] and count<5: print bappa.status count = count +1 print count logging.basicConfig() time.sleep(2) obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Failed or Undelivered") obj.save() print "yoyo" time.sleep(5) twilioSMS(k,msg, count) else: #Saving to database in Night Time print "Night time" time.sleep(2) logging.basicConfig() obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Night Time") print obj obj.save() print "bappa" except: # Checking if the number is invalid print "yo bappa" obj = MessageLog(number=k, dateField=local_date.date(), timeField=local_date.time(), status="Not Sent") obj.save() print "error"
def deletemessages(): delnum = '+15107616409' client = Client(account_sid, auth_token) client.messages.get() #delete messages from twilio to the number twmsgs = client.messages.list(to=delnum) for twmsg in twmsgs: client.messages(twmsg.sid).delete() # delete msgs from twilio from the number twmsgs = client.messages.list(from_=delnum) for twmsg in twmsgs: client.messages(twmsg.sid).delete() #delete message to and from the number on mongo msgs = Message.objects(Q(to=delnum) | Q(from_=delnum)) for msg in msgs: msg.delete() flash('I think they are all deleted') return redirect(url_for('msgs'))
class TwilioClient(): def __init__(self, quote=None, author=None, recipient=None): self.account_sid = os.getenv('TWILIO_ACCOUNT_SID') self.auth_token = os.getenv('TWILIO_AUTH_TOKEN') self.client = Client(self.account_sid, self.auth_token) self.recipient = recipient self.sender = os.getenv("TWILIO_PHONE_NUMBER") self.quote = quote self.author = author def format(self): if self.author is None: body = self.quote else: body = f"{self.quote} | Author: {self.author}" return body def send_sms(self): """ sends quote using twilio API""" body = self.format() message = self.client.messages.create(to=self.recipient, from_=self.sender, body=body) print("TwilioClient sent a SMS") return message.sid def respond_to_sms(self): """ Sends response to inbound sms recieved, and saves details to database""" resp = MessagingResponse() sent_sms = self.client.messages.list(to=self.recipient, limit=1) for record in sent_sms: to_sid = record.sid from_sid = request.values.get('MessageSid', None) body = request.values.get('Body', None) DB = Manage_db(to_sid=to_sid) DB.modify_db(from_sid=from_sid, body=body) resp.message("Thanks, your feedback was recieved!") return str(resp) def incoming_sms(self, sid): """ Gets information from inbound sms""" message = self.client.messages(sid).fetch() body = message.body return body def start_ngrok(self): url = ngrok.connect(5000) print(' * Tunnel URL:', url) self.client.incoming_phone_numbers.list( phone_number=self.sender)[0].update(sms_url=url + '/rsms')
def send(id, otp): client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN) with open('contacts/contact_data.json', 'r') as f: contact_list = json.load(f) for contact in contact_list: if (contact['id'] == id): if (contact['Phone_number'] not in verified_list): return "failed" message = client.messages \ .create( body=text_message + " " + str(otp), from_=settings.TWILIO_PHONE_NUMBER, to=contact['Phone_number'] ) message_dict = client.messages(message.sid).fetch() return message_dict
def twilio_first_sms_status_check_task(): ''' after time specified in call parameter checks msg status with sms provider ''' logger.info("first sms status check") new_msgs = SMS.objects.filter(checked_once=False) ACCOUNT_SID = settings.TWILIO_ACCOUNT_SID AUTH_TOKEN = settings.TWILIO_AUTH_TOKEN client = Client(ACCOUNT_SID, AUTH_TOKEN) for msg in new_msgs: fetched = client.messages(msg.twilio_message_sid).fetch() msg.checked_once = True msg.save() if fetched.status == 'delivered': msg.twilio_message_status = 'delivered' msg.delivered = True msg.save() else: msg.twilio_message_status = fetched.status msg.save()
def example(): """ Some example usage of different twilio resources. """ client = Client(ACCOUNT_SID, AUTH_TOKEN) # Get all messages all_messages = client.messages.list() print('There are {} messages in your account.'.format(len(all_messages))) # Get only last 10 messages... some_messages = client.messages.list(limit=10) print('Here are the last 10 messages in your account:') for m in some_messages: sid = m.sid print(sid) mymsg = client.messages(sid).fetch() print(mymsg.body)
def handleButton(self): OTP = self.uname_lineEdit.text() # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACe6a26c83d6b8342daef53baab045bb1c" auth_token = "6fb86df5a1adad8fd094e83cc69322f1" client = Client(account_sid, auth_token) message = client.messages("SM02d78cca32e542269499a29e619a055c").fetch() z = message.body if (str(z[38:]) == str(OTP)): print('User Verified!!!') with open('/home/superuser/Desktop/project_KEYRING/myTextFile.txt', 'a') as myFile: myFile.write('\n') myFile.write(OTP) os.system( 'python /home/superuser/Desktop/project_KEYRING/facemodule/face.py' ) else: print('User Not verified!!')
def start_hunt(request, morsel_id): global morsel_id_session morsel = get_object_or_404(Morsel, pk=int(morsel_id)) twilio_account_sid = settings.TWILIO_ACCOUNT_SID twilio_auth_token = settings.TWILIO_AUTH_TOKEN twilio_number = settings.TWILIO_NUMBER twilio_client = Client(twilio_account_sid, twilio_auth_token) morsel_id_session = int(morsel_id) body = morsel.welcome_text + " Respond with 'yes' to start" outgoing_message = twilio_client.messages.create('+16467084542', body=body, from_=twilio_number) time.sleep(2) status_message = twilio_client.messages( outgoing_message.sid).fetch().status messages.success(request, "Message sent succesfully" ) if status_message == 'delivered' else messages.danger( request, "Message not sent succesfully") return HttpResponseRedirect('/app/morsels/')
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) client.messages("MM800f449d0399ed014aae2bcc0cc2f2ec") \ .delete() # Deletes entire message record
streams = json_response.get('data') # # test if streamer is live or not is_active = lambda stream: stream.get('type') == 'live' streams_active = filter(is_active, streams) at_least_one_active = (any(streams_active)) # print(at_least_one_active) twilio_acc_sid = f"{os.getenv('TWILIO_SID')}" twilio_auth_token = f"{os.getenv('TWILIO_AUTH_TOKEN')}" twilio_number = f"{os.getenv('TWILIO_NUMBER')}" my_number = f"{os.getenv('SEND_TO')}" client = Client(twilio_acc_sid, twilio_auth_token) last_messages_sent = client.messages.list(limit=1) if last_messages_sent: last_message_id = last_messages_sent[0].sid last_message_data = client.messages(last_message_id).fetch() last_message_content = last_message_data.body online_notified = "LIVE" in last_message_content offline_notified = not online_notified else: online_notified, offline_notified = False, False if at_least_one_active and not online_notified: client.messages.create(body='LIVE !!!', from_=twilio_number, to=my_number) if not at_least_one_active and not offline_notified: client.messages.create(body='OFFLINE !!!', from_=twilio_number, to=my_number)
return_message = p.get_follow(tag) # if no follow up if return_message == '': # get first tag tag = p.get_sub_tag(tag, 'yes') # get response return_message = p.get_response(tag) # clear tag tag = '' else: # get symptom sub_tag if my_message in YES: tag = p.get_sub_tag(tag, 'yes') elif my_message in NO: tag = p.get_sub_tag(tag, 'no') else: tag = '' # get response return_message = p.get_response(tag) # clear tag tag = '' # send message client.api.account.messages.create(to=message.from_, from_=my_num, body=return_message) try: # delete message client.messages(message.sid).delete() except: # error output print("error: no message to delete")
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) client.messages('MM800f449d0399ed014aae2bcc0cc2f2ec').delete()
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) message = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .update(body='body') print(message.to)
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) client.messages("MM800f449d0399ed014aae2bcc0cc2f2ec") \ .media("ME557ce644e5ab84fa21cc21112e22c485") \ .delete()
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = '"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) client.messages("MM800f449d0399ed014aae2bcc0cc2f2ec") \ .media("ME557ce644e5ab84fa21cc21112e22c485") \ .delete()
from twilio.rest import Client import credentials import send_sms import time account_sid = credentials.account_sid auth_token = credentials.auth_token client = Client(account_sid, auth_token) for old_message in client.messages.list(): client.messages(old_message.sid).update(body="") # keep running while True: for message in client.messages.list(): # print message when sent in if len(message.body) > 0: print(message.body) # delete message body client.messages(message.sid).update(body="") #send_sms.send_message(message) time.sleep(10)
from twilio.rest import Client from helpers import lookup import os import requests account_sid = os.environ.get("ACCOUNT_SID") api_key = os.environ.get("API_KEY") api_secret = os.environ.get("API_SECRET") auth_token = os.environ.get("AUTH_TOKEN") client = Client(account_sid, auth_token) message = client.messages('SM3d604cb879e1484eaee09edd01fd7965').fetch() #numbers_to_message = ['whatsapp:+971528067285', 'whatsapp:+971564833933'] #for number in numbers_to_message: message = client.messages.create( body=message.body, from_='whatsapp:+18178358402', #RSL APP Sender Number to='whatsapp:+919789229442', ) print(message.sid)
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) # A list of media objects with the properties described above medias = client.messages("MM800f449d0399ed014aae2bcc0cc2f2ec").media.list() for media in medias: print(media.content_type)
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) client.messages("MM800f449d0399ed014aae2bcc0cc2f2ec") \ .update(body="")
class TwilioClient(Configurable): """TwilioClient.""" ARGS = { ('TWILIO_CLIENT_SID', '--twilio_sid'): { 'dest': 'twilio_sid', 'help': 'Twilio account SID.', 'type': str, }, ('TWILIO_CLIENT_AUTH', '--twilio_token'): { 'dest': 'twilio_token', 'help': 'Twilio auth token.', 'type': str, }, ('TWILIO_FROM_NUMBER', '--twilio_from_number'): { 'dest': 'twilio_from_number', 'help': 'Twilio from number.', 'type': str, }, } @classmethod def patch_args(cls, args: Namespace, cfg: dict) -> dict: # print("** in twilio.py TwilioClient patch_args") # print(args) # print(cfg) if cfg is None: cfg = {} for key, value in (('sid', args.twilio_sid), ('token', args.twilio_token), ('from_number', args.twilio_from_number)): if value is not None: cfg[key] = value return cfg @classmethod def from_cfg(cls, cfg) -> TwilioClient: """Return output from cfg.""" # print("** in twilio.py TwilioClient from_cfg") # print(cfg) kwargs = { key: cast(cfg[key]) for key, cast in (('sid', str), ('token', str), ('from_number', str)) } return cls(**kwargs) def __init__(self, sid: str, token: str, from_number: str) -> None: """Initialize Twilio client.""" self.sid = sid self.token = token self.from_number = from_number self._twilio_client = Client(sid, token) def status(self, sid): return self._twilio_client.messages(sid).fetch().status def send(self, to, from_, body): return self._twilio_client.messages.create(to=to, from_=from_, body=body) def getListMessages(self, **kwargs) -> list: """from_ = strFrom, date_sent = dt_after, limit = nLimit""" return self._twilio_client.messages.list(kwargs)
# Download the Python helper library from twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" auth_token = "your_auth_token" client = Client(account_sid, auth_token) # Get an object from its sid. If you do not have a sid, # check out the list resource examples on this page sms = client.messages("SM800f449d0399ed014aae2bcc0cc2f2ec") \ .fetch() print(sms.body.encode('utf-8'))
# Download the Python helper library from twilio.com/docs/python/install import os from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure account_sid = os.environ['TWILIO_ACCOUNT_SID'] auth_token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account_sid, auth_token) # Get an object from its sid. If you do not have a sid, # check out the list resource examples on this page sms = client.messages("SM800f449d0399ed014aae2bcc0cc2f2ec") \ .fetch() print(sms.body.encode('utf-8'))
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) message = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').fetch() print(message.to)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) media = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .media \ .list(limit=20) for record in media: print(record.sid)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) media = client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .media('MEXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \ .fetch() print(media.content_type)
# Download the Python helper library from twilio.com/docs/python/install import os from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure account_sid = os.environ['TWILIO_ACCOUNT_SID'] auth_token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account_sid, auth_token) # A list of media objects with the properties described above medias = client.messages('MM800f449d0399ed014aae2bcc0cc2f2ec') \ .media \ .list() for media in medias: print(media.content_type)
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) client.messages('MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX').delete()
# /usr/bin/env python # Download the twilio-python library from twilio.com/docs/libraries/python from twilio.rest import Client # Find these values at https://twilio.com/user/account account_sid = "AC2fa452c81d34fc2952e00022a1c6e436" auth_token = "8e6fd396cf9a650c96a5031c43997f28" client = Client(account_sid, auth_token) # A list of message objects with the properties described above for message in client.messages.list(): if message.direction == "inbound": print(message.body) thing = message.sid client.messages(thing).delete()