def daily_photo(user_date=None): """ This will return the daily nasa photo. It can also return the photo from any selected date :param user_date: :return: """ planet_url = "https://api.nasa.gov/planetary/apod?" planet_date_prep = "date=" if user_date is None: photo_url = planet_url + API_KEY nasa_json = get_json_data.grab_json_data(photo_url) return nasa_json["hdurl"] else: photo_url = planet_url + planet_date_prep + user_date + API_KEY nasa_json = get_json_data.grab_json_data(photo_url) return nasa_json["hdurl"]
def return_stock_prices(quote): """ This function will take a stock symbol, such as aapl and provide the current stock data on it :param quote: This is the symbol the user needs to provide :return: lots of stock data """ partial_url = "https://api.iextrading.com/1.0/stock/" end_url = "/quote" full_url = partial_url + quote + end_url try: r = get_json_data.grab_json_data(full_url) except json.decoder.JSONDecodeError: return "Please provide a valid stock symbol" # Setting this data up in a namedtuple for readability Stock_data = collections.namedtuple( "Stocks", "Company " "Symbol " "Market_Open_Price " "Market_Low_Value " "Market_High_Value " "Market_Close_Value " "Market_Latest_Price") company_data = Stock_data(r["companyName"], r["symbol"], r["open"], r["low"], r["high"], r["close"], r["iexRealtimePrice"]) return f"Stock data for : {company_data[0]} ({company_data[1]})\n" \ f"Opening Price: {company_data[2]}\n" \ f"Market Low Price: {company_data[3]}\n" \ f"Market High Price: {company_data[4]}\n" \ f"Closing Price: {company_data[5]}\n" \ f"Latest Price (After hours trading): {company_data[6]}"
def return_lat_long(city_state, use_data=None): """ This method is pulling out the latitude and longitude of a city / state (or city / country). Depending on how this will be used, it will either return nicely formatted info or it will return just the data. :param city_state: :param use_data: :return: """ partial_url = "https://maps.googleapis.com/maps/api/geocode/json?&address=" end_url = "&key=" split_location = city_state.split() city = split_location[0] state = split_location[1] location = city.lower() + "+" + state.lower() # making sure it's lowercase and space is swapped to + full_url = partial_url + location + end_url + API_KEY data = get_json_data.grab_json_data(full_url) location_data = data["results"][0]["geometry"]["location"] # makes is easier to work with latitude = format(location_data["lat"], ".4f") # limiting latitude results to 4 decimal places longitude = format(location_data["lng"], ".4f") # limiting longitude results to 4 decimal places if use_data is None: # if we only want the latitude and longitude, this will be the result return f"Latitude: {latitude}\n" \ f"Longitude: {longitude}" else: # if this data will be used in another method call, this data will be the result return str(latitude), str(longitude)
def return_chuck_norris_joke(): """ Simple method to return a random Chuck Norris joke. :return: """ data = get_json_data.grab_json_data(URL) return data["value"]
def syn_and_ants(word): """ This function will take in the word and return the synonyms and antonyms of the word :param word: :return: ant_words, syn_words """ user_word = word.lower() syn_ant = "/synonyms;antonyms" url = base_url + user_word + syn_ant results = get_json_data.grab_json_data(url, True, app_id, app_key) synonyms = results["results"][0]["lexicalEntries"][0]["entries"][0][ "senses"][0]["synonyms"] antonyms = results["results"][0]["lexicalEntries"][0]["entries"][0][ "senses"][0]["antonyms"] # we need to toss these into a list since there are multiple entries ant_words = [] syn_words = [] for items in antonyms: for ant_key, ant_value in items.items(): if ant_key == "id": ant_words.append(ant_value) for entries in synonyms: for syn_key, syn_value in entries.items(): if syn_key == "id": syn_words.append(syn_value) return ant_words, syn_words
def return_number_facts(): """ This will return a random number and a fact containing that number :return: data['number'], data['text'] """ # simple url to call url = "http://numbersapi.com/random?json" data = get_json_data.grab_json_data(url) return f"Number: {data['number']}\n" \ f"Fact: {data['text']}"
def return_joke(): """ Simple method to pull a random joke :return: setup, punchline """ # URL for random joke url = "https://08ad1pao69.execute-api.us-east-1.amazonaws.com/dev/random_joke" data = get_json_data.grab_json_data(url) # pulling data (json format) setup = remove_chars.clean_text(data["setup"]) punchline = remove_chars.clean_text(data["punchline"]) return f"{setup}\n" \ f"{punchline}"
def asteroids(start_date, end_date): """ This function will display asteroid info. Right now I'm not using it because there is way too much data to present. I'm only using this to post info to slack. :param start_date: :param end_date: :return: asteroid_json """ asteroid_url = "https://api.nasa.gov/neo/rest/v1/feed?" asteroid_start_prep = "start_date=" asteroid_end_prep = "&end_date=" asteroid_url = asteroid_url + asteroid_start_prep + start_date + asteroid_end_prep + end_date + API_KEY asteroid_json = get_json_data.grab_json_data(asteroid_url) return asteroid_json["hdurl"]
def return_trivia(): """ This connects to an API to pull a random trivia question. It is then returned :return: data[0]['question'], answer """ # URL for trivia API url = "http://jservice.io/api/random" data = get_json_data.grab_json_data(url) # need to strip out the formatting characters answer = remove_chars.clean_text(data[0]["answer"]) return f"Question: {data[0]['question']}\n" \ f"Answer: {answer}"
def slack_response(user_input): """ This method will return our contents to our slack channel :param user_input: :return: """ try: user_zip_code = int(user_input) full_weather_url = weather_url(user_zip_code) except ValueError: full_weather_url = weather_url(user_input, True) # Not sure why I set this here instead in the 'grab weather data function values = get_json_data.grab_json_data(full_weather_url) return grab_weather_data(values)
def define(word): """ This function will return the definition of a word. :param word: :return: define_word """ word = word.lower() url = base_url + word results = get_json_data.grab_json_data(url, True, app_id, app_key) define_word = [] get_def = results["results"][0]["lexicalEntries"][0]["entries"][0][ "senses"] for things in get_def: define_word.extend(things["definitions"]) return define_word
def prep_title(movie_name): """ This function take a movie name and return the title, release date, and overview of the movie. The search string for the URL needs white spaces to contain + instead example: https://api.themoviedb.org/3/search/movie?api_key={API Key}&query=Jack+Reacher :param movie_name: :return: title, release date, overview """ partial_url = "https://api.themoviedb.org/3/search/movie?api_key=" query = "&query=" # Replacing white spaces with + symbols movie_search_format = movie_name.replace(" ", "+") url = partial_url + API_KEY + query + movie_search_format data = get_json_data.grab_json_data(url) # we only want to return title, release date, and info about the movie for info in data["results"]: return info["original_title"], info["release_date"], info["overview"]
def gather_bitcoin_values(): """ This is gathering data from the free market API :return: """ r = get_json_data.grab_json_data(URL) # Setting up variable list cryptocurrency_data = [] count = 0 # Building namedtuple to quick build the lists of data Cryptocurrency = collections.namedtuple( "Cryptocurrency", "Name Rank Price Price_1h Price_24h Price_7d") while count <= 9: # this can change based on how many we pull from the URL above cryptocurrency_data.append( Cryptocurrency(r[count]["name"], r[count]["rank"], r[count]["price_usd"], r[count]["percent_change_1h"], r[count]["percent_change_24h"], r[count]["percent_change_7d"])) count += 1 # yeah yeah. I know I've got a ton of repeated data. I don't know how to get # the return method to loop through and return each piece of data. # I've tried the count = 0 # while count < len(cryptocurrency_data: return stuff # no luck with it return f"{cryptocurrency_data[0]}\n" \ f"{cryptocurrency_data[1]}\n" \ f"{cryptocurrency_data[2]}\n" \ f"{cryptocurrency_data[3]}\n" \ f"{cryptocurrency_data[4]}\n" \ f"{cryptocurrency_data[5]}\n" \ f"{cryptocurrency_data[6]}\n" \ f"{cryptocurrency_data[7]}\n" \ f"{cryptocurrency_data[8]}\n" \ f"{cryptocurrency_data[9]}"
def get_flights_overhead(city_state): """ This function will grab the data (json) from get_airplane_data. Once it has this data, we extract the useful info and convert it to a namedtuple. This was the easiest way to return 50+ flights at a time. :param city_state: :return: """ # Need to grab flight data latitude, longitude = google_lat_long.return_lat_long(city_state, True) full_url = PARTIAL_URL + latitude + LNG_URL + longitude + END_URL data = get_json_data.grab_json_data(full_url) flight_data = data["acList"] # Variable list to return lots of flights flight_origination = [] flight_destination = [] flight_id = [] model = [] airline_name = [] call_sign = [] country = [] full_flight_data = [] for items in flight_data: # looping though all keys / values in the list for key, value in items.items(): if key == "From": flight_origination.append(value) if key == "To": flight_destination.append(value) if key == "Id": flight_id.append(value) if key == "Mdl": model.append(value) if key == "Op": airline_name.append(value) if key == "Call": call_sign.append(value) if key == "Cou": country.append(value) # running this because I can't get the return to iterate through with the returns Flights = collections.namedtuple( 'Flights', "Airline Model Flight_ID Call_Sign Origination Destination Country") flight_count = 0 # for the while loop to use while flight_count < len(call_sign): # calling the named tuple to build a list of lists try: full_flight_data.append( Flights(airline_name[flight_count], model[flight_count], flight_id[flight_count], call_sign[flight_count], flight_origination[flight_count], flight_destination[flight_count], country[flight_count])) except IndexError: # needed to include this because not all call_sign or flight data is present break flight_count += 1 # need to increase the count each time it loops through if len(call_sign) == 0: return "Errors were present. Check out the URL / Code" else: return f"{full_flight_data}"
def return_next_launch(): """ This is a quick a dirty function to print the next SpaceX launch. I don't print / display anything more than the next flight. This is because SpaceX doesn't provide it until it locks down the info, location, time, etc. :return: flight_number, launch date, payload info, flight time """ url = "https://api.spacexdata.com/v2/launches/upcoming" # a_url = "https://api.spacexdata.com/v2/launches/upcoming?launch_year=2017" spacex_data = get_json_data.grab_json_data(url) # setting up our list variables. This is because SpaceX knows about the next ~3 launches, # but only provides full details of the next launch. launch_dates = [] launch_times = [] spacex = [] date_count = 0 # this is to loop through the while loop in our launch_dates list while date_count < len(spacex_data): launch_dates.append(spacex_data[date_count]["launch_date_local"]) date_count += 1 # This will convert our ISO date time format to human readable material (Year-Month-Date @ Hour:Minute:Second) # For example, 2018-01-23 @ 13:00:00 for times in launch_dates: try: ts = time.strptime(times[:19], "%Y-%m-%dT%H:%M:%S") # need to use strptime launch_times.append(time.strftime( "%Y-%m-%d @ %H:%M:%S", ts)) # appending our formatted content to the list except ValueError: # I've only run into this error once and it may have been a fluke, being safe continue # Creating a namedtuple to store our data. Eventually, I need to learn how to print properly formatted # data for the 3 flights listed. Spacex = collections.namedtuple( "SpaceX", "Flight_Number " "Launch_Date " "Rocket_Name " "First_Stage_Reused " "Second_Stage_Reused " "Payload_ID " "Payload_Type " "Payload_Weight " "Customer " "Launch_Site") # I'm not sure if this is the best way. I can't alter these tuple values (that I know of). # I also don't know how to return multiple entries which is why I went this way. count = 0 # This will help us change the count for the while loop below while count < len(spacex_data): spacex.append( Spacex( spacex_data[count]["flight_number"], launch_times[count], spacex_data[count]["rocket"]["rocket_name"], spacex_data[count] ["rocket"]["first_stage"]["cores"][0]["reused"], spacex_data[count]["rocket"]["second_stage"]["payloads"][0] ["reused"], spacex_data[count]["rocket"]["second_stage"] ["payloads"][0]["payload_id"], spacex_data[count]["rocket"] ["second_stage"]["payloads"][0]["payload_type"], spacex_data[count]["rocket"]["second_stage"]["payloads"][0] ["payload_mass_kg"], spacex_data[count]["rocket"] ["second_stage"]["payloads"][0]["customers"], spacex_data[count]["launch_site"]["site_name_long"])) count += 1 # I know this is a cryptic return statement. If I could figure out how to loop through a return statement # I'd use something like spacex[0].flight_number so it is easier to read return f"{spacex[0]}\n" \ f"{spacex[1]}\n" \ f"{spacex[2]}\n"