Beispiel #1
0
def get_weather(self, e):

    #This callback handling code should be able to be reused in any other function
    if get_weather.waitfor_callback:
        return

    try:
        location = e.location
    except:
        location = e.input
    
    if location and user.get_location(location): location = user.get_location(location) #allow looking up by nickname
        
    if location == "" and user:
        location = user.get_location(e.nick)
        if location == "":
            get_weather.waitfor_callback = True
            user.get_geoIP_location(self, e, "", "", "", get_weather)
            
            return
    
    # Try weather functions in order
    forecast_io(self,  e, location)
    
    if not e.output:
        get_wwo(self, location, e)
    if not e.output:
        return get_weather2(self, e)
        
    return e
Beispiel #2
0
def get_weather(self, e):

    #This callback handling code should be able to be reused in any other function
    if get_weather.waitfor_callback:
        return

    try:
        location = e.location
    except:
        location = e.input

    if location and user.get_location(location):
        location = user.get_location(location)  #allow looking up by nickname

    if location == "" and user:
        location = user.get_location(e.nick)
        if location == "":
            get_weather.waitfor_callback = True
            user.get_geoIP_location(self, e, "", "", "", get_weather)

            return

    # Try weather functions in order
    forecast_io(self, e, location)

    if not e.output:
        get_wwo(self, location, e)
    if not e.output:
        return get_weather2(self, e)

    return e
Beispiel #3
0
def wolfram_time(self, e):
    if e.input:
        location = user.get_location(e.input)
        if location:
            e.input = "current time in %s" % location
            return get_wolfram(self, e)
    else:
        location = user.get_location(e.nick)
        if location:
            e.input = "current time in %s" % location
            return get_wolfram(self, e)
Beispiel #4
0
def wolfram_time(self, e):
    if e.input:
        location = user.get_location(e.input)
        if location:
            e.input = "current time in %s" % location
            return get_wolfram(self, e)
    else:
        location = user.get_location(e.nick)
        if location:
            e.input = "current time in %s" % location
            return get_wolfram(self, e)
Beispiel #5
0
def get_weather(self, e):
    #google weather of place specified in 'zip'
    zip = e.input

    if zip == "" and user:
        zip = user.get_location(e.nick)

    url = "http://www.google.com/ig/api?weather=" + urllib.quote(zip)
    dom = xml.dom.minidom.parse(urllib2.urlopen(url))

    if not dom.getElementsByTagName('problem_cause'):
        degree_symbol = unichr(176)
        city = dom.getElementsByTagName('city')[0].getAttribute('data')
        temp_f = dom.getElementsByTagName('current_conditions')[
            0].getElementsByTagName('temp_f')[0].getAttribute('data')
        temp_c = dom.getElementsByTagName('current_conditions')[
            0].getElementsByTagName('temp_c')[0].getAttribute('data')
        try:
            humidity = dom.getElementsByTagName('current_conditions')[
                0].getElementsByTagName('humidity')[0].getAttribute('data')
        except:
            humidity = ""

        try:
            wind = dom.getElementsByTagName(
                'current_conditions')[0].getElementsByTagName(
                    'wind_condition')[0].getAttribute('data')
        except:
            wind = ""

        try:
            condition = dom.getElementsByTagName('current_conditions')[
                0].getElementsByTagName('condition')[0].getAttribute('data')
        except:
            condition = ""

        try:
            high_f = dom.getElementsByTagName('forecast_conditions')[
                0].getElementsByTagName('high')[0].getAttribute('data')
            high_c = str(int(
                (5.0 / 9.0) * float(int(high_f) - 32))) + degree_symbol + "C"
            high_f = "High: " + high_f + degree_symbol + "F"
            low_f = dom.getElementsByTagName('forecast_conditions')[
                0].getElementsByTagName('low')[0].getAttribute('data')
            low_c = str(int(
                (5.0 / 9.0) * float(int(low_f) - 32))) + degree_symbol + "C"
            low_f = "Low: " + low_f + degree_symbol + "F"
        except:
            high_f = ""
            low_f = ""
            high_c = ""
            low_c = ""

        chanmsg = "%s / %s / %s%sF %s%sC / %s / %s / %s %s - %s %s" % (
            city, condition, temp_f, degree_symbol, temp_c, degree_symbol,
            humidity, wind, high_f, high_c, low_f, low_c)
        e.output = chanmsg.encode('utf-8')
        return e
    else:
        return get_weather2(self, e)
