コード例 #1
0
ファイル: weather_widget.py プロジェクト: joeda/qt
 def update_data(self):
     new_data = pywapi.get_weather_from_google(self.location_code)
     if new_data != self.data:
         self.data = new_data
         self.set_data()
     else:
         new_data = None
コード例 #2
0
ファイル: weather.py プロジェクト: SandyWalsh/pyhole
    def weather(self, params=None, **kwargs):
        """Display current weather report (ex: .w [set] [<location>])"""
        if params:
            location = params
            if location.startswith("set "):
                location = location[4:]
                utils.write_file(self.name, self.irc.source, location)
                self.irc.reply("Location information saved")
        else:
            location = utils.read_file(self.name, self.irc.source)
            if not location:
                self.irc.reply(self.weather.__doc__)
                return

        try:
            w = pywapi.get_weather_from_google(location)
        except Exception:
            self.irc.reply("Unable to fetch weather data")
            return

        if w["current_conditions"]:
            city = w["forecast_information"]["city"]
            temp_f = w["current_conditions"]["temp_f"]
            temp_c = w["current_conditions"]["temp_c"]
            humidity = w["current_conditions"]["humidity"]
            wind = w["current_conditions"]["wind_condition"]
            condition = w["current_conditions"]["condition"]

            result = "%s: %sF/%sC   %s   %s   %s" % (city, temp_f, temp_c,
                    humidity, wind, condition)
            self.irc.reply(result)
        else:
            self.irc.reply("Location not found: '%s'" % location)
コード例 #3
0
ファイル: jarvis.py プロジェクト: trostonfernandes/jarvis
def get_weather():
    """Return the weather temperature and conditions for the day."""
    geodata = urllib2.urlopen("http://j.maxmind.com/app/geoip.js").read()
    country_result = re.split("country_name\(\) \{ return \'", geodata)
    country_result = re.split("'; }", country_result[1])
    city_result = re.split("city\(\)         \{ return \'", geodata)
    city_result = re.split("'; }", city_result[1])
    country = country_result[0]
    city = city_result[0]

    weather = pywapi.get_weather_from_google(city, country)

    if not weather['current_conditions']:
        print 'ERROR: Get weather failed.\n'
        return ''

    current_condition = string.lower(
        weather['current_conditions']['condition'])
    current_temp = weather['current_conditions']['temp_c']
    high_temp_f = weather['forecasts'][0]['high']
    low_temp_f = weather['forecasts'][0]['low']

    high_temp_c = int((int(high_temp_f) - 32) / 1.8)
    low_temp_c = int((int(low_temp_f) - 32) / 1.8)

    return 'The weather in ' + city + ' is currently ' + current_condition + \
           ' with a temperature of ' + current_temp + ' degrees. Today there ' + \
           'will be a high of ' + str(high_temp_c) + ', and a low of ' + str(low_temp_c) + '. '
コード例 #4
0
ファイル: weather.py プロジェクト: silent1mezzo/HackTO
 def getCurrentCondition(self):
     condition = None
     weatherDetails = pywapi.get_weather_from_google(self.location)
     cc = weatherDetails.get("current_conditions", None)
     if cc:
         condition = cc.get("condition", None)
     return condition
コード例 #5
0
ファイル: weather.py プロジェクト: comstud/pyhole
    def weather(self, params=None, **kwargs):
        """Display current weather report (ex: .w <location>)"""
        if params:
            try:
                w = pywapi.get_weather_from_google(params)
            except Exception:
                self.irc.reply("Unable to fetch weather data")
                return

            if w["current_conditions"]:
                city = w["forecast_information"]["city"]
                temp_f = w["current_conditions"]["temp_f"]
                temp_c = w["current_conditions"]["temp_c"]
                humidity = w["current_conditions"]["humidity"]
                wind = w["current_conditions"]["wind_condition"]
                condition = w["current_conditions"]["condition"]

                result = "%s: %sF/%sC   %s   %s   %s" % (city, temp_f, temp_c,
                                                         humidity, wind,
                                                         condition)
                self.irc.reply(result)
            else:
                self.irc.reply("Location not found: '%s'" % params)
        else:
            self.irc.reply(self.weather.__doc__)
コード例 #6
0
ファイル: saa.py プロジェクト: makinen/roibot
def handle_saa(bot, channel, user, message):

    city = message
    if not city:
        city = "Rovaniemi"

    result = pywapi.get_weather_from_google(city, 'FI')
    #{'current_conditions': {}, 'forecast_information': {}, 'forecasts': []

    if not result['current_conditions']:
        answer = "Weather condition for '%s' was not found.  " % city
        bot.sendMessage(channel, user, answer.encode('utf-8'))
        return

    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(result)

    celsius = " "+u'\u00B0'+"C"
    condition = result['current_conditions']['condition'].lower()
    humidity = result['current_conditions']['humidity'].lower()
    temp = result['current_conditions']['temp_c'].lower()+celsius
    wind = result['current_conditions']['wind_condition'].lower()

    city = u'\u0002'+city[0].capitalize() + city[1:]+u'\u000F'
    current = "%s %s, %s, %s, %s" % (city, temp, condition,humidity, wind)
    forecast = "("
    forecasts = result['forecasts']
    for day in forecasts:
        forecast += day['day_of_week'] + " " + day['low'] + "-"+day['high'] +celsius+ ", "
    forecast = forecast[:len(forecast)-2]+")"
    answer = current + " " + forecast
    bot.sendMessage(channel, user, answer.encode('utf-8'))
