コード例 #1
0
def wrongsyn(query):
    """
    Exits if query value is empty
    :param query:
    :return:
    """
    if query == "":
        printer.print_warning("Wrong syntax!...\n")
        printer.helpman()
        sys.exit(1)
    else:
        return
コード例 #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)
コード例 #3
0
def main():
    """
    The main logic for how options in a command is checked.
    """
    global query
    namespace = parse_arguments(sys.argv[1:])
    search.load_user_agents()  # Populates the user agents array
    query_tag = ' '.join(namespace.browse)  # Tags

    # Query
    if namespace.query:
        # Query when args are present
        query = ' '.join(namespace.query)
    elif namespace.userQuery:
        # Query without any args
        query = ' '.join(namespace.userQuery)

    if namespace.help:
        # Display command line syntax
        printer.helpman()
        sys.exit(0)

    if namespace.debug:  # If --debug flag is present
        # Prints out error used for debugging
        printer.DEBUG = True
        debug_requests_on()

    if namespace.new:  # If --new flag is present
        # Opens StackOverflow website in the browser to create a  new question
        import webbrowser
        printer.print_warning("Opening stack overflow in your browser...")
        webbrowser.open(search.so_url + "/questions/ask")
        sys.exit(0)

    if namespace.api:  # If --api flag is present
        # Sets custom API key
        user_module.set_api_key()
        sys.exit(0)

    if namespace.user is not None:  # If --user flag is present
        # Stackoverflow user profile support
        if namespace.user != '(RANDOM_STRING_CONSTANT)':  # If user provided a user ID
            user_module.manual = 1  # Enabling manual mode
            user = namespace.user
        else:  # If user did not provide a user id
            user = user_module.retrieve_saved_profile()  # Reading saved user id from app data
        user_module.user_page(user)
        sys.exit(0)

    if namespace.delete:  # If --delete flag is present
        # Deletes user data
        user_module.del_datafile()
        printer.print_warning("Data files deleted...")
        sys.exit(0)

    if namespace.sosearch:  # If --sosearch flag is present
        # Disables google search
        search.google_search = False

    if namespace.tag:  # If --tag flag is present
        global tag
        search.google_search = False
        tag = namespace.tag
        has_tags()  # Adds tags to StackOverflow url (when not using google search.
    if namespace.open_url:
        import webbrowser
        open_in_browser=False
        display_condition=True
        url_to_use=namespace.open_url[0]
        if re.findall(r"^https:\/\/",url_to_use) !=[]:
            pass
        else:
            url_to_use="https://" + url_to_use
        try:
            if url_to_use == "https://stackoverflow.com/questions/":
                raise Exception('URL Error')
            if url_to_use == "https://www.stackoverflow.com/questions/":
                raise Exception('URL Error')
            requests.get(url_to_use)
        except Exception:
            printer.print_warning("Error, could be:\n- invalid url\n- url cannot be opened in socli\n- internet connection error")
            sys.exit(0)
        nostackoverflow=re.findall(r"stackoverflow\.com",url_to_use)
        if nostackoverflow == []:
            open_in_browser=True
            display_condition=False
            printer.print_warning("Your url is not a stack overflow url.\nOpening in your browser...")
        tag_matcher=re.findall(r"\/tag.+\/",url_to_use)
        blog_matcher=re.findall(r"blog",url_to_use)
        if tag_matcher != []:
            extracted_tag=""
            if re.findall(r"tagged",url_to_use) == []:
                extracted_tag=re.split(r"\/",url_to_use)[4]
            else:
                extracted_tag=re.split(r"\/",url_to_use)[5]
            open_in_browser=False
            display_condition=False
            tag=extracted_tag
            search.socli_interactive(tag)
        if blog_matcher != []:
            open_in_browser=True
            display_condition=False
            printer.print_warning("Your url belongs to blog")
            printer.print_warning("Opening in browser...")
        if display_condition:
            open_in_browser=False
            display_results(url_to_use)
        if open_in_browser:
            webbrowser.open(url_to_use)
    if namespace.res is not None:  # If --res flag is present
        # Automatically displays the result specified by the number
        question_number = namespace.res
        if namespace.query != [] or namespace.tag is not None:  # There must either be a tag or a query
            search.socli_manual_search(query, question_number)
        else:
            printer.print_warning('You must specify a query or a tag. For example, use: "socli -r 3 -q python for loop" '
                             'to retrieve the third result when searching about "python for loop". '
                             'You can also use "socli -r 3 -t python" '
                             'to retrieve the third result when searching for posts with the "python" tag.')

    if namespace.browse:
        # Browse mode
        search.google_search = False
        socli_browse_interactive(query_tag)
    elif namespace.query != [] or namespace.tag is not None:  # If query and tag are not both empty
        if namespace.interactive:
            search.socli_interactive(query)
        else:
            socli(query)
    elif query not in [' ', ''] and not (
            namespace.tag or namespace.res or namespace.interactive or namespace.browse):  # If there are no flags
        socli(query)
    else:
        # Help text for interactive mode
        if namespace.interactive and namespace.query == [] and namespace.tag is None:
            printer.print_warning('You must specify a query or a tag. For example, use: "socli -iq python for loop" '
                             'to search about "python for loop" in interactive mode. '
                             'You can also use "socli -it python" '
                             'to search posts with the "python" tag in interactive mode.')
        else:
            printer.helpman()
