async def callback_telegram(request: Dict[str, Any] = Body(...), dp: Dispatcher = Depends(bot_dispatcher)): Bot.set_current(dp.bot) Dispatcher.set_current(dp) telegram_update = types.Update(**request) await dp.process_update(telegram_update) return {'status': 'OK'}
async def myupdate(): update = { "update_id": 960323333, "message": { "message_id": 3846, "from": { "id": 20936078, "is_bot": False, "first_name": "ᴅᴀᴠʟᴀᴛᴊᴏɴ🐼", "username": "******", "language_code": "ru" }, "chat": { "id": 20936078, "first_name": "ᴅᴀᴠʟᴀᴛᴊᴏɴ🐼", "username": "******", "type": "private" }, "date": 1602509595, "text": "/start", "entities": [{ "offset": 0, "length": 6, "type": "bot_command" }] } } # mydict = {k: v.encode("utf-8") for k, v in update.items()} # update = json.dumps(update) update = types.Update(**update) Bot.set_current(dp.bot) Dispatcher.set_current(dp) await dp.process_updates([update])
def __init__(self, dispatcher, skip_updates=None, check_ip=False, retry_after=None, loop=None): if loop is not None: self._loop = loop self.dispatcher = dispatcher self.skip_updates = skip_updates self.check_ip = check_ip self.retry_after = retry_after self._identity = secrets.token_urlsafe(16) self._web_app = None self._on_startup_webhook = [] self._on_startup_polling = [] self._on_shutdown_webhook = [] self._on_shutdown_polling = [] self._freeze = False from aiogram import Bot, Dispatcher Bot.set_current(dispatcher.bot) Dispatcher.set_current(dispatcher)
def bot_dispatcher() -> Dispatcher: """ Set context manually for properly processing webhook updates. """ Bot.set_current(dp.bot) Dispatcher.set_current(dp) return dp
def bot_dispatcher() -> Dispatcher: bot = Bot(token=token, parse_mode="MarkdownV2") dp = Dispatcher(bot) Bot.set_current(dp.bot) Dispatcher.set_current(dp) @dp.message_handler(lambda msg: msg.from_user.id not in whitelist, commands=["start"]) async def start_handler(message: Message): await message.answer( text(escape_md("Send me your message now."), f"I will reply *as soon as I can*")) mention = message.from_user.get_mention(as_html=False) await dp.bot.send_message( channel_id, text(f"Launched by {mention}", escape_md(f"(id={message.from_user.id})"))) @dp.message_handler(lambda msg: msg.from_user.id not in whitelist, content_types=ContentTypes.TEXT | ContentTypes.PHOTO | ContentTypes.DOCUMENT) async def forward_handler(message: Message): await message.forward(channel_id) @dp.message_handler(lambda msg: msg.from_user.id not in whitelist, content_types=ContentTypes.ANY) async def trash_handler(message: Message): await message.delete() return dp
def initialize_project(dispatcher: Dispatcher = None, bot: Bot = None, loop=None) -> typing.Tuple[Dispatcher, Bot]: if not TELEGRAM_BOT_TOKEN and not bot: raise exceptions.BotTokenNotDefined if not dispatcher: loop = loop or asyncio.get_event_loop() bot = bot or Bot(token=TELEGRAM_BOT_TOKEN, parse_mode=PARSE_MODE) dp = dispatcher or Dispatcher(bot=bot, storage=BOT_STORAGE, loop=loop) else: dp = dispatcher bot = bot or dp.bot Dispatcher.set_current(dp) dp.filters_factory.bind( Entities, event_handlers=[dp.message_handlers, dp.poll_handlers]) dp.filters_factory.bind( ChatTypeFilter, event_handlers=[dp.message_handlers, dp.callback_query_handlers]) dp.filters_factory.bind( ChatMemberStatus, event_handlers=[dp.message_handlers, dp.callback_query_handlers]) dp.filters_factory.bind(PollTypeFilter, event_handlers=[ dp.message_handlers, dp.callback_query_handlers, dp.poll_handlers ]) dp.filters_factory.bind( DiceEmoji, event_handlers=[dp.message_handlers, dp.callback_query_handlers]) dp.filters_factory.bind(FuncFilter) utils.import_all_modules_in_project(project=PROJECT) views = utils.get_non_original_subclasses(BaseView, 'aiogram_oop_framework') for middleware in MIDDLEWARES: dp.middleware.setup(middleware()) from aiogram.types import BotCommand command_objects = {} ordered_views = utils.order_views(views) for view in ordered_views: view.bot = view.bot or bot if UserBaseView in view.__bases__: continue if AUTO_REGISTER_VIEWS is True and view.auto_register is True: view.register(dp=dp) if view.short_description and view.set_my_commands: commands = utils.resolve_set_my_commands(view) for command in commands: command_objects[command] = command_objects.get( command, BotCommand(command, view.short_description)) if command_objects: dp.loop.run_until_complete( bot.set_my_commands(list(command_objects.values()))) return dp, bot
def bot_dispatcher() -> Dispatcher: """ Set context manually for properly processing webhook updates. Source: https://t.me/aiogram_ru/167051 """ Bot.set_current(dispatcher.bot) Dispatcher.set_current(dispatcher) return dispatcher
def get_dispatcher(self): dp = self.request.app[self.request.path] try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dp) Bot.set_current(dp.bot) except RuntimeError: pass return dp
async def execute(req: web.Request) -> web.Response: upds = [types.Update(**(await req.json()))] Bot.set_current(dp.bot) Dispatcher.set_current(dp) try: await dp.process_updates(upds) except Exception as e: logger.error(e) finally: return web.Response()
def __init__(self, webhook_url, token, full_webhook_path, server = False): self.bot = Bot(token=token, parse_mode = "HTML") self.dp = Dispatcher(self.bot) self.dp.data['start_time'] = datetime.now() self.webhook_url = webhook_url self.full_webhook_path = full_webhook_path Dispatcher.set_current(self.dp) Bot.set_current(self.dp.bot) BotController.set_current(self)
async def webhook_handler( update_raw: Dict[str, Any] = Body(...), dp: Dispatcher = Depends(bot_dispatcher), ) -> Response: """Set route /hook with POST method will trigger this method.""" telegram_update = Update(**update_raw) Dispatcher.set_current(dp) Bot.set_current(dp.bot) await dp.process_update(telegram_update) return Response(status_code=HTTP_200_OK)
async def webhook_handle(request): update = await request.json() update = types.Update(**update) Bot.set_current(dp.bot) # без этого не работает Dispatcher.set_current(dp) try: await dp.process_update(update) except Exception: traceback.print_exception(*sys.exc_info()) return web.Response(text='ok')
def init_dp(token: str = config.TG_BOT_TOKEN) -> Dispatcher: bot = Bot( token=token, parse_mode=ParseMode.HTML, proxy=config.PROXY_URL, proxy_auth=BasicAuth(**config.PROXY_AUTH), server=TelegramAPIServer.from_base(config.TG_API_SERVER), ) storage: BaseStorage = init_storage() dp = Dispatcher(bot, storage=storage) Bot.set_current(bot) Dispatcher.set_current(dp) return dp
def get_dispatcher(app): """ Get Dispatcher instance from environment :return: :class:`aiogram.Dispatcher` """ dispatcher = app.config.get("dispatcher") try: from aiogram import Bot, Dispatcher Dispatcher.set_current(dispatcher) Bot.set_current(dispatcher.bot) except RuntimeError: pass return dispatcher
def __init__(self, dispatcher, **kwargs): self.dispatcher = dispatcher self.skip_updates = kwargs['skip_updates'] self.check_ip = kwargs['check_ip'] self.retry_after = kwargs['retry_after'] self.loop = kwargs['loop'] self.on_startup = kwargs['on_startup'] self.on_shutdown = kwargs['on_shutdown'] self._web_app = None self._frozen = False from aiogram import Bot, Dispatcher Bot.set_current(dispatcher.bot) Dispatcher.set_current(dispatcher) self._setup()
async def proceed_update(req: web.Request): upds = [types.Update(**(await req.json()))] Bot.set_current(req.app['bot']) Dispatcher.set_current(req.app['dp']) await req.app['dp'].process_updates(upds)
def bot_dispatcher() -> Dispatcher: Bot.set_current(dispatcher.bot) Dispatcher.set_current(dispatcher) return dispatcher