Пример #1
0
 def stocks(self, command=None):
     #https://api.iextrading.com/1.0/stock/aapl/quote
     if command:
         symbols = command.command_args
         if symbols:
             symbols = re.split(",", symbols)
             messages = []
             for symbol in symbols:
                 request.get(
                     self,
                     uri="https://api.iextrading.com/1.0/stock/{}/quote".
                     format(symbol))
                 if self.success:
                     messages.append(
                         "{} - Price: ${} | Open: ${} | Low: ${} | High: ${} | Percent change: {}%"
                         .format(
                             self.response["symbol"],
                             self.response["delayedPrice"],
                             self.response["open"],
                             self.response["high"],
                             self.response["low"],
                             self.response["changePercent"],
                         ))
                 else:
                     messages.append("Symbol {} not found".format(symbol))
             utils.make_success(command, content=messages)
         else:
             utils.make_error(command,
                              content=[
                                  "No symbols specified.",
                                  "Usage: {}".format(
                                      command.command["usage"])
                              ])
     else:
         utils.make_error(command, content="An unknown error has occurred.")
Пример #2
0
    def weather(self, command=None):
        if command:
            location = command.command_args
            if location:
                uri = "https://query.yahooapis.com/v1/public/yql?format=json&q=select woeid from geo.places where text='{}' limit 1".format(
                    location)
                request.get(self, uri=uri)
                if self.success:
                    woeid = self.response["query"]["results"]["place"]["woeid"]
                    uri = "https://query.yahooapis.com/v1/public/yql?format=json&q=select * from weather.forecast where woeid={}".format(
                        woeid)
                    request.get(self, uri=uri)
                    if self.success:
                        max_forecast_days = 5
                        messages = []
                        condition = self.response["query"]["results"][
                            "channel"]["item"]["condition"]
                        current_condition = condition["text"]
                        current_f = condition["temp"]
                        current_c = utils.farenheit_to_celsius(current_f)

                        messages.append("Currently {}°F ({}°C) and {}.".format(
                            current_f, int(current_c), current_condition))
                        forecast = self.response["query"]["results"][
                            "channel"]["item"]["forecast"]
                        num_days = len(forecast) if len(
                            forecast) >= max_forecast_days else len(forecast)
                        for i, daily_forecast in enumerate(forecast):
                            if i == 0:
                                daily_forecast["date"] += " (Today)"

                            if i <= (max_forecast_days - 1):
                                high_f = daily_forecast["high"]
                                high_c = utils.farenheit_to_celsius(high_f)
                                low_f = daily_forecast["low"]
                                low_c = utils.farenheit_to_celsius(low_f)
                                messages.append(
                                    "{} - High: {}°F ({}°C) | Low: {}°F ({}°C)"
                                    .format(daily_forecast["date"], high_f,
                                            int(high_c), low_f, int(low_c)))
                        utils.make_success(command, content=messages)
                    else:
                        utils.make_error(command,
                                         "Failed to fetch weather data.")
                else:
                    utils.make_error(
                        command,
                        "Could not find the WOEID for {}.".format(location))
            else:
                utils.make_error(command,
                                 content=[
                                     "No location specified.",
                                     "Usage: {}".format(
                                         command.command["usage"])
                                 ])
        else:
            utils.make_error(command, content="An unknown error has occurred.")
Пример #3
0
 def tiny(self, command=None):
     if command:
         if self.bitly_key:
             if url:
                 url = command.command_args
                 url = re.sub("^\<", "", url)
                 url = re.sub("\>$", "", url)
                 if utils.validate_url(url) == True:
                     uri = "https://api-ssl.bitly.com/v3/shorten?access_token={}&longUrl={}".format(
                         self.bitly_key, url)
                     request.get(self, uri=uri)
                     if self.success:
                         if "status_code" in self.response:
                             if self.response["status_code"] == 200:
                                 if self.response["status_txt"].lower(
                                 ) == "ok":
                                     utils.make_success(
                                         command,
                                         content=self.response["data"]
                                         ["url"])
                                 elif self.response["status_txt"].lower(
                                 ) == "already_a_bitly_link":
                                     utils.make_error(
                                         command,
                                         content=
                                         "You cannot shorten a shortened link."
                                     )
                                 else:
                                     utils.make_error(
                                         command,
                                         content=
                                         "The URL shortener returned an error: {}."
                                         .format(
                                             self.response["status_txt"]))
                     else:
                         utils.make_error(
                             command,
                             content="An unknown error has occurred.")
                 else:
                     utils.make_error(
                         command, content="You specified an invalid URL.")
             else:
                 utils.make_error(command,
                                  content=[
                                      "No URL specified.",
                                      "Usage: {}".format(
                                          command.command["usage"])
                                  ])
         else:
             utils.make_error(
                 command,
                 content="Cannot perform the command at this time.")
     else:
         utils.make_error(command, content="An unknown error has occurred.")
