예제 #1
0
파일: examples.py 프로젝트: rkbala/py-bot
 def do_POST(self):
     body = self.rfile.read(int(self.headers['Content-Length']))
     data = json.loads(str(body, 'utf-8'))
     activity = Activity.deserialize(data)
     self._adapter = BotFrameworkAdapter(APP_ID, APP_PASSWORD)
     self._adapter.on_receive = self.on_receive
     self._adapter.receive(self.headers.get("Authorization"), activity)
예제 #2
0
async def handle_mention(request: aiohttp.web.Request):
    body = await request.read()

    if not authenticate_request(request, body):
        return aiohttp.web.Response(text="Unauthenticated", status=401)

    data = json.loads(body)

    activity = Activity.deserialize(data)

    response_activity = Activity()
    response_activity.text = ""
    mo = re.findall("(#|TP)(?P<id>[0-9]+)", activity.text)

    if mo:
        for tp_id in mo:
            resp = await tp.get_assignable_by_id(tp_id[1])
            items = resp['Items']
            if items:
                response_activity.text = f"""{response_activity.text}<h1>{tp_id[1]} - {items[0]['Name']}</h1><br/>
                <a href="https://tp.niradynamics.local/entity/{tp_id[1]}">view in TP</a><br/>
                """
            else:
                response_activity.text = f"{response_activity.text}No such TP item #<b>{tp_id[1]}</b><br/>"
    else:
        response_activity.text = "Sorry, I don't understand. Please include a TP issue formatted as <b>#99999</b>"

    print(response_activity.as_dict())

    return aiohttp.web.json_response(response_activity.as_dict())
예제 #3
0
파일: main.py 프로젝트: sharatsc/tutorial
    def do_POST(self):
        body = self.rfile.read(int(self.headers['Content-Length']))
        data = json.loads(str(body, 'utf-8'))
        activity = Activity.deserialize(data)

        if not self.__handle_authentication(activity):
            return

        if activity.type == ActivityTypes.conversation_update.value:
            self.__handle_conversation_update_activity(activity)
        elif activity.type == ActivityTypes.message.value:
            self.__handle_message_activity(activity)
        else:
            self.__unhandled_activity()
예제 #4
0
async def handle_all_activity(request):
    global bot
    data = request.json
    activity = Activity.deserialize(data)
    if not await bot.authenticate(request, activity):
        return request.Response(code=500)
    if activity.type == ActivityTypes.conversation_update.value:
        bot.handle_initial_activity(activity)
        return request.Response(code=202)
    elif activity.type == ActivityTypes.message.value:
        bot.handle_message_activity(activity)
        return request.Response(code=200)
    else:
        return request.Response(code=404)
예제 #5
0
 def do_POST(self):
     body = self.rfile.read(int(self.headers['Content-Length']))
     data = json.loads(str(body, 'utf-8'))
     activity = Activity.deserialize(data)
     if activity.type == ActivityTypes.conversation_update.value:  #Initial call
         self.__handle_conversation_update_activity(activity)
     elif activity.type == ActivityTypes.message.value:
         if Bot.init == True:  # The first run
             self.__handle_initial_activity(activity)
         else:
             self.__handle_message_activity(
                 activity)  #Handles rest of all the replies
     else:
         self.__unhandled_activity()
예제 #6
0
    async def test_streaming_response_set_body_success(self):
        sut = StreamingResponse()
        activity = Activity(text="hi", type="message")

        sut.set_body(activity)

        self.assertIsNotNone(sut.streams)
        self.assertEqual(1, len(sut.streams))
        self.assertIsInstance(sut.streams[0].content, list)
        self.assertIsInstance(sut.streams[0].content[0], int)

        assert_activity = Activity.deserialize(
            json.loads(bytes(sut.streams[0].content).decode("utf-8-sig")))

        self.assertEqual(activity.text, assert_activity.text)
        self.assertEqual(activity.type, assert_activity.type)
