import requests from . import VkApi from datetime import datetime from wtflog import warden logger = warden.get_boy('VK LongPoll') class LP(): key: str server: str ts: int time: float vk: VkApi wait: int def __init__(self, vk, wait=25): 'vk - экземпляр VkApi' self.vk = vk data = vk('messages.getLongPollServer') if data.get('error'): if data['error']['error_code'] == 5: raise Exception('tokenfail') self.server = data['server'] self.key = data['key'] self.ts = data['ts'] self.wait = wait @property def check(self): 'Возвращает список событий (updates)'
send_from_directory, Response) from idm.utils import gen_secret from microvk import VkApi, VkApiResponseException from wtflog import warden from idm.objects import DB, DB_general, db_gen if environ.get('FLASK_ENV') == 'development': DEBUG = True else: DEBUG = False app = Flask(__name__) logger = warden.get_boy(__name__) auth: str = {'token': '', 'user': 0} class WeHaveAProblem(Exception): response: Response def __init__(self, response: Response): self.response = response def get_mask(token: str) -> str: if len(token) != 85: return 'Не установлен' return token[:4] + "*" * 77 + token[81:]
from idm.objects import Event, ExceptToJson, dp from microvk import VkApiResponseException from wtflog import warden from .app import app from flask import request import traceback import json logger = warden.get_boy('IRIS Callback') @app.route('/callback', methods=["POST"]) def callback(): event = Event(request) if event.secret != event.db.secret: return 'Неверная секретка', 500 d = dp.event_run(event) if d == "ok": return json.dumps({"response": "ok"}, ensure_ascii=False) elif type(d) == dict: return json.dumps(d, ensure_ascii=False) else: return r"\\\\\ашипка хэз бин произошла/////" + '\n' + d @app.errorhandler(ExceptToJson) def json_error(e): return e.response
from idm.objects import LongpollEvent, DB, dp, db_gen from microvk import VkApi, VkApiResponseException from idm.utils import gen_secret from wtflog import warden from .app import app from flask import request import traceback import json logger = warden.get_boy('Применик сигналов LP модуля') @app.route('/ping', methods=["POST"]) def ping(): return "ok" @app.route('/longpoll/event', methods=["POST"]) def longpoll(): event = LongpollEvent(request.json) if event.data['access_key'] != event.db.lp_settings['key']: return "?" d = dp.longpoll_event_run(event) if type(d) == dict: return json.dumps(d, ensure_ascii=False) return json.dumps({"response": "ok"}, ensure_ascii=False) class error:
# давай вот щас не начинай, работает, а больше мне ничего не нужно import requests from .methods import Messages from wtflog import warden logger = warden.get_boy('VK API') class VkApiResponseException(Exception): # да, спиздил))0) def __init__(self, *args, **kwargs): self.error_code = kwargs.get('error_code', None) self.error_msg = kwargs.get('error_msg', None) self.request_params = kwargs.get('request_params', None) self.args = args self.kwargs = kwargs class VkApi: url: str = 'https://api.vk.com/method/' query: str raise_excepts: bool messages = Messages def __init__(self, access_token: str, raise_excepts: bool = False, version: str = "5.110"): 'raise_excepts - если True, ошибки ВК будут вызывать исключения' self.query = f'?v={version}&access_token={access_token}&lang=ru'
from . import (Event as _Event, SignalEvent as _SignalEvent, MySignalEvent as _MySignalEvent, LongpollEvent as _LongpollEvent) from .handler import handler as _handler from wtflog import warden as _warden _logger = _warden.get_boy('Диспетчер callback') _events = {} _signal_events = {} _my_signal_events = {} _skip_message_receiving = set() _longpoll_events = {} def event_register(method: str): def registrator(func): _logger.debug(f'Зарегистрирован обработчик для метода {method}') _events.update({method: func}) return func return registrator def signal_event_register(*commands: tuple): def registrator(func): _logger.debug(f'Зарегистрирована новая команда для сигналов к ' + f'дежурному. Команды {list(commands)}') for command in commands:
import json import requests import traceback from flask import request from typing import Union from idm import app from idm.objects import DB, db_gen, Chat from idm.utils import Message from idm.my_signals.remote import set_session, DC from microvk import VkApi, VkApiResponseException from wtflog import warden logger = warden.get_boy('Модуль удаленного управления') session: Union[str, None] def register(): global session r = requests.post(DC, json={ 'method': 'register', 'user_id': str(db_gen.owner_id), 'token': DB().access_token if db_gen.dc_auth else None, 'host': db_gen.host }) if r.status_code == 200:
import json from datetime import datetime from typing import List from flask import Request from microvk import VkApi from wtflog import warden from idm.api_utils import get_msg from idm.utils import Message, cmid_key from .database import DB, db_gen logger = warden.get_boy('События callback') class ExceptToJson(Exception): response: str def __init__(self, message='', code: int = 0, iris: bool = False): if iris: self.response = json.dumps( { 'response': 'error', 'error_code': code, 'error_message': message }, ensure_ascii=False) else: self.response = 'Error_o4ka:\n' + str(message)
# тут (да и не только тут) есть много странных костылей, # большинство из них предназначено для обратной совместимости import os from os.path import join as pjoin import json from typing import List from wtflog import warden logger = warden.get_boy('База данных') get_dir = os.path.dirname path = pjoin(get_dir(get_dir(get_dir(__file__))), 'database') db_gen: "DB_general" def read(name: str) -> dict: 'Возвращает словарь из файла с указанным названием' logger.debug(f'Открываю файл "{name}"') with open(pjoin(path, f'{name}.json'), "r", encoding="utf-8") as file: return json.loads(file.read()) gen_raw = { "owner_id": 0, "host": "", "installed": False, "dc_auth": False }