Beispiel #6
0
def get_wolfram(self, e):

    #query 'input' on wolframalpha and get the plaintext result back
    if user:
        location = urllib.quote(user.get_location(e.nick))
    socket.setdefaulttimeout(30)
    url = "http://api.wolframalpha.com/v2/query?appid=%s&format=plaintext&input=%s&location=%s" % (
        tools.config.wolframAPIkey, urllib.quote(e.input), location)
    dom = xml.dom.minidom.parse(urllib2.urlopen(url))
    socket.setdefaulttimeout(10)

    if (dom.getElementsByTagName("queryresult")[0].getAttribute("success") ==
            "false"):
        try:
            related = dom.getElementsByTagName(
                "relatedexample")[0].getAttribute("input")
            e.input = related
            return get_wolfram(self, e)
        except Exception as inst:
            print "!wolframrelated " + e.input + " : " + str(inst)
    else:
        try:
            query = dom.getElementsByTagName("plaintext")[0].childNodes[0].data
            try:
                result = dom.getElementsByTagName(
                    "plaintext")[1].childNodes[0].data
            except:
                result = ""
            output = query.replace("\n", " || ") + " :: " + result.replace(
                "\n", " || ")

            e.output = output.encode("utf-8")
            return e
        except Exception as inst:
            print "!wolfram " + e.input + " : " + str(inst)
Beispiel #7
0
def google_sun(term, sun, nick):
    if term == "" and user:
       term = user.get_location(nick)
    term = urllib.quote(term)
    url = "http://www.google.com/search?hl=en&client=opera&hs=6At&rls=en&q=%s+%s&aq=f&aqi=g1&aql=&oq=&gs_rfai=" % (sun, term)
    request = urllib2.Request(url, None, {})
    request.add_header('User-Agent', "Opera/9.80 (Windows NT 6.0; U; en) Presto/2.2.15 Version/10.10")
    request.add_header('Range', "bytes=0-40960")
    response = urllib2.urlopen(request).read()

    m = re.search('(-40.gif.*?\<b\>)(.*?)(\<\/b\> )(.*?)( -\s*\<b\>)(.*?)(\<\/b\> in\s*)(.*?)(\s*?\<tr\>.*?top\"\>)(.*?)(\<\/table\>)', response)
    
    try:
      settime = m.group(2)
      setday = m.group(4)
      setday = re.sub("\s+"," ",setday)
      setword = m.group(6)
      setcity = m.group(8)
      settimeword = m.group(10)
      
      result = "%s in %s: %s %s (%s)" % (sun, setcity,settime,setday,settimeword)
   
      #print result
    except:
      pass
      return

    return tools.remove_html_tags(result)
Beispiel #8
0
def google_sun(self, location, sun, nick):
    if location == "" and user:
       location = user.get_location(nick)
    location = urllib.parse.quote(location)
    url = "http://www.google.com/search?hl=en&client=opera&hs=6At&rls=en&q=%s+%s&aq=f&aqi=g1&aql=&oq=&gs_rfai=" % (sun, location)
    request = urllib.request.Request(url, None, {})
    request.add_header('User-Agent', "Opera/9.80 (Windows NT 6.0; U; en) Presto/2.2.15 Version/10.10")
    request.add_header('Range', "bytes=0-40960")
    response = urllib.request.urlopen(request).read().decode('utf-8')
    

    m = re.search('(-40.gif.*?\<b\>)(.*?)(\<\/b\> )(.*?)( -\s*\<b\>)(.*?)(\<\/b\> in\s*)(.*?)(\s*?\<tr\>.*?top\"\>)(.*?)(\<\/table\>)', response)
    
    try:
      settime = m.group(2)
      setday = m.group(4)
      setday = re.sub("\s+"," ",setday)
      setword = m.group(6)
      setcity = m.group(8)
      settimeword = m.group(10)
      
      result = "%s in %s: %s %s (%s)" % (sun, setcity,settime,setday,settimeword)
   
      #print result
    except:
      pass
      return

    return tools.remove_html_tags(result)