コード例 #7
0
ファイル: jarvis.py プロジェクト: adammansfield/jarvis
def get_weather():
    """Return the weather temperature and conditions for the day."""
    geodata = urllib2.urlopen("http://j.maxmind.com/app/geoip.js").read()
    country_result = re.split("country_name\(\) \{ return \'", geodata)
    country_result = re.split("'; }", country_result[1])
    city_result = re.split("city\(\)         \{ return \'", geodata)
    city_result = re.split("'; }", city_result[1])
    country = country_result[0]
    city = city_result[0]
    
    weather = pywapi.get_weather_from_google(city, country)
    
    if not weather['current_conditions']:
        print 'ERROR: Get weather failed.\n'
        return ''
    
    current_condition = string.lower(weather['current_conditions']['condition'])
    current_temp = weather['current_conditions']['temp_c']
    high_temp_f = weather['forecasts'][0]['high']
    low_temp_f = weather['forecasts'][0]['low']
    
    high_temp_c = int((int(high_temp_f) - 32) / 1.8)
    low_temp_c = int((int(low_temp_f) - 32) / 1.8)
    
    return 'The weather in ' + city + ' is currently ' + current_condition + \
           ' with a temperature of ' + current_temp + ' degrees. Today there ' + \
           'will be a high of ' + str(high_temp_c) + ', and a low of ' + str(low_temp_c) + '. '
コード例 #8
0
ファイル: weather.py プロジェクト: dormbase/dashboard
def getWeather(zipcode, pathPrefix = ''):
    weather = pywapi.get_weather_from_google('02139')
    result = {}
    result['nowtime'] = weather['forecast_information']['current_date_time']
    result['nowicon'] = pathPrefix + getIcon(weather['current_conditions']['condition'])
    result['nowtemp'] = weather['current_conditions']['temp_f'] + '&deg;'
    result['nowtitle'] = weather['current_conditions']['condition'] 
    result['nowlocation'] = weather['forecast_information']['city']
    
    result['todayicon'] = pathPrefix + getIcon(weather['forecasts'][0]['condition']) 
    result['todaytitle'] = weather['forecasts'][0]['condition']
    result['todaytemphigh'] = weather['forecasts'][0]['high']  + '&deg;'
    result['todaytemplow'] = weather['forecasts'][0]['low'] + '&deg;'

    result['tomorrowicon'] = pathPrefix + getIcon(weather['forecasts'][1]['condition'])
    result['tomorrowtitle'] = weather['forecasts'][1]['condition']
    result['tomorrowtemphigh'] = weather['forecasts'][1]['high']  + '&deg;'
    result['tomorrowtemplow'] = weather['forecasts'][1]['low']  + '&deg;'

    result['dayaftericon'] = pathPrefix + getIcon(weather['forecasts'][2]['condition'])
    result['dayaftertitle'] = weather['forecasts'][2]['condition']
    result['dayaftertemphigh'] = weather['forecasts'][2]['high']  + '&deg;'
    result['dayaftertemplow'] = weather['forecasts'][2]['low']  + '&deg;'
    
    return result
コード例 #9
0
ファイル: google.py プロジェクト: kodeaffe/weathermashup
def source(location):
    info = pywapi.get_weather_from_google(location)
    if not info['forecast_information']:
        return
    assert info['forecast_information']['unit_system'] == 'US'

    cur = info['current_conditions']
    start = datetime.strptime(
        info['forecast_information']['current_date_time'].rsplit(None, 1)[0],
        '%Y-%m-%d %H:%M:%S')
    yield dict(
        time_from = start,
        time_to = start + timedelta(seconds=1),
        temperature_current = float(cur['temp_c']),
        wind_direction = cur['wind_condition'].split()[1],
        wind_speed = mph(cur['wind_condition'].split()[3]),
        condition = cur['condition'],
        humidity = float(cur['humidity'].split()[1].rstrip('%')),
    )

    # let's hope they are ordered
    for day, forecast in enumerate(info['forecasts']):
        yield dict(
            # educated guess: temperature maximum reached at 12-o-clock
            time_from = start.replace(hour=12, minute=0) + timedelta(days=day),
            time_to = (start + timedelta(days=day)).replace(hour=12, minute=0),
            condition = forecast['condition'],
            temperature_min = fahrenheit(forecast['low']),
            temperature_max = fahrenheit(forecast['high']),
        )
コード例 #10
0
ファイル: final.py プロジェクト: joeda/qt
 def run(self):
     time.sleep(2)
     weather_data = pywapi.get_weather_from_google("de-76187")
     res = "temp: " + weather_data["current_conditions"]["temp_c"]
     res = QString(res)
     print "run worked"
     print res
     self.emit(SIGNAL("output(QString)"), res)
コード例 #11
0
ファイル: weather.py プロジェクト: twpage/hankscorpio
 def getWeather(self, dbref, zipcode):
     google_result = pywapi.get_weather_from_google(zipcode)
     condition = str(google_result["current_conditions"]["condition"])
     temp_f = str(google_result["current_conditions"]["temp_f"])
     temp_c = str(google_result["current_conditions"]["temp_c"])
     city = str(google_result["forecast_information"]["city"])
     
     msg = "It is %(condition)s and %(temp_f)sF (%(temp_c)sC) in %(city)s" % locals()
     self.mushPemit(dbref, msg)
コード例 #12
0
ファイル: flukso_gui.py プロジェクト: 0110/pythonflukso
 def update_weather(self):
     # Here the weather location has to be inserted
     google_result = pywapi.get_weather_from_google('68199', 'DE')
     weather = "Heute " + google_result['current_conditions'][
         'condition'] + " bei " + google_result['current_conditions'][
             'temp_c'] + " C\n" + google_result['current_conditions'][
                 'wind_condition'] + "\nin " + google_result[
                     'forecast_information']['city'] + "."
     self.weather.set_text(weather)
