def __init__(self, token: str, group_id: typing.Optional[int] = None, loop: typing.Optional[asyncio.AbstractEventLoop] = None, uvloop: bool = False): """ exist group_id - bot_type == BOT group_id is none - bot_type == USER """ if uvloop: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) self.token = token self.group_id = group_id self._api_session = create_api_session_aiohttp(token) self.api = self._api_session.api self.api_context = self.api.get_context() self.loop = loop or asyncio.get_event_loop() if self.group_id is not None: self.longpoll = BotLongpoll(self.api_context, BotLongpollData(self.group_id)) self.get_event_object = bot_get_event_object else: self.longpoll = UserLongpoll(self.api_context, UserLongpollData()) self.get_event_object = user_get_event_object
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()
class LowLevelBot: """ Bot with raw longpoll for more performance """ def __init__(self, token: str, group_id: typing.Optional[int] = None, loop: typing.Optional[asyncio.AbstractEventLoop] = None, uvloop: bool = False): """ exist group_id - bot_type == BOT group_id is none - bot_type == USER """ if uvloop: import uvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) self.token = token self.group_id = group_id self._api_session = create_api_session_aiohttp(token) self.api = self._api_session.api self.api_context = self.api.get_context() self.loop = loop or asyncio.get_event_loop() if self.group_id is not None: self.longpoll = BotLongpoll(self.api_context, BotLongpollData(self.group_id)) self.get_event_object = bot_get_event_object else: self.longpoll = UserLongpoll(self.api_context, UserLongpollData()) self.get_event_object = user_get_event_object async def _listen(self, ignore_errors: bool): if ignore_errors: while True: try: async for event in self.longpoll.event_by_event(): yield event except Exception as e: logger.error(e) await asyncio.sleep(0.1) continue else: async for event in self.longpoll.event_by_event(): yield event async def listen( self, fast_mode: bool = False, ignore_errors: bool = False ) -> typing.AsyncGenerator[typing.Union[BaseBotEvent, BaseUserEvent, Update], None]: """ Listening for events :param fast_mode: - return raw events :param ignore_errors: - ignore all lp errors, (internet connection or vk internal server errors) """ if fast_mode: return_event = lambda _event: _event else: return_event = lambda _event: self.get_event_object(_event) async for event in self._listen(ignore_errors=ignore_errors): yield return_event(event) def react(self, reaction: typing.Union[typing.Awaitable]): self.loop.create_task(reaction) def run(self, main_loop: typing.Awaitable): self.loop.create_task(main_loop) self.loop.run_forever()