1

I am working on a facebook mini-chat bot and I am encountering a problem which consists on the bot to receive the same message over and over even though it has already answered the message.

it keeps receiving the same text from FB and replying to it over and over

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"}
    )

I get that I need to send a status 200 every time, which I did but still receiving the same text over and over

Here are the events I am subscribed to

conversations, message_deliveries, message_reads, messages, messaging_optins, messaging_postbacks, picture

I removed messaging_echoes because I thought it was the problem turned out to not

kaizer
  • 490
  • 1
  • 6
  • 17
  • I doubt this is your issue, but for me whenever I have an error, facebook sends the message several times at increasing intervals of time. Figured I'd mention it. – user2322082 Jul 15 '16 at 19:38
  • @user2322082 the thing is in the logs I can see that I'm receiving the same text multiple times so the bot is treating it again and again – kaizer Jul 15 '16 at 19:43
  • If you include the print statements that show when you send a single message in your question, it may help people solve your issue – user2322082 Jul 15 '16 at 19:45
  • @user2322082 thinking about it, might be the **20s** reply frame that's the issue, I reduce the size of the dictionary to speed up the word_gen() and the issue seems to be gone – kaizer Jul 15 '16 at 20:04
  • Interesting, I'm curious. Were you under 20 seconds and still having the issue? But now that you're under like say 3 seconds the issue is gone? Or were you just over 20 seconds – user2322082 Jul 15 '16 at 20:21
  • 1
    @user2322082 I was over the 20s as the generator was taking 40s in avg to process, now I'm at 12s in avg and the issue is gone – kaizer Jul 15 '16 at 20:29
  • @kaizer Could you also look at my code I have the same issue. But I don't want to solve it that way of creating a database. Did u find any other way to solve it ?? I always thought it was because of the python not sending a status 200 to FB webhook. https://stackoverflow.com/questions/44848406/facebook-webhook-maiking-multiple-calls-for-the-same-message – Arsenal Fanatic Jul 03 '17 at 12:34

1 Answers1

2

I have resolved this issue by writing a function and checking duplicate messages in my Web API service.

Here I am generating message unique id either by payload or message received from Facebook which user clicks or types and then comparing with earlier stored unique value from concurrent dictionary.

_messageUniqueKeysBySender is ConcurrentDictionary and I am caching values by Sender Id for 30 minutes.

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;
    }

And then by checking in main code

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;
        }
  • Could you also look at my code I have the same issue. But I don't want to solve it that way of creating a database. Did u find any other way to solve it ?? I always thought it was because of the python not sending a status 200 to FB webhook. https://stackoverflow.com/questions/44848406/facebook-webhook-maiking-multiple-calls-for-the-same-message – Arsenal Fanatic Jul 03 '17 at 12:35