예제 #1
0
 def __init__(self, tokens: typing.Union[str, typing.List[str]]):
     self.client = AIOHTTPClient()
     self.tokens = (
         BotSyncSingleToken(Token(tokens))
         if isinstance(tokens, str)
         else BotSyncPoolTokens([Token(token) for token in tokens])
     )
     self.api = API(clients=self.client, tokens=self.tokens)
예제 #2
0
async def get_api():
    client = AIOHTTPClient()
    token = Token(TOKEN)
    bot_token = BotSyncSingleToken(token)
    vk_session = API(
        clients=client,
        tokens=bot_token,
    )

    api = vk_session.get_context()
    return api
예제 #3
0
async def test_vk_storage():
    token = os.environ.get("VK_BOT_TOKEN")
    if not token:
        pytest.skip("unsupported configuration")

    client = AIOHTTPClient()
    token = BotSyncSingleToken(token)
    api_session = API(token, client)
    api = api_session.get_context()

    storage = VKStorage(api)
    await storage_interact_test(storage)
    await client.close()
예제 #4
0
async def main():
    client = AIOHTTPClient()
    token = BotSyncSingleToken(bot_token)
    api_session = API(token, client)
    api = api_session.get_context()
    lp_data = BotLongpollData(gid)
    longpoll = BotLongpoll(api, lp_data)
    token_storage = TokenStorage[GroupId]()
    dp = Dispatcher(api_session, token_storage)
    lp_extension = BotLongpollExtension(dp, longpoll)

    dp.add_router(router)
    await dp.cache_potential_tokens()
    await lp_extension.start()
예제 #5
0
async def main():
    async def error_handler(error: dict, api_ctx):
        print(error)
        # some crazy stuff

    # on some code errors you can re-do request and return result of response
    # they are: 1, 6, 14

    async def error_handler_another(error: dict, api_ctx) -> dict:
        # doing request
        result = ...
        return result

    # also you can set default error handler if handler for this code is not found.
    # code 4 -> finding handler -> ...
    # found -> run that handler
    # not found -> run this handler

    # if default error handler isn't set exception will be raised
    async def default(error: dict, api_ctx):
        if error["error"]["error_code"] in RETURN_RESULT_ERRORS:
            ...
        else:
            ...

    api = API(tokens="...", clients=AIOHTTPClient())
    api.default_api_options.error_dispatcher.add_handler(
        3, error_handler)  # unknown method passed
    api.default_api_options.error_dispatcher.add_handler(
        6, error_handler_another)  # too many requests
    api.default_api_options.error_dispatcher.set_default_error_handler(
        default)  # default handler

    ctx = api.get_context()

    await ctx.status.get()
예제 #6
0
class _APIContextManager:
    def __init__(self, tokens: typing.Union[str, typing.List[str]]):
        self.client = AIOHTTPClient()
        self.tokens = (
            BotSyncSingleToken(Token(tokens))
            if isinstance(tokens, str)
            else BotSyncPoolTokens([Token(token) for token in tokens])
        )
        self.api = API(clients=self.client, tokens=self.tokens)

    async def __aenter__(self):
        return self.api.get_context()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()

    async def close(self):
        await self.client.close()
예제 #7
0
from vkwave.bots.core.tokens.storage import TokenStorage
from vkwave.bots.core.tokens.types import GroupId
from vkwave.client.default import AIOHTTPClient
from vkwave.longpoll.bot import BotLongpoll, BotLongpollData

basicConfig(level="DEBUG")
logger = getLogger(__name__)

text = lambda text: TextFilter(text)
text_startswith = lambda text: lambda event: event.object.object.message.text.startswith(
    text)
new_message = EventTypeFilter("message_new")

router = DefaultRouter()
wd = router.registrar.with_decorator
api = API(BotSyncSingleToken(getenv("TOKEN")), AIOHTTPClient())
token_storage = TokenStorage[GroupId]()

dp = Dispatcher(api, token_storage)
ext = BotLongpollExtension(
    dp, BotLongpoll(api.get_context(), BotLongpollData(getenv("GROUP_ID"))))

client = AsyncUrbanClient()


def make_result(defs: List[UrbanDefinition]) -> str:
    result = ""

    for i, d in enumerate(defs, start=1):
        if i == 4:
            break
예제 #8
0
    for param in error["error"]["request_params"]:
        if param["key"] in ("oauth", "v", "method"):
            continue
        request_params[param["key"]] = param["value"]

    key = await solve_captcha(error["error"]["captcha_img"])

    request_params.update({"captcha_sid": error["error"]["captcha_sid"], "captcha_key": key})
    await api_ctx.api_request(method, params=request_params)


# Easy way

bot = SimpleLongPollBot(tokens="MyToken", group_id=123456789)
bot.api_session.default_api_options.error_dispatcher.add_handler(14, captcha_handler)


# Not easy way


api_session = API(BotSyncSingleToken(Token("MyToken")), AIOHTTPClient())
api = api_session.get_context()
dp = Dispatcher(api_session, TokenStorage[GroupId]())
lp_extension = BotLongpollExtension(dp, BotLongpoll(api, BotLongpollData(123456789)))

api_session.default_api_options.error_dispatcher.add_handler(14, captcha_handler)




예제 #9
0
from vkwave.api.token.token import Token, BotSyncSingleToken
from vkwave.bots.utils.uploaders.photo_uploader import PhotoUploader
from vkwave.client.default import AIOHTTPClient
from vkwave.api.methods import API
import asyncio

client = AIOHTTPClient()
api = API(
    clients=client,
    tokens=BotSyncSingleToken(Token("token")),
)

uploader = PhotoUploader(api.get_context())


async def main():
    big_attachment = await uploader.get_attachments_from_links(
        peer_id=1234,
        links=[
            "https://user-images.githubusercontent.com/28061158/75329873-7f738200-5891-11ea-9565-fd117ea4fc9e.jpg",
            "https://camo.githubusercontent.com/9c8d6519e5997860b7a4b28f74719c0c2f83142b/68747470733a2f2f692e696d6775722e636f6d2f386955334578366c2e6a7067",
            "https://user-images.githubusercontent.com/28061158/74590410-239e3300-501f-11ea-9774-27ee507a1e1e.jpg",
        ],
    )
    await api.get_context().messages.send(user_id=1234,
                                          attachment=big_attachment,
                                          random_id=0)
    # TODO: voice


asyncio.get_event_loop().run_until_complete(main())