def admin(): db_gen = DB_general() login_check(request) if not db_gen.installed: return redirect('/install') db = DB() warning = None users = VkApi(db.access_token)('users.get', user_ids=db.duty_id) if type(users) == dict: username = '******' warning = {'type': 'danger', 'text': 'Ошибка доступа, смени токены'} else: username = f"{users[0]['first_name']} {users[0]['last_name']}" db.access_token = get_mask(db.access_token) db.me_token = get_mask(db.me_token) return render_template('pages/admin.html', db=db, db_gen=db_gen, users=users, warn=warning, username=username)
def setup(): if db_gen.installed: return redirect('/') tokens = format_tokens( [request.form.get('access_token'), request.form.get('me_token')]) user_id = check_tokens(tokens)[0] if type(user_id) != int: return user_id db_gen.set_user(user_id) db = DB() db.access_token = tokens[0] db.me_token = tokens[1] db.secret = gen_secret() db_gen.host = "https://" + request.host db_gen.installed = True db.trusted_users.append(db.duty_id) db.save() db_gen.save() VkApi(db.access_token).msg_op( 1, -174105461, f'+api {db.secret} https://{request.host}/callback') return redirect('/login')
def get_last_th_msgs(peer_id: int, api: VkApi) -> List[dict]: return api.exe('''return (API.messages.getHistory({"peer_id":"%(peer)s", "count":"200", "offset":0}).items) + (API.messages.getHistory({"peer_id": "%(peer)s", "count":"200", "offset":200}).items) + (API.messages.getHistory({"peer_id": "%(peer)s", "count":"200", "offset":400}).items) + (API.messages.getHistory({"peer_id": "%(peer)s", "count":"200", "offset":600}).items) + (API.messages.getHistory({"peer_id": "%(peer)s", "count":"200", "offset":800}).items);''' % {'peer': peer_id})
def admin(): db_gen = DB_general() if environ.get('FLASK_ENV') == 'development': db = DB() else: db, response = db_check_user(request) if response != 'ok': return db warning = 0 login = login_check(request, db, db_gen) if login: return login users = VkApi(db.access_token)('users.get', fields='photo_50', user_ids=db.duty_id) if type(users) == dict: username = '******' warning = {'type': 'danger', 'text': 'Ошибка доступа, смени токены'} else: username = f"{users[0]['first_name']} {users[0]['last_name']}" db.access_token = get_mask(db.access_token) db.me_token = get_mask(db.me_token) return render_template('pages/admin.html', db=db, db_gen=db_gen, users=users, warn=warning, username=username)
def __init__(self, request: Request): if request != None and request.data == b'': self.user_id = None self.msg = None self.obj = None self.secret = None self.method = 'ping' else: _data = json.loads(request.data) self.secret = _data.get('secret') self.obj = _data.get('object', {}) self.msg = _data.get('message', {}) try: self.db = DB(_data.get('user_id')) except ExcDB: raise ExceptToJson('Неверный ID дежурного') self.time = datetime.now().timestamp() self.api = VkApi(self.db.access_token, raise_excepts=True) self.method = _data.get('method', 'ping') self.responses = self.db.responses if self.method in { 'sendSignal', 'sendMySignal', 'subscribeSignals', 'toGroup' }: self.set_chat() elif self.method in {'ping', 'groupbots.invited', 'bindChat'}: pass else: self.chat = Chat(self.db.chats[self.obj['chat']], self.obj['chat']) if self.method not in {'sendSignal', 'sendMySignal'}: logger.info(self.__str__())
def check_tokens(tokens: list): user_ids = [] for i in range(len(tokens)): try: user_ids.append( VkApi(tokens[i], raise_excepts=True)('users.get')[0]['id']) time.sleep(0.4) except VkApiResponseException: raise WeHaveAProblem(int_error("Неверный токен, попробуй снова")) return user_ids
def send(db: DB, data: dict): chat = Chat(db.chats[data['chat']], data['chat']) vk = VkApi(db.access_token, raise_excepts=True) msg = vk("messages.getByConversationMessageId", conversation_message_ids=data['local_id'], peer_id=chat.peer_id)['items'][0] msg = Message(msg) if msg.reply: replies = {'reply_to': msg.reply['id']} elif msg.fwd: replies = { 'forward_messages': ','.join([str(fwd['id']) for fwd in msg.fwd]) } else: replies = {} vk.msg_op(1, chat.peer_id, msg.payload, **replies, attachment=','.join(msg.attachments))
def __init__(self, data: dict): self.time = datetime.now().timestamp() self.data = data self.msg = data['message'] self.parse() self.command = data.get('command', self.command) self.db = DB() if data['chat'] is None: self.chat = Chat({'peer_id': self.msg['peer_id']}, 'N/A') else: self.chat = Chat(self.db.chats[data['chat']], data['chat']) self.api = VkApi(self.db.access_token, raise_excepts=True) self.responses = self.db.responses logger.debug(self.__str__())
def get_data(): token = json.loads(request.data)['token'] try: if VkApi(token)('users.get')[0]['id'] != db_gen.owner_id: raise ValueError except (KeyError, IndexError, ValueError): return json.dumps({'error': error.AuthFail}) db = DB() db.lp_settings['key'] = gen_secret(length=20) db.save() return json.dumps({ 'chats': db.chats, 'deleter': db.responses['del_self'], 'settings': db.lp_settings, 'self_id': db.duty_id })
def __init__(self, request: Request): if request.data == b'': self.user_id = None self.msg = None self.obj = None self.secret = None self.method = 'ping' else: _data = json.loads(request.data) self.secret = _data.get('secret') self.obj = _data.get('object', {}) self.msg = _data.get('message', {}) if _data.get('user_id') != db_gen.owner_id: raise ExceptToJson('Неверный ID дежурного') self.db = DB() self.time = datetime.now().timestamp() self.api = VkApi(self.db.access_token, raise_excepts=True) self.method = _data.get('method', 'ping') self.responses = self.db.responses if self.method in { 'sendSignal', 'sendMySignal', 'subscribeSignals', 'toGroup' }: self.set_chat() elif self.method in { 'ping', 'groupbots.invited', 'bindChat', 'meetChatDuty' }: pass else: chat = self.obj['chat'] if chat not in self.db.chats: raise ExceptToJson(f'Чат #{chat} не связан!') self.chat = Chat(self.db.chats[chat], chat) if self.method not in {'sendSignal', 'sendMySignal'}: logger.info(self.__str__())
def api(method: str): login_check(request) db = DB() if method == "edit_current_user": tokens = format_tokens([ request.form.get('access_token', ''), request.form.get('me_token', '') ]) if tokens[0]: db.access_token = tokens[0] if tokens[1]: db.me_token = tokens[1] db.save() if method == 'connect_to_iris': try: VkApi(db.access_token, raise_excepts=True)( 'messages.send', peer_id=-174105461, message=f'+api {db.secret} https://{request.host}/callback', random_id=0) except VkApiResponseException as e: return int_error(f'Ошибка VK #{e.error_code}: {e.error_msg}') if method == "edit_responses": for key in db.responses.keys(): response = request.form.get(key) if response: db.responses[key] = response db.save() return redirect('/admin#Responses') if method == "edit_dyntemplates": name = request.form['temp_name'] length = int(request.form['length']) i = 0 frames = [] while True: if i >= length: break frame = request.form.get(f'frame{i}') if frame: frames.append(frame) elif i < length: frames.append('Пустой кадр') else: break i += 1 temp = { 'name': request.form['new_name'], 'frames': frames, 'speed': float(request.form['speed']) } for i in range(len(db.anims)): if db.anims[i]['name'] == name: db.anims[i].update(temp) break db.save() return redirect('/admin#DynTemplates') if method == 'add_dyntemplate': db.anims.append({ 'name': 'анимка', 'frames': ['Отсутствует'], 'speed': 1.0 }) db.save() return redirect('/admin#DynTemplates') if method == 'delete_anim': name = request.form['name'] for i in range(len(db.anims)): if db.anims[i]['name'] == name: del (db.anims[i]) db.save() return redirect('/admin#DynTemplates') if method == 'dc_auth': if request.form.get('permit') == 'on': db_gen.dc_auth = True else: db_gen.dc_auth = False db_gen.save() return redirect('/')
def get_msgs(peer_id, api: VkApi, offset=0): return api.exe('''return (API.messages.getHistory({"peer_id":"%s", "count":"200", "offset":"%s"}).items) + (API.messages.getHistory({"peer_id": "%s", "count":"200", "offset":"%s"}).items);''' % (peer_id, offset, peer_id, offset + 200))
def api(method: str): if method == "setup_cb": #-------------------------------------------------------------- if db_gen.installed: return redirect('/') tokens = format_tokens( [request.form.get('access_token'), request.form.get('me_token')]) user_id = check_tokens(tokens)[0] if type(user_id) != int: return user_id db_gen.set_user(user_id) db = DB(user_id) db.access_token = tokens[0] db.me_token = tokens[1] db.secret = gen_secret() # db_gen.vk_app_id = int(request.form.get('vk_app_id')) # db_gen.vk_app_secret = request.form.get('vk_app_secret') db_gen.host = "http://" + request.host db_gen.installed = True db.trusted_users.append(db.duty_id) db.save() db_gen.save() return redirect('/login?next=/admin') db = DB(auth['user']) login = login_check(request, db, db_gen) if login: return login if method == "edit_current_user": #-------------------------------------------------------------- tokens = format_tokens([ request.form.get('access_token', ''), request.form.get('me_token', '') ]) if tokens[0]: db.access_token = tokens[0] if tokens[1]: db.me_token = tokens[1] db.save() return redirect('/admin') if method == 'connect_to_iris': try: VkApi(db.access_token, raise_excepts=True)( 'messages.send', random_id=0, message=f'+api {db.secret} {db.gen.host}/callback', peer_id=-174105461) except VkApiResponseException as e: return int_error(f'Ошибка VK #{e.error_code}: {e.error_msg}') return redirect('/') if method == "edit_responses": #-------------------------------------------------------------- for key in db.responses.keys(): response = request.form.get(key) if response: db.responses[key] = response db.save() return redirect('/admin#Responses') if method == "edit_dyntemplates": name = request.form['temp_name'] length = int(request.form['length']) i = 0 frames = [] while True: if i >= length: break frame = request.form.get(f'frame{i}') if frame: frames.append(frame) elif i < length: frames.append('Пустой кадр') else: break i += 1 temp = { 'name': request.form['new_name'], 'frames': frames, 'speed': float(request.form['speed']) } for i in range(len(db.anims)): if db.anims[i]['name'] == name: db.anims[i].update(temp) break db.save() return redirect('/admin#DynTemplates') if method == 'add_dyntemplate': db.anims.append({ 'name': 'анимка', 'frames': ['Отсутствует'], 'speed': 1.0 }) db.save() return redirect('/admin#DynTemplates') if method == 'delete_anim': name = request.form['name'] for i in range(len(db.anims)): if db.anims[i]['name'] == name: del (db.anims[i]) db.save() return redirect('/admin#DynTemplates') if method == 'dc_auth': if request.form.get('permit') == 'on': db_gen.dc_auth = True else: db_gen.dc_auth = False db_gen.save() return redirect('/admin') return int_error('Тебя здесь быть не должно')