def testCoverage(self): # Python version extra tests invalid_number = PhoneNumber(country_code=210, national_number=123456L) self.assertEquals( "", geocoder.country_name_for_number(invalid_number, "en")) # Add in some script and region specific fictional names TEST_GEOCODE_DATA['1650960'] = { 'en': u'Mountain View, CA', "en_GB": u'Mountain View California', "en_Latn": u'MountainView' } self.assertEquals( "Mountain View California", geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="GB")) self.assertEquals( "MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn")) self.assertEquals( "MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB")) TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA'}
def normalize_single_number(phone): try: parsed = pn.parse(phone, 'US') except: phones = { 'E164': 'Invalid Number', 'International': 'Invalid Number', 'National': 'Invalid Number', 'Country': 'Invalid Number' } return phones if pn.is_possible_number(parsed) != True: phones = { 'E164': 'Invalid Number', 'International': 'Invalid Number', 'National': 'Invalid Number', 'Country': 'Invalid Number' } return phones else: E164 = pn.format_number(parsed, pn.PhoneNumberFormat.E164) International = pn.format_number(parsed, pn.PhoneNumberFormat.INTERNATIONAL) National = pn.format_number(parsed, pn.PhoneNumberFormat.NATIONAL) Country = pngc.country_name_for_number(parsed, 'en') phones = { 'E164': E164, 'International': International, 'National': National, 'Country': Country } return phones
def create(self, validated_data): caller = validated_data['caller'] destination = validated_data['destination'] if validated_data['direction'] == 'outbound': # Because of GRID-4965, the API returns the destination number in the same format user inserted it, # so if country code is missing let's patch it with the one from the caller number. if not destination['number'].startswith('+'): if caller['number'].startswith('+'): try: caller_number = phonenumbers.parse( caller['number'], None) country_code = get_country_code_by_country( geocoder.country_name_for_number( caller_number, 'en')) destination_number = phonenumbers.parse( destination['number'], country_code) if phonenumbers.is_valid_number(destination_number): destination['number'] = phonenumbers.format_number( destination_number, phonenumbers.PhoneNumberFormat.E164) except NumberParseException, e: logger.error(traceback.format_exc(e)) data = self.match_external_participant(destination) if not data['source']: # We don't save outbound calls where the destination isn't an account or a contact. # This is the only reliable way to filter out internal calls. return CallRecord()
def create(self, validated_data): caller = validated_data['caller'] destination = validated_data['destination'] if validated_data['direction'] == 'outbound': # Because of GRID-4965, the API returns the destination number in the same format user inserted it, # so if country code is missing let's patch it with the one from the caller number. if not destination['number'].startswith('+'): if caller['number'].startswith('+'): try: caller_number = phonenumbers.parse(caller['number'], None) country_code = get_country_code_by_country( geocoder.country_name_for_number(caller_number, 'en') ) destination_number = phonenumbers.parse(destination['number'], country_code) if phonenumbers.is_valid_number(destination_number): destination['number'] = phonenumbers.format_number( destination_number, phonenumbers.PhoneNumberFormat.E164 ) except NumberParseException, e: logger.error(traceback.format_exc(e)) data = self.match_external_participant(destination) if not data['source']: # We don't save outbound calls where the destination isn't an account or a contact. # This is the only reliable way to filter out internal calls. return CallRecord()
def validate_number(number, country, include_description=True) -> Optional[Number]: try: p = parse_number(number, country) except NumberParseException: return if not is_valid_number(p): return is_mobile = number_type(p) in MOBILE_NUMBER_TYPES descr = None if include_description: country = country_name_for_number(p, 'en') region = description_for_number(p, 'en') descr = country if country == region else f'{region}, {country}' return Number( number=format_number(p, PhoneNumberFormat.E164), country_code=f'{p.country_code}', number_formatted=format_number(p, PhoneNumberFormat.INTERNATIONAL), descr=descr, is_mobile=is_mobile, )
def simple_scan(self, working=True): # function to get the basic info about a number (phonenumbers module) phone = phonenumbers.parse(self.phonenumber) if not phonenumbers.is_valid_number(phone): return False if phonenumbers.is_possible_number(phone): print(f"{b}{plus} The number is valid and possible.") else: print(f"{b}{warn} The number is valid but not possible.") international = phonenumbers.format_number( phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL) countrycode = phonenumbers.format_number( phone, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(" ")[0] country = geocoder.country_name_for_number(phone, 'en') location = geocoder.description_for_number(phone, 'en') carrierr = carrier.name_for_number(phone, 'en') # ------------------------------------------------------------------------ if working: print(f'{b}{plus} International Format : {international}') print( f'{b}{plus} Country name : {country} ({countrycode})') print(f'{b}{plus} City/Province : {location}') print(f'{b}{plus} Carrier : {carrierr}') for time in timezone.time_zones_for_number(phone): print(f'{b}{plus} Timezone : {time}')
def localScan(InputNumber, print_results=True): print("Running local scan...") FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: print(e) else: if not phonenumbers.is_valid_number(PhoneNumberObject): return False number = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164 ).replace("+", "") numberCountryCode = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL ).split(" ")[0] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode) ) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164 ).replace(numberCountryCode, "") internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL ) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, "en") if print_results: print("International format: {}".format(internationalNumber)) print("Local format: {}".format(localNumber)) print("Country found: {} ({})".format(country, numberCountryCode)) print("City/Area: {}".format(location)) print("Carrier: {}".format(carrierName)) for timezoneResult in timezone.time_zones_for_number(PhoneNumberObject): print("Timezone: {}".format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): print("The number is valid and possible.") else: print("The number is valid but might not be possible.") numberObj = {} numberObj["input"] = InputNumber numberObj["default"] = number numberObj["local"] = localNumber numberObj["international"] = internationalNumber numberObj["country"] = country numberObj["countryCode"] = numberCountryCode numberObj["countryIsoCode"] = numberCountry numberObj["location"] = location numberObj["carrier"] = carrierName return numberObj
def numberScan(): global phoneNumberGET, phoneNumber, numberNSCAN, numberCC, numberC, numberLOCAL, numberINTER, countryNSCAN, locationNSCAN, carrierNameNSCAN phoneNumberGET = numberSCANentryVar.get() #GET INFORMATIONS - PHONE NUMBER SCANNER FRAME phoneNumber = phonenumbers.parse(phoneNumberGET, None) numberNSCAN = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCC = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] numberC = phonenumbers.region_code_for_country_code(int(numberCC)) numberLOCAL = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.E164).replace(numberCC, '') numberINTER = phonenumbers.format_number( phoneNumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL) countryNSCAN = geocoder.country_name_for_number(phoneNumber, 'en') locationNSCAN = geocoder.description_for_number(phoneNumber, 'en') carrierNameNSCAN = carrier.name_for_number(phoneNumber, 'en') #APPLY RESULTS - PHONE NUMBER SCANNER FRAME numberReset() numberSCANentryVar.set(phoneNumberGET) localNSCANentryVar.set(numberLOCAL) interNSCANentryVar.set(numberINTER) countryNSCANentryVar.set("{} ({})".format(countryNSCAN, numberCC)) areaNSCANentryVar.set(locationNSCAN) carrierNSCANentryVar.set(carrierNameNSCAN) for timezoneResult in timezone.time_zones_for_number(phoneNumber): timezoneNSCANentryVar.set(timezoneResult) if phonenumbers.is_possible_number(phoneNumber): validNSCANentryVar.set("VALID+POSSIBLE") else: validNSCANentryVar.set("INVALID")
def scan(InputNumber, print_results=True): test('Running local scan...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: throw(e) else: if not phonenumbers.is_valid_number(PhoneNumberObject): return False number = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCountryCode = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') if print_results: plus('International format: {}'.format(internationalNumber)) plus('Local format: {}'.format(localNumber)) plus('Country found: {} ({})'.format(country, numberCountryCode)) plus('City/Area: {}'.format(location)) plus('Carrier: {}'.format(carrierName)) for timezoneResult in timezone.time_zones_for_number( PhoneNumberObject): plus('Timezone: {}'.format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): plus('The number is valid and possible!') else: warn('The number is valid but might not be possible.') numberObj = {} numberObj['input'] = InputNumber numberObj['default'] = number numberObj['local'] = localNumber numberObj['international'] = internationalNumber numberObj['country'] = country numberObj['countryCode'] = numberCountryCode numberObj['countryIsoCode'] = numberCountry numberObj['location'] = location numberObj['carrier'] = carrierName return numberObj
def phone_to_country(number: str): # Helper function to take a country from a phone number parsed = phonenumbers.parse(number) if not phonenumbers.is_possible_number(parsed): raise ValueError("Invalid phone number") return geocoder.country_name_for_number(parsed, "en")
def get_country_by_phone_number(phone_number): """ Get the English text representation of the country the number belongs to. Netherlands is used as fallback. """ try: number_obj = phonenumbers.parse(phone_number, None) country = geocoder.country_name_for_number(number_obj, "en") except phonenumbers.NumberParseException: country = "Netherlands" return country
def localScan(InputNumber): global number global localNumber global internationalNumber global numberCountryCode global numberCountry print(code_info + 'Running local scan...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: return False else: if not phonenumbers.is_valid_number(PhoneNumberObject): return False number = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCountryCode = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '0') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') print(code_result + 'International format: {}'.format(internationalNumber)) print(code_result + 'Local format: 0{}'.format(localNumber)) print(code_result + 'Country found: {} ({})'.format(country, numberCountryCode)) print(code_result + 'City/Area: {}'.format(location)) print(code_result + 'Carrier: {}'.format(carrierName)) for timezoneResult in timezone.time_zones_for_number( PhoneNumberObject): print(code_result + 'Timezone: {}'.format(timezoneResult)) if phonenumbers.is_possible_number(PhoneNumberObject): print(code_info + 'The number is valid and possible.') else: print(code_warning + 'The number is valid but might not be possible.')
def localScan(InputNumber): global number global localNumber global internationalNumber global numberCountryCode global numberCountry print(code_info + 'Executando verificação local...') FormattedPhoneNumber = "+" + formatNumber(InputNumber) try: PhoneNumberObject = phonenumbers.parse(FormattedPhoneNumber, None) except Exception as e: return False else: if not phonenumbers.is_valid_number(PhoneNumberObject): return False number = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace('+', '') numberCountryCode = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] numberCountry = phonenumbers.region_code_for_country_code( int(numberCountryCode)) localNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.E164).replace( numberCountryCode, '0') internationalNumber = phonenumbers.format_number( PhoneNumberObject, phonenumbers.PhoneNumberFormat.INTERNATIONAL) country = geocoder.country_name_for_number(PhoneNumberObject, "en") location = geocoder.description_for_number(PhoneNumberObject, "en") carrierName = carrier.name_for_number(PhoneNumberObject, 'en') print(code_result + f'Formato internacional:{B} {internationalNumber}') print(code_result + f'Formato local:{B} 0 {localNumber}') print(code_result + f'País: {B}{country} ({numberCountryCode})') print(code_result + f'Cidade/Estado:{B} {location}') print(code_result + f'Operadora:{B} {carrierName}') for timezoneResult in timezone.time_zones_for_number( PhoneNumberObject): print(code_result + f'Fuso horário:{B} {timezoneResult}') if phonenumbers.is_possible_number(PhoneNumberObject): print(code_info + 'O número é válido e possível.') else: print(code_warning + 'O número é válido, mas pode não ser possível.')
def getCoordFromPhoneAndPublish(self, phoneNumber, categ): try: rep = phonenumbers.parse(phoneNumber, None) if not (phonenumbers.is_valid_number(rep) or phonenumbers.is_possible_number(rep)): self.logger.warning("Phone number not valid") return country_name = geocoder.country_name_for_number(rep, "en") country_code = self.country_to_iso[country_name] if country_code is None: self.logger.warning("Non matching ISO_CODE") return coord = self.country_code_to_coord[ country_code.lower()] # countrycode is in upper case coord_dic = {'lat': coord['lat'], 'lon': coord['long']} ordDic = OrderedDict() #keep fields with the same layout in redis ordDic['lat'] = coord_dic['lat'] ordDic['lon'] = coord_dic['lon'] coord_list = [coord['lat'], coord['long']] if not self.coordinate_list_valid(coord_list): raise InvalidCoordinate( "Coordinate do not match EPSG:900913 / EPSG:3785 / OSGEO:41001" ) self.push_to_redis_zset(self.keyCategCoord, json.dumps(ordDic)) self.push_to_redis_zset(self.keyCategCountry, country_code) ordDic = OrderedDict() #keep fields with the same layout in redis ordDic['categ'] = categ ordDic['value'] = phoneNumber self.push_to_redis_geo(self.keyCategRad, coord['long'], coord['lat'], json.dumps(ordDic)) to_send = { "coord": coord_dic, "categ": categ, "value": phoneNumber, "country": country_name, "specifName": "", "cityName": "", "regionCode": country_code, } j_to_send = json.dumps(to_send) self.serv_coord.publish(self.CHANNELDISP, j_to_send) self.live_helper.add_to_stream_log_cache('Map', j_to_send) self.logger.info('Published: {}'.format(json.dumps(to_send))) except phonenumbers.NumberParseException: self.logger.warning("Can't resolve phone number country") except InvalidCoordinate: self.logger.warning("Coordinate do not follow redis specification")
def lookup(phonenum): returndict = {} phoneobj = phonenumbers.parse(phonenum) returndict['valid'] = phonenumbers.is_valid_number(phoneobj) returndict['local_format'] = phonenumbers.format_in_original_format( phoneobj, 'local') returndict[ 'intl_format'] = phonenumbers.format_out_of_country_keeping_alpha_chars( phoneobj, 'world') returndict['carrier'] = carrier.name_for_number(phoneobj, "en") returndict['country_code'] = geocoder.region_code_for_number(phoneobj) returndict['country_name'] = geocoder.country_name_for_number( phoneobj, "en") returndict['location'] = geocoder.description_for_number(phoneobj, "en") returndict['line_type'] = get_type(phonenumbers.number_type(phoneobj)) return json.dumps(returndict)
def lscan(unumber): print("Scanning [" + unumber + "] using *Python Scan* phoneSc - by Qzacy") sleep(0.5) try: numberObj = phonenumbers.parse(unumber, None) except Exception as err: print("\n\nError: " + err) trm() else: if not phonenumbers.is_valid_number(numberObj): return False iNum = phonenumbers.format_number( numberObj, phonenumbers.PhoneNumberFormat.INTERNATIONAL) cCode = phonenumbers.format_number( numberObj, phonenumbers.PhoneNumberFormat.INTERNATIONAL).split(' ')[0] lNum = phonenumbers.format_number( numberObj, phonenumbers.PhoneNumberFormat.E164).replace(cCode, '') country = geocoder.country_name_for_number(numberObj, "en") city = geocoder.description_for_number(numberObj, "en") nCarrier = carrier.name_for_number(numberObj, "en") timezones = str(timezone.time_zones_for_number(numberObj)) if iNum == "": iNum = "/" if lNum == "": lNum = "/" if country == "": country = "/" if cCode == "": cCode = "/" if city == "": city = "/" if nCarrier == "": nCarrier = "/" if timezones == "": timezones = "/" print("\nInternational format: {}".format(iNum)) print("Local format: {}".format(lNum)) print("Country: {}".format(country)) print("Country Code: {}".format(cCode)) print("City: {}".format(city)) print("Carrier: {}".format(nCarrier)) print("Timezones: {}\n".format(timezones)) trm()
def number_to_text(num): try: if not num.startswith('+'): num = '+' + num x = phonenumbers.parse(num) def number_type_desc(num_type): if num_type == PhoneNumberType.PREMIUM_RATE: return 'premium-rate' elif num_type == PhoneNumberType.TOLL_FREE: return 'toll-free' elif num_type == PhoneNumberType.MOBILE: return 'mobile' elif num_type == PhoneNumberType.FIXED_LINE: return 'fixed-line' elif num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE: return 'fixed-line or mobile' elif num_type == PhoneNumberType.SHARED_COST: return 'shared cost' elif num_type == PhoneNumberType.VOIP: return 'VoIP' elif num_type == PhoneNumberType.PERSONAL_NUMBER: return 'personal number' elif num_type == PhoneNumberType.PAGER: return 'pager' elif num_type == PhoneNumberType.UAN: return 'company "universal access number"' elif num_type == PhoneNumberType.VOICEMAIL: return 'voicemail' else: return 'unknown type' number = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL) numtype = number_type_desc(phonenumbers.number_type(x)) country = geocoder.country_name_for_number(x, "en") desc = geocoder.description_for_number(x, "en") if not desc or desc == country: return '%s\n%s - %s' % (number, country, numtype) else: return '%s\n%s, %s - %s' % (number, desc, country, numtype) except: return '%s\ninvalid' % (num)
def phone_number_simple_info(data: Dict[str, Any]) -> str: phone_numbers = [] for match in phonenumbers.PhoneNumberMatcher(data["document"], "PT"): phone_numbers.append(( match.number, carrier.name_for_number(match.number, "en"), geocoder.country_name_for_number(match.number, "en") )) sub_msg = [f"the number {n[0].national_number} originally from {n[1]} located in {n[2]}" for n in phone_numbers] if len(phone_numbers) == 0: msg = "I didn't found a number to analyze!" elif len(phone_numbers) == 1: msg = f"The number found was {sub_msg[0]}" else: msg = f"The numbers found were: {', '.join(sub_msg[:-1])} and {sub_msg[-1]}." return msg
def main(): st.title("Phone Number Location Tracker & Service operator") st.subheader("Built With Python") mobile = st.text_input("Enter Phone Number") if st.button("Track"): ch_number = phonenumbers.parse(mobile, 'CH') st.success("Country Name {}".format( geocoder.description_for_number(ch_number, "en"))) service_operator = phonenumbers.parse(mobile, 'RO') st.success("Service Operator: {}".format( carrier.name_for_number(service_operator, "en"))) time_place = phonenumbers.parse(mobile, "RO") st.success("The timezone: {}".format( timezone.time_zones_for_geographical_number(time_place))) area = phonenumbers.parse(mobile, "CH") st.success("Area length: {}".format( geocoder.country_name_for_number(area, "en"))) meta = phonenumbers.parse(mobile, "EN") st.success("Meta Info: {}".format( phonemetadata.PhoneMetadata(meta, "en")))
def getCoordFromPhoneAndPublish(self, phoneNumber, categ): try: print('function accessed') rep = phonenumbers.parse(phoneNumber, None) if not (phonenumbers.is_valid_number(rep) or phonenumbers.is_possible_number(rep)): print("Phone number not valid") country_name = geocoder.country_name_for_number(rep, "en") country_code = self.country_to_iso[country_name] if country_code is None: print("Non matching ISO_CODE") coord = self.country_code_to_coord[ country_code.lower()] # countrycode is in upper case coord_dic = {'lat': coord['lat'], 'lon': coord['long']} ordDic = OrderedDict() #keep fields with the same layout in redis ordDic['lat'] = coord_dic['lat'] ordDic['lon'] = coord_dic['lon'] coord_list = [coord['lat'], coord['long']] self.push_to_redis_zset(self.keyCategCoord, json.dumps(ordDic)) self.push_to_redis_zset(self.keyCategCountry, country_code) ordDic = OrderedDict() #keep fields with the same layout in redis ordDic['categ'] = categ ordDic['value'] = phoneNumber self.push_to_redis_geo(self.keyCategRad, coord['long'], coord['lat'], json.dumps(ordDic)) to_send = { "coord": coord_dic, "categ": categ, "value": phoneNumber, "country": country_name, "specifName": "", "cityName": "", "regionCode": country_code, } print(to_send) self.serv_coord.publish(self.CHANNELDISP, json.dumps(to_send)) except phonenumbers.NumberParseException: print("Can't resolve phone number country")
def testCoverage(self): # Python version extra tests invalid_number = PhoneNumber(country_code=210, national_number=123456L) self.assertEqual("", geocoder.country_name_for_number(invalid_number, "en")) # Add in some script and region specific fictional names TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA', "en_GB": u'Mountain View California', "en_US": u'Mountain View, Sunny California', "en_Latn": u'MountainView'} # The following test might one day return "Mountain View California" self.assertEqual("United States", geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="GB")) self.assertEqual("Mountain View, Sunny California", geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="US")) self.assertEqual("MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn")) self.assertEqual("United States", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB")) # Get a different result when there is a script-specific variant self.assertEqual("MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US")) TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA'}
def testCoverage(self): # Python version extra tests invalid_number = PhoneNumber(country_code=210, national_number=123456) self.assertEqual("", country_name_for_number(invalid_number, "en")) # Ensure we exercise all public entrypoints directly self.assertEqual("CA", _prefix_description_for_number(TEST_GEOCODE_DATA, TEST_GEOCODE_LONGEST_PREFIX, US_NUMBER1, "en")) self.assertEqual("CA", description_for_valid_number(US_NUMBER1, "en")) self.assertEqual("", description_for_valid_number(US_INVALID_NUMBER, "en")) # Add in some script and region specific fictional names TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA"), "en_GB": u("Mountain View California"), "en_US": u("Mountain View, Sunny California"), "en_Xyzz_US": u("MTV - xyzz"), "en_Latn": u("MountainView")} # The following test might one day return "Mountain View California" self.assertEqual("United States", description_for_number(US_NUMBER2, _ENGLISH, region="GB")) self.assertEqual("Mountain View, Sunny California", description_for_number(US_NUMBER2, _ENGLISH, region="US")) self.assertEqual("MountainView", description_for_number(US_NUMBER2, _ENGLISH, script="Latn")) self.assertEqual("United States", description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB")) self.assertEqual("MTV - xyzz", description_for_number(US_NUMBER2, _ENGLISH, script="Xyzz", region="US")) self.assertEqual("Mountain View, Sunny California", description_for_number(US_NUMBER2, _ENGLISH, script="Zazz", region="US")) # Get a different result when there is a script-specific variant self.assertEqual("MountainView", description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US")) TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA")} # Test the locale mapping TEST_GEOCODE_DATA['8868'] = {'zh': u("Chinese"), 'zh_Hant': u("Hant-specific")} tw_number = FrozenPhoneNumber(country_code=886, national_number=810080123) self.assertEqual("Hant-specific", description_for_number(tw_number, "zh", region="TW")) del TEST_GEOCODE_DATA['8868']
def testCoverage(self): # Python version extra tests invalid_number = PhoneNumber(country_code=210, national_number=123456L) self.assertEqual( "", geocoder.country_name_for_number(invalid_number, "en")) # Add in some script and region specific fictional names TEST_GEOCODE_DATA['1650960'] = { 'en': u'Mountain View, CA', "en_GB": u'Mountain View California', "en_US": u'Mountain View, Sunny California', "en_Latn": u'MountainView' } # The following test might one day return "Mountain View California" self.assertEqual( "United States", geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="GB")) self.assertEqual( "Mountain View, Sunny California", geocoder.description_for_number(US_NUMBER2, _ENGLISH, region="US")) self.assertEqual( "MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn")) self.assertEqual( "United States", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB")) # Get a different result when there is a script-specific variant self.assertEqual( "MountainView", geocoder.description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US")) TEST_GEOCODE_DATA['1650960'] = {'en': u'Mountain View, CA'}
def testCoverage(self): # Python version extra tests invalid_number = PhoneNumber(country_code=210, national_number=123456) self.assertEqual("", country_name_for_number(invalid_number, "en")) # Ensure we exercise all public entrypoints directly self.assertEqual("CA", _prefix_description_for_number(TEST_GEOCODE_DATA, TEST_GEOCODE_LONGEST_PREFIX, US_NUMBER1, "en")) self.assertEqual("CA", description_for_valid_number(US_NUMBER1, "en")) self.assertEqual("", description_for_valid_number(US_INVALID_NUMBER, "en")) # Add in some script and region specific fictional names TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA"), "en_GB": u("Mountain View California"), "en_US": u("Mountain View, Sunny California"), "en_Xyzz_US": u("MTV - xyzz"), "en_Latn": u("MountainView")} # The following test might one day return "Mountain View California" self.assertEqual("United States", description_for_number(US_NUMBER2, _ENGLISH, region="GB")) self.assertEqual("Mountain View, Sunny California", description_for_number(US_NUMBER2, _ENGLISH, region="US")) self.assertEqual("MountainView", description_for_number(US_NUMBER2, _ENGLISH, script="Latn")) self.assertEqual("United States", description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="GB")) self.assertEqual("MTV - xyzz", description_for_number(US_NUMBER2, _ENGLISH, script="Xyzz", region="US")) self.assertEqual("Mountain View, Sunny California", description_for_number(US_NUMBER2, _ENGLISH, script="Zazz", region="US")) # Get a different result when there is a script-specific variant self.assertEqual("MountainView", description_for_number(US_NUMBER2, _ENGLISH, script="Latn", region="US")) TEST_GEOCODE_DATA['1650960'] = {'en': u("Mountain View, CA")} # Test the locale mapping TEST_GEOCODE_DATA['8862'] = {'zh': u("Chinese"), 'zh_Hant': u("Hant-specific")} tw_number = FrozenPhoneNumber(country_code=886, national_number=221234567) self.assertEqual("Hant-specific", description_for_number(tw_number, "zh", region="TW")) del TEST_GEOCODE_DATA['8862']
def _parse_single_number_single_locale(phone_number, locale, language=DEFAULT_LANGUAGE): ''' Tries to parse number. Raises: NumberParseException if the string is not a potentially viable number ValueError if the string was for a potentially viable number that is not valid ''' number = phonenumbers.parse(phone_number, locale) if not phonenumbers.is_valid_number(number): raise ValueError("not a valid number") number_details = {} number_details['raw_input'] = phone_number number_details['E164'] = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164) number_details['assumed_local_locale'] = locale number_details['region'] = phonenumbers.region_code_for_number(number) number_details['country'] = geocoder.country_name_for_number(number, language) number_details['description'] = geocoder.description_for_number(number, language) number_details['carrier'] = carrier.safe_display_name(number, language) number_details['comment'] = "" return number_details
#!/usr/bin/python2 import phonenumbers from phonenumbers import geocoder, carrier print ("\033[1;32m Hacker \033[0m") os.system("figlet Black.1") num = input("number : ") phoneNumber = phonenumbers.parse("+"+num) Carrier = carrier.name_for_number(phoneNumber, 'en') country = geocoder.country_name_for_number(phoneNumber, "en") state = geocoder.description_for_number(phoneNumber, 'en') print("carrier = "+Carrier) print("Country = "+country) print("state = "+state)
phonenumbers.is_valid_number(z) print dir(phonenumbers.PhoneNumberFormat) print print x.country_code print x print str(x) p = z resp = { "countryCode": p.country_code, "nationalNumber": p.national_number, "isPossible": phonenumbers.is_possible_number(p), "isValid": phonenumbers.is_valid_number(p), "e164": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164), "international": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.INTERNATIONAL), "national": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.NATIONAL), "rfc3966": phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.RFC3966), "location": geocoder.description_for_number(p, "en"), "country": geocoder.country_name_for_number(p, "en"), } print json.dumps(resp, indent=2) exit() print y print z print repr(carrier.name_for_number(x, "en")) print repr(carrier.name_for_number(y, "en")) print repr(carrier.name_for_number(z, "en"))
def get_country(self): self.phonenumber_details['country'] = country_name_for_number( self.phonenumber_object, "en") return self.phonenumber_details['country']
from phonenumbers.phonenumberutil import PhoneMetadata from phonenumbers import geocoder from phonenumbers.phonenumberutil import ( region_code_for_country_code, region_code_for_number, national_significant_number ) from phonenumbers import carrier from phonenumbers import timezone text = '+16473612505' text1 = '+73812332308' x=phonenumbers.parse(text1, None) print(x) y=str(geocoder.country_name_for_number(x, "en")) print(y) z=str(geocoder.description_for_number(x, "en")) print(z) code=region_code_for_country_code(x.country_code) print(code) country = pycountry.countries.get(alpha_2=str(code)) print(country) #short = national_significant_number(text1) short1= PhoneMetadata.short_metadata_for_region(code) print(short1)
phonenumbers.is_valid_number(z) print dir(phonenumbers.PhoneNumberFormat) print print x.country_code print x print str(x) p = z resp = { 'countryCode' : p.country_code, 'nationalNumber' : p.national_number, 'isPossible' : phonenumbers.is_possible_number(p), 'isValid' : phonenumbers.is_valid_number(p), 'e164' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164), 'international' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.INTERNATIONAL), 'national' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.NATIONAL), 'rfc3966' : phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.RFC3966), 'location' : geocoder.description_for_number(p, "en"), 'country' : geocoder.country_name_for_number(p, 'en') } print json.dumps(resp, indent=2) exit() print y print z print repr(carrier.name_for_number(x, "en")) print repr(carrier.name_for_number(y, "en")) print repr(carrier.name_for_number(z, "en"))
def get_country(self): self.phonenumber_details['country'] = country_name_for_number(self.phonenumber_object, "en") return self.phonenumber_details['country']
def kapi(request): import csv try: accountcode = request.GET.get('accountcode') month = request.GET.get('month') base_filename = settings.MEDIA_ROOT + 'cdr-rates/' + month + '-' + accountcode except: logging.error( 'Malformed request. Please request an accountcode as an integer and a month string like 2018-05' ) try: rate_object = Rate.objects.get(accountcode=accountcode) except: logger.error('No rate entry for accountcode ' + accountcode) return (JsonResponse({'call_charges': 0, 'call_overages': 0})) try: cached_rate = CachedRate.objects.get(accountcode=rate_object, month=month) return (JsonResponse({ 'call_charges': cached_rate.call_charges, 'call_overages': cached_rate.call_overages })) except: pass local_area = rate_object.local_calling_area pulse = rate_object.pulse channels = rate_object.channels inbound_rate = float(rate_object.inbound_rate) inbound_tollfree_rate = float(rate_object.inbound_tollfree_rate) outbound_rate = float(rate_object.outbound_rate) canadian_ld_rate = float(rate_object.canadian_ld_rate) united_states_ld_rate = float(rate_object.united_states_ld_rate) international_ld_rate = float(rate_object.international_ld_rate) default_ld_rate = min( [canadian_ld_rate, united_states_ld_rate, international_ld_rate]) default_international_rate = .5 burst_rate = .03 pic_rate = .0085 inbound_minutes = 0 outbound_minutes = 0 pic_minutes = 0 ld_minutes = 0 international_low_rate_minutes = 0 inbound_tollfree_minutes = 0 independent_call_cost = 0 international_call_cost = 0 burst_call_cost = 0 total_cost = 0 call_discounts = 0 concurrent_calls = {} international_low_rate_countries = ('United Kingdom', 'Ireland', 'Germany', 'Italy', 'France', 'Spain', 'Netherlands', 'Portugal', 'Luxembourg', 'Belgium', 'Austria', 'Denmark', 'Switzerland', 'China', 'Hong Kong', 'Australia', 'Malaysia', 'Singapore') connection = pymysql.connect(host='10.2.0.50', user='******', password='******', db='*****', charset='utf8mb4') #get all the pic numbers try: with connection.cursor() as cursor: sql = 'SELECT number FROM pic_customer_number where account = ' + str( accountcode) cursor.execute(sql) pics = list(itertools.chain(*cursor.fetchall())) finally: connection.close() for index, pic in enumerate(pics): row = pic.strip().lower().replace(' ', '').replace('-', '').replace('_', '') pics[index] = row pics = set(pics) #get all the npaas independent_npaas = IndependentRate.objects.all().values_list( 'e164_prefix') independent_npaas = [str(u[0]) for u in independent_npaas] international_low_rate_npaas = InternationalLowRate.objects.all( ).values_list('e164_prefix') international_low_rate_npaas = [ str(u[0]) for u in international_low_rate_npaas ] international_npaas = InternationalHighRate.objects.all().values_list( 'e164_prefix') international_npaas = [str(u[0]) for u in international_npaas] #this builds a set of cities we can call locally local_calling_cities = set() exchanges = [] if len(local_area) > 4: local_calling_cities.add(local_area) try: exchanges = eval( LocalCallingArea.objects.get( locality=local_area).local_calling_areas) except: pass if len(exchanges) > 0: for exchange in exchanges: local_calling_cities.add( LocalCallingArea.objects.get(exchange=exchange).locality) else: local_calling_cities = {'Nowhere, XX'} #get the cdrs #now that CDRs are in django model we should use it instead of directly querying connection = psycopg2.connect(dbname='cdr-pusher', user='******', password='******', host='localhost', port='9700') cursor = connection.cursor('CDRs from CDR-Pusher') sql = 'select caller_id_number,caller_id_name,destination_number,starting_date,duration,direction \ from cdr_import where accountcode = \'' + accountcode + '\' and hangup_cause_id = 16 and duration > 0 and \ to_char(starting_date, \'YYYY-MM\') = \'' + month + '\' order by starting_date;' cursor.execute(sql) file = open(base_filename + '.csv', 'w', encoding='utf-8') csvfile = csv.writer(file) csvfile.writerow([ 'Day', 'Time', 'Duration', 'Call Cost', 'Call Class', 'Caller ID', 'Source Number', 'Destination Number', 'Source Location', 'Destination Location', 'Destination Country' ]) for cdr in cursor: #some defaults direction = 'Outbound' if cdr[5] == 1: direction = 'Inbound' call_class = 'Local' # could be Incoming, Incoming Toll-free, Local, Local Network, Toll-free, Long Distance, Independent, Low Rate International, International, International Default Rate call_minutes = 0 call_cost = 0 call_minutes = math.ceil(int(cdr[4]) / 60) pulsed_call_minutes = math.ceil(int(cdr[4]) / pulse) * (pulse / 60) source = cdr[0].strip().lower().replace(' ', '').replace('-', '').replace( '_', '').replace('+', '') destination = cdr[2].strip().lower().replace(' ', '').replace( '-', '').replace('_', '').replace('+', '') destination_location = '' destination_country = '' #put minutes in the burst buckets for minute in range(call_minutes): current_minute = ( cdr[3] + datetime.timedelta(minutes=minute)).strftime('%d:%H:%M') if current_minute in concurrent_calls: concurrent_calls[current_minute] += 1 else: concurrent_calls[current_minute] = 1 #format call source if len(source) > 6: try: source_number = phonenumbers.format_number( phonenumbers.parse(source, 'CA'), phonenumbers.PhoneNumberFormat.E164) except: if source.isdigit(): source_number = source else: source_number = '' elif source.isdigit(): source_number = source else: source_number = '' #locate call source if source_number[-10:-7] in tollfree: source_location = 'Toll-Free' else: try: source_location = geocoder.description_for_number( phonenumbers.parse(source_number, 'CA'), 'en') except: source_location = '' #format destination number if len(destination) > 6 and destination.isdigit(): try: destination_number = phonenumbers.format_number( phonenumbers.parse(destination, 'CA'), phonenumbers.PhoneNumberFormat.E164) except: destination_number = destination if len(destination) < 7 and destination.isdigit(): destination_number = destination if destination in ['211', '311', '511', '611', '811', '911']: call_class = 'Special Number' elif destination == '411': call_class = 'Directory Assistance' else: call_class = 'Extension' if not destination.isdigit(): destination_number = '' if destination_number[-10:-7] in tollfree: destination_location = 'Toll-Free' else: try: destination_location = geocoder.description_for_number( phonenumbers.parse(destination_number, 'CA'), 'en') except: destination_location = '' try: destination_country = geocoder.country_name_for_number( phonenumbers.parse(destination_number, 'CA'), 'en') except: destination_country = '' #bill call if direction == 'Inbound': inbound_minutes += pulsed_call_minutes call_cost = pulsed_call_minutes * inbound_rate call_class = direction if destination_location == 'Toll-Free': call_class = 'Inbound Toll-Free' inbound_tollfree_minutes += pulsed_call_minutes call_cost = call_minutes * inbound_tollfree_rate else: #call is outbound outbound_minutes += pulsed_call_minutes call_cost = pulsed_call_minutes * outbound_rate if call_class not in [ 'Local Network', 'Toll-Free' ] and destination_location not in local_calling_cities: if destination_country == 'Canada': call_class = 'Long Distance' for npaa in sorted(independent_npaas, key=len, reverse=True): if destination_number.startswith('+' + npaa): call_class = 'Independent' call_rate = float( IndependentRate.objects.get( e164_prefix=npaa).rate) if call_rate <= canadian_ld_rate: call_cost = canadian_ld_rate * call_minutes else: call_cost = call_rate * call_minutes independent_call_cost += call_cost destination_location = IndependentRate.objects.get( e164_prefix=npaa).destination break if call_class == 'Long Distance': call_cost = canadian_ld_rate * pulsed_call_minutes ld_minutes += pulsed_call_minutes elif destination_country == 'United States' or destination_number.startswith( '+1'): call_class = 'Long Distance' for npaa in sorted(independent_npaas, key=len, reverse=True): if destination_number.startswith('+' + npaa): call_class = 'Independent' call_rate = float( IndependentRate.objects.get( e164_prefix=npaa).rate) if call_rate <= united_states_ld_rate: call_cost = united_states_ld_rate * call_minutes else: call_cost = call_rate * call_minutes independent_call_cost += call_cost destination_location = IndependentRate.objects.get( e164_prefix=npaa).destination break if call_class == 'Long Distance': call_cost = united_states_ld_rate * pulsed_call_minutes ld_minutes += pulsed_call_minutes #check if it's an independant destination and charge int rates to the independant bucket. if not charge 2c to LD bucket elif destination_country in international_low_rate_countries: call_class = 'International Low Rate' #check if it's a high rate internatioal dest and charge int rate to int bucket. if not charge 2c to int low rate bucket for npaa in sorted(international_low_rate_npaas, key=len, reverse=True): if destination_number.startswith('+' + npaa): call_class = 'International' call_rate = float( InternationalLowRate.objects.get( e164_prefix=npaa).rate) if call_rate <= international_ld_rate: call_cost = international_ld_rate * call_minutes else: call_cost = call_rate * call_minutes international_call_cost += call_cost destination_location = InternationalLowRate.objects.get( e164_prefix=npaa).destination break if call_class == 'International Low Rate': call_cost = international_ld_rate * pulsed_call_minutes international_low_rate_minutes += pulsed_call_minutes elif destination_country not in [ 'Canada', 'United States', '' ]: call_class = 'International Default Rate' #check if it's has and internation amount and charge that. if not charge 50c. for npaa in sorted(international_npaas, key=len, reverse=True): if destination_number.startswith('+' + npaa): call_class = 'International' call_rate = float( InternationalHighRate.objects.get( e164_prefix=npaa).rate) if call_rate <= international_ld_rate: call_cost = international_ld_rate * call_minutes else: call_cost = call_rate * call_minutes international_call_cost += call_cost destination_location = InternationalHighRate.objects.get( e164_prefix=npaa).destination break if call_class == 'International Default Rate': call_cost = default_international_rate * call_minutes international_call_cost += call_cost for pic in pics: if pic in source_number: pic_minutes += call_minutes #there is some uncertainty here. our newest rate table says we stack 0.0085 on top of pic calls #we'll have to clarify with dan or shannon. if we do just uncomment this #call_cost += pic_rate * call_minutes if call_class in ['Local Network', 'Extension', 'Special Number']: call_cost = 0 elif call_class == 'Directiory Assistance': call_cost = .5 if '\"' in cdr[1]: caller_id_name = cdr[1].split('\"')[1] else: caller_id_name = cdr[1] csvfile.writerow([ cdr[3].strftime('%d'), cdr[3].strftime('%H:%M:%S'), cdr[4], round(call_cost, 4), call_class, caller_id_name, source_number, destination_number, source_location, destination_location, destination_country ]) total_cost += call_cost connection.close() #find out if we used more channels than were paid for if channels != 0: epoch = str(int(time.mktime(time.strptime(month, '%Y-%m')))) start_date = str(int(epoch) - 1) rrdtool.create(base_filename + '.rrd', '-s60', 'DS:concurrent_calls:GAUGE:60:0:U', 'RRA:MAX:0:1:44640', '-b ' + start_date) for minute in sorted(concurrent_calls): epoch = str( int( time.mktime( time.strptime(month + ' ' + minute, '%Y-%m %d:%H:%M')))) rrdtool.update(base_filename + '.rrd', epoch + ":" + str(concurrent_calls[minute])) if concurrent_calls[minute] > channels: burst_call_cost += (concurrent_calls[minute] - channels) * burst_rate end_date = epoch rrdtool.graph( base_filename + '.pdf', '--width', '1920', '--height', '400', '--full-size-mode', '--start', start_date, '--end', end_date, 'DEF:calls=' + base_filename + '.rrd:concurrent_calls:MAX', 'CDEF:_calls=calls,UN,0,calls,IF', 'AREA:_calls#8aacd2: Total Concurrent Calls', '--imgformat', 'PDF', '--font', 'DEFAULT:11:\"Droid Sans\"', '--color', 'SHADEA#00000000', '--color', 'SHADEB#00000000', '--color', 'ARROW#00000000', '--color', 'BACK#00000000', '--color', 'CANVAS#00000000', '--lower-limit', '0', '--rigid', #'VDEF:average_calls=_calls,AVERAGE', #'GPRINT:average_calls:Average Concurrent Calls\: %.2lf' ) #if two pass billing is enabled for this account run it if rate_object.two_pass_billing: def account_231(): #second-pass billing logic for account 231 from shutil import move savings = 0 with open(base_filename + '.csv', 'r') as f: reader = csv.reader(f) file = open(base_filename + '-0.csv', 'w', encoding='utf-8') csvfile = csv.writer(file) for row in reader: if row[0] != 'Day': if row[4] != 'Independent' and row[ 4] != 'International': if int(row[2]) > 30: pulsed_call_minutes = math.ceil( int(row[2]) / 30) * (30 / 60) call_rate = float(row[3]) / pulsed_call_minutes pulsed_call_minutes = math.ceil( int(row[2]) / 6) * (6 / 60) new_call_charge = round( (call_rate * pulsed_call_minutes), 4) savings += float(row[3]) - new_call_charge row[3] = new_call_charge csvfile.writerow(row) move(base_filename + '-0.csv', base_filename + '.csv') return (round(savings, 2)) def account_2681(): #second-pass billing logic for account 2681 from shutil import move savings = 0 with open(base_filename + '.csv', 'r') as f: reader = csv.reader(f) file = open(base_filename + '-0.csv', 'w', encoding='utf-8') csvfile = csv.writer(file) for row in reader: if row[4] == 'Inbound Toll-Free': pulsed_call_minutes = math.ceil( int(row[2]) / 30) * (30 / 60) new_call_charge = round((.015 * pulsed_call_minutes), 4) savings += float(row[3]) - new_call_charge row[3] = new_call_charge csvfile.writerow(row) move(base_filename + '-0.csv', base_filename + '.csv') return (round(savings, 2)) try: call_discounts = eval('account_' + accountcode + '()') except: logger.error('Second-pass rating failed for account ' + accountcode + '!') #these should all become cost lines in silver. #echelon doesnt support extra fields so we just log them for now logger.info('Inbound minutes: %.1f' % inbound_minutes) logger.info('Outbound minutes: %.1f' % outbound_minutes) logger.info('Outbound PIC minutes: %.1f' % pic_minutes) logger.info('Long distance minutes: %.1f' % ld_minutes) logger.info('International low rate minutes: %.1f' % international_low_rate_minutes) logger.info('Toll-free incoming minutes: %.1f' % inbound_tollfree_minutes) if channels > 0: logger.info('Burst call charges: %.2f' % burst_call_cost) logger.info('Independent call charges: %.2f' % independent_call_cost) logger.info('International call charges: %.2f' % international_call_cost) logger.info('Total call charges: %.2f' % total_cost) if call_discounts > 0: logger.info('Total call discounts: %.2f' % call_discounts) if channels > 0: logger.info('Total call overages: %.2f' % burst_call_cost) cached_rate = CachedRate( accountcode=rate_object, month=month, call_charges=float('{0:.2f}'.format(total_cost - call_discounts)), call_overages=float('{0:.2f}'.format(burst_call_cost))) cached_rate.save() #give echelon what it wants. that pig return (JsonResponse({ 'call_charges': float('{0:.2f}'.format(total_cost - call_discounts)), 'call_overages': float('{0:.2f}'.format(burst_call_cost)) }))
import phonenumbers from phonenumbers import timezone from phonenumbers import carrier from phonenumbers import geocoder mob = phonenumbers.parse('+447986') car = carrier.name_for_number(mob, 'en') print(car) location = geocoder.country_name_for_number(mob, 'en') print(location) tz = timezone.time_zones_for_geographical_number(mob) print(tz) # is number already registered x = phonenumbers.is_valid_number(mob) print(x) # can be the number registered y = phonenumbers.is_possible_number(mob) print(y) text = 'hii my name is xyz and my phone number is +916387873015' for match in phonenumbers.phonenumbermatcher(text, 'US'): print(match)
def phonetrack(): try: country = input("{} [🌟] {}country code = {}".format(R, B, W)) except KeyboardInterrupt: exit() if country == "91": br = mechanize.Browser() number = input("{} [🌟] {}Phone number = {}".format(R, B, W)) url = 'https://www.findandtrace.com/trace-mobile-number-location' phoneNumber = phonenumbers.parse("+" + country + number) Country = geocoder.country_name_for_number(phoneNumber, "en") state = geocoder.description_for_number(phoneNumber, 'en') validate = phonenumbers.is_valid_number(phoneNumber) time = timezone.time_zones_for_number(phoneNumber) br.open(url) br.select_form(name='trace') br['mobilenumber'] = number res = br.submit().read() soup = BeautifulSoup(res, 'html.parser') tbl = soup.find_all('table', class_='shop_table') data = tbl[0].find('tfoot') print("{}\n [{}✴{}]{} country: ".format(R, G, R, G) + Country) c = 0 for i in data: c += 1 if c in (1, 4, 6, 8): continue th = i.find('th') td = i.find('td') print("{}\n [{}✴{}]{} ".format(R, G, R, G) + th.text, td.text) try: data = tbl[1].find('tfoot') except: print("{}\n [{}✴{}]{} state: ".format(R, G, R, G) + state) print("{}\n [{}✴{}]{} valid mobile number: ".format(R, G, R, G), validate) print("{}\n [{}✴{}]{} Timezone: ".format(R, G, R, G), time) c = 0 for i in data: c += 1 if c in (2, 20, 22, 26): th = i.find('th') td = i.find('td') print("{}\n [{}✴{}]{} ".format(R, G, R, G) + th.text, td.text + "\033[0m") else: number = input("{} [🌟]{} Phone number = {}".format(R, B, W)) phoneNumber = phonenumbers.parse("+" + country + number) Country = geocoder.country_name_for_number(phoneNumber, "en") state = geocoder.description_for_number(phoneNumber, 'en') validate = phonenumbers.is_valid_number(phoneNumber) time = timezone.time_zones_for_number(phoneNumber) res = requests.get( "https://api.telnyx.com/anonymous/v2/number_lookup/" + country + number).content load = json.loads(res) data = load['data'] carrier = data['carrier'] print("\n{} [{}✴{}]{} Country prefix = {}+".format(R, G, R, G, W) + country) code = ("\n{} [{}✴{}]{} Country code = {}".format(R, G, R, G, W) + data['country_code']) national = ( "\n{} [{}✴{}]{} National Format = {}".format(R, G, R, G, W) + data['national_format']) phone = ("\n{} [{}✴{}]{} International Format = {}".format( R, G, R, G, W) + data['phone_number']) name = ("\n{} [{}✴{}]{} Carrier = {}".format(R, G, R, G, W) + carrier['name']) type = ("\n{} [{}✴{}]{} Line type = {}".format(R, G, R, G, W) + carrier['type']) for i in national, phone, type: print(i) print("\n{} [{}✴{}]{} Valid mobile number ={}".format(R, G, R, G, W), validate) for i in name, code: print(i) print("\n{} [{}✴{}]{} Country = {}".format(R, G, R, G, W) + Country) print("\n{} [{}✴{}]{} State = {}".format(R, G, R, G, W) + state) print("\n{} [{}✴{}]{} Timezone ={}".format(R, G, R, G, W), time)
btcadd = Fore.MAGENTA + 'bc1q5v7p34qsghjyzv8dc7n8egkuz80kc5xw38n7yn' print(banner) time.sleep(2) print(social) print(help) print(Fore.YELLOW + 'Support me by donating in my bitcoin wallet:' + Fore.BLUE + btcadd) while True: command = input(wi + rd + "[+]Input a command: ") if command == "./phoneinfo -h": print(help) elif command == "./phoneinfo -p -s": phonenum = input("Input a Phone Number to start: ") phone_number = phonenumbers.parse(phonenum) validate = phonenumbers.is_valid_number(phone_number) location = geocoder.country_name_for_number(phone_number, 'en') region = geocoder.description_for_number(phone_number, 'en') probability = phonenumbers.is_possible_number(phone_number) metadata = phonenumbers.PhoneMetadata(phone_number) carrier_desc = carrier.name_for_number(phone_number, 'en') timezone = timezone.time_zones_for_number(phone_number) source = phonenumbers.PhoneNumberDesc(phone_number) str(validate) print(Fore.MAGENTA + "Checking if Phone Number is Valid...") time.sleep(2) print(Fore.CYAN + str(validate)) time.sleep(1) print(Fore.MAGENTA + "Location: " + Fore.CYAN + location) time.sleep(1) print(Fore.MAGENTA + "Probability(If False): " + Fore.CYAN + str(probability)) time.sleep(1)