Ejemplo n.º 1
0
def check_lender_count(lender,verbose=False):
        ''' (str,[bool]) -> int
        
        Returns total loan count for passed lender id.
        '''
        lender_url = "http://api.kivaws.org/v1/lenders/" + lender + ".json?app_id=" + app_id
        global total_loans
        try:
                if verbose:
                    print "Getting lender loan count: %s" % lender_url
                f = urllib.urlopen(lender_url)
                rate.get_rate(f)
                d = json.loads(f.read())
                total_loans = int(d["lenders"][0]["loan_count"])
        except:
                rate.get_rate(f, True)
                if d["message"]:
                    print d["message"]
                else:
                    print "Error loading lender page. Confirm your ID at http://www.kiva.org/myLenderId"
                exit(1)
        return total_loans
Ejemplo n.º 2
0
def find_loans(code,verbose=True):
    ''' (str) -> bool
        
    Return True if at least one new country is found.
        
    '''
    search_url = "http://api.kivaws.org/v1/loans/search.json?app_id=" + app_id + "&status=fundraising&country_code="
    loans_found = False
    loans = -1
    url = search_url + code
    if verbose:
        if 'GATEWAY_INTERFACE' not in environ:
            print "Checking url: %s" % url
        else:
            if ',' not in code:
                print 'Checking <a href="%s" target=_top>%s</a>' % (url,country_codes[code])
            else:
                print 'Checking <a href="%s" target=_top>%s</a>' % (url,code)
    try:   
        f = urllib.urlopen(url)
        rate.get_rate(f)
        d = json.loads(f.read())
        if d["paging"]["total"] > 0:
            loans = d["paging"]["total"]
    except:
        rate.get_rate(f, True)
        if d["message"]:
            print d["message"]
        else:
            print "Error loading loans for %s. Try again later." % code    
        exit(1)
    if loans > 0:
        if verbose and len(code) < 3:
            print "Found %s loans for country %s" % (loans, country_codes[code])
        loans_found = True
    return loans_found
Ejemplo n.º 3
0
def send_text(message):
    if message.text.lower() == 'развлечения':
        bot.send_message(message.chat.id, 'В данный момент я могу скидывать мемы и информацию о доте', reply_markup=fun_keyboard)
    elif message.text.lower() == 'мем':
        send_mem(message.chat.id, get_random_meme())
    elif message.text.lower() == 'что происходит?':
        bot.send_message(message.chat.id, 'Ты можешь узнать курсы валют, прогноз погоды и информацию о Covid-19', reply_markup=news_keyboard)
    elif message.text.lower() == 'что с рублем?':
        bot.send_message(message.chat.id, get_rate(), reply_markup=main_keyboard)
    elif message.text.lower() == 'погода':
        bot.send_message(message.chat.id, 'Напиши свой город', reply_markup=city_keyboard)
        bot.register_next_step_handler(message, choice_city)
    elif message.text.lower() == 'расскажи о себе':
        bot.send_message(message.chat.id, 'Привет, я могу скидывать мемы. Так же у меня можно узнать актуальные новости и посмотреть какого героя выбрать в доте!')
    elif message.text.lower() == 'дота':
        bot.send_message(message.chat.id, 'Напиши имя героя', reply_markup=dota_keyboard)
        bot.register_next_step_handler(message, choice_dota)
    elif message.text.lower() == 'covid-19':
        bot.send_message(message.chat.id, 'Выбери страну', reply_markup=covid_keyboard)
        bot.register_next_step_handler(message, choice_country)
    else:
        bot.send_message(message.chat.id, 'Не понимаю!')
Ejemplo n.º 4
0
def fetch_old_loans(lender,private=False,verbose=False):
        ''' (str,[bool],[bool]) -> dict,dict

        Polls Kiva API for lender, gathering loan count per country.

        Returns dict of country codes lent to and count. Returns dict of country codes and countries not lent to.

        '''
        global my_countries
        global not_loaned
        global total_loans
        global loan_count
        page = (loan_count//20) # Starting page number
        if page == 0:
            page = 1 # There is no page 0.
        pages = page # Starting limit, this will update after the first call.
        # Since we're starting part way through the list, the newest loans should always be at the end...
        lender_url = "http://api.kivaws.org/v1/lenders/" + lender + "/loans.json?app_id=" + app_id + "&sort_by=oldest&page="

        while page <= pages and loan_count != total_loans:
                url = lender_url + str(page)
                try:
                        if verbose:
                            print "Collecting previous loan data from page: %s" % page
                        f = urllib.urlopen(url)
                        d = json.loads(f.read())
                        pages = d["paging"]["pages"]
                except:
                        rate.get_rate(f, True)
                        if d["message"]:
                            print d["message"]
                        else:
                            print "Error loading lender page. Confirm your ID at http://www.kiva.org/myLenderId"
                        exit(1)


                for x in d["loans"]:
                        code = x["location"]["country_code"].encode('ascii','ignore')
                        loan_id = int(x["id"])
                        if code not in my_countries:
                            if verbose:
                                print "Adding country: %s" % code
                            my_countries[code] = []
                            my_countries[code].append(loan_id)
                        elif loan_id not in my_countries[code]:
                            if verbose:
                                print "Adding loan_id: %s" % loan_id
                            my_countries[code].append(loan_id)
                        else:
                            if verbose:
                                print "Loan already tracked: %s" % loan_id                            
                            
                        if code in not_loaned:
                            del not_loaned[code]
                page += 1

                # Keep track of current loan count so we know when to stop calling the api.
                counter = 0
                for code in my_countries:
                    counter += len(my_countries[code])
                loan_count = counter
                    
                # Leave some breathing room on the api rate limit.
                rate_remaining,rate_limit = rate.get_rate(f)
                if rate_remaining <= rate_limit/10:
                    print "Warning: Approaching API rate limit. Exiting."
                    if not private:
                        write_lender_file(lender)
                    exit(1)
                    
        if not private:
            write_lender_file(lender)
        if verbose:
            if loan_count != total_loans:
                print "Error loading old loans! Loan counts don't match! %s vs %s" % (total_loans,loan_count)
        return my_countries, not_loaned