Пример #4
0
 def __tiny_url(self, url=None):
     if self.bitly_key:
         uri = "https://api-ssl.bitly.com/v3/shorten?access_token={}&longUrl={}".format(
             self.bitly_key, url)
         request.get(self, uri=uri)
         if self.success:
             if "status_code" in self.response:
                 if self.response["status_code"] == 200:
                     if self.response["status_txt"].lower() == "ok":
                         return self.response["data"]["url"]
         else:
             pprint(self.response)
             return url
     else:
         return url
Пример #5
0
 def udict(self, command=None):
     if command:
         phrase = command.command_args
         if phrase:
             uri = "http://api.urbandictionary.com/v0/define?term={}".format(
                 phrase)
             request.get(self, uri=uri)
             if self.success:
                 if "list" in self.response:
                     if len(self.response["list"]) > 0:
                         utils.make_success(
                             command,
                             content="{}: {}".format(
                                 phrase,
                                 self.response["list"][0]["definition"]))
                     else:
                         utils.make_error(
                             command,
                             content=
                             "Definition for {} not found on Urban Dictionary."
                             .format(phrase))
                 else:
                     utils.make_error(
                         command,
                         content=
                         "Definition for {} not found on Urban Dictionary.".
                         format(phrase))
             else:
                 utils.make_error(
                     command,
                     content=
                     "Definition for {} not found on Urban Dictionary.".
                     format(phrase))
         else:
             utils.make_error(command,
                              content=[
                                  "No phrase specified.",
                                  "Usage: {}".format(
                                      command.command["usage"])
                              ])
     else:
         utils.make_error(command, content="An unknown error has occurred.")
Пример #6
0
 def dict(self, command=None):
     if command:
         if self.wordnik_key:
             word = command.command_args
             if word:
                 limit = 3
                 uri = "http://api.wordnik.com/v4/word.json/{}/definitions?api_key={}&includeRelated=false&includeTags=false&limit={}&sourceDictionaries=all&useCanonical=false".format(
                     word, self.wordnik_key, limit)
                 request.get(self, uri=uri)
                 if self.success:
                     if len(self.response["body"]) > 0:
                         messages = []
                         for d in self.response["body"]:
                             messages.append("{}: {}: {}".format(
                                 word, d["partOfSpeech"], d["text"]))
                         utils.make_success(command, content=messages)
                     else:
                         utils.make_error(
                             command,
                             content=
                             "Unable to fetch the dictionary definition.")
                 else:
                     utils.make_error(
                         command,
                         content="Unable to fetch the dictionary definition."
                     )
             else:
                 utils.make_error(command,
                                  content=[
                                      "No word specified.",
                                      "Usage: {}".format(
                                          command.command["usage"])
                                  ])
         else:
             utils.make_error(
                 command,
                 content="Cannot perform the command at this time.")
     else:
         utils.make_error(command, content="An unknown error has occurred.")
Пример #7
0
    def zip(self, command=None):
        if command:
            if self.geonames_key:
                opts = command.command_args
                if opts:
                    state = None
                    bits = re.split(r"\s*,\s*", str(opts))
                    if len(bits) == 3:
                        (city, state, country) = bits
                        if country.lower() != "us":
                            utils.make_error(
                                command,
                                content=
                                "You may only specify a state when the country is US."
                            )
                            return
                    elif len(bits) == 2:
                        (city, country) = bits
                    else:
                        utils.make_error(
                            command,
                            content=
                            "You must minimally specify country and city.")
                        return

                    zips = []
                    batch_size = 32
                    uri = "http://api.geonames.org/postalCodeSearchJSON?placename={}&country={}&username={}&maxRows=200".format(
                        city, country, self.geonames_key)
                    request.get(self, uri=uri)
                    if self.success:
                        if "postalCodes" in self.response:
                            if len(self.response["postalCodes"]) > 0:
                                if state:
                                    zips = [
                                        x["postalCode"]
                                        for x in self.response["postalCodes"]
                                        if state.lower() ==
                                        x["adminCode1"].lower()
                                    ]
                                else:
                                    zips = [
                                        x["postalCode"]
                                        for x in self.response["postalCodes"]
                                    ]
                                utils.make_success(command,
                                                   content=", ".join(
                                                       sorted(zips)))
                            else:
                                utils.make_error(
                                    command,
                                    content=
                                    "Location not found in postal code data.")
                        else:
                            utils.make_error(
                                command,
                                content="Failed to fetch postal code data.")
                    else:
                        utils.make_error(
                            command,
                            content="Failed to fetch postal code data.")
                else:
                    utils.make_error(command,
                                     content=[
                                         "No location specified.",
                                         "Usage: {}".format(
                                             command.command["usage"])
                                     ])
            else:
                utils.make_error(
                    command,
                    content="Cannot perform the command at this time.")
        else:
            utils.make_error(command, content="An unknown error has occurred.")