Beispiel #9
0
def get_wolfram(self, e):
    
    #query 'input' on wolframalpha and get the plaintext result back
    if user:
        location = urllib.quote(user.get_location(e.nick))
    socket.setdefaulttimeout(30)
    url = "http://api.wolframalpha.com/v2/query?appid=%s&format=plaintext&input=%s&location=%s" % (tools.config.wolframAPIkey, urllib.quote(e.input), location)
    dom = xml.dom.minidom.parse(urllib2.urlopen(url))
    socket.setdefaulttimeout(10)

    if (dom.getElementsByTagName("queryresult")[0].getAttribute("success") == "false"):
        try:
            related = dom.getElementsByTagName("relatedexample")[0].getAttribute("input")
            e.input = related
            return get_wolfram(self, e)
        except Exception as inst:
            print "!wolframrelated " + e.input + " : " + str(inst)
    else:
        try:
            query = dom.getElementsByTagName("plaintext")[0].childNodes[0].data
            try:
                result = dom.getElementsByTagName("plaintext")[1].childNodes[0].data
            except:
                result = ""
            output = query.replace("\n", " || ") + " :: " + result.replace("\n", " || ")
            
            e.output = output.encode("utf-8")
            return e
        except Exception as inst:
            print "!wolfram " + e.input + " : " + str(inst)
Beispiel #10
0
def google_sunrise(self, e):
    #returns the next sunrise time and time from now of the place specified
    #This callback handling code should be able to be reused in any other function
    if google_sunrise.waitfor_callback:
        return
    

    try:
        location = e.location
    except:
        location = e.input
        
    if location == "" and user:
        location = user.get_location(e.nick)
        if location=="":
            google_sunrise.waitfor_callback=True
            user.get_geoIP_location(self, e, "", "", "", google_sunrise)
            
            return
        
    
    
    #End callback handling code
    e.output = google_sun(self, location, "Sunrise", e.nick)
    return e
Beispiel #11
0
def get_weather2(self, e):
    #wunderground weather of place specified in 'zipcode'
    zipcode = e.input
    if zipcode == "" and user:
        zipcode = user.get_location(e.nick)

    url = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + urllib.parse.quote(
        zipcode)
    dom = xml.dom.minidom.parse(urllib.request.urlopen(url))
    city = dom.getElementsByTagName('display_location')[
        0].getElementsByTagName('full')[0].childNodes[0].data
    if city != ", ":
        temp_f = dom.getElementsByTagName('temp_f')[0].childNodes[0].data
        temp_c = dom.getElementsByTagName('temp_c')[0].childNodes[0].data
        try:
            condition = dom.getElementsByTagName(
                'weather')[0].childNodes[0].data
        except:
            condition = ""
        try:
            humidity = "Humidity: " + str(
                dom.getElementsByTagName('relative_humidity')
                [0].childNodes[0].data)
        except:
            humidity = ""
        try:
            wind = "Wind: " + str(
                dom.getElementsByTagName('wind_string')[0].childNodes[0].data)
        except:
            wind = ""

        degree_symbol = chr(176)
        chanmsg = "%s / %s / %s%sF %s%sC / %s / %s" % (
            city, condition, temp_f, degree_symbol, temp_c, degree_symbol,
            humidity, wind)
        e.output = chanmsg
        return e
    else:
        if user:
            ziptry = user.get_location(e.input)
            if ziptry:
                e.nick = e.input
                e.input = ""
                return get_weather(self, e)
            else:
                return None
Beispiel #12
0
def get_weather2(self, e):
    #wunderground weather of place specified in 'zipcode'
    zipcode = e.input
    if zipcode == "" and user:
        zipcode = user.get_location(e.nick)

    url = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + urllib.parse.quote(zipcode)
    dom = xml.dom.minidom.parse(urllib.request.urlopen(url))
    city = dom.getElementsByTagName('display_location')[0].getElementsByTagName('full')[0].childNodes[0].data
    if city != ", ":
        temp_f = dom.getElementsByTagName('temp_f')[0].childNodes[0].data
        temp_c = dom.getElementsByTagName('temp_c')[0].childNodes[0].data
        try:
            condition = dom.getElementsByTagName('weather')[0].childNodes[0].data
        except:
            condition = ""
        try:
            humidity = "Humidity: " + str(dom.getElementsByTagName('relative_humidity')[0].childNodes[0].data)
        except:
            humidity = ""
        try:
            wind = "Wind: " + str(dom.getElementsByTagName('wind_string')[0].childNodes[0].data)
        except:
            wind = ""

        degree_symbol = chr(176)
        chanmsg = "%s / %s / %s%sF %s%sC / %s / %s" % (city,
                                                       condition,
                                                       temp_f,
                                                       degree_symbol,
                                                       temp_c,
                                                       degree_symbol,
                                                       humidity,
                                                       wind)
        e.output = chanmsg
        return e
    else:
        if user:
            ziptry = user.get_location(e.input)
            if ziptry:
                e.nick = e.input
                e.input = ""
                return get_weather(self, e)
            else:
                return None
