8000 TypeError: the JSON object must be str, not 'bytes' version 6.4 python 3.5 · Issue #358 · twilio/twilio-python · GitHub
[go: up one dir, main page]

Skip to content
TypeError: the JSON object must be str, not 'bytes' version 6.4 python 3.5 #358
Closed
@brianherman

Description

@brianherman

twilio==6.4.0
Text Messaging

Code Snippet

from twilio.rest import Client
from twilio.rest.lookups import Lookups
from twilio.base.domain import Domain
import logging
import traceback
import requests
logging.basicConfig(format='%(asctime)s %(message)s', filename='texting.log',filemode='a+', level=logging.INFO)
class TwilioError(Exception):
    def __init__(self, message):
        self.message = message
class PNTxt(object):
    def __init__(self):
        self.blocked_xx = []
        self.blocked_xx = []
        self.blocked_xxx = []
        self.load_files()
    def send_text(self, campaign = "xxxxx",  phone_number="+", text="Error!", SID="PUT YOUR SID HERE", AUTH="PUT YOUR AUTH TOKEN HERE", dry_run=False):
        ''' Takes in a string, and a list of IT_Nums, ancomd text messages each of the given IT_Nums
            via the given twilio outgoing_num. The SID (Account SID) and AUTH (Auth Token)
            parameters are from our Twilio account, "www.twilio.com/console".
        '''
        outgoing_num = "+"
        if "+" not in phone_number:
           phone_number = "+" + phone_number
        phone_number = phone_number.replace("(", '').replace(')', '').replace('-', '')
        if campaign == "xxx":
            outgoing_num = "+"

        if campaign == "xxx":
            outgoing_num = "+xxxxxxxxxxxx"

        if campaign == "xxx":
            outgoing_num = "+xxxxxxxxxxxx"

        if campaign == "xxx":
            outgoing_num = "+xxxxxxxxxxxx"

        if campaign == "xxx":
            outgoing_num = "+xxxxxxxxxxxx"

        ###################################################

        ###################################################
        if campaign == "xxx":
            return "No number yet"
            #outgoing_num = "+xxxxxxxxxxxx"

        ###################################################

        ###################################################
        if campaign == "stonegate":
            return "No number yet"

            #outgoing_num = "+xxxxxxxxxxxx"

        ###################################################

        if self.check_if_blocked(phone_number, campaign):
            logging.info("Blocked {} {} {}".format(outgoing_num,phone_number,text) )
            return "Blocked"
        if text == "Error!":
            return "Error!"
        if not text:
            logging.error("NO MESSAGE BODY NOT SENDING TEXT {} {} {}".format(outgoing_num,phone_number,text) )
            return "Error!"
        if self.check_if_cellphone(phone_number) == False:
            logging.info("{} is a landline The message was {} ".format(phone_number, text))
            return "{} is a landline The message was {} ".format(phone_number, text)
        print (self.check_if_cellphone(phone_number))
        logging.debug("Attempting to Send Text Message...")
        account_sid = SID
        auth_token  = AUTH
        if dry_run:
            logging.info("Dry Run Text Message not sent. {} {} {}".format(str(text),phone_number,outgoing_num))
            return "Dry Run Successful"
        client = Client(account_sid, auth_token)
        message = client.messages.create(body = str(text),
                                            to = phone_number,
                                            from_ = outgoing_num)
    
        if not message.sid:
            logging.error("Twilio Error please check account")
        logging.info("Sent Text Message. {} {} {}".format(str(text),phone_number,outgoing_num))
        if message:
            return message
        else:
            return -1

    def check_if_blocked(self, number, campaign):
        if "xxx" in campaign:
            if number in self.blocked_unq:
                return True 
            return False
        if "xx" in campaign:
            if number in self.blocked_sg:
                return True 
            return False
        if "xx" in campaign:
            if number in self.blocked_lh:
                return True
            return False
    def load_files(self):
        self.blocked_unq = []
        self.blocked_sg = []
        self.blocked_lh = []

        with open("xxx.txt", "r+") as f:
            for line in f:
                self.blocked_unq.append(line.strip())
        with open("xxx.txt", "r+") as f:
            for line in f:
                self.blocked_sg.append(line.strip())
        with open("xxx.txt", "r+") as f:
            for line in f:
                self.blocked_lh.append(line.strip())
    def halt_messages(self, number):
        if number not in blocked:
            self.blocked.append(number)
            self.save_file()
    def check_if_cellphone(self,number, SID="xxx", AUTH="xxx"):
        assert ("xxx" == AUTH)
        assert ("xxx" == SID)
        try:
            TWILIO_LOOKUP_URL = "https://lookups.twilio.com/v1/PhoneNumbers/{}?Type=carrier"
            response = requests.get(TWILIO_LOOKUP_URL.format(number),
                                auth=(SID, AUTH))
            print(response.text)
        
            carrier =  response.json()['carrier']
            if carrier:
                if carrier['type'] == "mobile":
                    return True
                if carrier['type'] == 'landline':
                    return False
            print(response.json())
        except:
            logging.error("We are getting twilio errors!!!")
            
        logging.error("Invalid carrier information for {}".format(number))
        return False

def tests():  
    i = PNTxt() 
    print(i.send_text(campaign = "UNQ NM TXT Campaign", phone_number="+xxx", text="test", dry_run=False))


if __name__ == '__main__':
    tests()

Exception / Log

Traceback (most recent call last):
  File "TwilioUtil.py", line 163, in <module>
    tests()
  File "TwilioUtil.py", line 159, in tests
    print(i.send_text(campaign = "UNQ NM TXT Campaign", phone_number="+16307509505", text="test", dry_run=False))
  File "TwilioUtil.py", line 79, in send_text
    from_ = outgoing_num)
  File "/home/xxxxx/projects/python3_5/lib/python3.5/site-packages/twilio/rest/api/v2010/account/message/__init__.py", line 78, in create
    data=data,
  File "/home/xxxxx/projects/python3_5/lib/python3.5/site-packages/twilio/base/version.py", line 214, in create
    return json.loads(response.content)
  File "/usr/lib/python3.5/json/__init__.py", line 312, in loads
    s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'

Steps to Reproduce

  1. Send a text message with my code

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Pr 306E ojects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0