Exemplo n.º 1
0
    def command(self, bot, user, cmd, args):
        if cmd != 'j': return

        if args:
            names = args.split(" ", 2)
            if (len(names) == 1):
                jsonData = download(
                    "http://api.icndb.com/jokes/random?firstName=" + names[0] +
                    "&lastName=")
            else:
                jsonData = download(
                    "http://api.icndb.com/jokes/random?firstName=" + names[0] +
                    "&lastName=" + names[1])
        else:
            jsonData = download("http://api.icndb.com/jokes/random")
        if not jsonData:
            return "Jokes not available at the moment."
        data = json.loads(jsonData)
        if not data:
            return "Jokes can not be parsed."

        joke = data["value"]["joke"]
        if not joke:
            return "Joke not found"
        return joke
Exemplo n.º 2
0
def weather_forecast(place):
    '''
    Polls thefuckingweather.com (sic) site for current weather data at specific
    place. Returns a text containing current temperature, whether it's raining etc.
    '''
    if not place or len(str(place).strip()) == 0:
        return "No place supplied."
    
    url = "http://www.thefuckingweather.com/?zipcode=%s&CELSIUS=yes" % urllib2.quote(place)
    fw_site = download(url)
    if not fw_site: return "Could not retrieve weather information."
    
    # Look up for the contents of <div class="large">
    m = WEATHER_DIV.search(fw_site)
    if m:
        # Get the contents
        degrees = m.groupdict().get("degrees")
        comment = m.groupdict().get("comment")        
        if degrees:
            
            # Try to fetch the actual place
            m = WEATHER_PLACE_DIV.search(fw_site)
            if m:   place = m.groupdict().get("place", place)
        
            res = "%s: %s^C" % (place, degrees)
            if comment:
                comment = str(comment).lower()
                comment = re.sub(r"\<br\s*/?\>", " ", comment) # Convert br's to spaces
                comment = re.sub(r"\sfucking", "", comment)
                res += " (%s)" % comment
            return res
            
    return "Could not find weather information."
Exemplo n.º 3
0
    def command(self, bot, channel, user, cmd, args):
        if not args:
            return

        url = WEATHER_URL + "?q=%s&lang=eng" % urllib2.quote(args)
        json_data = download(url)
        if not json_data:
            return "Weather not available at the moment."

        try:
            data = json.loads(json_data)
        except ValueError:
            self.error(bot, channel)
            return

        city = data.get("name")
        if not city:
            return "Could not find weather information."

        country = data.get("sys").get("country")
        description = data.get("weather")[0].get("description")
        temperature = self._kelvins_to_celsius(data.get("main").get("temp"))

        wind_speed = self._mps_to_kmps(data.get("wind").get("speed"))
        wind_chill = self._calculate_wind_chill(temperature, wind_speed)

        msg = ("{city}, {country}: "
               "{temperature:.1f}^C -- {description}").format(**locals())
        if wind_chill is not None:
            msg = ("{city}, {country}: "
                   "{temperature:.1f}^C (felt as {wind_chill:.0f}^C) -- "
                   "{description}").format(**locals())
        return msg
Exemplo n.º 4
0
Arquivo: web.py Projeto: Xion/seejoo
def _google_websearch(query):
    '''
    Performs a query to Google Web Search API and returns resulting JSON object.
    '''
    url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s" % urllib2.quote(query)
    response = download(url)
    return json.loads(response)
Exemplo n.º 5
0
Arquivo: web.py Projeto: gflerm/seejoo
def weather_forecast(place):
    '''
    Polls thefuckingweather.com (sic) site for current weather data at specific
    place. Returns a text containing current temperature, whether it's raining etc.
    '''
    if not place or len(str(place).strip()) == 0:
        return "No place supplied."

    fw_site = download(
        "http://www.thefuckingweather.com/?zipcode=%s&CELSIUS=yes" %
        urllib2.quote(place))
    if not fw_site:
        return "Could not retrieve weather information."

    soup = BeautifulSoup(fw_site)

    try:
        degrees = soup.find('span', {'class': 'temperature'}).text
        remark = soup.find('p', {'class': 'remark'}).text
        flavor = soup.find('p', {'class': 'flavor'}).text
    except AttributeError:
        return "Could not find weather information."

    remark = re.sub(r"\sfucking", "", remark.lower())  # behave!
    return "%s: %s^C -- %s [%s]" % (place, degrees, remark, flavor)