Beispiel #13
0
def get_weather(self, e):
    #google weather of place specified in 'zip'
   zip = e.input
   
   if zip == "" and user:
       zip = user.get_location(e.nick)

   url = "http://www.google.com/ig/api?weather=" + urllib.parse.quote(zip)
   
   try:
    pageString = urllib.request.urlopen(url).read().decode('utf-8')
   except UnicodeDecodeError:
    pageString = urllib.request.urlopen(url).read().decode('latin-1').encode('utf-8').decode('utf-8')
   
   dom = xml.dom.minidom.parseString(pageString)
   
   if not dom.getElementsByTagName('problem_cause'):
       degree_symbol = chr(176)
       city = dom.getElementsByTagName('city')[0].getAttribute('data')
       temp_f = dom.getElementsByTagName('current_conditions')[0].getElementsByTagName('temp_f')[0].getAttribute('data')
       temp_c = dom.getElementsByTagName('current_conditions')[0].getElementsByTagName('temp_c')[0].getAttribute('data')
       try:
        humidity = dom.getElementsByTagName('current_conditions')[0].getElementsByTagName('humidity')[0].getAttribute('data')
       except:
        humidity = ""
       
       try: 
        wind = dom.getElementsByTagName('current_conditions')[0].getElementsByTagName('wind_condition')[0].getAttribute('data')
       except:
        wind = "" 
        
       try:
        condition = dom.getElementsByTagName('current_conditions')[0].getElementsByTagName('condition')[0].getAttribute('data')
       except:
        condition = "" 
        
       try:
        high_f = dom.getElementsByTagName('forecast_conditions')[0].getElementsByTagName('high')[0].getAttribute('data')
        high_c = str(int((5.0/9.0) * float(int(high_f) -32)))+ degree_symbol + "C"
        high_f = "High: " + high_f + degree_symbol + "F"
        low_f = dom.getElementsByTagName('forecast_conditions')[0].getElementsByTagName('low')[0].getAttribute('data')
        low_c = str(int((5.0/9.0) * float(int(low_f) -32))) + degree_symbol + "C"
        low_f = "Low: " + low_f + degree_symbol + "F"
       except:
           high_f = ""
           low_f = ""
           high_c = ""
           low_c = ""

       
       chanmsg = "%s / %s / %s%sF %s%sC / %s / %s / %s %s - %s %s" % (city, condition, temp_f,degree_symbol, temp_c, degree_symbol, humidity, wind, high_f, high_c,low_f,low_c)
       e.output = chanmsg
       return e
   else:
       return get_weather2(self, e)
Beispiel #14
0
def get_wolfram(self, e):
    #query 'input' on wolframalpha and get the plaintext result back
    if get_wolfram.waitfor_callback:
        return
    
    try:
        location = e.location
    except:
        location = ""
    
    if location == "" and user:
        location = user.get_location(e.nick)
        if location=="":
            get_wolfram.waitfor_callback=True
            user.get_geoIP_location(self, e, "", "", "", get_wolfram)
            
            return
            
    location = urllib.parse.quote(location)
            
    socket.setdefaulttimeout(30)
    url = "http://api.wolframalpha.com/v2/query?appid=%s&format=plaintext&input=%s&location=%s" % (self.botconfig["APIkeys"]["wolframAPIkey"], urllib.parse.quote(e.input), location)
    dom = xml.dom.minidom.parse(urllib.request.urlopen(url))
    socket.setdefaulttimeout(10)

    if (dom.getElementsByTagName("queryresult")[0].getAttribute("success") == "false"):
        try:
            related = dom.getElementsByTagName("relatedexample")[0].getAttribute("input")
            e.input = related
            return get_wolfram(self, e)
        except Exception as inst:
            traceback.print_exc()
            print("!wolframrelated " + e.input + " : " + str(inst))
            result = self.bangcommands["!error"](self, e).output
            e.output = result
            return e
    else:
        try:
            query = dom.getElementsByTagName("plaintext")[0].childNodes[0].data
            try:
                result = dom.getElementsByTagName("plaintext")[1].childNodes[0].data
            except:
                result = self.bangcommands["!error"](self, e).output

            output = query.replace("\n", " || ") + " :: " + result.replace("\n", " || ")
            e.output = output
            return e
        except Exception as inst:
            traceback.print_exc()
            print("!wolfram " + e.input + " : " + str(inst))
            result = self.bangcommands["!error"](self, e).output
            e.output = result
            return e
