def _initConfig():
    config = {
        'user': {
            'username': '******',
            'password': '******'
        },
        'forum': {
            'kw': u'c语言',
            'fid': 22545
        },
        'debug': False,
        'workingType': '',
        'configFilename': 'config/default.json',
        'stdincoding': 'utf8'
    }

    _parseArgument(config)

    if config['debug']:
        setStdLevel('debug')
        stdLog(u'已启用调试模式', 'debug')

    _getStdinCoding(config)
    stdLog(u'输入编码为:' + config['stdincoding'], 'debug')

    return config
def _initConfig():
	config = {
		'user': {
			'username': '******',
			'password': '******'
		},
		'forum': {
			'kw': u'c语言',
			'fid': 22545
		},
		'debug': False,
		'workingType': '',
		'configFilename': 'config/default.json',
		'stdincoding': 'utf8'
	}

	_parseArgument(config)

	if config['debug']:
		setStdLevel('debug')
		stdLog(u'已启用调试模式', 'debug')

	_getStdinCoding(config)
	stdLog(u'输入编码为:' + config['stdincoding'], 'debug')

	return config
def initKeywords(keywords):

    if isFileUpdated("config/keywords.txt"):
        del keywords[:]
        keywords.extend(_getKeywords())
        stdLog(u'获取关键词成功', 'success')
        _compileKeywords(keywords)
        stdLog(u'编译关键词成功', 'success')
        return True
    else:
        return False
def initKeywords(keywords):

	if isFileUpdated("config/keywords.txt"):
		del keywords[:]
		keywords.extend(_getKeywords())
		stdLog(u'获取关键词成功', 'success')
		_compileKeywords(keywords)
		stdLog(u'编译关键词成功', 'success')
		return True
	else:
		return False
def _block(config):
	stdLog(u'黑名单初始化中...', 'info')
	blacklist = initBlacklist()
	stdLog(u'黑名单初始化完毕', 'success')

	for black in blacklist:
		if black['times'] > 0:
			print '%s %s' % (datetime.datetime.now().strftime('%y/%m/%d %H:%M:%S'), black['username'])
			blockID(black['username'],
					config['forum'],
					'你在%s吧黑名单中,剩余%d天解封。' % (config['forum']['kw'], black['times'] - 1))
			black['times'] -= 1
			time.sleep(5)
		if black['times'] == 0:
			blacklist.remove(black)

	_saveBlacklist(blacklist)
Beispiel #6
0
def _block(config):
    stdLog(u'黑名单初始化中...', 'info')
    blacklist = initBlacklist()
    stdLog(u'黑名单初始化完毕', 'success')

    for black in blacklist:
        if black['times'] > 0:
            print '%s %s' % (datetime.datetime.now().strftime(
                '%y/%m/%d %H:%M:%S'), black['username'])
            blockID(
                black['username'], config['forum'], '你在%s吧黑名单中,剩余%d天解封。' %
                (config['forum']['kw'], black['times'] - 1))
            black['times'] -= 1
            time.sleep(5)
        if black['times'] == 0:
            blacklist.remove(black)

    _saveBlacklist(blacklist)
def _getUserConfigration(config):
	try:
		f = open(config['configFilename'], 'r')
		try:
			jsonObj = json.load(f)
			if ['apikey', 'kw', 'password', 'username'] == sorted(jsonObj.keys()):
				config['user']['username'] = jsonObj['username'].decode('utf8')
				config['user']['password'] = jsonObj['password'].decode('utf8')
				config['forum']['kw']      = jsonObj['kw'].decode('utf8')
				config['apikey']           = jsonObj['apikey'].decode('utf8')
			else:
				stdLog(u'无效的配置文件,请使用 TiebaAutoTool.py config 来生成配置文件', 'info', ('console'))
				sys.exit(1)
		except Exception as e:
			errLog(300, pause = False)
			sys.exit(1)
	except Exception as e:
		errLog(200, pause = False)
		sys.exit(1)
Beispiel #8
0
def _deleteThread(threadData, config):
	stdLog(u'正在删除帖子', 'info')
	if deleteThread(threadData['thread'], config['forum']):
		threadData['forum'] = config['forum']['kw']
		threadData['operation']['operationTime'] = getLogTime()
		stdLog(u'删除成功', 'success')
		stdLog(u'操作时间:' + threadData['operation']['operationTime'], 'debug')
		postLog(threadData, ('file', 'cloud'), config['apikey'])
		return True
	else:
		stdLog(u'删除失败', 'error')
		return False
def _getUserConfigration(config):
    try:
        f = open(config['configFilename'], 'r')
        try:
            jsonObj = json.load(f)
            if ['apikey', 'kw', 'password',
                    'username'] == sorted(jsonObj.keys()):
                config['user']['username'] = jsonObj['username'].decode('utf8')
                config['user']['password'] = jsonObj['password'].decode('utf8')
                config['forum']['kw'] = jsonObj['kw'].decode('utf8')
                config['apikey'] = jsonObj['apikey'].decode('utf8')
            else:
                stdLog(u'无效的配置文件,请使用 TiebaAutoTool.py config 来生成配置文件', 'info',
                       ('console'))
                sys.exit(1)
        except Exception as e:
            errLog(300, pause=False)
            sys.exit(1)
    except Exception as e:
        errLog(200, pause=False)
        sys.exit(1)
