Ejemplo n.º 1
0
def init_db(cookies):
    if cookies is not None:
        c.check_type(cookies, 'cookies', str)

    # login in with cookies file
    if cookies:
        author = ZhihuClient(cookies=cookies).me()
    # login in terminal
    else:
        client = ZhihuClient()

        try:
            cookies = client.login_in_terminal()
        except KeyboardInterrupt:
            print()
            cookies = ''

        if not cookies:
            L.error(s.log_login_failed)
            L.info(s.exit)
            exit(0)

        author = client.me()

    try:
        conn = db.create_db(author)
        db.create_table(conn)
        db.dump_init_data_to_db(conn, author)
        db.close_db(conn)
        print(s.success)
    except FileExistsError as e:
        L.error(s.file_exist.format(e.filename))
        print(s.failed)
Ejemplo n.º 2
0
def set_config(my_app):

    ensure_dir(CONFIG_PATH)
    try:
        with open(CONFIG_PATH, 'r') as f:
            data = f.readline()
            if data:
                try:
                    config = json.loads(data)
                except ValueError:
                    return

    except FileNotFoundError:  # first run or delete config file
        with open(CONFIG_PATH, 'w'):
            pass

    if data:
        if config["is_sign"] and config["is_sign"] is not str or list:
            try:
                with open(COOKIES_PATH, 'r') as f:
                    FeedsList.client = ZhihuClient(COOKIES_PATH)
                    Noticer.client = ZhihuClient(COOKIES_PATH)
            except FileNotFoundError:  # first run or delete config file
                with open(CONFIG_PATH, 'w'):
                    pass
        else:
            FeedsList.client = ZhihuClient()
            Noticer.client = ZhihuClient()
        if config["proxy"]:
            FeedsList.client.set_proxy(config["proxy"])
            Noticer.client.set_proxy(config["proxy"])
Ejemplo n.º 3
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import re
from zhihu import ZhihuClient

Cookies_File = 'cookies.json'
client = ZhihuClient(Cookies_File)

# url = 'http://www.zhihu.com/people/excited-vczh'
# author = client.author(url)
#
# print('用户名 %s' % author.name)
# print('用户简介 %s' % author.motto)
# print('用户关注人数 %d' % author.followee_num)
# print('取用户粉丝数 %d' % author.follower_num)
# print('用户得到赞同数 %d' % author.upvote_num)
# print('用户得到感谢数 %d' % author.thank_num)
# print('用户提问数 %d' % author.question_num)
# print('用户答题数 %d' % author.answer_num)
#
# print('用户专栏文章数 %d,名称分别为:' % author.post_num)
# for column in author.columns:
#   print(column.name)
# print('用户收藏夹数 %d,名称分别为:' % author.collection_num)
# for collection in author.collections:
#   print(collection.name)

# author = client.author('http://www.zhihu.com/people/excited-vczh')
# for act in author.activities:
#    if act.type == client.ActType.UPVOTE_ANSWER:
Ejemplo n.º 4
0
from zhihu import ZhihuClient
ZhihuClient().create_cookies('cookies.json',
                             need_captcha=False,
                             use_getpass=False)
