Exemple #1
0
    def __add_on_connection_close_callback(self):
        """This method adds an on close callback that will be invoked by pika
        when RabbitMQ closes the connection to the publisher unexpectedly.

        """
        log_debug('Adding connection close callback')
        self._connection.add_on_close_callback(self.__on_connection_closed)
Exemple #2
0
def get_athlete(name_athlete):
    """
    Get info of athlete
    :param name_athlete: str
    :return:
    """
    if not name_athlete:
        return 'nhập tên vận động viên'
    connection = Connection().get_connection()
    try:
        cursor = connection.cursor()  # prepare an object cursor

        query = """
                    SELECT * FROM athlete WHERE name='{}';
                """.format(name_athlete.strip().lower())
        log_debug(query)
        cursor.execute(query)
        result = cursor.fetchall()
        result = answer_athele(name_athlete, result)
        # cursor.close()
        # del cursor
        # connection.close()
        return result
    except MySQLError as ex:
        connection.close()
        log_error("Can't get if of athlete with name - {}: {}".format(name_athlete, ex))
        return []
Exemple #3
0
def check_exists_create(fb_id, page_id):
    """
    Check user is exists, if not create new one
    :param fb_id: str
    :param page_id: str
    :return:
    """
    connection = Connection().get_connection()
    try:
        cursor = connection.cursor()  # prepare an object cursor
        query = """
                SELECT * FROM follower WHERE fb_id={};
                """.format(fb_id)
        log_debug(query)
        cursor.execute(query)
        result = cursor.fetchone()
        if not result:
            query = """
                    INSERT INTO follower (fb_id, page_id)
                    VALUES ('{}', '{}');
                    """.format(fb_id, page_id)
            log_debug(query)
            cursor.execute(query)
            cursor.close()
            del cursor
            connection.commit()
        # connection.close()
    except MySQLError as ex:
        # connection.close()
        log_error("Can't check exists then create one: {}".format(ex))
Exemple #4
0
    def __add_on_channel_close_callback(self):
        """This method tells pika to call the on_channel_closed method if
        RabbitMQ unexpectedly closes the channel.

        """
        log_debug('Adding channel close callback')
        self._channel.add_on_close_callback(self.__on_channel_closed)
 def convert_facebook(self, recipient_id: str = "", content: str = '', obj: list = None):
     """
     message send by format facebook
     :return:
     """
     page_id = recipient_id.split("_")[1]
     fb_id = recipient_id.split("_")[0]
     data = json.dumps({
         "recipient": {
             "id": fb_id
         },
         "message": {
             "attachment": {
                 "type": "image",
                 "payload": {
                     "url": content,
                     "is_reusable": True
                 }
             }
         }
     })
     pages = self.connect.get("pages")
     if pages:
         pages = json.loads(pages)
         access_token = [_.get("page_token") for _ in pages if
                         str(_.get("page_id")) == page_id][0]
         params = {
             "access_token": "{}".format(access_token)
         }
         request = requests.post(FACEBOOK_API_ENDPOINT + "me/messages", params=params,
                                 headers=self.headers,
                                 data=data)
         log_debug('############## %s ##############' % request.text)
     else:
         log_debug("############## Can't get pages ##############")
Exemple #6
0
    def __add_on_cancel_callback(self):
        """Add a callback that will be invoked if RabbitMQ cancels the consumer
        for some reason. If RabbitMQ does cancel the consumer,
        on_consumer_cancelled will be invoked by pika.

        """
        log_debug('Adding consumer cancellation callback')
        self._channel.add_on_cancel_callback(self.__on_consumer_cancelled)
Exemple #7
0
    def __open_channel(self):
        """Open a new channel with RabbitMQ by issuing the Channel.Open RPC
        command. When RabbitMQ responds that the channel is open, the
        on_channel_open callback will be invoked by pika.

        """
        log_debug('Creating a new channel')
        self._connection.channel(on_open_callback=self.__on_channel_open)
Exemple #8
0
 def convert_zalo(self,
                  recipient_id: str = "",
                  content: str = "",
                  obj: list = None):
     """
     message send by format facebook
     :return:
     """
     log_debug(recipient_id)
Exemple #9
0
    def __on_exchange_declareok(self, unused_frame):
        """Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
        command.

        :param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame

        """
        log_debug('Exchange declared')
        self.__setup_queue(self.QUEUE)
Exemple #10
0
    def __setup_queue(self, queue_name):
        """Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
        command. When it is complete, the on_queue_declareok method will
        be invoked by pika.

        :param str|unicode queue_name: The name of the queue to declare.

        """
        log_debug('Declaring queue {}'.format(queue_name))
        self._channel.queue_declare(self.__on_queue_declareok, queue_name)
Exemple #11
0
    def __on_connection_open(self, unused_connection):
        """This method is called by pika once the connection to RabbitMQ has
        been established. It passes the handle to the connection object in
        case we need it, but in this case, we'll just mark it unused.

        :type unused_connection: pika.SelectConnection

        """
        log_debug('Connection opened')
        self.__add_on_connection_close_callback()
        self.__open_channel()
Exemple #12
0
    def __on_consumer_cancelled(self, method_frame):
        """Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
        receiving messages.

        :param pika.frame.Method method_frame: The Basic.Cancel frame

        """
        log_debug(
            'Consumer was cancelled remotely, shutting down: {}'.format(method_frame))
        if self._channel:
            self._channel.close()