Beispiel #15
0
def get_weather(self, e):

    try:
        location = e.location
    except:
        location = e.input

    if location and user.get_location(location):
        location = user.get_location(location)  #allow looking up by nickname

    if location == "" and user:
        location = user.get_location(e.nick)

    # Try weather functions in order
    forecast_io(self, e, location)

    if not e.output:
        get_wwo(self, location, e)
    if not e.output:
        return get_weather2(self, e)

    return e
Beispiel #16
0
def get_sun(self, e):
    apikey = self.botconfig["APIkeys"]["wunderAPIkey"]
    location = e.input
    if location == "" and user:
        location = user.get_location(e.nick)

    url = "http://api.wunderground.com/api/{}/astronomy/q/{}.json"
    url = url.format(apikey, urllib.parse.quote(location))

    response = urllib.request.urlopen(url).read().decode("utf-8", "replace")
    data = json.loads(response)['moon_phase']
    time = "{}:{}".format(data['current_time']['hour'],
                          data['current_time']['minute'])

    sunrise = "{}:{}".format(data['sunrise']['hour'],
                             data['sunrise']['minute'])
    sunset = "{}:{}".format(data['sunset']['hour'], data['sunset']['minute'])

    now = datetime.strptime(time, "%H:%M")
    sunriseobj = datetime.strptime(sunrise, "%H:%M")
    sunsetobj = datetime.strptime(sunset, "%H:%M")

    sunlength = sunsetobj - sunriseobj
    if sunriseobj > now:
        ago = "from now"
        td = sunriseobj - now
    else:
        td = now - sunriseobj
        ago = "ago"
    til = self.tools['prettytimedelta'](td)
    #til = td
    sunrise = "{} ({} {})".format(sunrise, til, ago)
    if sunsetobj > now:
        ago = "from now"
        td = sunsetobj - now
    else:
        ago = "ago"
        td = now - sunsetobj
    #til = td
    til = self.tools['prettytimedelta'](td)
    sunset = "{} ({} {})".format(sunset, til, ago)

    out = "[ {} ] Sunrise: {} / Sunset: {} / Day Length: {}".format(
        location, sunrise, sunset, sunlength)
    e.output = out
    return e
Beispiel #17
0
def get_sun(self, e):
    apikey = self.botconfig["APIkeys"]["wunderAPIkey"]
    location = e.input
    if location == "" and user:
        location = user.get_location(e.nick)
    
    location = urllib.parse.quote(location)
    url = "http://api.wunderground.com/api/{}/astronomy/q/{}.json"
    url = url.format(apikey, location)

    response = urllib.request.urlopen(url).read().decode("utf-8", "replace")
    data = json.loads(response)['moon_phase']
    time = "{}:{}".format(data['current_time']['hour'], data['current_time']['minute'])

    sunrise = "{}:{}".format(data['sunrise']['hour'], data['sunrise']['minute'])
    sunset = "{}:{}".format(data['sunset']['hour'], data['sunset']['minute'])

    now = datetime.strptime(time, "%H:%M")
    sunriseobj = datetime.strptime(sunrise, "%H:%M")
    sunsetobj = datetime.strptime(sunset, "%H:%M")

    sunlength = sunsetobj - sunriseobj
    if sunriseobj > now:
       ago = "from now"
       td = sunriseobj - now
    else:
       td = now - sunriseobj
       ago = "ago"
    til = self.tools['prettytimedelta'](td)
    #til = td
    sunrise = "{} ({} {})".format(sunrise, til, ago)
    if sunsetobj > now:
       ago = "from now"
       td = sunsetobj - now
    else:
       ago = "ago"
       td = now - sunsetobj
    #til = td
    til = self.tools['prettytimedelta'](td)
    sunset = "{} ({} {})".format(sunset, til, ago)

    out = "Sunrise: {} / Sunset: {} / Day Length: {}".format(sunrise, sunset, sunlength)
    e.output = out
    return e