コード例 #13
0
ファイル: v1.py プロジェクト: codesf/tincan
 def exec_weather(self, bow, msg_zipcode):
     """
     """
     zipcode = bow[1] if len(bow)>=2 and bow[1] else msg_zipcode
     forecast = pywapi.get_weather_from_google(zipcode)['current_conditions']
     f_tmp = forecast['temp_f']
     condition = forecast['condition']
     weather = "The weather at %s is %sf and %s" % (zipcode, f_tmp, condition)
     return weather
コード例 #14
0
ファイル: get_report.py プロジェクト: mauriciocap/peko
def gparser (city):	#Gets weather from google in case station is not working
	
	try:
		result=pywapi.get_weather_from_google(city)
		
	except:
		print '\nNo data for'+ city
		result =0

	return result
コード例 #15
0
def fetchWeatherGoogle():
    global g_google_result
    try:
        tmp = pywapi.get_weather_from_google(CITY)
        if DEBUG:
            print "Google read: %s" % tmp
        g_google_result = tmp
    # don't ignore user Ctrl-C or out of memory
    except KeyboardInterrupt, MemoryError:
        raise
コード例 #16
0
ファイル: dayhacker.py プロジェクト: shimon/dayhacker
def add_weather_info(canvas, x, y, weather_location):
    try:
        import pywapi
    except ImportError:
        return None

    try:
        weather_info = pywapi.get_weather_from_google(weather_location)
    except Exception, e:
        return None
コード例 #17
0
def add_weather_info(canvas, x, y, weather_location):
    try:
        import pywapi
    except ImportError:
        return None

    try:
        weather_info = pywapi.get_weather_from_google(weather_location)
    except Exception, e:
        return None
コード例 #18
0
ファイル: weather.py プロジェクト: regevs/dtour
 def GetCondition(self, latlong):
     """
     Returns the current condition from google's servers.
     
     latlong     - latitude/longitude coordinates
     """
     try:
         res = pywapi.get_weather_from_google(",,,%d,%d" % tuple([int(round(x * (10**6))) for x in latlong]))        
         return res['current_conditions']['condition']
     except:
         return u""
コード例 #19
0
def get_weather(loc_id):
    try:
        weather = pywapi.get_weather_from_google(loc_id)
    except Exception as e:
        print e
        return "error"

    if len(weather["current_conditions"]) == 0:
        return "invalid loc_id"

    return weather
コード例 #20
0
ファイル: hu_googleweather.py プロジェクト: dcellucci/hu
def getData():
    """
	gets the weather at the specified location.
	"""

    try:
        googleWeather = pywapi.get_weather_from_google(location)
        condition = googleWeather['current_conditions']['condition']
        temp = googleWeather['current_conditions']['temp_c']
        return "<weather location=\"" + location + "\" condition=\"" + condition + "\" temp=\"" + temp + "c" + "\"/>"
    except:
        return ""
コード例 #21
0
ファイル: hu_googleweather.py プロジェクト: dcellucci/hu
def getData():
    """
	gets the weather at the specified location.
	"""

    try:
        googleWeather = pywapi.get_weather_from_google(location)
        condition = googleWeather["current_conditions"]["condition"]
        temp = googleWeather["current_conditions"]["temp_c"]
        return '<weather location="' + location + '" condition="' + condition + '" temp="' + temp + "c" + '"/>'
    except:
        return ""
コード例 #22
0
ファイル: weather.py プロジェクト: kryptn/icvbot
def main(l, argv):
	argv = ' '.join(argv)
	try:
		google_result = pywapi.get_weather_from_google(argv)
		condition = string.lower(google_result['current_conditions']['condition'])
		temp = google_result['current_conditions']['temp_f']
		city = google_result['forecast_information']['city']
		result = 'It is currently %s and %sF in %s.' % (condition, temp, city)
	except Exception:
		result = 'Invalid location'

	return result.encode('ascii', 'replace')
コード例 #23
0
ファイル: hu_googleweather.py プロジェクト: GunioRobot/hu
def getData():
	"""
	gets the weather at the specified location.
	"""
	
	try:
		googleWeather = pywapi.get_weather_from_google(location)
		condition = googleWeather['current_conditions']['condition']
		temp = googleWeather['current_conditions']['temp_c']
		return "<weather location=\"" + location + "\" condition=\"" + condition + "\" temp=\"" + temp + "c" + "\"/>"
	except:
		return ""
コード例 #24
0
ファイル: mrtgGetWeather.py プロジェクト: nAk123/fluffyhome
def main():
    global options

    optionParser = optparse.OptionParser(
        version="%prog 0.1",
        description="Get weather in format approperate for MRTG",
        usage="%prog [options] city")
    optionParser.add_option('--verbose', '-v', action='store_true')
    optionParser.add_option('--metric',
                            '-m',
                            action='store_true',
                            help="use metric values. Default is imperial")
    optionParser.add_option(
        '--humidity',
        '',
        action='store_true',
        help="Return relative humidity instead of temperature.")
    options, arguments = optionParser.parse_args()

    if (len(arguments) != 1):
        optionParser.error("Must provide one city name such as 'Calgary,AB' ")

    if options.verbose:
        print "City is " + arguments[0]

    result = pywapi.get_weather_from_google(arguments[0])

    if options.humidity:
        humRes = result['current_conditions']['humidity']
        hum = "%s" % humRes
        if options.verbose:
            print "Raw humidity string is " + hum
        h = int(float(hum.lstrip("Humidity: ").rstrip("%")))
        if options.verbose:
            print "Parsed humidity is %d" % h
        print "%d" % h
        print 0
        print 0
        print "OutsideHumidity"
    else:
        if options.metric:
            print result['current_conditions']['temp_c']
            print 0
            print 0
            print "OutsideTempCelcius"
        else:
            print result['current_conditions']['temp_f']
            print 0
            print 0
            print "OutsideTempFahrenheit"

    return 0