Exemple #13
0
    def __setup_exchange(self, exchange_name):
        """Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
        command. When it is complete, the on_exchange_declareok method will
        be invoked by pika.

        :param str|unicode exchange_name: The name of the exchange to declare

        """
        log_debug('Declaring exchange {}'.format(exchange_name))
        self._channel.exchange_declare(self.__on_exchange_declareok, exchange_name,
                                       self.EXCHANGE_TYPE)
Exemple #14
0
    def __on_channel_open(self, channel):
        """This method is invoked by pika when the channel has been opened.
        The channel object is passed in so we can make use of it.

        Since the channel is now open, we'll declare the exchange to use.

        :param pika.channel.Channel channel: The channel object

        """
        log_debug('Channel opened')
        self._channel = channel
        self.__add_on_channel_close_callback()
        self.__setup_exchange(self.EXCHANGE)
        self.__start_consuming()
Exemple #15
0
    def __start_consuming(self):
        """This method sets up the consumer by first calling
        add_on_cancel_callback so that the object is notified if RabbitMQ
        cancels the consumer. It then issues the Basic.Consume RPC command
        which returns the consumer tag that is used to uniquely identify the
        consumer with RabbitMQ. We keep the value to use it when we want to
        cancel consuming. The on_message method is passed in as a callback pika
        will invoke when a message is fully received.

        """
        log_debug('Issuing consumer related RPC commands')
        self.__add_on_cancel_callback()
        self._consumer_tag = self._channel.basic_consume(
            self.__on_message, self.QUEUE)
Exemple #16
0
    def handle(self, data):
        """
        Handle message from user
        """
        # endpoint for processing incoming messaging events
        # log_debug(data)
        log_debug(data)
        if data.get("source") == "facebook":
            if data.get("object") == "page":
                for entry in data.get("entry"):
                    for messaging_event in entry['messaging']:
                        log_debug('handle - souce = "facebook"')
                        log_debug('+++++++++++++++++++++++++++++++++++++++')
                        self.handle_message_facebook(messaging_event)

            return
        if data.get("source") == "zalo":
            if data.get("event_name") == "user_send_text":
                if data.get('message'):
                    log_debug('handle - source = "zalo"')
                    log_debug('+++++++++++++++++++++++++++++++++++++++')
                    self.handle_message_zalo(data)
            return
Exemple #17
0
def get_ranking():
    """
    Get ranking
    :return:
    """
    connection = Connection().get_connection()
    try:
        cursor = connection.cursor()  # prepare an object cursor

        query = """
                SELECT * FROM ranking ORDER BY position ASC;
                """
        log_debug(query)
        cursor.execute(query)
        result = cursor.fetchall()
        result = answer_ranking(result)
        # cursor.close()
        # del cursor
        # connection.close()
        return result
    except MySQLError as ex:
        connection.close()
        log_error("Can't get ranking: {}".format(ex))
        return []
Exemple #18
0
    def get_snips(self, sentence):
        """
        get snips in sentence
        :param sentence: str
        :return:
        {
            "intent": "schedule",
            "sentence": "lịch thi đấu ngày mai",
            "entity": {
                date_start: ngay mai
            }
        }
        """
        res = dict()
        log_debug('############# PREPROCESSING ##############')
        sentence = unicodedata.normalize("NFC", sentence.lower())
        log_debug("Sentence after preprocessing: {}".format(sentence))

        log_debug('############# NER ##############')
        entity = self.nlu.parse_nlu(sentence)
        log_debug("Entity: {}".format(entity))

        sentence = sentence.replace(
            entity["is_name"][0],
            'vận động viên') if entity["is_name"] else sentence

        sentence = sentence.replace(entity["is_name"][0], entity["is_name"][0] + ' bộ môn') if \
            entity["is_name"] else sentence

        log_debug('############# CLASSIFICATION ##############')
        intent = self.intent.predict(sentence, entity)
        log_debug("Intent: {}".format(intent))

        res["sentence"] = sentence
        res["entity"] = entity
        res["intent"] = intent
        return res
Exemple #19
0
    def convert_facebook(self,
                         recipient_id: str = "",
                         content: str = "",
                         obj: list = None):
        """
        message send by format facebook
        :return:
        """
        page_id = recipient_id.split("_")[1]
        fb_id = recipient_id.split("_")[0]

        list_product = []
        for item in obj:
            product = {
                "title":
                "%s" % item.get("title"),
                "image_url":
                "%s" % item.get("image_url")
                if item.get("image_url") is not None else IMAGE_URL,
                "default_action": {
                    "type":
                    "web_url",
                    "url":
                    "%s" % item.get("product_url")
                    if item.get("product_url") is not None else WEB_URL,
                    "webview_height_ratio":
                    "tall",
                },
            }
            if content != "default":
                product.update({
                    "buttons": [{
                        "type": "postback",
                        "title": TITLE,
                        "payload": PRODUCT + "_%s" % item.get("id")
                    }]
                })
            list_product.append(product)
        list_product = list_product[:10]
        data = json.dumps({
            "recipient": {
                "id": fb_id
            },
            "message": {
                "attachment": {
                    "type": "template",
                    "payload": {
                        "template_type": "generic",
                        "elements": list_product
                    }
                }
            }
        })
        print(data)

        pages = self.connect.get("pages")
        if pages:
            pages = json.loads(pages)
            access_token = [
                _.get("page_token") for _ in pages
                if str(_.get("page_id")) == page_id
            ][0]
            params = {"access_token": "{}".format(access_token)}
            request = requests.post(FACEBOOK_API_ENDPOINT + "me/messages",
                                    params=params,
                                    headers=self.headers,
                                    data=data)
            log_debug("############## %s ##############" % request.text)
        else:
            log_debug("############## Can't get pages ##############")