Beispiel #18
0
def forecast_io(self, e, location=""):
    apikey = self.botconfig["APIkeys"]["forecastIO_APIkey"]
    print("Entered Forecast.IO function. Location %s or %s" %
          (location, e.input))
    if location == "":
        location = e.input
    if location == "" and user:
        location = user.get_location(e.nick)

    address, lat, lng, country = google_geocode(self, location)

    url = "https://api.forecast.io/forecast/{}/{},{}"
    url = url.format(apikey, lat, lng)

    try:
        request = urllib.request.Request(url, None,
                                         {'Referer': 'http://irc.00id.net'})
        response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as err:
        print(err.read())

    #try:
    results_json = json.loads(response.read().decode('utf-8'))
    timezone_offset = results_json['offset']
    current_conditions = results_json['currently']

    temp = current_conditions['temperature']
    humidity = int(100 * current_conditions['humidity'])
    precip_probability = current_conditions['precipProbability']
    current_summary = current_conditions['summary']

    wind_speed = int(round(current_conditions['windSpeed'], 0))
    wind_speed_kmh = int(round(wind_speed * 1.609, 0))

    wind_direction = current_conditions['windBearing']
    wind_direction = bearing_to_compass(wind_direction)

    cloud_cover = int(100 * current_conditions['cloudCover'])

    feels_like = current_conditions['apparentTemperature']

    min_temp = int(round(results_json['daily']['data'][0]['temperatureMin'],
                         0))
    #min_temp_time = time.strftime("%I%p",time.gmtime(results_json['daily']['data'][0]['temperatureMinTime'] + (timezone_offset * 3600))).lstrip("0")
    min_temp_c = int(round((min_temp - 32) * 5 / 9, 0))

    max_temp = int(round(results_json['daily']['data'][0]['temperatureMax'],
                         0))
    #max_temp_time = time.strftime("%I%p",time.gmtime(results_json['daily']['data'][0]['temperatureMaxTime'] + (timezone_offset * 3600))).lstrip("0")
    max_temp_c = int(round((max_temp - 32) * 5 / 9, 0))

    if feels_like != temp:
        if country:
            feels_like = " / Feels like: %s°C" % (int(
                round((feels_like - 32) * 5 / 9, 0)))
        else:
            feels_like = " / Feels like: %s°F" % (int(round(feels_like, 0)))

    else:
        feels_like = ""

    temp_c = int(round((temp - 32) * 5 / 9, 0))
    temp = int(round(temp, 0))

    # If the minute by minute outlook isn't available, grab the hourly
    try:
        outlook = "%s %s " % (results_json['minutely']['summary'],
                              results_json['daily']['summary'])
    except:
        outlook = "%s %s" % (results_json['hourly']['summary'],
                             results_json['daily']['summary'])

    if not country:  #If we're in the US, use Fahrenheit, otherwise Celsius
        output = "{} / {} / {}°F{} / Humidity: {}% / Wind: {} at {} mph / Cloud Cover: {}% / High: {}°F Low: {}°F / Outlook: {}"
        e.output = output.format(address, current_summary, temp, feels_like,
                                 humidity, wind_direction, wind_speed,
                                 cloud_cover, max_temp, min_temp, outlook)
    else:  #Outside of the US
        outlookt = re.search("(-?\d+)°F", outlook)
        if outlookt:
            try:
                tmp = int(outlookt.group(1))
                tmpstr = "{}°C".format(int(round((tmp - 32) * 5 / 9, 0)))
                outlook = re.sub("-?\d+°F", tmpstr, outlook)
            except:
                pass

        output = "{} / {} / {}°C{} / Humidity: {}% / Wind: {} at {} km/h / Cloud Cover: {}% / High: {}°C Low: {}°C / Outlook: {}"
        e.output = output.format(address, current_summary, temp_c, feels_like,
                                 humidity, wind_direction, wind_speed_kmh,
                                 cloud_cover, max_temp_c, min_temp_c, outlook)
    return e