Beispiel #10
0
def autoBlock(config):
    stdLog(u'启动自动小黑屋', 'info')

    stdLog(u'登录中...', 'info')
    if adminLogin(config['user'], config['configFilename'][:-5] + '.co'):
        stdLog(u'登陆成功', 'success')
        while (True):
            s = sched.scheduler(time.time, time.sleep)
            tomorrow = datetime.datetime.replace(datetime.datetime.now() +
                                                 datetime.timedelta(days=1),
                                                 hour=0,
                                                 minute=0,
                                                 second=0,
                                                 microsecond=0)
            s.enter((tomorrow - datetime.datetime.now()).seconds, 1, _block,
                    (config, ))
            s.run()

    else:
        stdLog(u'登陆失败', 'error')
        sys.exit(1)
Beispiel #11
0
def _judgeThread(threadData, config, keywords):
	if judge(threadData, keywords):
		postLog(threadData, ('console'))
		if not config['debug']:
			return True
		else:
			stdLog(u'请确认是否删除(按y删除):', 'info', ('console'), '')
			if raw_input() == 'y':
				stdLog(u'已确认删除帖子...', 'debug')
				return True
			else:
				stdLog(u'跳过删帖', 'debug')

	return False
Beispiel #12
0
def autoBlock(config):
	stdLog(u'启动自动小黑屋', 'info')

	stdLog(u'登录中...', 'info')
	if adminLogin(config['user'], config['configFilename'][:-5] + '.co'):
		stdLog(u'登陆成功', 'success')
		while(True):
			s = sched.scheduler(time.time, time.sleep)
			tomorrow = datetime.datetime.replace(datetime.datetime.now() +
												datetime.timedelta(days = 1),
												hour = 0,
												minute = 0,
												second = 0,
												microsecond = 0)
			s.enter((tomorrow - datetime.datetime.now()).seconds,
					1,
					_block,
					(config,))
			s.run()

	else:
		stdLog(u'登陆失败', 'error')
		sys.exit(1)
Beispiel #13
0
def _delete(config, keywords):
	deleteCount = 0
	stdLog(u'获取首页...', 'info')
	threadDataList = getThreadDataList(config['forum'])
	for threadData in threadDataList:
		if _judgeThread(threadData, config, keywords):
			if _deleteThread(threadData, config):
				deleteCount += 1
				if not config['debug']:
					sleep(5)
			else:
				sleep(5)
				return

	if deleteCount != 0:
		stdLog(u'删除 {0} 个帖子'.format(deleteCount), 'info')
	#仅在未开启调试,且删帖数为0时才显示
	elif not config['debug']:
		stdLog(u'等待更多新帖...', 'info')
		_smartSleep(deleteCount)
	else :
		sleep(5)
def initialization():
    logInitialization()
    stdLog(u'初始化中...', 'info')

    stdLog(u'配置初始化中...', 'info')
    config = _initConfig()
    stdLog(u'配置初始化完毕', 'success')

    stdLog(u'网络初始化中...', 'info')
    baiduInitialization(config['configFilename'][:-5] + '.co')
    stdLog(u'网络初始化完毕', 'success')

    if config['workingType'] == 'autoDelete' or config[
            'workingType'] == 'autoBlock':
        stdLog(u'用户配置文件初始化中...', 'info')
        _initUserConfigration(config)
        stdLog(u'用户配置文件初始化完毕', 'success')

    stdLog(u'初始化完毕', 'success')
    os.system('cls' if os.name == 'nt' else 'clear')

    return config
Beispiel #15
0
def autoDelete(config):
	stdLog(u'启动自动删贴机', 'info')
	stdLog(u'关键词初始化中...', 'info')
	keywords = list()
	if initKeywords(keywords):
		stdLog(u'关键词初始化完毕', 'success')

	stdLog(u'登录中...', 'info')
	if adminLogin(config['user'], config['configFilename'][:-5] + '.co'):
		stdLog(u'登陆成功', 'success')
		while(True):
			if initKeywords(keywords):
			 	stdLog("更新关键词成功!", "success")
			_delete(config, keywords)
	else:
		stdLog(u'登陆失败', 'error')
		sys.exit(1)