Exemplo n.º 6
0
def _google_websearch(query):
    '''
    Performs a query to Google Web Search API and returns resulting JSON object.
    '''
    url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s" % urllib2.quote(query)
    response = download(url)
    return json.loads(response)
Exemplo n.º 7
0
    def _resolve_url(self, url):
        """Handle URL being spoken on a channel where the bot is."""
        page_content = download(url)
        if not page_content:
            logging.debug("Could not download URL %s" % url)
            return

        html = BeautifulSoup(page_content)
        if YOUTUBE_URL_RE.match(url):
            return self._handle_youtube_video(html)
        else:
            return self._handle_regular_page(html)
Exemplo n.º 8
0
 def command(self, bot, user, cmd, args):
     if cmd != 'j':    return
     
     if args:
         names = args.split(" ", 2)
         if(len(names) == 1):
             jsonData = download("http://api.icndb.com/jokes/random?firstName=" + names[0] + "&lastName=")
         else:
             jsonData = download("http://api.icndb.com/jokes/random?firstName=" + names[0] + "&lastName=" + names[1])
     else:
         jsonData = download("http://api.icndb.com/jokes/random")
     if not jsonData:
         return "Jokes not available at the moment.";
     data = json.loads(jsonData)
     if not data:
         return "Jokes can not be parsed.";
     
     joke = data["value"]["joke"]
     if not joke:
         return "Joke not found"
     return joke
Exemplo n.º 9
0
def get_wikipage_content(title):
    '''
    Returns raw markup of given Wikipedia page using API call.
    '''
    url = get_wikipage_api_url(title)
    resp = download(url)
    if not resp:    return None
   
    resp = json.loads(resp)
    try:
        pages = resp['query']['pages']
        page = pages.values()[0]
        content = page['revisions'][0].values()[0]
    except (KeyError, AttributeError), _:
        return None
Exemplo n.º 10
0
Arquivo: web.py Projeto: Xion/seejoo
def get_recent_rss_items(url):
    '''
    Retrieves the few most recent items from the given RSS feed.
    '''
    rss = download(url)
    if not rss:
        return "Could not retrieve RSS feed."
    rss_xml = ElementTree.ElementTree(ElementTree.fromstring(rss))

    title = rss_xml._root.find('channel/title').text
    items = [i.text for i in rss_xml._root.findall('channel/item/title')]
    items = items[:MAX_QUERY_RESULTS]

    res = title + " :: "
    res += " | ".join(items)
    return res
Exemplo n.º 11
0
def get_recent_rss_items(url):
    '''
    Retrieves the few most recent items from the given RSS feed.
    '''
    rss = download(url)
    if not rss: return "Could not retrieve RSS feed."
    rss_xml = ElementTree.ElementTree(ElementTree.fromstring(rss))
    
    # Get title of channel and titles of items
    title = rss_xml._root.find('channel/title').text
    items = [i.text for i in rss_xml._root.findall('channel/item/title')]
    items = items[:MAX_QUERY_RESULTS]
    
    # Construct result
    res = title + " :: "
    res += " | ".join(items)
    return res
Exemplo n.º 12
0
    def command(self, bot, user, cmd, args):
        '''
        Called when user issues a command.
        '''
        if cmd == 't':
            
            url = args or self.last_url
            if not url: return "I don't recall anything that looks like an URL."

            # Download the page
            site = download(url)     
            if not site:    return "(Could not retrieve page)"
            
            # Find the title and return it
            m = TITLE_RE.search(site)
            if not m:   return "(Untitled)"
            title = m.group('title')
            return normalize_whitespace(title)
Exemplo n.º 13
0
    def command(self, bot, user, cmd, args):
        '''
        Called when user issues a command.
        '''
        if cmd == 't':

            url = args or self.last_url
            if not url:
                return "I don't recall anything that looks like an URL."

            # Download the page
            site = download(url)
            if not site: return "(Could not retrieve page)"

            # Find the title and return it
            m = TITLE_RE.search(site)
            if not m: return "(Untitled)"
            title = m.group('title')
            return normalize_whitespace(title)