コード例 #25
0
ファイル: weather.py プロジェクト: Etherkon/3d-Virtual-Eye
def set_to_current_conditions():
    print "Setting current weather conditions"
    conditions = pywapi.get_weather_from_google("weather=tampere,finland")
    wind = conditions['current_conditions']['wind_condition'].split()
    # Wind: X at x mph
    support.set_wind(
        float(wind[3]) * mph2ms_rate, wind_directions.get((wind[1])))
    # Humidity: X%
    support.set_humidity(
        float(conditions['current_conditions']['humidity'].split()[1][:-1]))
    support.set_temperature(float(conditions['current_conditions']['temp_c']))
    # Set weather based on current condition
    setweather(conditions['current_conditions']['condition'])
def fetchWeatherGoogle():
    """ every 300 calls check the weather """
    global g_google_result
    global g_google_cnt

    if g_google_cnt==0:
        try:
            tmp = pywapi.get_weather_from_google('10025')
            print "Google read: %s" % tmp
            g_google_result = tmp
        except:
            pass 
    g_google_cnt = (g_google_cnt+1) % 300   
コード例 #27
0
ファイル: zipweather.py プロジェクト: sdubois/ZipWeather
def weather(zipcode):
    boolzip = zipcode.isdigit()
    if boolzip:
        valid = True
    else:
        valid = False
    try:
        result = pywapi.get_weather_from_google(zipcode)
        condition = result['current_conditions']['condition']
        options = {
            'Sunny': 'Sunny.png',
            'Clear': 'Sunny.png',
            'Thunderstorm': 'Thunderstorm.png',
            'Chance of TStorm' : 'Thunderstorm.png',
            'Scattered Thunderstorms': 'Thunderstorm.png',
            'Chance of Storm': 'Thunderstorm.png',
            'Rain': 'Thunderstorm.png',
            'Storm': 'Rain.png', 
            'Showers': 'Rain.png', 
            'Scattered Showers': 'Rain.png', 
            'Chance of Rain': 'Rain.png', 
            'Light Rain': 'RainLight.png',
            'Rain and Snow': 'RainSnow.png',
            'Snow Showers': 'Snow.png',
            'Chance of Snow': 'Snow.png',
            'Snow': 'Snow.png',
            'Light Snow': 'SnowLight.png',
            'Flurries': 'SnowLight.png',
            'Hail': 'Hail.png',
            'FreezingDrizzle': 'FreezingDrizzle.png',
            'Partly Cloudy': 'MostlyCloudy.png',
            'Mostly Cloudy': 'MostlyCloudy.png',
            'Mostly Sunny': 'MostlySunny.png',
            'Partly Cloudy': 'MostlySunny.png',
            'Cloudy': 'Cloudy.png',
            'Overcast': 'Cloudy.png',
            'Sleet': 'Sleet.png',
            'Icy': 'Sleet.png',
            'Mist': 'Mist.png',
            'Fog': 'Fog.png',
            'Smoke': 'Smoke.png',
            'Dust': 'Dust.png',
            'Haze': 'Dust.png',}
        image = "../static/images/weather/"+options[condition]
        return render_template('weather.html', \
        zipcode=zipcode, valid=valid, weather=result,  image=image)
    except IndexError:
        valid = False
        return render_template('weather.html', \
        zipcode=zipcode, valid=valid,)
コード例 #28
0
ファイル: jarvis.py プロジェクト: WilfridNgo/Jarvis
def get_weather():
    """Return the weather temperature and conditions for the day."""
    weather = pywapi.get_weather_from_google(city, country)
    
    current_condition = string.lower(weather['current_conditions']['condition'])
    current_temp = weather['current_conditions']['temp_c']
    high_temp_f = weather['forecasts'][0]['high']
    low_temp_f = weather['forecasts'][0]['low']
    
    high_temp_c = int(round((int(high_temp_f) - 32) / 1.8))
    low_temp_c = int(round((int(low_temp_f) - 32) / 1.8))
    
    return 'The weather in ' + city + ' is currently ' + current_condition + \
           ' with a temperature of ' + current_temp + ' degrees. Today there ' + \
           'will be a high of ' + str(high_temp_c) + ', and a low of ' + str(low_temp_c) + '. '
コード例 #29
0
ファイル: mrtgGetWeather.py プロジェクト: nAk123/fluffyhome
def main():
    global options

    optionParser = optparse.OptionParser(
        version="%prog 0.1", description="Get weather in format approperate for MRTG", usage="%prog [options] city"
    )
    optionParser.add_option("--verbose", "-v", action="store_true")
    optionParser.add_option("--metric", "-m", action="store_true", help="use metric values. Default is imperial")
    optionParser.add_option(
        "--humidity", "", action="store_true", help="Return relative humidity instead of temperature."
    )
    options, arguments = optionParser.parse_args()

    if len(arguments) != 1:
        optionParser.error("Must provide one city name such as 'Calgary,AB' ")

    if options.verbose:
        print "City is " + arguments[0]

    result = pywapi.get_weather_from_google(arguments[0])

    if options.humidity:
        humRes = result["current_conditions"]["humidity"]
        hum = "%s" % humRes
        if options.verbose:
            print "Raw humidity string is " + hum
        h = int(float(hum.lstrip("Humidity: ").rstrip("%")))
        if options.verbose:
            print "Parsed humidity is %d" % h
        print "%d" % h
        print 0
        print 0
        print "OutsideHumidity"
    else:
        if options.metric:
            print result["current_conditions"]["temp_c"]
            print 0
            print 0
            print "OutsideTempCelcius"
        else:
            print result["current_conditions"]["temp_f"]
            print 0
            print 0
            print "OutsideTempFahrenheit"

    return 0