def configFileGenerator(config):
	stdLog(u'启动配置文件生成工具', 'info')

	stdLog(u'请输入配置文件的文件名(按回车使用默认文件):', 'info', ('console'), '')
	filename = raw_input()
	if filename == '':
		filename = 'config/default.json'
	else:
		filename = 'config/' + filename
	stdLog(u'使用配置文件 ' + filename, 'info', ('console'))

	while os.path.exists(filename):
		stdLog(u'文件已存在,本操作将覆盖此文件,是否继续?(y/n):', 'info', ('console'), '')
		choose = raw_input()
		if choose in ['n', 'N']:
			stdLog(u'已取消', 'info', ('console'))
			sys.exit(0)
		elif choose in ['y', 'Y']:
			break

	while True:
		stdLog(u'请输入用户名:', 'info', ('console'), '')
		config['user']['username'] = raw_input().decode(config['stdincoding'])
		stdLog(u'请输入密码(无回显)', 'info', ('console'), '')
		config['user']['password'] = getpass.getpass(':')

		stdLog(u'登陆测试', 'info', ('console'))
		if not config['debug']:
			if adminLogin(config['user'], config = True):
				stdLog(u'登陆成功', 'success', ('console'))
				break
			else:
				stdLog(u'登陆失败', 'error', ('console'))
				while True:
					stdLog(u'是否继续尝试?(y/n):', 'info', ('console'), '')
					choose = raw_input()
					if choose in ['n', 'N']:
						stdLog(u'程序退出,未作出任何更改', 'info', ('console'))
						sys.exit(0)
					elif choose in ['y', 'Y']:
						break
		else:
			stdLog(u'因调试而跳过登陆验证', 'debug', ('console'))
			break

	stdLog(u'请输入贴吧名(不带‘吧’,如c语言吧则输入‘c语言’):', 'info', ('console'), '')
	config['forum']['kw'] = raw_input().decode(config['stdincoding'])
	stdLog(u'请输入API key(若没有请按回车):', 'info', ('console'), '')
	config['apikey'] = raw_input()

	stdLog(u'-----------------', 'info', ('console'))
	stdLog(u'使用用户名:' + config['user']['username'], 'info', ('console'))
	stdLog(u'密码:' + '*' * len(config['user']['password']), 'info', ('console'))
	stdLog(u'管理贴吧:' + config['forum']['kw'], 'info', ('console'))
	if config['apikey']:
		stdLog(u'API key:' + config['apikey'], 'info', ('console'))
	while True:
		stdLog(u'请检查输入的信息是否正确?(y/n):', 'info', ('console'), '')
		choose = raw_input()
		if choose in ['n', 'N']:
			stdLog(u'程序退出,未作出任何更改', 'info', ('console'))
			sys.exit(0)
		elif choose in ['y', 'Y']:
			try:
				f = open(filename, 'w')
				f.write('{\n')
				f.write('	"username": "******",\n')
				f.write('	"password": "******",\n')
				f.write('	"kw": "' + config['forum']['kw'].encode('utf8') + '",\n')
				f.write('	"apikey": "' + config['apikey'] + '"\n')
				f.write('}')
			except Exception as e:
				errLog(200, pause = False)
				sys.exit(1)
			stdLog(u'写入成功', 'success', ('console'))
			if filename == 'config/default.json':
				stdLog(u'请使用 python2 TiebaAutoTool.py run 来使用本配置运行', 'info', ('console'))
			else:
				stdLog(u'请使用 python2 TiebaAutoTool.py run -c %s 来使用本配置运行' % filename, 'info', ('console'))
			break
def initialization():
	logInitialization()
	stdLog(u'初始化中...', 'info')

	stdLog(u'配置初始化中...', 'info')
	config = _initConfig()
	stdLog(u'配置初始化完毕', 'success')

	stdLog(u'网络初始化中...', 'info')
	baiduInitialization(config['configFilename'][:-5] + '.co')
	stdLog(u'网络初始化完毕', 'success')

	if config['workingType'] == 'autoDelete' or config['workingType'] == 'autoBlock':
		stdLog(u'用户配置文件初始化中...', 'info')
		_initUserConfigration(config)
		stdLog(u'用户配置文件初始化完毕', 'success')

	stdLog(u'初始化完毕', 'success')
	os.system('cls' if os.name == 'nt' else 'clear')

	return config
def _initUserConfigration(config):
	stdLog(u'用户配置文件:%s' % config['configFilename'], 'info')
	_getUserConfigration(config)
	stdLog(u'获取用户配置文件成功', 'success')
	config['forum']['fid'] = getFid(config['forum'])
	stdLog(u'获取贴吧fid成功', 'success')
	stdLog(u'使用用户名:%s' % config['user']['username'], 'info')
	stdLog(u'管理贴吧:%s(%s)' % (config['forum']['kw'], config['forum']['fid']), 'info')
	if config['apikey']:
		stdLog(u'使用apikey:%s' % config['apikey'], 'info')
def _initUserConfigration(config):
    stdLog(u'用户配置文件:%s' % config['configFilename'], 'info')
    _getUserConfigration(config)
    stdLog(u'获取用户配置文件成功', 'success')
    config['forum']['fid'] = getFid(config['forum'])
    stdLog(u'获取贴吧fid成功', 'success')
    stdLog(u'使用用户名:%s' % config['user']['username'], 'info')
    stdLog(u'管理贴吧:%s(%s)' % (config['forum']['kw'], config['forum']['fid']),
           'info')
    if config['apikey']:
        stdLog(u'使用apikey:%s' % config['apikey'], 'info')