示例#1
0
def bot_dispatcher() -> Dispatcher:
    """
    Set context manually for properly processing webhook updates.
    """
    Bot.set_current(dp.bot)
    Dispatcher.set_current(dp)
    return dp
示例#2
0
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])
示例#3
0
async def main(req: func.HttpRequest) -> func.HttpResponse:
    update = req.get_json()
    updateObj = types.Update.to_object(update)
    logging.info('Update: ' + str(updateObj))
    Bot.set_current(dp.bot)
    await dp.process_update(updateObj)
    return func.HttpResponse("", status_code=200) 
示例#4
0
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
示例#5
0
    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)
示例#6
0
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'}
示例#7
0
 def __init__(self, *args, update_frequency=10, without_db=False, **kwargs):
     super(Mailer, self).__init__(*args, **kwargs)
     self.update_frequency = update_frequency
     Bot.set_current(self)
     if without_db:
         return
     self.ACTIVE_CHATS = {chat.recipient for chat in Chats.select()}
示例#8
0
async def test_booking_command(telegram_bot, booking_message, monkeypatch):
    Bot.set_current(telegram_bot._bot)
    monkeypatch.setattr(types.Message,
                        "answer",
                        mock_answer_booking,
                        raising=True)
    await telegram_bot._handle_update(booking_message)
示例#9
0
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
示例#10
0
async def process_event(event, dp: Dispatcher):
    """
    Converting an AWS Lambda event to an update and handling that
    update
    """

    Bot.set_current(dp.bot)
    update = types.Update.to_object(event)
    await dp.process_update(update)
示例#11
0
 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
示例#12
0
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()
示例#13
0
 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)
示例#14
0
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)
示例#15
0
文件: main.py 项目: Hollow667/gatee
    async def on_startup():
        bot = Bot(token=os.getenv("API_TOKEN"), parse_mode="Markdown")
        Bot.set_current(bot)
        dp = Dispatcher()

        loop = asyncio.get_event_loop()

        include_routers(dp)
        app.state.bot = bot

        loop.create_task(dp.start_polling(bot))
async def process_event(event, dp: Dispatcher):
    """
    Converting an Yandex.Cloud functions event to an update and
    handling tha update.
    """

    update = json.loads(event['body'])
    log.debug('Update: ' + str(update))

    Bot.set_current(dp.bot)
    update = types.Update.to_object(update)
    await dp.process_update(update)
示例#17
0
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
示例#18
0
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
示例#19
0
    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()
示例#20
0
 async def _process_update(self, event: DialogUpdateEvent):
     Bot.set_current(event.bot)
     User.set_current(event.from_user)
     Chat.set_current(event.chat)
     await self.update_handler.notify(event)
示例#21
0
    def __init__(self):
        # Logging setup
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        # Bot setup
        try:
            self.bot = SafeBot(token=os.environ['BOT_TOKEN'])
            Bot.set_current(
                self.bot
            )  # just to be sure with all of that class override things
        except KeyError:
            logging.critical('Please specify BOT_TOKEN ENV variable')
            exit(-1)
        self.dp = Dispatcher(self.bot)
        commands.apply_handlers(self)

        try:
            aapi_host = os.environ['AAPI_HOST']
        except KeyError:
            logging.critical(
                'Please specify AAPI_HOST (admission api host link) ENV variable'
            )
            exit(-1)

        try:
            aapi_token = os.environ['AAPI_TOKEN']
        except KeyError:
            logging.critical(
                'Please specify AAPI_TOKEN (admission api bearer token) ENV variable'
            )
            exit(-1)

        # noinspection PyUnboundLocalVariable
        self.aapi = AdmissionAPI(aapi_host, aapi_token)
        # i18n setup

        cwd = getcwd()
        translations_dir = path.abspath(path.join(cwd, 'translations'))
        if not path.isdir(translations_dir):
            logging.error(
                f"i18n: Translations path ({translations_dir}) does not exist")
            exit(-1)

        i18n.load_path.append(translations_dir)
        i18n.set('filename_format', '{locale}.{format}')
        i18n.set('locale', 'ua')
        i18n.set('fallback', 'ua')

        async def send_message_handler(request: web.Request):
            if request.headers['Authorization'] != f'Bearer {aapi_token}':
                return web.Response(status=401)
            query = parse_qs(request.query_string)
            await self.bot.send_message(chat_id=query['uid'][0],
                                        text=query['text'][0],
                                        parse_mode=query['parse_mode'][0]
                                        if 'parse_mode' in query else None)
            return web.Response()

        webapp = web.Application()
        webapp.router.add_post('/sendMessage', send_message_handler)

        self.runner = web.AppRunner(webapp)
示例#22
0
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)
示例#23
0
    def __init__(self, message_data, bot=None, **kwargs):
        super().__init__(**kwargs)
        self._body, self._headers = self.parse_data(message_data)

        if isinstance(bot, Bot):
            Bot.set_current(bot)
示例#24
0
def bot_dispatcher() -> Dispatcher:
    Bot.set_current(dispatcher.bot)
    Dispatcher.set_current(dispatcher)
    return dispatcher