async def main(): # await bb.start() # stor.asyncio_loop.stop() # return path = os.path.dirname(os.path.abspath(__file__)) full_path = f"{path}/base/config{mode}.json" with open(full_path, 'r') as file: stor.config = json.load(file) bot_tokens = Token(stor.config['TOKEN']) user_tokens = Token(stor.config['USER_TOKEN']) stor.config['BASEFILE'] = f"{path}/base/{stor.config['BASEFILE']}" stor.config['LOGFILE'] = f"{path}/base/{stor.config['LOGFILE']}" stor.config['CONFIG'] = full_path logging.basicConfig(level=stor.config['LOGLEVEL'], filename=stor.config['LOGFILE']) logging.addLevelName(11, 'OK') logging.addLevelName(12, 'DONE') logging.addLevelName(13, 'NO') logging.addLevelName(14, 'BAD') base_logger = logging.getLogger('base') command_logger = logging.getLogger('co') utils.st.logger = command_logger stor.start_time = int(time.time()) user_client = AIOHTTPClient() user_tokens = [UserSyncSingleToken(tok) for tok in user_tokens] stor.user_api = API(user_tokens, user_client) client = AIOHTTPClient() tokens = [BotSyncSingleToken(tok) for tok in bot_tokens] api_session = API(tokens, client) api = api_session.get_context() lp_data = BotLongpollData(stor.config['GROUP_ID']) longpoll = BotLongpoll(api, lp_data) token_storage = TokenStorage[GroupId]() dp = Dispatcher(api_session, token_storage) dp.add_router(await hand.initiate_router(DefaultRouter())) await dp.cache_potential_tokens() await base.initiate(stor.config['BASEFILE'], base_logger) # storage = ConfirmationStorage() # storage.add_confirmation(GroupId(stor.config['GROUP_ID']),stor.config['CONFIRMATION']) # cb_extension = AIOHTTPCallbackExtension( # dp, path="/", host="0.0.0.0", port=80, secret=stor.config['SECRET'], confirmation_storage=storage # ) lp_extension = BotLongpollExtension(dp, longpoll) # await cb_extension.start() await lp_extension.start()
async def main(): client = AIOHTTPClient() token = BotSyncSingleToken(bot_token) api_session = API(token, client) api = api_session.get_context() longpoll = UserLongpoll(api, UserLongpollData()) token_storage = UserTokenStorage[UserId](bot_token) dp = Dispatcher(api_session, token_storage) lp_extension = UserLongpollExtension(dp, longpoll) dp.add_router(router) await lp_extension.start()
def __init__(self, tokens: typing.Union[str, typing.List[str]], bot_type: BotType): self.client = AIOHTTPClient() if bot_type.USER: self.tokens = (UserSyncSingleToken(Token(tokens)) if isinstance( tokens, str) else BotSyncPoolTokens( [Token(token) for token in tokens])) else: 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 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()
async def main(): client = AIOHTTPClient() token = BotSyncSingleToken(bot_token) api_session = API(token, client) token_storage = TokenStorage[GroupId]() dp = Dispatcher(api_session, token_storage) storage = ConfirmationStorage() storage.add_confirmation(GroupId(gid), "CONFIRMATION_KEY") cb_extension = AIOHTTPCallbackExtension(dp, path="/", host="127.0.0.1", port=80, secret="SECRET_KEY", confirmation_storage=storage) dp.add_router(router) await dp.cache_potential_tokens() await cb_extension.start()
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()
from loguru import logger from vkwave.api import API from vkwave.bots import DefaultRouter from vkwave.bots import MessageFromConversationTypeFilter from vkwave.bots import SimpleBotEvent from vkwave.bots import simple_bot_message_handler from vkwave.client import AIOHTTPClient from database import utils as db from database.models import Student from services import filters from services import keyboard as kbs from services.logger.config import config contacts_router = DefaultRouter() api_session = API(tokens=os.getenv("VK_TOKEN"), clients=AIOHTTPClient()) api = api_session.get_context() logger.configure(**config) @simple_bot_message_handler( contacts_router, filters.PLFilter({"button": "contacts"}), MessageFromConversationTypeFilter("from_pm"), ) @logger.catch() async def start_contacts(ans: SimpleBotEvent): with logger.contextualize(user_id=ans.object.object.message.from_id): db.shortcuts.update_admin_storage( db.students.get_system_id_of_student( ans.object.object.message.from_id),
def __init__(self, token: str, api_version: typing.Optional[str] = None): client = AIOHTTPClient() token = UserSyncSingleToken(Token(token)) self._api = LibAPI(tokens=token, clients=client, api_version=api_version)
import asyncio from vkwave.api import Token, BotSyncSingleToken, API from vkwave.bots.utils import PhotoUploader from vkwave.client import AIOHTTPClient client = AIOHTTPClient() api = API(clients=client, tokens=BotSyncSingleToken(Token("token")),) uploader = PhotoUploader(api.get_context()) # same with VoiceUploader etc. 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) asyncio.get_event_loop().run_until_complete(main())
# not the greatest implementation, but you can make any method = error["error"]["request_params"]["method"] request_params = {} 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}) return await api_ctx.api_request(method, params=request_params) # Easy way bot = SimpleLongPollBot(tokens="MyToken", group_id=123456789) bot.api_session.api.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)
GroupId, ) from vkwave.client import AIOHTTPClient from vkwave.longpoll 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