コード例 #30
0
ファイル: module_weather.py プロジェクト: lysol/pyfibot-pesto
def command_weather(bot, user, channel, args):
    """ Just pass city's name and i tell you the current weather for that location."""
    if not has_pywapi: return

    result_dict = pywapi.get_weather_from_google(args)
    if not all(result_dict.values()):
        bot.say(channel, 'Unknown location')
        return

    direction, kmph, mps = parse_google_wind_condition(result_dict['current_conditions']['wind_condition'])
    city = result_dict['forecast_information']['city']
    condition = result_dict['current_conditions']['condition']
    temperature = int(result_dict['current_conditions']['temp_c'])
    
    answer = u'%s: %s, %d°C feels like %d°C, Wind: %.1f m/s to %s' % \
	     (city, condition, temperature, feels_like(temperature, kmph), mps, direction)
    answer = answer.encode("utf-8")
    return bot.say(channel, answer)
コード例 #31
0
ファイル: main.py プロジェクト: theclai/Cuaca-kota-mataram
    def get(self):
        auth = tweepy.OAuthHandler('mM6qxghuXMaGH86lHVVOWA','JOM29LabfIJ6v8ZccVwchPFWomapYyvlTeQ0uwBelQ')
        auth.set_access_token('400026591-m4lMAuCtsw5xDGQ9suPsgqSr4ykwYWJClmXOdxpn', '7xjgEqqbdMmcwtQ0XRcgdQ65ecVdi8TYWnDH1mtoHs')
        api = tweepy.API(auth)

	location = 'Mataram'
	resGoogle = pywapi.get_weather_from_google(location)
	resYahoo = pywapi.get_weather_from_yahoo('IDXX0032', 'metric')
	time = datetime.datetime.utcnow() + datetime.timedelta(hours = 8)
	
	visibility = resYahoo['atmosphere']['visibility'] + ' km'
	sunrise = resYahoo['astronomy']['sunrise']
	sunset = resYahoo['astronomy']['sunset']
	
	update = time.strftime("%Y-%m-%d, %H:%M") + ' WITA: ' + location + ' ' + resGoogle['current_conditions']['condition'] + ', ' + resGoogle['current_conditions']['temp_c'] + ' C' + ', ' + resGoogle['current_conditions']['humidity']  +', ' +  resGoogle['current_conditions']['wind_condition'] + ', Visibility: ' + visibility + ', Sunrise: ' + sunrise + ', Sunset: ' + sunset
	self.response.out.write(update)

	
        api.update_status(update)
コード例 #32
0
ファイル: _localsq.py プロジェクト: Kyle2501/localsq_beta
    def get(self):
    	# - database
    	add_event = self.request.get('add_event')
    	events_query = Event.all().ancestor(
    	    eventbook_key(add_event)).order('-addTime')
    	events = events_query.fetch(100)
    	# - clock
    	mst = timezone('US/Mountain')
    	ms_time = datetime.now(mst)
    	clock = ms_time.strftime('%I:%M %p')
    	day = ms_time.strftime("%a")
    	Day = ms_time.strftime("%A")
    	date = ms_time.strftime('%d')
    	month = ms_time.strftime("%B")
    	# - weather
    	google_result = pywapi.get_weather_from_google('83353')
    	weather = google_result['current_conditions']['temp_f']
    	# - user
    	user = users.get_current_user()
    	if users.get_current_user():
    		gate = users.create_logout_url(self.request.uri)
    		door = 'Exit'
    		hello = user.nickname()
    	else:
    		gate = users.create_login_url(self.request.uri)
    		door = 'Enter'
    		hello = 'LocalSq'
    		
        template_values = {
            'gate': gate,
            'door': door,
            'hello': hello,
            'clock': clock,
            'day': day,
            'date': date,
            'month': month,
            'weather': weather,
            'events': events,
        }

        path = os.path.join(os.path.dirname(__file__), 'apps/events.html')
        self.response.out.write(template.render(path, template_values))
コード例 #33
0
ファイル: weather.py プロジェクト: rbistolfi/Lalita-plugins
    def forecast(self, user, channel, command, *args):
        u'''@forecast ciudad[país]: pronóstico del clima.'''

        self.logger.debug("command %s from %s (args: %s)", command, user, args)
        
        #from pudb import set_trace; set_trace()
        
        if args:
            city = " ".join(args)
            data = pywapi.get_weather_from_google(city, self.lang)
            header = u'El pronóstico para %(city)s es: '
            template = u'%(day_of_week)s: %(condition)s, Máxima: %(high)s, Mínima: '\
                    u'%(low)s.'
            try:
                forecasts = [ template % j for j in data['forecasts'] ]
                txt = u'%s %s' % (header % data['forecast_information'], \
                        ' '.join(forecasts))
            except Exception, e:
                self.logger.debug('%s', e)
                txt = u'%s: No sé, fijate en el diario.' % user