예제 #7
0
    async def handle_POST(self, request):
        "main handler; all bot communications happens over HTTP POST"

        if self._closing.is_set():
            return aiohttp.web.Response(text="Service is shutting down",
                                        status=503)

        # set up a timestamp and counter
        n = arrow.now()
        self.counter += 1
        ts = '%i-%i-%i-%i' % (n.year, n.month, n.day, self.counter)

        # parse into Activity
        jsonmsg = await request.json()
        activity = Activity.deserialize(jsonmsg)

        # try to authenticate if required
        if not self.authenticated and self.authentication_required:
            result = await self.authenticate(request, activity)
            if result == False:
                return aiohttp.web.Response(text="Bot could not authenticate",
                                            status=401)

        # handle different activities
        if activity.type == ActivityTypes.conversation_update.value:
            self.handle_join(activity)
        elif activity.type == ActivityTypes.message.value:
            connector = ConnectorClient(self.credentials,
                                        base_url=activity.service_url)
            orig = (activity, connector)
            msg = Message(activity.text, activity.from_property,
                          activity.channel_id, self, orig)
            self._queue.put_nowait(msg)
            _LOGGER.debug("queued message")
        else:
            _LOGGER.warning("got invalid activity in message %s: %s", ts,
                            activity.name)
            _LOGGER.debug(activity)
            _LOGGER.debug(jsonmsg)

        return aiohttp.web.Response(text="OK", status=200)
예제 #8
0
    def message_received(self):
        """ handles incoming messages """
        logger.info(f"Received message: \n {request.get_json()}")
        activity = Activity.deserialize(request.get_json())
        authorization = request.headers.get("Authorization")

        # if not self._handle_authentication(authorization, activity):
        #    logger.info("Authorization failed. Not processing request")
        #    return ""
        self._service_url = activity.service_url
        try:
            if activity.type == ActivityTypes.message.value:
                self._update_user_map(activity)
                mentions = self._extract_mentions(activity)
                message_text = activity.text
                matched = False
                for match_type, matcher, func in self._messagehooks:
                    if match_type == "REGEX":
                        if matcher.findall(message_text.lower()):
                            func(activity, mentions)
                            matched = True
                            break
                    elif match_type == "FUNC":
                        if matcher(message_text):
                            func(activity, mentions)
                            matched = True
                            break
                if not matched and self._messagehook_unknown:
                    self._messagehook_unknown(activity, mentions)
            self._save_system_config()
        except Exception as e:
            traceback.print_exc()
            try:
                self.send_reply("Es ist ein Fehler aufgetreten: %s" % e, reply_to=activity)
            except:
                traceback.print_exc()
        return ""
    async def process_request(
            self,
            request: ReceiveRequest,
            logger: Logger,  # pylint: disable=unused-argument
            context: object,  # pylint: disable=unused-argument
    ) -> StreamingResponse:
        # pylint: disable=pointless-string-statement
        response = StreamingResponse()

        # We accept all POSTs regardless of path, but anything else requires special treatment.
        if not request.verb == StreamingRequest.POST:
            return self._handle_custom_paths(request, response)

        # Convert the StreamingRequest into an activity the adapter can understand.
        try:
            body_str = await request.read_body_as_str()
        except Exception as error:
            traceback.print_exc()
            response.status_code = int(HTTPStatus.BAD_REQUEST)
            # TODO: log error

            return response

        try:
            # TODO: validate if should use deserialize or from_dict
            body_dict = loads(body_str)
            activity: Activity = Activity.deserialize(body_dict)

            # All activities received by this StreamingRequestHandler will originate from the same channel, but we won't
            # know what that channel is until we've received the first request.
            if not self.service_url:
                self._service_url = activity.service_url

            # If this is the first time the handler has seen this conversation it needs to be added to the dictionary so
            # the adapter is able to route requests to the correct handler.
            if not self.has_conversation(activity.conversation.id):
                self._conversations[activity.conversation.id] = datetime.now()
            """
            Any content sent as part of a StreamingRequest, including the request body
            and inline attachments, appear as streams added to the same collection. The first
            stream of any request will be the body, which is parsed and passed into this method
            as the first argument, 'body'. Any additional streams are inline attachments that need
            to be iterated over and added to the Activity as attachments to be sent to the Bot.
            """

            if len(request.streams) > 1:
                stream_attachments = [
                    Attachment(content_type=stream.content_type,
                               content=stream.stream)
                    for stream in request.streams
                ]

                if activity.attachments:
                    activity.attachments += stream_attachments
                else:
                    activity.attachments = stream_attachments

            # Now that the request has been converted into an activity we can send it to the adapter.
            adapter_response = await self._activity_processor.process_streaming_activity(
                activity, self._bot.on_turn)

            # Now we convert the invokeResponse returned by the adapter into a StreamingResponse we can send back
            # to the channel.
            if not adapter_response:
                response.status_code = int(HTTPStatus.OK)
            else:
                response.status_code = adapter_response.status
                if adapter_response.body:
                    response.set_body(adapter_response.body)

        except Exception as error:
            traceback.print_exc()
            response.status_code = int(HTTPStatus.INTERNAL_SERVER_ERROR)
            response.set_body(str(error))
            # TODO: log error

        return response