def __init__( self, tokens: typing.Union[str, typing.List[str]], bot_type: BotType, router: typing.Optional[BaseRouter] = None, group_id: typing.Optional[int] = None, uvloop: bool = False, ): if uvloop: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) self.group_id = group_id self.bot_type = bot_type self.api_session = create_api_session_aiohttp(tokens, bot_type) self.api_context: APIOptionsRequestContext = self.api_session.api.get_context( ) if self.bot_type is BotType.USER: if not isinstance(tokens, str): raise RuntimeError("Only one str token") self.SimpleBotEvent = SimpleUserEvent self._lp = UserLongpoll(self.api_context, UserLongpollData()) self._token_storage = UserTokenStorage[UserId](tokens) self.dispatcher = Dispatcher(self.api_session.api, self._token_storage) self._lp = UserLongpollExtension(self.dispatcher, self._lp) else: self.SimpleBotEvent = SimpleBotEvent self._lp = BotLongpoll(self.api_context, BotLongpollData(group_id)) self._token_storage = TokenStorage[GroupId]() self.dispatcher = Dispatcher(self.api_session.api, self._token_storage) self._lp = BotLongpollExtension(self.dispatcher, self._lp) self.middleware_manager = self.dispatcher.middleware_manager # auf self.add_middleware = self.middleware_manager.add_middleware self.router = router or DefaultRouter() self.dispatcher.add_router(self.router) self.text_filter = TextFilter self.event_type_filter = EventTypeFilter self.payload_filter = PayloadFilter self.chat_action_filter = ChatActionFilter self.command_filter = CommandsFilter self.regex_filter = RegexFilter self.state_filter = StateFilter self.vbml_filter = VBMLFilter self.reply_filter = ReplyMessageFilter self.args_filter = MessageArgsFilter self.fwd_filter = FwdMessagesFilter self.conversation_type_filter = MessageFromConversationTypeFilter self.text_contains_filter = TextContainsFilter self.payload_contains_filter = PayloadContainsFilter self.text_startswith_filter = TextStartswithFilter if self.bot_type is BotType.USER: self.from_me_filter = FromMeFilter
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()
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() 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()
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 result += f"{d.word}: {d.definition}\nExample: \n{d.example}" return result
class BaseSimpleLongPollBot: def __init__(self, tokens: typing.Union[str, typing.List[str]], bot_type: BotType, router: typing.Optional[BaseRouter] = None, group_id: typing.Optional[int] = None, uvloop: bool = False): if uvloop: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) self.bot_type = bot_type self.api_session = create_api_session_aiohttp(tokens, bot_type) self.api_context: APIOptionsRequestContext = self.api_session.api.get_context( ) if self.bot_type is BotType.USER: if not isinstance(tokens, str): raise RuntimeError("Only one str token") self.SimpleBotEvent = SimpleUserEvent self._lp = UserLongpoll(self.api_context, UserLongpollData()) self._token_storage = UserTokenStorage[UserId](tokens) self.dispatcher = Dispatcher(self.api_session.api, self._token_storage) self._lp = UserLongpollExtension(self.dispatcher, self._lp) else: self.SimpleBotEvent = SimpleBotEvent self._lp = BotLongpoll(self.api_context, BotLongpollData(group_id)) self._token_storage = TokenStorage[GroupId]() self.dispatcher = Dispatcher(self.api_session.api, self._token_storage) self._lp = BotLongpollExtension(self.dispatcher, self._lp) self.middleware_manager = self.dispatcher.middleware_manager # auf self.router = router or DefaultRouter() self.handler = self.router.registrar.with_decorator self.dispatcher.add_router(self.router) self.text_filter = TextFilter self.event_type_filter = EventTypeFilter self.payload_filter = PayloadFilter self.chat_action_filter = ChatActionFilter self.command_filter = CommandsFilter self.regex_filter = RegexFilter self.state_filter = StateFilter self.vbml_filter = VBMLFilter self.args_filter = MessageArgsFilter self.fwd_filter = FwdMessagesFilter self.conversation_type_filter = MessageFromConversationTypeFilter self.text_contains_filter = TextContainsFilter if self.bot_type is BotType.USER: self.from_me_filter = FromMeFilter class SimpleBotCallback(BaseCallback): def __init__( self, func: typing.Callable[[BaseEvent], typing.Awaitable[typing.Any]], bot_type: BotType, ): self.bot_type = bot_type self.func = func async def execute( self, event: typing.Union[UserEvent, BotEvent]) -> typing.Any: if self.bot_type is BotType.BOT: new_event = SimpleBotEvent(event) else: new_event = SimpleUserEvent(event) if inspect.iscoroutinefunction(self.func): return await self.func(new_event) return self.func(new_event) class SimpleBotMiddleware(BaseMiddleware): async def pre_process_event(self, event: BaseEvent) -> MiddlewareResult: pass def handler(self, *filters: BaseFilter): """ Handler for all events """ def decorator(func: typing.Callable[..., typing.Any]): record = self.router.registrar.new() record.with_filters(*filters) record.handle(self.SimpleBotCallback(func, self.bot_type)) self.router.registrar.register(record.ready()) return func return decorator def message_handler(self, *filters: BaseFilter): """ Handler only for message events """ def decorator(func: typing.Callable[..., typing.Any]): record = self.router.registrar.new() record.with_filters(*filters) if self.bot_type is BotType.BOT: record.filters.append(EventTypeFilter( BotEventType.MESSAGE_NEW)) else: record.filters.append( EventTypeFilter(EventId.MESSAGE_EVENT.value)) record.handle(self.SimpleBotCallback(func, self.bot_type)) self.router.registrar.register(record.ready()) return func return decorator def middleware(self): def decorator( func: typing.Callable[[typing.Union[UserEvent, BotEvent]], MiddlewareResult]): middleware = self.SimpleBotMiddleware() middleware.pre_process_event = func self.middleware_manager.add_middleware(middleware) return func return decorator async def run(self): if self.bot_type is BotType.BOT: await self.dispatcher.cache_potential_tokens() await self._lp.start() def run_forever(self, loop: typing.Optional[asyncio.AbstractEventLoop] = None): loop = loop or asyncio.get_event_loop() loop.create_task(self.run()) loop.run_forever()
# 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)