コード例 #34
0
ファイル: module_forecast.py プロジェクト: ktze/newpyfibot
def command_forecast(bot, user, channel, args):
    '''this module tells weather forecast for location'''
    if not has_pywapi: return

    result_dict = pywapi.get_weather_from_google(args)
    if not all(result_dict.values()):
        bot.say(channel, 'unknown location')
        return

    def format_day(day):
        return (u'%s: %s (%.0f°C/%.0f°C)' % (day['day_of_week'], \
                          day['condition'], \
                          fahrenheit_to_celcius(day['low']), \
                          fahrenheit_to_celcius(day['high'])))


    answerstr = u'%s: ' % (result_dict['forecast_information']['city'])
    answerstr += u", ".join(format_day(day) for day in result_dict['forecasts'])

    bot.say(channel, answerstr.encode('utf-8'))
コード例 #35
0
ファイル: py_weather.py プロジェクト: zakhomuth/PyWeather
def generateAndMailReport(recipient = 'default recipient', location = 'n2l6b6', airport = 'CYKF'):
  report = ""
  google_result = None
  yahoo_result = None
  noaa_result = None

  try:
    google_result = pywapi.get_weather_from_google(location)
  except:
    pass

  try:
    yahoo_result = pywapi.get_weather_from_yahoo(location)
  except:
    pass

  try:
    noaa_result = pywapi.get_weather_from_noaa(airport)
  except:
    pass

  report += "Current Conditions" + "\n"
  report += "------------------" + "\n"
  if google_result != None:
    report += "  Google: " + google_result['current_conditions']['temp_c'] + "C and " + google_result['current_conditions']['condition'] + "\n"
  if yahoo_result != None:
    report += "  Yahoo : " + yahoo_result['condition']['temp'] + "C and " + yahoo_result['condition']['text'] + "\n"
  if noaa_result != None:
    report += "  NOAA  : " + noaa_result['temp_c'] + "C and " + noaa_result['weather'] + "\n"
  report += "\n"

  for fore in google_result['forecasts']:
    report += "Google's Forecast (" + fore['day_of_week'] + ")" + "\n"
    report += "------------------" + "\n"
    report += "  High: %.1fC\n" % ((float(fore['high']) - 32.0) / (9.0/5.0))
    report += "  Low : %.1fC\n" % ((float(fore['low']) - 32.0) / (9.0/5.0))
    report += "  Cond: " + fore['condition'] + "\n"
    report += "\n"

  sendMail(recipient, '[WEATHER] Daily Weather Report for n2l6b6', report)
コード例 #36
0
ファイル: gweather.py プロジェクト: putnopvut/phennymods
def gweather(phenny, input):
    loc = input.group(2)
    try:
        weather = pywapi.get_weather_from_google(loc)
    except:
        return

    if not weather:
        return

    try:
        result = "[%s] %s, %sF, %sC, %s, %s" % \
            (weather['forecast_information']['city'],
                weather['current_conditions']['condition'],
                weather['current_conditions']['temp_f'],
                weather['current_conditions']['temp_c'],
                weather['current_conditions']['humidity'],
                weather['current_conditions']['wind_condition'])
    except:
        return

    phenny.say(result)
コード例 #37
0
ファイル: _localsq.py プロジェクト: Kyle2501/localsq_beta
    def get(self):
    	# - clock
    	mst = timezone('US/Mountain')
    	ms_time = datetime.now(mst)
    	clock = ms_time.strftime('%I:%M %p')
    	day = ms_time.strftime("%a")
    	Day = ms_time.strftime("%A")
    	date = ms_time.strftime('%d')
    	month = ms_time.strftime("%B")    	
    	# - weather
    	google_result = pywapi.get_weather_from_google('83353')
    	weather = google_result['current_conditions']['temp_f']
    	# - user
    	user = users.get_current_user()
    	if users.get_current_user():
    		gate = users.create_logout_url(self.request.uri)
    		door = 'Exit'
    		hello = user.nickname()
    	else:
    		gate = users.create_login_url(self.request.uri)
    		door = 'Enter'
    		hello = 'LocalSq'
        # - data
        name = 'localsq'     
        
        template_values = {
            'gate': gate,
            'door': door,
            'hello': hello,
            'clock': clock,
            'day': day,
            'date': date,
            'month': month,
            'weather': weather,
            'name': name,
        }

        path = os.path.join(os.path.dirname(__file__), 'apps/message.html')
        self.response.out.write(template.render(path, template_values))
コード例 #38
0
ファイル: weather.py プロジェクト: Etherkon/3d-Virtual-Eye
# For getting weather information from Google

import pywapi
import cigi_support_methods as support

# Conversion rate
mph2ms_rate = 0.44704

# Gets current conditions
conditions = pywapi.get_weather_from_google("weather=tampere,finland")
wind_directions = {
    "N": 360,
    "NE": 45,
    "E": 90,
    "SE": 135,
    "S": 180,
    "SW": 225,
    "W": 270,
    "NW": 315
}

#print conditions

#Test printing
print conditions['current_conditions']['condition']
#set_weather(...)
print conditions['current_conditions']['wind_condition']


# Method to get latest weather forecasts
def set_to_current_conditions():
コード例 #39
0
###
#
# Get Newcastle, AU weather from Google weather API.
# Requires module pywapi - http://code.google.com/p/python-weather-api/
# Install with pip - `pip install pywapi`
#
# By Josh Lapham [[email protected]]
#
###

import pywapi
import pprint
import string

pp = pprint.PrettyPrinter(indent=4)

# Choose Newcastle Australia as the city to get weather from.
google_result = pywapi.get_weather_from_google('Newcastle,AU')

# Print complete output of available infomation from Google.
#pp.pprint(google_result)

# Simply print the current temperature.
#print (google_result['current_conditions']['temp_c'] + "C")