Beispiel #19
0
def get_weather(self, e):
    # WWO weather of place specified in 'zip'
    # http://www.worldweatheronline.com/free-weather-feed.aspx
    
    #This callback handling code should be able to be reused in any other function
    if get_weather.waitfor_callback:
        return
    

    try:
        location = e.location
    except:
        location = e.input
        
    if location == "" and user:
        location = user.get_location(e.nick)
        if location == "":
            get_weather.waitfor_callback=True
            user.get_geoIP_location(self, e, "", "", "", get_weather)
            
            return
        
    location = urllib.parse.quote(location)
    
    #End callback handling code
    url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q={}&format=json&num_of_days=1&includeLocation=yes&key={}".format(location, self.botconfig["APIkeys"]["wwoAPIkey"])

    response = urllib.request.urlopen(url).read().decode('utf-8')
    weather = json.loads(response)
    weatherdata = weather["data"]

    if 'error' not in weatherdata:
    
        country = weatherdata['nearest_area'][0]['country'][0]['value']
        
        if country == "United States Of America" or country == "Canada" or country == "USA":
            country = ""
        elif country == "United Kingdom":
            country = ", UK"
        else: 
            country = ", " + country
        
        
        try:
            region = ", " + weatherdata['nearest_area'][0]['region'][0]['value']
        except:
            region = ""
        
        city = "%s%s%s" % (weatherdata['nearest_area'][0]['areaName'][0]['value'], region, country)
        desc = weatherdata['current_condition'][0]['weatherDesc'][0]['value']
        temp = "{}°F {}°C".format(weatherdata['current_condition'][0]['temp_F'], weatherdata['current_condition'][0]['temp_C'])
        humidity = "%s%%" % (weatherdata['current_condition'][0]['humidity'])
        high = "{}°F {}°C".format(weatherdata['weather'][0]['tempMaxF'], weatherdata['weather'][0]['tempMaxC'])
        low = "{}°F {}°C".format(weatherdata['weather'][0]['tempMinF'], weatherdata['weather'][0]['tempMinC'])
        outlook = weatherdata['weather'][0]['weatherDesc'][0]['value']

        if  int(weatherdata['current_condition'][0]['cloudcover']) > 5:
            cloudcover = "Cloud Cover: %s%% / " % (weatherdata['current_condition'][0]['cloudcover'])
        else:
            cloudcover = ""

        if float(weatherdata['current_condition'][0]['precipMM']) > 0:
            precip = "Precipitation: %s mm / " % (weatherdata['current_condition'][0]['precipMM'])
        else:
            precip = ""

        if int(weatherdata['current_condition'][0]['visibility']) < 10:
            visibility = "Visibility: %skm / " % (weatherdata['current_condition'][0]['visibility'])
        else: 
            visibility = ""
            
        if int(weatherdata['current_condition'][0]['windspeedMiles']) > 0:
            wind = "Wind: %s at %s mph (%s km/h) / " % (weatherdata['current_condition'][0]['winddir16Point'], weatherdata['current_condition'][0]['windspeedMiles'], weatherdata['current_condition'][0]['windspeedKmph'])
        else:
            wind = ""

        message = "{} / {} / {} / Humidity: {} / {}{}{}{}High: {} - Low: {} Outlook: {}".format(city, desc, temp, humidity, visibility, wind, cloudcover, precip, high, low, outlook)
        e.output = message
        return e
    else:
        return get_weather2(self, e)
Beispiel #20
0
def get_wolfram(self, e):
    #query 'input' on wolframalpha and get the plaintext result back
    if get_wolfram.waitfor_callback:
        return
    
    try:
        location = e.location
    except:
        location = ""
    
    if location == "" and user:
        location = user.get_location(e.nick)
#        if location=="":
#            get_wolfram.waitfor_callback=True
#            user.get_geoIP_location(self, e, "", "", "", get_wolfram)
            
#            return
    address, lat, lng, country = google_geocode(self,location)

    location = urllib.parse.quote(address)

    socket.setdefaulttimeout(30)
    url = "http://api.wolframalpha.com/v2/query?appid={}&format=plaintext&input={}&location={}&latlong={},{}"
    url = url.format(self.botconfig["APIkeys"]["wolframAPIkey"],
                     urllib.parse.quote(e.input),
                     location, lat, lng)
    self.logger.debug("URL is {}".format(url))
    req = urllib.request.urlopen(url).read()
    dom = xml.dom.minidom.parseString(req)

    socket.setdefaulttimeout(10)
    if (dom.getElementsByTagName("queryresult")[0].getAttribute("success") == "false"):
        try:
            related = dom.getElementsByTagName("relatedexample")[0].getAttribute("input")
            e.input = related
            return get_wolfram(self, e)
        except Exception as inst:
            traceback.print_exc()
            print("!wolframrelated " + e.input + " : " + str(inst))
            result = self.bangcommands["!error"](self, e).output
            e.output = result
            return e
    else:
        try:
            query = dom.getElementsByTagName("plaintext")[0].childNodes[0].data
            try:
                result = dom.getElementsByTagName("plaintext")[1].childNodes[0].data
            except:
                result = self.bangcommands["!error"](self, e).output

            output = query.replace("\n", " || ") + " :: " + result.replace("\n", " || ")
            unicodes = re.findall("\\\\:[0-9a-zA-Z]{4}", output)
            if unicodes:
                print(unicodes)
                newchars = []
                for ch in unicodes:
                    ch = ch.encode().replace(b"\\:",b"\\u").decode("unicode-escape")
                    newchars.append(ch)
                output = re.sub("\\\\:[0-9a-zA-Z]{4}", "{}", output)
                output = output.format(*newchars) 
            e.output = output
            return e
        except Exception as inst:
            traceback.print_exc()
            print("!wolfram " + e.input + " : " + str(inst))
            result = self.bangcommands["!error"](self, e).output
            e.output = result
            return e
