def test_request_behind_proxy(self): proxies = { 'http': 'http://proxy.twilio.com', 'https': 'https://proxy.twilio.com', } self.client = TwilioHttpClient(proxy=proxies) self.client.request('doesnt matter', 'doesnt matter') self.assertEqual(proxies, self.session_mock.proxies)
def test_session_not_preserved(self): self._setup_session_response('response_1') client = TwilioHttpClient(pool_connections=False) response_1 = client.request('GET', 'https://api.twilio.com') self._setup_session_response('response_2') response_2 = client.request('GET', 'https://api.twilio.com') # Used different session, responses should be different self.assertEqual(response_1.content, 'response_1') self.assertEqual(response_2.content, 'response_2')
def test_session_not_preserved(self): self._setup_session_response('response_1') client = TwilioHttpClient(pool_connections=False) response_1 = client.request('GET', 'https://api.twilio.com') self._setup_session_response('response_2') response_2 = client.request('GET', 'https://api.twilio.com') # Used different session, responses should be different self.assertEqual(response_1.content, 'response_1') self.assertEqual(response_2.content, 'response_2')
def test_session_preserved(self): self._setup_session_response('response_1') client = TwilioHttpClient() response_1 = client.request('GET', 'https://api.twilio.com') self._setup_session_response('response_2') response_2 = client.request('GET', 'https://api.twilio.com') # Used same session, response should be the same self.assertEqual(response_1.content, 'response_1') self.assertEqual(response_2.content, 'response_1')
def test_session_preserved(self): self._setup_session_response('response_1') client = TwilioHttpClient() response_1 = client.request('GET', 'https://api.twilio.com') self._setup_session_response('response_2') response_2 = client.request('GET', 'https://api.twilio.com') # Used same session, response should be the same self.assertEqual(response_1.content, 'response_1') self.assertEqual(response_2.content, 'response_1')
def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Response(200, 'testing-unicode: Ω≈ç√, 💩') self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient()
def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Mock( status_code=200, content=six.u('testing-unicodeΩ≈ç√')) self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient()
def __init__(self, username=None, password=None, account_sid=None, region=None, http_client=None, environment=None): """ Initializes the Twilio Client :param str username: Username to authenticate with :param str password: Password to authenticate with :param str account_sid: Account Sid, defaults to Username :param str region: Twilio Region to make requests to :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient :param dict environment: Environment to look for auth details, defaults to os.environ :returns: Twilio Client :rtype: twilio.rest.Client """ environment = environment or os.environ self.username = username or environment.get('TWILIO_ACCOUNT_SID') """ :type : str """ self.password = password or environment.get('TWILIO_AUTH_TOKEN') """ :type : str """ self.account_sid = account_sid or self.username """ :type : str """ self.region = region """ :type : str """ if not self.username or not self.password: raise TwilioException( "Credentials are required to create a TwilioClient") self.auth = (self.username, self.password) """ :type : tuple(str, str) """ self.http_client = http_client or TwilioHttpClient() """ :type : HttpClient """ # Domains self._accounts = None self._api = None self._chat = None self._fax = None self._ip_messaging = None self._lookups = None self._monitor = None self._notify = None self._preview = None self._pricing = None self._proxy = None self._taskrouter = None self._trunking = None self._video = None self._messaging = None self._wireless = None self._sync = None self._studio = None self._verify = None
def kirim_wa(): account_sid = request.args.get('account_sid') auth_token = request.args.get('auth_token') from_wa = request.args.get('from_wa') to_wa = request.args.get('to_wa') body_message = request.args.get('body_message') proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} # account_sid = 'AC394d58a2fc9ae8ca6fb7bc3bacc37cbe' # auth_token = '81b425ff12855a14cfb04ea98f662058' account_sid = str(account_sid) auth_token = str(auth_token) from_wa = str(from_wa) to_wa = str(to_wa) body_message = str(body_message) client = Client(account_sid, auth_token, http_client=proxy_client) # twilio api calls will now work from behind the proxy: # message = client.messages.create(to="whatsapp:+6285947593178", from_='whatsapp:+14155238886', body='Bahaya, suhu rumah kamu {} derajat'.format(131)) message = client.messages.create(to="whatsapp:+{}".format(to_wa), from_="whatsapp:+{}".format(from_wa), body=body_message) return 'Sukses kirim via WA, pesan : {}'.format(body_message)
def send_twilio(to, body): from twilio.rest import Client from twilio.base.exceptions import TwilioRestException from twilio.http.http_client import TwilioHttpClient client = "" #Client(base64.b64decode(CONFIG['account']), base64.b64decode(CONFIG['token'])) try: proxy_client = TwilioHttpClient() # assuming your proxy is available via the standard env var https_proxy: ## (this is the case on pythonanywhere) proxy_client.session.proxies = {'https': os.environ['https_proxy']} client = Client(base64.b64decode(CONFIG['account']), base64.b64decode(CONFIG['token']), http_client=proxy_client) except KeyError: try: client = Client(base64.b64decode(CONFIG['account']), base64.b64decode(CONFIG['token'])) return client.messages.create(to=to, from_=CONFIG['from'], body=body) except TypeError: logging.error( "Please check your config file as properly base64 encoded content" ) except ConnectionError: logging.error("Opps !! Check you Internet connection. \n{}".format( sys.exc_info())) except TwilioRestException: logging.error("Opps!! Check your credentials in config file : \ {} or server issue \n{}".format(CFGFILE, sys.exc_info())) except TypeError: logging.error( "Please check your config file as properly base64 encoded content" )
def __init__(self, source_number, account_sid, auth_token): self.source_number = source_number self.account_sid = account_sid self.auth_token = auth_token self.proxy = TwilioHttpClient() self.proxy.session.proxies = {'https' : os.environ['https_proxy']} self.client = Client(self.account_sid, self.auth_token, http_client=self.proxy)
def send_to_sms(receive_number, message, send_number, account_sid, auth_token): proxy_client = TwilioHttpClient() proxy_client.session.proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080" } client = Client(account_sid, auth_token, http_client=proxy_client) client.messages.create(body=message, from_=send_number, to=receive_number)
def send_text(): proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} account_sid = '' auth_token = '' client = Client(account_sid, auth_token, http_client=proxy_client) message_text = "Tattoo is a gooooooooo! https://www.instagram.com/melaniesteinway" message = client.messages.create(to="+13104158457", from_='+112015813048', body=message_text)
def __init__(self): self.proxy_client = TwilioHttpClient() self.proxy_client.session.proxies = { 'https': os.environ['https_proxy'], 'http': os.environ['http_proxy'] } self.account_sid = account_sid self.auth_token = auth_token self.client = Client(self.account_sid, self.auth_token,http_client=self.proxy_client)
def send_message(forecast_message): proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} client = Client(account_sid, auth_token) message = client.messages \ .create( body=forecast_message, from_=config.get("SENDER"), to='Your recipient number' ) print(message.sid)
def kirimwa(): proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} if request.method == 'POST': client = Client(request.form['account_sid'], request.form['auth_token'], http_client=proxy_client) message = client.messages.create( to="whatsapp:+{}".format(str(request.form['to_wa'])), from_="whatsapp:+{}".format(str(request.form['from_wa'])), body=str(request.form['body_message'])) return render_template("form_wa.html")
def __init__(self): self.account_sid = os.environ['TWILIO_SID'] self.auth_token = os.environ['TWILIO_AUTH'] self.my_phone = os.environ['MY_PHONE'] self.from_phone = os.environ['TWILIO_PHONE'] if "PYTHONANYWHERE_DOMAIN" in os.environ: self.proxy_client = TwilioHttpClient() self.proxy_client.session.proxies = { 'https': os.environ['https_proxy'] } else: self.proxy_client = None
class TestHttpClientRequest(unittest.TestCase): def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Response( 200, 'testing-unicode: Ω≈ç√, 💩') self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient() def tearDown(self): self.session_patcher.stop() def test_request_sets_host_header_if_missing(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) def test_request_with_unicode_response(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} response = self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content)
def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Response(200, 'testing-unicode: Ω≈ç√, 💩') self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient()
def main(): proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} # TWILIO SETUP STUFF # Your Account SID from twilio.com/console account_sid = "YOUR_ACCOUNT_SID" # Your Auth Token from twilio.com/console auth_token = "YOUR_AUTH_TOKEN" client = Client(account_sid, auth_token) BASE_URL = 'https://www.scu.edu/apps/ws/courseavail/search/4000/ugrad/math+51' print("url: " + BASE_URL) #get the json response from a URL r = requests.get(BASE_URL) json_file = r.json( ) # if response type was set to JSON, then you'll automatically have a JSON response here... results = json_file['results'] print for i in results: #define all useful vars name = i['subject'] + " " + i['catalog_nbr'] + ": " + i['class_descr'] number = i['class_nbr'] time = i['mtg_days_1'] + " " + i['mtg_time_beg_1'] prof = i['instr_1'] seats = int(i['seats_remaining']) #print out the results print(name) print(number) print(time) print(prof) print("Seats: " + str(seats)) # MYSTUFF if (number == "74942"): if (seats > 0): message = client.messages.create(to="+YOUR_NUMBER_HERE", from_="+12065391594", body=("Your class has " + seats + " left!")) print("Your class has " + str(seats) + " seats left!") print
def generateOTP(phno): try: proxy_client = TwilioHttpClient() #proxy_client.session.proxies = {'https': os.environ['https_proxy']} account_sid = os.environ.get('account_sid') auth_token = os.environ.get('auth_token') client = Client(account_sid, auth_token) n = random.randint(1000, 9999) client.messages.create(body='OTP is - ' + str(n), from_='+12074642648', to='+91' + str(phno)) return n except (e): print('Error') print(e)
def send_text(message): account_sid = os.environ['TWILIO_SID'] auth_token = os.environ['TWILIO_AUTH'] my_phone = os.environ['MY_PHONE'] from_phone = os.environ['TWILIO_PHONE'] if "PYTHONANYWHERE_DOMAIN" in os.environ: proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} else: proxy_client = None client = Client(account_sid, auth_token, http_client=proxy_client) message = client.messages.create(body=message, from_=from_phone, to=my_phone) print(message.status)
def twilio_wa(): proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} if request.method == 'POST': if request.form['account_sid'] == '': data = 'Invalid Credentials. Please try again.' else: client = Client(request.form['account_sid'], request.form['auth_token'], http_client=proxy_client) message = client.messages.create( to="whatsapp:+{}".format(str(request.form['to_wa'])), from_="whatsapp:+{}".format(str(request.form['from_wa'])), body=str(request.form['body_message'])) return render_template("whatsapp.html")
def twilioSMS(phone_number, message): print(phone_number,message) er = ''; if phone_number: if all([settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN, settings.TWILIO_FROM_NUMBER]): try: proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https://127.0.0.1:8000','http://127.0.0.1:8000','https://api.twilio.com:443','http://127.0.0.1:3128','https://127.0.0.1:3128'} twilio_client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN,http_client=proxy_client) twilio_client.messages.create( body=str(message), to=str('+84%s'%(phone_number)), from_=settings.TWILIO_FROM_NUMBER ) return True, er except Exception as e: er=e print(e) else: print('Twilio credentials are not set') return False, er
def send_data_to_owner(data): print('Abhishek') message_item = [ time.asctime(time.localtime()), data["Email"], data["Subject"], data["Message"] ] try: account_sid = os.getenv('ACCOUNT_SID') auth_token = os.getenv('AUTH_TOKEN') proxy_client = TwilioHttpClient(proxy={ 'http': os.environ['http_proxy'], 'https': os.environ['https_proxy'] }) client = Client(account_sid, auth_token, http_client=proxy_client) message = client.messages.create(from_='+15202140910', body=str(message_item), to='+919662667244') print(message.sid) print("Executed Successfully.") except TwilioRestException as e: print(e)
def __init__(self): owm_endpoint = "https://api.openweathermap.org/data/2.5/onecall" # We are using Environment Variables, they need to be set via export OWM_API_KEY=xxx where xxx is your variable # If using a script, you can set the environment variables before the "python3 main.py" call, ending lines with # a semi-column api_key = os.environ.get("OWM_API_KEY") account_sid = "YOUR ACCOUNT SID" auth_token = os.environ.get("AUTH_TOKEN") weather_params = { "lat": "YOUR LATITUDE", "lon": "YOUR LONGITUDE", "appid": api_key, "exclude": "current,minutely,daily" } response = requests.get(owm_endpoint, params=weather_params) response.raise_for_status() weather_data = response.json() weather_slice = weather_data["hourly"][:12] will_rain = False for hour_data in weather_slice: condition_code = hour_data["weather"][0]["id"] if int(condition_code) < 700: will_rain = True if will_rain: proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} client = Client(account_sid, auth_token, http_client=proxy_client) message = client.messages \ .create( body="It's going to rain today. Remember to bring an ☔️", from_="YOUR TWILIO VIRTUAL NUMBER", to="YOUR TWILIO VERIFIED REAL NUMBER" ) print(message.status)
def main(): # get time (Pacific) time = (datetime.utcnow().time().hour - 7) % 24 print("[Trigger]: Hour {}".format(time)) # only run if not in the middle of the night if time in [22, 23, 0, 1, 2, 3, 4, 5, 6, 7, 8]: print("[Skipping]: Late at night") return # set up Twilio client proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} client = Client(get_account_sid(), get_auth_token(), http_client=proxy_client) # set up phone numbers twilio_number = get_Twilio_number() phone_numbers = get_phone_numbers() num_sent = 0 for number in phone_numbers: # Google search query = get_query() url = random.choice(get_image_urls(query)) print("[Query]: {}".format(query)) # send message try: message = client.messages.create(from_=twilio_number, media_url=url, to=number) num_sent += 1 print("[Sending]: {}".format(message.sid)) except: pass print("[Messages succesful]: {}".format(num_sent))
def kirim_wa(): account_sid = request.args.get('account_sid') auth_token = request.args.get('auth_token') from_wa = request.args.get('from_wa') to_wa = request.args.get('to_wa') body_message = request.args.get('body_message') proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} account_sid = str(account_sid) auth_token = str(auth_token) from_wa = str(from_wa) to_wa = str(to_wa) body_message = str(body_message) client = Client(account_sid, auth_token, http_client=proxy_client) message = client.messages.create(to="whatsapp:+{}".format(to_wa), from_="whatsapp:+{}".format(from_wa), body=body_message) return 'Sukses kirim via WA, pesan : {}'.format(body_message)
class TestHttpClientRequest(unittest.TestCase): def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Response(200, 'testing-unicode: Ω≈ç√, 💩') self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient() def tearDown(self): self.session_patcher.stop() def test_request_sets_host_header_if_missing(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertIsNotNone(self.client.last_request) self.assertIsNotNone(self.client.last_response) def test_request_with_unicode_response(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} response = self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) def test_last_request_last_response_exist(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.request('doesnt-matter-method', 'doesnt-matter-url', {'params-value': 'params-key'}, {'data-value': 'data-key'}, {'headers-value': 'headers-key'}, ['a', 'b']) self.assertIsNotNone(self.client.last_request) self.assertEqual('doesnt-matter-url', self.client.last_request.url) self.assertEqual('DOESNT-MATTER-METHOD', self.client.last_request.method) self.assertEqual({'params-value': 'params-key'}, self.client.last_request.params) self.assertEqual({'data-value': 'data-key'}, self.client.last_request.data) self.assertEqual({'headers-value': 'headers-key'}, self.client.last_request.headers) self.assertEqual(['a', 'b'], self.client.last_request.auth) self.assertIsNotNone(self.client.last_response) self.assertEqual(200, self.client.last_response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', self.client.last_response.text) def test_last_response_empty_on_error(self): self.session_mock.send.side_effect = Exception('voltron') with self.assertRaises(Exception): self.client.request('doesnt-matter', 'doesnt-matter') self.assertIsNotNone(self.client.last_request) self.assertIsNone(self.client.last_response)
class TestHttpClientRequest(unittest.TestCase): def setUp(self): self.session_patcher = patch('twilio.http.http_client.Session') self.session_mock = Mock(wraps=Session()) self.request_mock = Mock() self.session_mock.prepare_request.return_value = self.request_mock self.session_mock.send.return_value = Response( 200, 'testing-unicode: Ω≈ç√, 💩') self.request_mock.headers = {} session_constructor_mock = self.session_patcher.start() session_constructor_mock.return_value = self.session_mock self.client = TwilioHttpClient() def tearDown(self): self.session_patcher.stop() def test_request_sets_host_header_if_missing(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertIsNotNone(self.client.last_request) self.assertIsNotNone(self.client.last_response) def test_request_with_timeout(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} response = self.client.request('doesnt matter', 'doesnt matter', None, None, None, None, 30, None) self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) def test_request_where_method_timeout_equals_zero(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} try: self.client.request('doesnt matter', 'doesnt matter', None, None, None, None, 0, None) except Exception as e: self.assertEqual(ValueError, type(e)) def test_request_where_class_timeout_manually_set(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.timeout = 30 response = self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) def test_request_where_class_timeout_equals_zero(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.timeout = 0 try: self.client.request('doesnt matter', 'doesnt matter') except Exception as e: self.assertEqual(type(e), ValueError) def test_request_where_class_timeout_and_method_timeout_set(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.timeout = 30 response = self.client.request('doesnt matter', 'doesnt matter', None, None, None, None, 15, None) self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) def test_request_with_unicode_response(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} response = self.client.request('doesnt matter', 'doesnt matter') self.assertEqual('other.twilio.com', self.request_mock.headers['Host']) self.assertEqual(200, response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', response.content) def test_last_request_last_response_exist(self): self.request_mock.url = 'https://api.twilio.com/' self.request_mock.headers = {'Host': 'other.twilio.com'} self.client.request('doesnt-matter-method', 'doesnt-matter-url', {'params-value': 'params-key'}, {'data-value': 'data-key'}, {'headers-value': 'headers-key'}, ['a', 'b']) self.assertIsNotNone(self.client.last_request) self.assertEqual('doesnt-matter-url', self.client.last_request.url) self.assertEqual('DOESNT-MATTER-METHOD', self.client.last_request.method) self.assertEqual({'params-value': 'params-key'}, self.client.last_request.params) self.assertEqual({'data-value': 'data-key'}, self.client.last_request.data) self.assertEqual({'headers-value': 'headers-key'}, self.client.last_request.headers) self.assertEqual(['a', 'b'], self.client.last_request.auth) self.assertIsNotNone(self.client.last_response) self.assertEqual(200, self.client.last_response.status_code) self.assertEqual('testing-unicode: Ω≈ç√, 💩', self.client.last_response.text) def test_last_response_empty_on_error(self): self.session_mock.send.side_effect = Exception('voltron') with self.assertRaises(Exception): self.client.request('doesnt-matter', 'doesnt-matter') self.assertIsNotNone(self.client.last_request) self.assertIsNone(self.client.last_response) def test_request_behind_proxy(self): proxies = { 'http': 'http://proxy.twilio.com', 'https': 'https://proxy.twilio.com', } self.client = TwilioHttpClient(proxy=proxies) self.client.request('doesnt matter', 'doesnt matter') self.assertEqual(proxies, self.session_mock.proxies) def test_exception_with_details(self): v1 = MyVersion(self.client) error_text = """{ "code": 20001, "message": "Bad request", "more_info": "https://www.twilio.com/docs/errors/20001", "status": 400, "details": { "foo":"bar" } }""" self.session_mock.send.return_value = Response(400, error_text) try: v1.fetch("get", "none", None, None, None, None, None) self.fail('should not happen') except TwilioRestException as err: self.assertEqual(400, err.status) self.assertEqual(20001, err.code) self.assertEqual("get", err.method) self.assertEqual("Unable to fetch record: Bad request", err.msg) self.assertEqual({"foo": "bar"}, err.details)
def _get_client(self, sid, token): proxy_client = TwilioHttpClient() proxy_client.session.proxies = getproxies() return Client(sid, token, http_client=proxy_client)
for day in days: lst.append(day) day1 = float(days[lst[0]]['4. close']) day2 = float(days[lst[1]]['4. close']) arrow = '🔺' if day1 - day2 > 0 else '🔻' percent = str(abs(day1 - day2) / day2 * 100).split('.')[0] if int(percent) > 0: response = requests.get(NEWS_ENDPOINT, params=NEWS_PARAMETERS) articles = response.json()['articles'] three_articles = [(articles[i]['title'], articles[i]['description']) for i in range(3)] proxy_client = TwilioHttpClient() proxy_client.session.proxies = {'https': os.environ['https_proxy']} client = Client(account_sid, auth_token, http_client=proxy_client) num = random.randint(0, 2) message = client.messages \ .create( body=f"{STOCK_NAME}: {arrow}{percent}%\nHeadline: {three_articles[num][0]}\nBrief: {three_articles[num][1]}", from_='+14159961359', to='+19292549035' ) print(message.status) # When stock price increase/decreases by 5% between yesterday and the day before yesterday then print("Get News"). #TODO 1. - Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries. e.g. [new_value for (key, value) in dictionary.items()]
def __init__(self) -> None: # Proxy server are require to be use for PythonAnyWhere self.proxy_client = TwilioHttpClient() self.proxy_client.session.proxies = {'https': os.environ['https_proxy']} # Defining client self.client = Client(ACCOUNT_SID, AUTH_TOKEN, http_client=self.proxy_client)
def __init__(self, username=None, password=None, account_sid=None, region=None, http_client=None, environment=None, edge=None): """ Initializes the Twilio Client :param str username: Username to authenticate with :param str password: Password to authenticate with :param str account_sid: Account SID, defaults to Username :param str region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient :param dict environment: Environment to look for auth details, defaults to os.environ :param str edge: Twilio Edge to make requests to, defaults to None :returns: Twilio Client :rtype: twilio.rest.Client """ environment = environment or os.environ self.username = username or environment.get('TWILIO_ACCOUNT_SID') """ :type : str """ self.password = password or environment.get('TWILIO_AUTH_TOKEN') """ :type : str """ self.account_sid = account_sid or self.username """ :type : str """ self.edge = edge or environment.get('TWILIO_EDGE') """ :type : str """ self.region = region or environment.get('TWILIO_REGION') """ :type : str """ if not self.username or not self.password: raise TwilioException( "Credentials are required to create a TwilioClient") self.auth = (self.username, self.password) """ :type : tuple(str, str) """ self.http_client = http_client or TwilioHttpClient() """ :type : HttpClient """ # Domains self._accounts = None self._api = None self._autopilot = None self._chat = None self._conversations = None self._events = None self._fax = None self._flex_api = None self._frontline_api = None self._insights = None self._ip_messaging = None self._lookups = None self._media = None self._messaging = None self._monitor = None self._notify = None self._numbers = None self._preview = None self._pricing = None self._proxy = None self._serverless = None self._studio = None self._sync = None self._taskrouter = None self._trunking = None self._trusthub = None self._verify = None self._video = None self._voice = None self._wireless = None self._supersim = None self._bulkexports = None