Exemplo n.º 14
0
Arquivo: imdb.py Projeto: Xion/seejoo
    def command(self, bot, channel, user, cmd, args):
        if not args:
            return

        title = ''
        year = ''
        try:
            m = re.search(r"\s+\((\d+)\)", args)
            year = m.group(1) # '2005'

            # Remove year from args
            title = args[:m.start()] + args[m.end():]
        except Exception:
            title = args
            year = ''

        url = API_URL + "?t=%s&y=%s" % (urllib2.quote(title), year)
        json_data = download(url)
        if not json_data:
            return "IMDB not available at the moment."

        try:
            data = json.loads(json_data)
        except ValueError:
            self.error(bot, channel)
            return

        title = data.get("Title")
        if not title:
            return "Could not find specified movie."

        year = data.get("Year")
        genre = data.get("Genre")
        actors = data.get("Actors")
        plot = data.get("Plot")
        country = data.get("Country")
        rating = data.get("imdbRating")
        type = data.get("Type")

        message = ("[{title} ({year}, {country}) {genre}/{type}] "
                   "{rating}/10 - Starring: {actors}: {plot}").format(
                   **locals())
        return message
Exemplo n.º 15
0
Arquivo: chuck.py Projeto: Xion/seejoo
    def command(self, bot, channel, user, cmd, args):
        url = JOKES_URL
        if args:
            names = args.split(None, 1)
            url_params = {'firstName': names[0]}
            if len(names) > 1:
                url_params['lastName'] = names[1]
            url += '?' +  urlencode(url_params)

        jsonData = download(url)
        if not jsonData:
            return "Jokes not available at the moment."

        try:
            data = json.loads(jsonData)
        except ValueError:
            return "Jokes can not be parsed."

        joke = data.get("value", {}).get("joke")
        return joke or "Joke not found."
Exemplo n.º 16
0
def urban_dictionary(term):
    '''
    Looks up given term in urbandictionary.com. Returns the first sentence
    of definition.
    '''
    if not term or len(str(term).strip()) == 0:
        return "No term supplied."
    
    url = "http://www.urbandictionary.com/define.php?term=%s" % urllib2.quote(term)
    ud_site = download(url)
    if not ud_site: return "Could not retrieve definition of '%s'." % term
    
    # Look for definition
    m = UD_DEF_DIV.search(ud_site)
    if m:
        definition = strip_html(m.groupdict().get('def'))
        definition = find_first_sentences(definition, 5)
        if len(definition.strip()) > 0:
            return "'%s': %s" % (term, definition)
    
    return "Could not find definition of '%s'." % term
Exemplo n.º 17
0
    def command(self, bot, channel, user, cmd, args):
        '''
        Called when user issues a command.
        '''
        if not channel:
            return
        if cmd != 't':
            return

        url = args or self.urls.get(channel)
        if not url:
            return "I don't recall anything that looks like an URL."

        site = download(url)
        if not site:
            return "(Could not retrieve page)"

        m = TITLE_RE.search(site)
        if not m:
            return "(Untitled)"
        title = m.group('title')
        return normalize_whitespace(title)
Exemplo n.º 18
0
def fetch_translation(text, target_lang, source_lang=None):
    """Get the translation of given text and return as Translation tuple."""
    url = get_translate_url(text, target_lang, source_lang)

    logging.debug("Fetching translation from URL: %s", url)
    response = unicode(download(url, user_agent=USER_AGENT), 'utf-8')

    # convert the protobuf wire format to something json module can swallow
    while ',,' in response:
        response = response.replace(',,', ',null,')
    data = json.loads(response)[0]

    # read the actual source language, which may have been autodetected
    try:
        source_lang = data[2]
    except IndexError:
        source_lang = source_lang or "?"

    return Translation(
        source_lang=source_lang,
        original_text=data[0][1],
        target_lang=str(target_lang).lower(),
        translated_text=data[0][0],
    )