コード例 #4
0
ファイル: socli.py プロジェクト: therajdeepbiswas/socli
def main():
    """
    The main logic for how options in a command is checked.
    """
    global query
    namespace = parse_arguments(sys.argv[1:])
    search.load_user_agents()  # Populates the user agents array
    query_tag = ' '.join(namespace.browse)  # Tags

    # Query
    if namespace.query:
        # Query when args are present
        query = ' '.join(namespace.query)
    elif namespace.userQuery:
        # Query without any args
        query = ' '.join(namespace.userQuery)

    if namespace.help:
        # Display command line syntax
        printer.helpman()
        sys.exit(0)

    if namespace.debug:  # If --debug flag is present
        # Prints out error used for debugging
        printer.DEBUG = True
        debug_requests_on()

    if namespace.new:  # If --new flag is present
        # Opens StackOverflow website in the browser to create a  new question
        import webbrowser
        printer.print_warning("Opening stack overflow in your browser...")
        webbrowser.open(search.so_url + "/questions/ask")
        sys.exit(0)

    if namespace.api:  # If --api flag is present
        # Sets custom API key
        user_module.set_api_key()
        sys.exit(0)

    if namespace.user is not None:  # If --user flag is present
        # Stackoverflow user profile support
        if namespace.user != '(RANDOM_STRING_CONSTANT)':  # If user provided a user ID
            user_module.manual = 1  # Enabling manual mode
            user = namespace.user
        else:  # If user did not provide a user id
            user = user_module.retrieve_saved_profile(
            )  # Reading saved user id from app data
        user_module.user_page(user)
        sys.exit(0)

    if namespace.delete:  # If --delete flag is present
        # Deletes user data
        user_module.del_datafile()
        printer.print_warning("Data files deleted...")
        sys.exit(0)

    if namespace.sosearch:  # If --sosearch flag is present
        # Disables google search
        search.google_search = False

    if namespace.tag:  # If --tag flag is present
        global tag
        search.google_search = False
        tag = namespace.tag
        has_tags(
        )  # Adds tags to StackOverflow url (when not using google search.

    if namespace.res is not None:  # If --res flag is present
        # Automatically displays the result specified by the number
        question_number = namespace.res
        if namespace.query != [] or namespace.tag is not None:  # There must either be a tag or a query
            search.socli_manual_search(query, question_number)
        else:
            printer.print_warning(
                'You must specify a query or a tag. For example, use: "socli -r 3 -q python for loop" '
                'to retrieve the third result when searching about "python for loop". '
                'You can also use "socli -r 3 -t python" '
                'to retrieve the third result when searching for posts with the "python" tag.'
            )

    if namespace.browse:
        # Browse mode
        search.google_search = False
        socli_browse_interactive(query_tag)
    elif namespace.query != [] or namespace.tag is not None:  # If query and tag are not both empty
        if namespace.interactive:
            search.socli_interactive(query)
        else:
            socli(query)
    elif query not in [
            ' ', ''
    ] and not (namespace.tag or namespace.res or namespace.interactive
               or namespace.browse):  # If there are no flags
        socli(query)
    else:
        # Help text for interactive mode
        if namespace.interactive and namespace.query == [] and namespace.tag is None:
            printer.print_warning(
                'You must specify a query or a tag. For example, use: "socli -iq python for loop" '
                'to search about "python for loop" in interactive mode. '
                'You can also use "socli -it python" '
                'to search posts with the "python" tag in interactive mode.')
        else:
            printer.helpman()