Beispiel #1
0
 def __init__(self, api: API, generate_attachment_strings: bool = False):
     """ Uploader base
     :param api: API Instance
     :param generate_attachment_strings: return attachment short strings after upload
     """
     self.api = api
     self.http = HTTPRequest()
     self.gas = generate_attachment_strings
Beispiel #2
0
async def request(
    method: str,
    params: dict,
    token: str,
    session: HTTPRequest = None,
    error_handler: "VKErrorHandler" = None,
    request_instance=None,
):
    url = "{}{method}/?access_token={token}&v={version}".format(
        API_URL,
        method=method,
        token=token,
        version=API_VERSION,
    )

    session = session or HTTPRequest()
    response = await session.post(url, data=params or {})

    if not isinstance(response, dict):
        delay = 1

        while not isinstance(response, dict):
            logger.error(
                "\n---"
                f"{time.strftime('%m-%d %H:%M:%S', time.localtime())} - DELAY {delay * 5} sec\n"
                f"Check your internet connection. Maybe VK died, request returned: {response}"
                f"Error appeared after request: {method}")
            await asyncio.sleep(delay * 5)
            response = await session.post(url, data=params or {})

        logger.success(
            f"--- {time.strftime('%m-%d %H:%M:%S', time.localtime())}\n"
            f"- METHOD SUCCESS after {5 * sum(range(1, delay))} sec\n"
            f"RESPONSE: {response}\n")

    if "error" in response:
        logger.debug("Error after request {method}, response: {r}",
                     method=method,
                     r=response)
        exception = VKError(
            response["error"]["error_code"],
            response["error"]["error_msg"],
            from_attr(
                Categories,
                [method.split(".")[0],
                 to_snake_case(method.split(".")[1])]
                if "." in method else method,
                (request_instance, None),
            ),
            params,
            raw_error=response["error"],
        )
        if not error_handler:
            raise exception
        return await error_handler.handle_error(exception)
    return response
Beispiel #3
0
    def __init__(
        self,
        tokens: typing.List[str] = None,
        generator: typing.Union[str] = "consistent",
        throw_errors: bool = True,
    ):
        self.token_generator: AbstractTokenGenerator = GENERATORS.get(
            generator, ConsistentTokenGenerator)(tokens)
        self._http: HTTPRequest = HTTPRequest()
        self.throw_errors: bool = throw_errors
        self._group_id: typing.Optional[int] = None
        self._user_id: typing.Optional[int] = None

        for category in self.__categories__:
            setattr(self, category, getattr(self, category)(self.api))
Beispiel #4
0
    def __init__(
        self,
        tokens: typing.Union[str, typing.List[str]] = None,
        generator: typing.Union[str] = "consistent",
        throw_errors: bool = True,
    ):
        if not isinstance(tokens, list):
            tokens = [tokens]

        self.token_generator: AbstractTokenGenerator = GENERATORS.get(
            generator, ConsistentTokenGenerator)(tokens)
        self._http: HTTPRequest = HTTPRequest()
        self.throw_errors: bool = throw_errors
        self._group_id: typing.Optional[int] = None
        self._user_id: typing.Optional[int] = None

        # Construct values
        self.error_handler: typing.Optional["VKErrorHandler"] = None
        self.extension: typing.Optional["AbstractExtension"] = None

        for category in self.__categories__:
            setattr(self, category, getattr(self, category)(self.api))
Beispiel #5
0
import asyncio
import warnings

import typing

from loguru import logger
from python_rucaptcha import ImageCaptcha
from vkbottle import VKError
from vkbottle.api import API
from vkbottle.api.api.error_handler import VKErrorHandler
from vkbottle.http import HTTPRequest
from vkbottle.utils import json

from const import DEFAULT_CONFIG, APPS

request = HTTPRequest()


class ErrorHandler(VKErrorHandler):

    async def unhandled_error(self, e: VKError):
        raise e


def read_config() -> dict:
    try:
        with open('config.json', 'r', encoding='utf-8') as file:
            return json.loads(file.read())
    except FileNotFoundError:
        write_config(DEFAULT_CONFIG)
        warnings.warn("ДБ не найдена, создал новую")