# Print a nice sentence describing the current weather conditions in Newcastle.
print "It is " + string.lower(
    google_result['current_conditions']
    ['condition']) + " and " + google_result['current_conditions'][
        'temp_c'] + "C right now in Newcastle."
コード例 #40
0
import pywapi
import string

google_result = pywapi.get_weather_from_google('95035')
yahoo_result = pywapi.get_weather_from_yahoo('95035', '')
noaa_result = pywapi.get_weather_from_noaa('KSJC')

print "Google says: It is " + string.lower(
    google_result['current_conditions']
    ['condition']) + " and " + google_result['current_conditions'][
        'temp_f'] + "F now in Milpitas.\n\n"

print "Yahoo says: It is " + string.lower(
    yahoo_result['condition']['text']
) + " and " + yahoo_result['condition']['temp'] + "F now in Milpitas.\n\n"

print "NOAA says: It is " + string.lower(
    noaa_result['weather']
) + " and " + noaa_result['temp_f'] + "F now in SJC.\n"
コード例 #41
0
 def __call__(self, location_id , hl):
     self.plugin.weather_data = pywapi.get_weather_from_google(location_id, hl)
     return self.plugin.weather_data
コード例 #42
0
import pywapi
import string

google_result = pywapi.get_weather_from_google('10001')
yahoo_result = pywapi.get_weather_from_yahoo('10001')
noaa_result = pywapi.get_weather_from_noaa('KJFK')

print "Google says: It is " + string.lower(
    google_result['current_conditions']
    ['condition']) + " and " + google_result['current_conditions'][
        'temp_c'] + "C now in New York.\n\n"

print "Yahoo says: It is " + string.lower(
    yahoo_result['condition']['text']
) + " and " + yahoo_result['condition']['temp'] + "C now in New York.\n\n"

print "NOAA says: It is " + string.lower(
    noaa_result['weather']
) + " and " + noaa_result['temp_c'] + "C now in New York.\n"
コード例 #43
0
ファイル: getservers.py プロジェクト: wzin/CS-Meteopathy
    except socket.timeout, err:
        print("Could not retrieve value: " + str(err))
        return 'None'
    except TypeError, err:
        print("Could not retrieve value: " + str(err))
        return 'None'
    except socket.error, err:
        print("Could not retrieve value: " + str(err))
        return 'None'
    except struct.error, err:
        print("Could not retrieve value: " + str(err))
        return 'None'


'''Getting status page source'''
google_result = pywapi.get_weather_from_google('Warsaw,Poland')
yahoo_result = pywapi.get_weather_from_yahoo('PLXX0028', 'metric')
Temperature = google_result['current_conditions']['temp_c']
Condition = google_result['current_conditions']['condition']
Humidity = google_result['current_conditions']['humidity']
Pressure = yahoo_result['atmosphere']['pressure']

urllib._urlopener = AppURLopener()
datasource = urllib.urlopen(
    'http://www.game-monitor.com/search.php?used=10&showEmpty=N&location=PL&num=100&game=cstrike2&vars=sv_password=0&game=cstrike2&location=PL&num=100'
)
doc = datasource.read()
soup = BeautifulSoup.BeautifulSoup(doc)
attrs = {'class': 'sip'}
sips_html = soup.findAll('td', attrs)
sips = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+', str(sips_html))
コード例 #44
0
def main_modules(request):
	removal = request.POST.getlist('event_check')
	username = request.session['username']#gets the user's name from the current session	
	new_event = request.POST.get('event')  #gets the newly added event from the event form
	event_date = request.POST.get('date')
	conn = MySQLdb.connect("localhost","piss","pisswithink","piss" )
	cursor = conn.cursor()
	module_cursor = conn.cursor()
	##gets the coresponding user_id  
	cursor.execute("""SELECT user_id FROM user WHERE user_name = '%s'""" % (username))
	results = cursor.fetchone ()
	user_id = results[0]
	#######gets the module order from the DB and sets them on the page according to user
	module_cursor.execute("""SELECT * FROM Module_order WHERE user_id = %d""" % (user_id))
	module_order = module_cursor.fetchall()
	#####puts results into choices so they can be sent to the html page for manipulation
	choice1 = str(module_order[0][1])
	choice2 = str(module_order[0][2])
	choice3 = str(module_order[0][3])
	choice4 = str(module_order[0][4])
	choice5 = str(module_order[0][5])
	choice6 = str(module_order[0][6])
	choice7 = str(module_order[0][7])
	choice8 = str(module_order[0][8])
	choice9 = str(module_order[0][9])
	choice10 = str(module_order[0][10])
	choice11 = str(module_order[0][11])
	choice12 = str(module_order[0][12])
	###puts the choices in a dictionary for easier access and output in the html
	choice_dict = [choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8, choice9, choice10, choice11, choice12]
		
	removal = request.POST.getlist('event_check')
	conn = MySQLdb.connect("localhost","piss","pisswithink","piss" )
	cursor = conn.cursor()
	all_events = Event.objects.all().order_by('-title')[:8]  #gets all of the objects in Events by title
	#event_list_form = eventCheck(request.POST) #a model for the event list checkbox form
	
	######gets the bookmarks from the db according to user
	cursor.execute("""SELECT bookmark FROM piss.bookmarks WHERE user_id = %d""" % (user_id))
	bm = cursor.fetchall()
	bm_list = [bm[0][0],bm[1][0],bm[2][0]]
	#####adds the bookmark list to the session for access in other views
	request.session['bm_list'] = bm_list
	
	#####gets the weather according to the user zip code###
	if username==None:
		return HttpResponseRedirect('/')
	cursor.execute("""SELECT zip_code FROM piss.user WHERE user_name = '%s'""" % (username))
	zip_code = cursor.fetchone()
	google_results = pywapi.get_weather_from_google('%s' % (zip_code))
	city = google_results['forecast_information']['city']
	temperature = google_results['current_conditions']['temp_f']
	####end weather app###
	
	###Custom Rss Feed Plugin#####	
	feed = rssParser()	
	feedTitle1 = feed.getRssTitle('%s' % ('http://rss.cnn.com/rss/cnn_world.rss'),random.randint(0,8))
	feedLink1 = feed.getRssLink('%s' % ('http://rss.cnn.com/rss/cnn_world.rss'),random.randint(0,8))
	feedTitle2 = feed.getRssTitle('%s' % ('http://sports.espn.go.com/espn/rss/news'),random.randint(0,8))
	feedLink2 = feed.getRssLink('%s' % ('http://sports.espn.go.com/espn/rss/news'),random.randint(0,8))
	feedTitle3 = feed.getRssTitle('%s' % ('http://www.dowjones.com/pressroom/press_rss.aspx?mode=u&catid=4'),random.randint(0,8))
	feedLink3 = feed.getRssLink('%s' % ('http://www.dowjones.com/pressroom/press_rss.aspx?mode=u&catid=4'),random.randint(0,8))
	####End Custom Rss Feed plugin####
	
	if new_event:
		add_event = Event(title = new_event)
		#add_event_date = Event(date = event_date)
		add_event.save()
		#add_event_date.save()		
	
	if removal:
		for deletion in removal:
			deletion=int(deletion)
			cursor.execute("""DELETE FROM piss.event WHERE event_id = %d;""" % (deletion))
	conn.commit()
	conn.close()
			#Event.objects.get(event_id__in=removal).delete()
	return render_to_response('main_page.html',{'results':google_results, 'choice1':choice1, 'choice2':choice2, 'choice3':choice3, 'choice4':choice4, 'choice5':choice5,'choice6':choice6, 'choice7':choice7, 'choice8':choice8, 'choice9':choice9, 'choice10':choice10, 'choice11':choice11, 'choice12':choice12, 
	'event_list': all_events, 'new_event': new_event, 'user':username, 'city': city, 
	'temperature':temperature, 'feedTitle1':feedTitle1, 'feedLink1':feedLink1,'feedTitle2':feedTitle2,'feedLink2':feedLink2,'feedTitle3':feedTitle3,'feedLink3':feedLink3,
	 'order':module_order, 'choice_dict':choice_dict, 'bm':bm_list}, context_instance=RequestContext(request))
