kaizer
kaizer

Reputation: 490

Facebook chat bot sending same message multiple times (Python)

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

Upvotes: 1

Views: 4415

Answers (1)

dhiraj1mumbai
dhiraj1mumbai

Reputation: 51

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

Upvotes: 2

Related Questions