Ejemplo n.º 5
0
    def run(self, database, msg, interval, log_file, max_old=10):
        c.check_type(database, 'database', str)

        L = logging.getLogger('qqqfome-backend')
        formatter = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(message)s')
        fh = logging.FileHandler(log_file)
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        sh.setFormatter(formatter)
        L.setLevel(logging.DEBUG)
        L.addHandler(fh)
        L.addHandler(sh)

        try:
            L.info(s.log_connected_to_db.format(database))
            conn = db.connect_db(database)
            L.info(s.success)
        except FileNotFoundError:
            L.exception(s.log_file_not_exist.format(database))
            L.info(s.exit)
            return

        # get cookies from database
        cookies = db.get_cookies(conn)

        if not cookies:
            L.exception(s.log_no_cookies_in_database)
            L.info(s.exit)
            return

        L.info(s.log_get_cookies_from_database)
        L.debug(cookies)

        try:
            client = ZhihuClient(cookies)
            L.info(s.log_build_zhihu_client)
        except Exception as e:
            L.exception(e)
            return

        while True:
            L.info(s.log_start_a_pass)

            i = 0
            while i < 5:
                try:
                    L.info(s.log_build_me)
                    me = client.me()
                    break
                except Exception as e:
                    L.exception(e)
                    i += 1
            else:
                L.error(s.log_fail_to_build_me)
                L.info(s.exit)
                return

            try:
                follower_num = me.follower_num
            except Exception as e:
                L.exception(e)
                L.info(s.log_get_follower_num_failed)
                L.info(s.log_finish_a_pass)
                time.sleep(interval)
                continue

            L.info(s.log_get_follower_num.format(follower_num))
            db.log_to_db(conn, follower_num, s.log_start_a_pass)

            continue_in_db = 0
            new_follower_num = 0

            try:
                for follower in me.followers:
                    L.info(
                        s.log_check_follower.format(follower.name,
                                                    follower.id))
                    if db.is_in_db(conn, follower.id):
                        L.info(s.log_follower_in_db.format(follower.id))
                        continue_in_db += 1
                    else:
                        L.info(s.log_follower_not_in_db.format(follower.name))
                        continue_in_db = 0

                        L.info(s.log_send_message.format(follower.name))

                        try:
                            message = calc_message(msg, me, follower,
                                                   new_follower_num)
                            new_follower_num += 1
                        except Exception as e:
                            L.exception(e)
                            message = msg

                        L.debug(message)

                        i = 0
                        while i < 5:
                            try:
                                me.send_message(follower, message)
                                break
                            except Exception as e:
                                L.exception(e)
                                L.debug(s.log_send_failed)
                                i += 1
                        else:
                            L.info(s.log_send_pass)
                            continue

                        L.info(s.success)
                        L.info(s.log_add_user_to_db.format(follower.name))
                        db.add_user_to_db(conn, follower)

                    if continue_in_db == max_old:
                        L.info(s.log_continue_reach_max.format(max_old))
                        break
            except Exception as e:
                L.exception(e)

            L.info(s.log_finish_a_pass)
            time.sleep(interval)
Ejemplo n.º 6
0
# ==============================

USER_URL = "https://www.zhihu.com/people/7sdream"

FOLLOWER_CHECK_MAX_NUM = 2000
ANSWER_CHECK_MAX_NUM = 20

# ==============================


def is_zero_user(author):
    return (author.upvote_num + author.question_num + author.answer_num) <= 3


client = ZhihuClient('test.json')

user = client.author(USER_URL)

print("检查用户{user.name} at {time}".format(user=user,
                                         time=datetime.datetime.now()))

if user.follower_num < FOLLOWER_CHECK_MAX_NUM:
    FOLLOWER_CHECK_MAX_NUM = user.follower_num

print("正在检查前{FOLLOWER_CHECK_MAX_NUM}个关注者....".format(**locals()))

zeros = 0
for _, follower in zip(range(FOLLOWER_CHECK_MAX_NUM), user.followers):
    if is_zero_user(follower):
        zeros += 1
Ejemplo n.º 7
0
import os
import unittest
import shutil

from zhihu import ZhihuClient

from .. import db

file_dir = os.path.dirname(os.path.abspath(__file__))
test_dir = os.path.join(file_dir, 'test')
json_path = os.path.join(file_dir, 'test.json')
author = ZhihuClient(json_path).me()
db_path = os.path.join(test_dir, db.author_to_db_filename(author))


class InitDBTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        os.makedirs(test_dir, exist_ok=True)
        os.chdir(test_dir)

    def tearDown(self):
        self.db.close() if (hasattr(self, 'db') and self.db) else None
        try:
            os.remove(db_path)
        except FileNotFoundError:
            pass

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(test_dir)