Beispiel #21
0
def forecast_io(self,e, location=""):
    apikey = self.botconfig["APIkeys"]["forecastIO_APIkey"]
    print ("Entered Forecast.IO function. Location %s or %s" % (location, e.input))
    if location == "":
        location = e.input
    if location == "" and user:
        location = user.get_location(e.nick)
  
    address, lat, lng, country = google_geocode(self,location)

    url = "https://api.forecast.io/forecast/{}/{},{}"
    url = url.format(apikey, lat, lng)

    try:
        request = urllib.request.Request(url, None, {'Referer': 'http://irc.00id.net'})
        response = urllib.request.urlopen(request)
    except urllib.error.HTTPError as err:
        print(err.read())

    #try:
    results_json = json.loads(response.read().decode('utf-8'))
    timezone_offset = results_json['offset']    
    current_conditions = results_json['currently']

    temp = current_conditions['temperature']
    humidity = int(100*current_conditions['humidity'])
    precip_probability = current_conditions['precipProbability']
    current_summary = current_conditions['summary']
    
    wind_speed = int(round(current_conditions['windSpeed'], 0))
    wind_speed_kmh = int(round(wind_speed * 1.609, 0))

    wind_direction = current_conditions['windBearing']
    wind_direction = bearing_to_compass(wind_direction)

    cloud_cover = int(100*current_conditions['cloudCover'])
    
    feels_like = current_conditions['apparentTemperature']

    min_temp = int(round(results_json['daily']['data'][0]['temperatureMin'],0))
    #min_temp_time = time.strftime("%I%p",time.gmtime(results_json['daily']['data'][0]['temperatureMinTime'] + (timezone_offset * 3600))).lstrip("0")
    min_temp_c = int(round((min_temp - 32)*5/9,0)) 
        
    max_temp = int(round(results_json['daily']['data'][0]['temperatureMax'],0))
    #max_temp_time = time.strftime("%I%p",time.gmtime(results_json['daily']['data'][0]['temperatureMaxTime'] + (timezone_offset * 3600))).lstrip("0")
    max_temp_c = int(round((max_temp - 32)*5/9,0))
        
    if feels_like != temp:
        if country:
            feels_like = " / Feels like: %s°C" % (int(round((feels_like- 32)*5/9,0)))
        else:
            feels_like = " / Feels like: %s°F" % (int(round(feels_like,0)))
    
    else:
        feels_like = ""
        
    temp_c = int(round((temp - 32)*5/9,0))
    temp = int(round(temp,0))

    # If the minute by minute outlook isn't available, grab the hourly
    try:
        outlook = "%s %s " % (results_json['minutely']['summary'], results_json['daily']['summary'])
    except:
        outlook = "%s %s" % (results_json['hourly']['summary'], results_json['daily']['summary'])


    if not country: #If we're in the US, use Fahrenheit, otherwise Celsius    
        output = "{} / {} / {}°F{} / Humidity: {}% / Wind: {} at {} mph / Cloud Cover: {}% / High: {}°F Low: {}°F / Outlook: {}"
        e.output = output.format(address, current_summary, temp,
                          feels_like, humidity,
                          wind_direction, wind_speed,
                          cloud_cover, max_temp, min_temp, outlook)
    else: #Outside of the US
        outlookt = re.search("(-?\d+)°F", outlook)
        if outlookt:
            try:
                tmp = int(outlookt.group(1))
                tmpstr = "{}°C".format(int(round((tmp - 32)*5/9,0)))
                outlook = re.sub("-?\d+°F", tmpstr, outlook)
            except:
                pass

        output = "{} / {} / {}°C{} / Humidity: {}% / Wind: {} at {} km/h / Cloud Cover: {}% / High: {}°C Low: {}°C / Outlook: {}"
        e.output = output.format(address, current_summary, temp_c,
                          feels_like, humidity, wind_direction,
                          wind_speed_kmh, cloud_cover, max_temp_c,
                          min_temp_c, outlook)
    return e