def execute(attempt, params): import psycopg2 global conn, enabled, emergency if conn is None and not emergency: if not config.get('db_logger.host') or not config.get( 'db_logger.database'): print('Incorrect database configuration!') enabled = False return try: conn = psycopg2.connect( "dbname='{}' user='******' host='{}' password='******'".format( config.get('db_logger.database'), config.get('db_logger.username'), config.get('db_logger.host'), config.get('db_logger.password'))) except psycopg2.OperationalError as e: print(e, flush=True) _log.write('error', 'PostgreSQL connection error: ' + str(e)) conn = None else: if os.path.isfile(accounts.getFile('db_log.csv')): try: restoreRecords() except psycopg2.Error: if attempt < 5: return execute(attempt + 1, params) else: emergency = True if emergency or attempt >= 5: if emergency and conn is not None: emergency = False try: restoreRecords() except psycopg2.Error: emergency = True return False return execute(attempt, params) if not emergency: t = threading.Thread(target=monitor) t.start() emergency = True with open(accounts.getFile('db_log.csv'), 'a') as f: csv.writer(f).writerow(params) return True else: if conn is None: return False try: conn.cursor().execute(PG_QUERY, params) conn.commit() except psycopg2.Error as e: print(e, flush=True) _log.write('error', 'PostgreSQL error: ' + str(e)) conn = None return False else: return True
def __init__(self, username='', password='', get_dialogs_interval=60): self.delay_on_reply = config.get('vkbot_timing.delay_on_reply', 'i') self.chars_per_second = config.get('vkbot_timing.chars_per_second', 'i') self.same_user_interval = config.get('vkbot_timing.same_user_interval', 'i') self.same_conf_interval = config.get('vkbot_timing.same_conf_interval', 'i') self.forget_interval = config.get('vkbot_timing.forget_interval', 'i') self.delay_on_first_reply = config.get( 'vkbot_timing.delay_on_first_reply', 'i') self.stats_dialog_count = config.get('stats.dialog_count', 'i') self.no_leave_conf = config.get('vkbot.no_leave_conf', 'b') self.api = vkapi.VkApi(username, password, ignored_errors=ignored_errors, timeout=config.get( 'vkbot_timing.default_timeout', 'i'), token_file=accounts.getFile('token.txt'), log_file=accounts.getFile('inf.log') if args.args['logging'] else '', captcha_handler=createCaptchaHandler()) stats.update('logging', bool(self.api.log_file)) # hi java self.users = UserCache( self.api, self.fields + ',' + FriendController.requiredFields(_getFriendControllerParams()), config.get('cache.user_invalidate_interval', 'i')) self.confs = ConfCache( self.api, config.get('cache.conf_invalidate_interval', 'i')) self.vars = json.load(open('data/defaultvars.json', encoding='utf-8')) self.vars['default_bf'] = self.vars['bf']['id'] self.initSelf(True) self.guid = int(time.time() * 5) self.last_viewed_comment = stats.get('last_comment', 0) self.good_conf = {} self.tm = ThreadManager() self.last_message = MessageCache() if os.path.isfile(accounts.getFile('msgdump.json')): try: data = json.load(open(accounts.getFile('msgdump.json'))) self.last_message.load(data['cache']) self.api.longpoll = data['longpoll'] except json.JSONDecodeError: logging.warning('Failed to load messages') os.remove(accounts.getFile('msgdump.json')) else: logging.info('Message dump does not exist') self.bad_conf_title = lambda s: False self.admin = None self.banned_list = [] self.message_lock = threading.Lock() self.banned = set() self.receiver = MessageReceiver(self.api, get_dialogs_interval) self.receiver.longpoll_callback = self.longpollCallback
def createCaptchaHandler(): captcha_params = { 'antigate_key': config.get('captcha.antigate_key'), 'png_filename': accounts.getFile('captcha.png'), 'txt_filename': accounts.getFile('captcha.txt'), 'checks_before_antigate': config.get('captcha.checks_before_antigate', 'i'), 'check_interval': config.get('captcha.check_interval', 'i'), } return captcha.CaptchaHandler(captcha_params)
def main_loop(): global reply_all, dialogs try: if timeto('setonline', setonline_interval): vk.setOnline() if timeto('filtercomments', filtercomments_interval): noaddUsers(vk.filterComments( lambda s: getBotReply(None, s, -1), lambda uid, html: vk.printableSender({'user_id': uid}, html)), reason='bad comment') if includeread_interval >= 0: vk.replyAll(reply, reply_all) else: time.sleep(1) reply_all = vk.api.captchaError vk.api.captchaError = False if timeto('addfriends', addfriends_interval): vk.addFriends(reply, test_friend) if timeto('unfollow', unfollow_interval): noaddUsers(vk.unfollow(banign.banned), reason='deleted me') if timeto('includeread', includeread_interval): reply_all = True if timeto('stats', stats_interval): new_dialogs = vk.dialogCount() if dialogs != new_dialogs: dialogs = new_dialogs with open(accounts.getFile('stats.txt'), 'w') as f: f.write(json.dumps({'dialogs': dialogs})) except Exception as e: log.error('global {}: {}'.format(e.__class__.__name__, str(e)), True) reply_all = True time.sleep(2)
def main(a, args): a.ignored_errors = { (177, 'friends.add'): None, } a.timeout = 10 banned = list(map(int, open(accounts.getFile('banned.txt')).read().split())) controller = scriptlib.createFriendController() friends = scriptlib.getFriends(a, fields=controller.fields) logging.info('Starting to delete') for i in friends: if not (controller.isGood(i) or i['id'] in banned): a.friends.delete.delayed(user_id=i['id']) logging.info('deleted ' + str(i['id'])) log.write('_update_friends', 'deleted ' + str(i['id'])) a.sync() foll = scriptlib.getFollowers(a, fields=controller.fields) logging.info('Starting to add') def cb(req, resp): logging.info(('added ' if resp else 'error ') + str(req['user_id'])) for i in foll: if controller.isGood(i): a.friends.add.delayed(user_id=i['id']).callback(cb) a.sync() logging.info('\nFinished')
def _load(): global _stats if _stats is None: try: _stats = json.loads(open(accounts.getFile('stats.txt')).read()) except Exception: _stats = {}
def getToken(self): if not self.token: try: self.token = open(accounts.getFile('token.txt')).read().strip() except FileNotFoundError: self.token = '' return self.token
def main_loop(): global reply_all, dialogs try: if timeto('setonline', setonline_interval): vk.setOnline() if timeto('filtercomments', filtercomments_interval): noaddUsers(vk.filterComments(lambda s:getBotReply(None, s, -1), lambda uid,html:vk.printableSender({'user_id':uid},html)), reason='bad comment') if includeread_interval >= 0: vk.replyAll(reply, reply_all) else: time.sleep(1) reply_all = vk.api.captchaError vk.api.captchaError = False if timeto('addfriends', addfriends_interval): vk.addFriends(reply, test_friend) if timeto('unfollow', unfollow_interval): noaddUsers(vk.unfollow(banign.banned), reason='deleted me') if timeto('includeread', includeread_interval): reply_all = True if timeto('stats', stats_interval): new_dialogs = vk.dialogCount() if dialogs != new_dialogs: dialogs = new_dialogs with open(accounts.getFile('stats.txt'), 'w') as f: f.write(json.dumps({'dialogs': dialogs})) except Exception as e: log.error('global {}: {}'.format(e.__class__.__name__, str(e)), True) reply_all = True time.sleep(2)
def update(name, value): with lock: if name in _stats and _stats[name] == value: return _stats[name] = value with open(accounts.getFile('stats.txt'), 'w') as f: f.write(json.dumps(_stats))
def update(name, value): with lock: _load() if name in _stats and _stats[name] == value: return _stats[name] = value with open(accounts.getFile('stats.txt'), 'w') as f: f.write(json.dumps(_stats))
def waitAllThreads(self, loop_thread, reply): lp = self.api.longpoll.copy() self.receiver.terminate_monitor = True loop_thread.join(60) while not self.receiver.longpoll_queue.empty(): self.replyAll(reply) for t in self.tm.all(): t.join(60) with open(accounts.getFile('msgdump.json'), 'w') as f: json.dump({'cache': self.last_message.dump(), 'longpoll': lp}, f)
def reset(self, params): if params.get('_checks_done') or params.get('_trying_external_key'): if 'captcha_key' in params: with open(accounts.getFile('captcha.txt'), 'w') as f: f.write('cor ' + params['captcha_key']) params['_checks_done'] = 0 params['_trying_external_key'] = False params['_sid'] = '' logging.info('Captcha no longer needed') self.delete()
def main(a, args): days = config.get('delfriends.days_till_unfriend', 'i') prepare = 'prepare' in args if prepare: f = open(accounts.getFile('_delfriends.txt'), 'w') else: try: f = set(map(int, open(accounts.getFile('_delfriends.txt')).read().split())) except FileNotFoundError: log.info('_delfriends.txt not found') return friends = [] log.info('Fetching friends') for i in range(1000000): log.info('page ' + str(i+1)) fr = a.friends.get(count=1000, offset=i*1000) friends.extend(fr['items']) if len(fr['items']) < 1000: break now = time.time() to_del = [] cnt = 0 def checkHistory(req, resp): nonlocal cnt if resp['count'] == 0 or now - resp['items'][0]['date'] > 3600 * 24 * days: if prepare: f.write(str(req['user_id']) + '\n') else: to_del.append(str(req['user_id']) + '\n') log.info('Found ' + str(req['user_id'])) cnt += 1 for i in friends: if not prepare and i not in f: continue a.messages.getHistory.delayed(count=1, user_id=i).callback(checkHistory) a.sync() if prepare: f.close() else: with open(accounts.getFile('noadd.txt'), 'a') as res: res.write(''.join(to_del)) log.info('Total: ' + str(cnt))
def get(param, typename='s'): global cp if not cp: cp = configparser.ConfigParser() cp.read(accounts.getFile('inf.cfg')) param = param.split('.') try: if typename == 'b': return cp[param[0]].getboolean(param[1]) # noinspection PyStatementEffect cp[param[0]][param[1]] # to make sure that it exists if typename == 's': return cp[param[0]].get(param[1]) elif typename == 'i': return cp[param[0]].getint(param[1]) elif typename == 'f': return cp[param[0]].getfloat(param[1]) except KeyError: if input('Parameter {}.{} does not exist. Rebuild configuration? [y/n] '.format(*param)).lower() == 'y': rebuild(accounts.getFile('inf.cfg'), accounts.default_config) sys.exit()
def main(a, args): days = config.get('delfriends.days_till_unfriend', 'i') prepare = 'prepare' in args if prepare: f = open(accounts.getFile('_delfriends.txt'), 'w') else: try: f = set( map(int, open(accounts.getFile('_delfriends.txt')).read().split())) except FileNotFoundError: logging.info('_delfriends.txt not found') return friends = scriptlib.getFriends(a) now = time.time() to_del = [] cnt = 0 def checkHistory(req, resp): nonlocal cnt if resp['count'] == 0 or now - resp['items'][0][ 'date'] > 3600 * 24 * days: if prepare: f.write(str(req['user_id']) + '\n') else: to_del.append(str(req['user_id'])) logging.info('Found ' + str(req['user_id'])) cnt += 1 for i in friends: if not prepare and i not in f: continue a.messages.getHistory.delayed(count=1, user_id=i).callback(checkHistory) a.sync() if prepare: f.close() else: scriptlib.createFriendController().appendNoadd(to_del) logging.info('Total: ' + str(cnt))
def login(self): log.info('Fetching new token') url = 'https://oauth.vk.com/token?grant_type=password&client_id=2274003&client_secret=hHbZxrka2uZ6jB1inYsH&username='******'&password='******'I don\'t know your login or password, sorry', fatal=True) try: json_string = urllib.request.urlopen(url, timeout=self.timeout).read().decode() except Exception: log.error('Authorization failed', fatal=True) data = json.loads(json_string) self.token = data['access_token'] with open(accounts.getFile('token.txt'), 'w') as f: f.write(self.token)
def main(a, args): days = config.get('delfriends.days_till_unfriend', 'i') prepare = 'prepare' in args if prepare: f = open(accounts.getFile('_delfriends.txt'), 'w') else: try: f = set(map(int, open(accounts.getFile('_delfriends.txt')).read().split())) except FileNotFoundError: logging.info('_delfriends.txt not found') return friends = scriptlib.getFriends(a) now = time.time() to_del = [] cnt = 0 def checkHistory(req, resp): nonlocal cnt if resp['count'] == 0 or now - resp['items'][0]['date'] > 3600 * 24 * days: if prepare: f.write(str(req['user_id']) + '\n') else: to_del.append(str(req['user_id'])) logging.info('Found ' + str(req['user_id'])) cnt += 1 for i in friends: if not prepare and i not in f: continue a.messages.getHistory.delayed(count=1, user_id=i).callback(checkHistory) a.sync() if prepare: f.close() else: check_friend.appendNoadd(to_del) logging.info('Total: ' + str(cnt))
def handle(self, data_array, params): params['_trying_external_key'] = False if params.get('_checks_done', 0) == 0: logging.warning('Captcha needed') params['_sid'] = data_array['error']['captcha_sid'] with open(accounts.getFile('captcha.txt'), 'w') as f: f.write('sid ' + params['_sid']) self.receive(data_array['error']['captcha_img']) elif params.get('_sid'): key = open(accounts.getFile('captcha.txt')).read() if key.startswith('key'): logging.info('Trying a key from captcha.txt') params['captcha_sid'] = params['_sid'] params['captcha_key'] = key.split()[1] del params['_sid'] self.delete() params['_checks_done'] = 0 params['_trying_external_key'] = True return if self.key and params.get('_checks_done') == self.checks_before_antigate: logging.info('Using antigate') open(accounts.getFile('captcha.txt'), 'w').close() ans = self.solve() if ans is None: time.sleep(5) elif not ans: self.receive(data_array['error']['captcha_img']) params['_sid'] = data_array['error']['captcha_sid'] else: params['captcha_sid'] = params['_sid'] params['captcha_key'] = ans params['_checks_done'] = 1 else: time.sleep(self.check_interval) params['_checks_done'] = params.get('_checks_done', 0) + 1
def __init__(self, username='', password=''): self.api = vkapi.VkApi(username, password, ignored_errors=ignored_errors, timeout=config.get('vkbot.default_timeout', 'i'), token_file=accounts.getFile('token.txt'), log_file=accounts.getFile('inf.log') if args.args['logging'] else '', captcha_handler=captcha.CaptchaHandler()) self.api.initLongpoll() self.users = UserCache(self.api, 'sex,crop_photo,blacklisted,blacklisted_by_me,' + check_friend.fields) self.confs = ConfCache(self.api) self.vars = json.load(open('data/defaultvars.json', encoding='utf-8')) self.initSelf(True) self.guid = int(time.time() * 5) self.last_viewed_comment = stats.get('last_comment', 0) self.good_conf = {} self.tm = ThreadManager() self.last_message = MessageCache() self.last_message_id = 0 self.whitelist = None self.whitelist_includeread = True self.bad_conf_title = lambda s: False self.admin = None self.banned_list = [] self.longpoll_queue = queue.Queue() self.message_lock = threading.Lock()
def main(a, args): a.timeout = 10 friends = [] banned = list(map(int, open(accounts.getFile('banned.txt')).read().split())) log.info('Fetching friends') for i in range(1000000): log.info('page ' + str(i)) fr = a.friends.get(fields=check_friend.fields, count=1000, offset=i * 1000) friends.extend(fr['items']) if len(fr['items']) < 1000: break log.info('Starting to delete') for i in friends: if not (check_friend.is_good(i) or i['id'] in banned): a.friends.delete.delayed(user_id=i['id']) log.info('deleted ' + str(i['id'])) log.info('\nFetching followers') foll = [] for i in range(1000000): log.info('page ' + str(i)) fr = a.users.getFollowers(fields=check_friend.fields, count=1000, offset=i * 1000) foll.extend(fr['items']) if len(fr['items']) < 1000: break log.info('Starting to add') for i in foll: if check_friend.is_good(i): a.friends.add.delayed(user_id=i['id']) log.info('added ' + str(i['id'])) log.info('\nFinished')
if args['script']: if not args['script'].replace('_', '').isalpha(): print('Invalid script') sys.exit() log.script_name = args['script'].lower() try: main = importlib.import_module('scripts.' + args['script'].lower()).main except ImportError: print('Invalid script') sys.exit() v = vk_api(login, password) main(v, args['args']) v.sync() sys.exit() pid_file = accounts.getFile('inf.pid') lock_file = accounts.getFile('inf.lock') fp = open(lock_file, 'w') single = False for i in range(100): try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: time.sleep(5) else: single = True break if not single: sys.exit(0) with open(pid_file, 'w') as f: f.write(str(os.getpid()))
import json import accounts import threading lock = threading.Lock() try: _stats = json.loads(open(accounts.getFile('stats.txt')).read()) except Exception: _stats = {} def update(name, value): with lock: if name in _stats and _stats[name] == value: return _stats[name] = value with open(accounts.getFile('stats.txt'), 'w') as f: f.write(json.dumps(_stats)) def get(name, default=None): with lock: return _stats.get(name, default)
if args['script']: if not args['script'].replace('_', '').isalpha(): print('Invalid script') availableScripts() sys.exit() log.script_name = args['script'].lower() try: script = importlib.import_module('scripts.' + args['script'].lower()) main = script.main need_auth = getattr(script, 'need_auth', False) except ImportError: print('Invalid script') availableScripts() sys.exit() v = VkApi(login, password, timeout=config.get('vkbot_timing.default_timeout', 'i'), token_file=accounts.getFile('token.txt'), log_file=accounts.getFile('inf.log') if args['logging'] else '', captcha_handler=createCaptchaHandler()) if need_auth: v.initLongpoll() main(v, args['args']) v.sync() sys.exit() import fcntl pid_file = accounts.getFile('inf.pid') lock_file = accounts.getFile('inf.lock') fp = open(lock_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError:
def appendNoadd(users): noadd.update(users) with open(accounts.getFile('noadd.txt'), 'a') as f: f.write('\n' + '\n'.join(map(str, sorted(users))))
def apiCall(self, method, params, retry=False): with self.api_lock: params['v'] = self.api_version url = 'https://api.vk.com/method/' + method + '?' + urllib.parse.urlencode(params) + '&access_token=' + self.getToken() now = time.time() if now - self.last_call < CALL_INTERVAL: time.sleep(CALL_INTERVAL - now + self.last_call) self.last_call = now try: json_string = urllib.request.urlopen(url, timeout=self.timeout).read() except OSError as e: log.warning(method + ' failed ({})'.format(e)) time.sleep(1) return self.apiCall(method, params) except Exception as e: if retry: log.error('({}) {}: {}'.format(method, e.__class__.__name__, str(e)), True) return None else: time.sleep(1) log.warning('({}) {}: {}, retrying'.format(method, e.__class__.__name__, str(e))) return self.apiCall(method, params, 1) try: data_array = json.loads(json_string.decode('utf-8')) except json.decoder.JSONDecodeError: log.error('Invalid JSON') data_array = None if self.logging: with open('inf.log', 'a') as f: print('[{}]\nmethod: {}, params: {}\nresponse: {}\n'.format(time.strftime(log.datetime_format, time.localtime()), method, json.dumps(params), json.dumps(data_array)), file=f) duration = time.time() - now if duration > self.timeout: log.warning('{} timeout'.format(method)) if data_array is None: return None if 'response' in data_array: if self.captcha_delayed or self.externalCaptcha: self.captcha_delayed = 0 self.externalCaptcha = False log.info('Captcha no longer needed') self.captcha_sid = '' captcha.delete() return data_array['response'] elif 'error' in data_array: if data_array['error']['error_code'] == 14: #Captcha needed self.externalCaptcha = False if self.captcha_delayed == 0: log.warning('Captcha needed') self.captcha_sid = data_array['error']['captcha_sid'] with open(accounts.getFile('captcha.txt'), 'w') as f: f.write('sid ' + self.captcha_sid) captcha.receive(data_array['error']['captcha_img']) elif self.captcha_sid: key = open(accounts.getFile('captcha.txt')).read() if key.startswith('key'): log.info('Trying a key from captcha.txt') params['captcha_sid'] = self.captcha_sid params['captcha_key'] = key.split()[1] self.captcha_sid = '' captcha.delete() self.captcha_delayed = 0 self.externalCaptcha = True return self.apiCall(method, params) if self.captcha_delayed == self.checks_before_antigate: log.info('Using antigate') ans = captcha.solve() if ans is None: self.captchaError = True time.sleep(5) elif not ans: captcha.receive(data_array['error']['captcha_img']) self.captcha_sid = data_array['error']['captcha_sid'] return self.apiCall(method, params) else: params['captcha_sid'] = self.captcha_sid params['captcha_key'] = ans self.captcha_delayed = 0 else: time.sleep(self.captcha_check_interval) self.captcha_delayed += 1 return self.apiCall(method, params) elif data_array['error']['error_code'] == 5: #Auth error self.login() return self.apiCall(method, params) elif (data_array['error']['error_code'], method) in self.ignored_errors: handler = self.ignored_errors[(data_array['error']['error_code'], method)] if not handler: return None if retry or not handler[1]: log.warning(handler[0]) return None else: log.warning(handler[0] + ', retrying') time.sleep(3) return self.apiCall(method, params, True) else: log.error('{}, params {}\ncode {}: {}'.format(method, json.dumps(params), data_array['error']['error_code'], data_array['error'].get('error_msg'))) return None else: return self.apiCall(method, params)
def writeNoadd(): with open(accounts.getFile('noadd.txt'), 'w') as f: f.write('\n'.join(map(str, sorted(noadd))))
if not args['script'].replace('_', '').isalpha(): print('Invalid script') sys.exit() log.script_name = args['script'].lower() try: main = importlib.import_module('scripts.' + args['script'].lower()).main except ImportError: print('Invalid script') sys.exit() v = vk_api(login, password) main(v, args['args']) v.sync() sys.exit() pid_file = accounts.getFile('inf.pid') lock_file = accounts.getFile('inf.lock') fp = open(lock_file, 'w') single = False for i in range(100): try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: time.sleep(5) else: single = True break if not single: sys.exit(0) with open(pid_file, 'w') as f: f.write(str(os.getpid()))
def createFriendController(): controller_params = _getFriendControllerParams() return FriendController(controller_params, accounts.getFile('noadd.txt'), accounts.getFile('allowed.txt'))
import configparser import accounts cp = configparser.ConfigParser() cp.read(accounts.getFile('inf.cfg')) def get(param, type='s'): param = param.split('.') if type == 's': return cp[param[0]].get(param[1]) elif type == 'i': return cp[param[0]].getint(param[1]) elif type == 'f': return cp[param[0]].getfloat(param[1]) elif type == 'b': return cp[param[0]].getboolean(param[1])
import stats import vkbot from args import args from calc import evalExpression from cppbot import CppBot from prepare import login, password from server import MessageServer from vkapi import CONF_START from vkapi.utils import getSender def isBotMessage(msg, regex=re.compile(r'^\(.+\).')): return regex.match(msg.strip()) noans = open(accounts.getFile('noans.txt'), encoding='utf-8').read().splitlines() smiles = open(accounts.getFile('smiles.txt'), encoding='utf-8').read().splitlines() random.shuffle(noans) class BanManager: def __init__(self, filename): self.filename = filename self.banned = set(map(int, open(filename).read().split())) def write(self): s = list(map(str, sorted(self.banned))) with open(self.filename, 'w') as f: f.write('\n'.join(s))
from urllib.request import urlopen import log import socket import urllib.error import os import time import config import accounts _key = config.get('antigate.key') png_filename = accounts.getFile('captcha.png') _has_captcha = False def receive(url, timeout=10): try: data = urlopen(url, timeout=timeout).read() except (urllib.error.URLError, socket.timeout): log.warning('captcha timeout') time.sleep(5) receive(url, timeout) except Exception: log.error('captcha.receive error', True) time.sleep(5) receive(url, timeout) else: global _has_captcha _has_captcha = True with open(png_filename, 'wb') as f: f.write(data) def delete():
import log import stats import vkbot from args import args from cache import LimiterCache from calc import evalExpression from cppbot import CppBot from prepare import login, password from server import MessageServer from vkapi import CONF_START from vkapi.utils import getSender def isBotMessage(msg, regex=re.compile(r'^\(.+\).')): return regex.match(msg.strip()) noans = open(accounts.getFile('noans.txt'), encoding='utf-8').read().splitlines() smiles = open(accounts.getFile('smiles.txt'), encoding='utf-8').read().splitlines() random.shuffle(noans) class BanManager: def __init__(self, filename): self.filename = filename self.banned = set(map(int, open(filename).read().split())) def write(self): s = list(map(str, sorted(self.banned))) with open(self.filename, 'w') as f: f.write('\n'.join(s)) def ban(self, pid): if pid in self.banned:
from urllib.request import urlopen import log import socket import urllib.error import os import time import config import accounts _key = config.get('antigate.key') png_filename = accounts.getFile('captcha.png') _has_captcha = False def receive(url, timeout=10): try: data = urlopen(url, timeout=timeout).read() except (urllib.error.URLError, socket.timeout): log.warning('captcha timeout') time.sleep(5) receive(url, timeout) except Exception: log.error('captcha.receive error', True) time.sleep(5) receive(url, timeout) else: global _has_captcha _has_captcha = True with open(png_filename, 'wb') as f: f.write(data)
print('Invalid script') availableScripts() sys.exit() log.script_name = args['script'].lower() try: script = importlib.import_module('scripts.' + args['script'].lower()) main = script.main need_auth = getattr(script, 'need_auth', False) except ImportError: print('Invalid script') availableScripts() sys.exit() v = VkApi(login, password, timeout=config.get('vkbot_timing.default_timeout', 'i'), token_file=accounts.getFile('token.txt'), log_file=accounts.getFile('inf.log') if args['logging'] else '', captcha_handler=createCaptchaHandler()) if need_auth: v.initLongpoll() main(v, args['args']) v.sync() sys.exit() import fcntl pid_file = accounts.getFile('inf.pid') lock_file = accounts.getFile('inf.lock') fp = open(lock_file, 'w') try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
if args['script'] is None: availableScripts() if args['script']: if not args['script'].replace('_', '').isalpha(): print('Invalid script') availableScripts() log.script_name = args['script'].lower() try: main = importlib.import_module('scripts.' + args['script'].lower()).main except ImportError: print('Invalid script') availableScripts() v = VkApi(login, password, timeout=config.get('vkbot.default_timeout', 'i'), token_file=accounts.getFile('token.txt'), log_file=accounts.getFile('inf.log') if args['logging'] else '', captcha_handler=captcha.CaptchaHandler()) v.initLongpoll() main(v, args['args']) v.sync() sys.exit() import fcntl pid_file = accounts.getFile('inf.pid') lock_file = accounts.getFile('inf.lock') fp = open(lock_file, 'w') single = False for attempt in range(100): try: fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
def writeNoadd(): with open(accounts.getFile('noadd.txt'), 'w') as f: f.write('\n'.join(map(str, sorted(noadd)))) stats.update('ignored', len(noadd))
def restoreRecords(): for line in csv.reader(open(accounts.getFile('db_log.csv'))): conn.cursor().execute(PG_QUERY, line) conn.commit() os.remove(accounts.getFile('db_log.csv'))
import time import config import accounts fields = 'photo_50,country,last_seen' s = open(accounts.getFile('allowed.txt'), encoding='utf-8').readlines() noadd = set(map(int, open(accounts.getFile('noadd.txt')).read().split())) allowed = set(s[0] + ' ') s = s[1].split() offline_allowed = config.get('check_friend.offline_allowed', 'i') def writeNoadd(): with open(accounts.getFile('noadd.txt'), 'w') as f: f.write('\n'.join(map(str, sorted(noadd)))) def appendNoadd(users): noadd.update(users) with open(accounts.getFile('noadd.txt'), 'a') as f: f.write('\n' + '\n'.join(map(str, sorted(users)))) def check_char(c): return c in allowed checks = [ (lambda fr:'deactivated' not in fr, 'Account is deactivated'), (lambda fr:fr['photo_50'] and not fr['photo_50'].endswith('camera_50.png'), 'No avatar'), (lambda fr:fr.get('country', {'id':0})['id'] in [0, 1, 2, 3], 'Bad country'), (lambda fr:all(check_char(i) for i in fr['first_name'] + fr['last_name']), 'Bad characters in name'), (lambda fr:'last_seen' in fr and time.time() - fr['last_seen']['time'] < 3600 * 24 * offline_allowed, 'Offline too long'),