コード例 #45
0
ファイル: GoogleWeather.py プロジェクト: shubhampost4u/UMWSN
 def getSensorValue(self):
     google_result = pywapi.get_weather_from_google(self.location)
     return google_result['current_conditions']['temp_c']
コード例 #46
0
import pywapi
import string

google_result = pywapi.get_weather_from_google('30005')

print google_result


def getCurrentWather():
    city = google_result['forecast_information']['city'].split(',')[0]
    print "It is " + string.lower(
        google_result['current_conditions']
        ['condition']) + " and " + google_result['current_conditions'][
            'temp_c'] + " degree centigrade now in " + city + ".\n\n"
    return "It is " + string.lower(
        google_result['current_conditions']
        ['condition']) + " and " + google_result['current_conditions'][
            'temp_c'] + " degree centigrade now in " + city


def getDayOfWeek(dayOfWk):
    #dayOfWk = dayOfWk.encode('ascii', 'ignore')
    return dayOfWk.lower()


def getWeatherForecast():
    #need to translate from sun/mon to sunday/monday
    dayName = {
        'sun': 'Sunday',
        'mon': 'Monday',
        'tue': 'Tuesday',
コード例 #47
0
import sys, feedparser, pywapi, time
import datetime
import tweepy

CONSUMER_KEY = ''
CONSUMER_SECRET = ''

ACCESS_KEY = ''
ACCESS_SECRET = ''

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

api = tweepy.API(auth)

google_result = pywapi.get_weather_from_google('Pune')

#print google_result

#print google_result["current_conditions"]

e = datetime.datetime.now()
f = str(e)

b = f + " " + 'Current temperature of #Pune is' + ">> " + google_result[
    'current_conditions']['temp_c'] + " degrees C\n" + "," + google_result[
        'current_conditions']['humidity']

#+", "

#+ google_result['current_conditions']['wind_condition']+" #pune"
コード例 #48
0
    Greet = 'Good Evening'

if Hour > 12:
    #Indicator for morning or evening, adjusted for 12 hour time.
    #comment out or delete this entire if statement for 24 hour time.
    indicator = 'P.M.'
    Hour -= 12
else:
    indicator = "A.M."

#Create a neat time string
#minute was made string above.
Time = str(Hour) + ':' + Minute + ' ' + indicator

try:
    Location = pywapi.get_weather_from_google(
        48825)  #Can also use yahoo and NDAAP

    Temp = int(Location['current_conditions']['temp_f'])
    #Pull Temp as unicode, just the digit, from google variable

    Sky = Location['current_conditions']['condition'].lower()
    #Pull Sky conditions, i.e. partly cloudy, from google variable

except:  #If no internet connection
    errorspeech = "however, I cannot obtain weather data for you."
    Speech = "%s Mr. Gardner. It is %s on %s, %s %d, %s" % (
        Greet, Time, Day, Month, Month_Day, errorspeech)
    #Creates the entire string to be spoken without internet

else:
    Speech = "%s Mr. Gardner. It is %s on %s, %s %d, and %d degrees \