Пример #8
0
    def yelp(self, command=None):
        if command:
            if self.yelp_key:
                sys.argv = command.argv
                try:
                    args = self.yelp_parser.parse_args()
                except:
                    utils.make_error(
                        command,
                        content=[
                            "Invalid input received.",
                            self.yelp_parser.format_help().rstrip()
                        ])
                    return

                # I need to make a Yelp module
                qs = {}
                qs["term"] = args.term
                qs["location"] = args.location
                if args.categories: qs["categories"] = args.categories
                if args.price:
                    price_map = {"$": "1", "$$": "2", "$$$": "3", "$$$$": "4"}
                    qs["price"] = ",".join([
                        price_map[p] for p in re.split(r"\s*,\s*", args.price)
                    ])

                self.response = {}
                uri = "https://api.yelp.com/v3/businesses/search?{}".format(
                    "&".join([urlencode({k: str(v)}) for k, v in qs.items()]))
                headers = {"Authorization": "Bearer {}".format(self.yelp_key)}
                request.get(self, uri=uri, extra_headers=headers)
                if self.success:
                    rating = float(args.rating) if args.rating else 1.0
                    results = [
                        b for b in self.response["businesses"]
                        if b["rating"] >= rating
                    ]
                    if len(results) > 0:
                        messages = []
                        formatter = "{:30}{:18}{:50}{:<10}{:<8}{:8}{:25}"
                        header = formatter.format("Name", "Phone", "Address",
                                                  "Reviews", "Rating", "Price",
                                                  "Yelp URL")
                        divider = "=" * len(header)
                        messages.append(header)
                        messages.append(divider)
                        for business in results:
                            messages.append(
                                formatter.format(
                                    business["name"][0:27],
                                    business["display_phone"],
                                    ", ".join(business["location"]
                                              ["display_address"])[0:47],
                                    business["review_count"],
                                    business["rating"],
                                    business["price"],
                                    self.__tiny_url(url=business["url"]),
                                ))
                        utils.make_success(command, content=messages)
                    else:
                        utils.make_success(
                            command,
                            content=
                            "No results found matching the specified criteria."
                        )
                else:
                    self.bot.logger.error(pformat(self.response))
                    utils.make_error(
                        command,
                        content="An error occurred while connecting to Yelp.")
            else:
                utils.make_error(
                    command,
                    content="Cannot perform the command at this time.")
        else:
            utils.make_error(command, content="An unknown error has occurred.")
Пример #9
0
    def currency(self, command=None):
        # List all currencies
        # https://free.currencyconverterapi.com/api/v5/currencies
        # Compact output
        # https://free.currencyconverterapi.com/api/v5/convert?q=USD_PHP&compact=y
        # Compact more
        # https://free.currencyconverterapi.com/api/v5/convert?q=USD_PHP&compact=ultra
        if command:
            sys.argv = command.argv
            try:
                args = self.currency_parser.parse_args()
            except:
                utils.make_error(
                    command,
                    content=[
                        "Invalid input received.",
                        self.currency_parser.format_usage().rstrip()
                    ])
                return

            from_symbol = getattr(args, "from").upper()
            to_symbol = getattr(args, "to").upper()
            from_amount = args.amount

            if re.search("^[A-Za-z]{3}$", from_symbol):
                from_symbol = from_symbol
            else:
                fs = db.get_currency_symbol(nation=from_symbol)
                if fs:
                    from_symbol = fs["symbol"]
                else:
                    utils.make_error(
                        command,
                        content="Could not find the currency symbol for {}.".
                        format(from_symbol))
                    return

            if re.search("^[A-Za-z]{3}$", to_symbol):
                to_symbol = to_symbol
            else:
                fs = db.get_currency_symbol(nation=to_symbol)
                if fs:
                    to_symbol = fs["symbol"]
                else:
                    utils.make_error(
                        command,
                        content="Could not find the currency symbol for {}.".
                        format(from_symbol))
                    return

            conversion = "{}_{}".format(from_symbol, to_symbol)
            uri = "http://free.currencyconverterapi.com/api/v5/convert?q={}&compact=ultra".format(
                conversion)
            request.get(self, uri=uri)
            if self.success:
                if conversion in self.response:
                    to_amount = float(from_amount) * float(
                        self.response[conversion])
                    utils.make_success(command,
                                       content="{:.2f} {} = {:.2f} {}".format(
                                           float(from_amount),
                                           from_symbol,
                                           float(to_amount),
                                           to_symbol,
                                       ))
                else:
                    utils.make_error(command,
                                     content="Failed to convert the currency.")
            else:
                utils.make_error(command,
                                 content="Failed to convert the currency.")
        else:
            utils.make_error(command, content="An unknown error has occurred.")