Exemplo n.º 1
0
def socli_browse_interactive_windows(query_tag):
    """
    Interactive mode for -b browse
    :param query_tag:
    :return:
    """
    try:
        search_res = requests.get(search.so_burl + query_tag)
        search.captcha_check(search_res.url)
        soup = BeautifulSoup(search_res.text, 'html.parser')
        try:
            soup.find_all("div", class_="question-summary")[0]  # For explicitly raising exception
            tmp = (soup.find_all("div", class_="question-summary"))
            i = 0
            question_local_url = []
            print(printer.bold("\nSelect a question below:\n"))
            while i < len(tmp):
                if i == 10:
                    break  # limiting results
                question_text = ' '.join((tmp[i].a.get_text()).split())
                question_text = question_text.replace("Q: ", "")
                printer.print_warning(str(i + 1) + ". " + printer.display_str(question_text))
                q_tag = (soup.find_all("div", class_="question-summary"))[i]
                answers = [s.get_text() for s in q_tag.find_all("a", class_="post-tag")][0:]
                ques_tags = " ".join(str(x) for x in answers)
                question_local_url.append(tmp[i].a.get("href"))
                print("  " + printer.display_str(ques_tags) + "\n")
                i = i + 1
            try:
                op = int(printer.inputs("\nType the option no to continue or any other key to exit:"))
                while 1:
                    if (op > 0) and (op <= i):
                        display_results(search.so_burl + question_local_url[op - 1])
                        cnt = 1  # this is because the 1st post is the question itself
                        while 1:
                            global tmpsoup
                            qna = printer.inputs(
                                "Type " + printer.bold("o") + " to open in browser, " + printer.bold(
                                    "n") + " to next answer, " + printer.bold(
                                    "b") + " for previous answer or any other key to exit:")
                            if qna in ["n", "N"]:
                                try:
                                    answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt + 1].get_text())
                                    printer.print_green("\n\nAnswer:\n")
                                    print("-------\n" + answer + "\n-------\n")
                                    cnt = cnt + 1
                                except IndexError:
                                    printer.print_warning(" No more answers found for this question. Exiting...")
                                    sys.exit(0)
                                continue
                            elif qna in ["b", "B"]:
                                if cnt == 1:
                                    printer.print_warning(" You cant go further back. You are on the first answer!")
                                    continue
                                answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt - 1].get_text())
                                printer.print_green("\n\nAnswer:\n")
                                print("-------\n" + answer + "\n-------\n")
                                cnt = cnt - 1
                                continue
                            elif qna in ["o", "O"]:
                                import webbrowser
                                printer.print_warning("Opening in your browser...")
                                webbrowser.open(search.so_burl + question_local_url[op - 1])
                            else:
                                break
                        sys.exit(0)
                    else:
                        op = int(input("\n\nWrong option. select the option no to continue:"))
            except Exception as e:
                printer.showerror(e)
                printer.print_warning("\n Exiting...")
                sys.exit(0)
        except IndexError:
            printer.print_warning("No results found...")
            sys.exit(0)

    except UnicodeEncodeError:
        printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
        sys.exit(0)
    except requests.exceptions.ConnectionError:
        printer.print_fail("Please check your internet connectivity...")
    except Exception as e:
        printer.showerror(e)
        sys.exit(0)
Exemplo n.º 2
0
def user_page(user_id):
    """
    Stack Overflow user profile browsing
    :param user_id:
    :return:
    """
    global app_data
    import stackexchange

    try:
        user_id = int(user_id)
    except ValueError:
        pr.print_warning("\nUser ID must be an integer.")
        print(
            "\nFollow the instructions on this page to get your User ID: http://meta.stackexchange.com/a/111130")
        exit(1)

    try:
        from urllib.error import URLError
    except ImportError:
        from urllib import URLError
    try:
        user_id = int(user_id)
    except ValueError:
        pr.print_warning("\nUser ID must be an integer.")
        print(
            "\nFollow the instructions on this page to get your User ID: http://meta.stackexchange.com/a/111130")
        exit(1)

    try:
        if "api_key" not in app_data:
            app_data["api_key"] = None
        userprofile = stackexchange.Site(stackexchange.StackOverflow, app_key=app_data["api_key"]).user(user_id)
        print(pr.bold("\n User: "******"\n\tReputations: " + userprofile.reputation.format())
        pr.print_warning("\n\tBadges:")
        print("\t\t   Gold: " + str(userprofile.gold_badges))
        print("\t\t Silver: " + str(userprofile.silver_badges))
        print("\t\t Bronze: " + str(userprofile.bronze_badges))
        print("\t\t  Total: " + str(userprofile.badge_total))
        pr.print_warning("\n\tStats:")
        total_questions = len(userprofile.questions.fetch())
        unaccepted_questions = len(userprofile.unaccepted_questions.fetch())
        accepted = total_questions - unaccepted_questions
        rate = accepted / float(total_questions) * 100
        print("\t\t Total Questions Asked: " + str(len(userprofile.questions.fetch())))
        print('\t\t        Accept rate is: %.2f%%.' % rate)
        # check if the user have answers and questions or no.
        if userprofile.top_answer_tags.fetch():
            print('\nMost experienced on %s.' % userprofile.top_answer_tags.fetch()[0].tag_name)
        else:
            print("You have 0 answers")
        if userprofile.top_question_tags.fetch():
            print('Most curious about %s.' % userprofile.top_question_tags.fetch()[0].tag_name)
        else:
            print("You have 0 questions")
    except URLError:
        pr.print_fail("Please check your internet connectivity...")
        exit(1)
    except Exception as e:
        pr.showerror(e)
        if str(e) == "400 [bad_parameter]: `key` doesn't match a known application":
            pr.print_warning("Wrong API key... Deleting the data file...")
            del_datafile()
            exit(1)
        elif str(e) in ("not enough values to unpack (expected 1, got 0)", "400 [bad_parameter]: ids"):
            global manual
            if manual == 1:
                pr.print_warning("Wrong user ID specified...")
                pr.helpman()
                exit(1)
            pr.print_warning("Wrong user ID... Deleting the data file...")
            del_datafile()
            exit(1)

        # Reaches here when rate limit exceeds
        pr.print_warning(
            "Stack Overflow exception. This might be caused due to the rate limiting: "
            "http://stackapps.com/questions/3055/is-there-a-limit-of-api-requests")
        print("Use http://stackapps.com/apps/oauth/register to register a new API key.")
        set_api_key()
        exit(1)