Facebook Chat bot może wysyłać tę samą wiadomość wielokrotnie (Python)

głosy
1

Pracuję na facebook mini-czat ​​bot i jestem napotykają problem, który polega na bota, aby otrzymać ten sam komunikat w kółko, mimo że już odpowiedział na wiadomość.

Utrzymuje otrzymujących ten sam tekst z FB i odpowiadanie na nią w kółko

def message_handler(request):
    data = json.loads(request.body.decode('utf-8'))

    if data and data['object'] == 'page':
        for pageEntry in data['entry']:
            print nombre de message, len(pageEntry['messaging'])
            for messagingEvent in pageEntry['messaging']:

                if messagingEvent.get('optin'):
                    print optin, messagingEvent
                    receivedAuthentication(messagingEvent)
                elif messagingEvent.get('message'):
                    print message, messagingEvent
                    receivedMessage(messagingEvent)
                elif messagingEvent.get('delivery'):
                    print delivery, messagingEvent
                    receivedDeliveryConfirmation(messagingEvent)
                elif messagingEvent.get('postback'):
                    print postback, messagingEvent
                    receivedPostback(messagingEvent)
                else:
                    print UnHandled
   return HttpResponse(status=200)

def receivedMessage(event):
   senderID = event.get('sender').get('id')
   message = event.get('message')

   messageText = message.get('text')
   messageAttachments = message.get('attachments')

   if messageText:
        if messageText == 'image':
            sendImageMessage(senderID)

        elif messageText == 'button':
            sendButtonMessage(senderID)

        elif messageText == 'generic':
            sendGenericMessage(senderID)

        elif messageText == 'receipt':
            sendReceiptMessage(senderID)
        elif messageText == 'hey':
           sendTextMessage(senderID, Get it. Gimme a moment to process it :). Will get back to you in a moment)
           send_seen()
           send_typing()
           words = words_gen()
           sendTextMessage(senderID, words)


def callSendAPI(messageData):
    requests.post(
           url='https://graph.facebook.com/v2.6/me/messages?access_token=' + config.page_token,
          data=json.dumps(messageData),
        headers={Content-Type:application/json}
    )

Mam, że muszę wysłać status 200 za każdym razem, co zrobiłem, ale nadal otrzymuje ten sam tekst w kółko

Oto wydarzenia Mam subskrybowane

Rozmowy, message_deliveries, message_reads, wiadomości, messaging_optins, messaging_postbacks, obraz

Usunąłem messaging_echoes bo myślałem, że to problem okazał się nie

Utwórz 15/07/2016 o 18:30
źródło użytkownik
W innych językach...                            


1 odpowiedzi

głosy
2

Mam rozwiązany ten problem pisząc funkcję i sprawdzanie zduplikowanych wiadomości w mojej służbie Web API.

Oto jestem generowania wiadomość unikalny identyfikator albo ładowności lub wiadomości otrzymanej z Facebook której użytkownik kliknie lub typy a następnie porównanie z wcześniej zapisanego wyjątkowej wartości z równoczesnym słownika.

_messageUniqueKeysBySender jest ConcurrentDictionary i jestem buforowanie wartości przez identyfikator nadawcy przez 30 minut.

private bool IsDuplicate(Messaging messaging)
    {
        var messageUniqueId = string.Empty;
        var messageMessaging = messaging as MessageMessaging;
        if (messageMessaging != null)
            messageUniqueId = messageMessaging.Message.Id + messageMessaging.Message.SequenceNumber;
        else if (messaging is PostbackMessaging)
            messageUniqueId = ((PostbackMessaging)messaging).Postback.Payload +
                              ((PostbackMessaging)messaging).TimestampUnix;
        if (string.IsNullOrEmpty(messageUniqueId)) return false;
        string existingUniqueId;
        if (_messageUniqueKeysBySender.TryGetValue(messaging.Sender.Id, out existingUniqueId))
        {
            if (existingUniqueId == messageUniqueId)
            {
                return true;
            }
            else
            {
                _messageUniqueKeysBySender.TryUpdate(messaging.Sender.Id, messageUniqueId, existingUniqueId);
                return false;
            }
        }
        _messageUniqueKeysBySender.TryAdd(messaging.Sender.Id, messageUniqueId);
        return false;
    }

A następnie poprzez sprawdzenie w kodzie głównym

try
        {
            if (!IsDuplicate(messaging))
            {
                var conversation = _conversationRepository[messaging.Sender.Id] ?? new Conversation(messaging.Sender.Id);
                message = await _bot.RespondToMessagingAsync(conversation, messaging);
                _conversationRepository[messaging.Sender.Id] = conversation;
                _logger.ForContext("FacebookMessage", messagingJson).LogDuration("Processing Facebook message", sw);
            }
            else
                _logger.ForContext("FacebookMessage", messagingJson).Warning("Duplicate message skipped");
        }
        catch (Exception ex)
        {
            _logger.ForContext("FacebookMessage", messagingJson).Error(ex, "Failed to process message");
            message = new TextMessage(Resources.Error);
            hasError = true;
        }
Odpowiedział 27/03/2017 o 02:02
źródło użytkownik

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more