Why is my first bot message (via REST API) shown before my first thread message?

307 Views Asked by At

I am working on a chat bot, that will return a certain piece of information based on the question of the user. The process of obtaining this information will likely take a couple of seconds, and I want to make sure the user is aware of this.

I therefore use the suggestion from this stackoverflow question, and return the first message via the REST API via a service account.

The second bot message is then via the normal implementation. I am using the template from the basic bot here, deployed to Google Cloud App Engine.

Here a snippet of my code:

@app.route("/", methods=["POST"])
def home_post():
    """Respond to POST requests to this endpoint.
    All requests sent to this endpoint from Hangouts Chat are POST
    requests.
    """

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        "credentials.json", scopes=SCOPES
    )
    http = httplib2.Http()
    chat = discovery.build("chat", "v1", http=credentials.authorize(http))

    event_data = request.get_json()
    thread = event_data["message"]["thread"]

    message = {"text": "Thanks for your question! Let me check :)", "thread": thread}
    chat.spaces().messages().create(
        parent=event_data["space"]["name"], body=message
    ).execute()

    # doing something to find information requested by user

    return json.jsonify({"text": "Here is my answer :)"})

Everything is working as expected, except that the first message coming through in chat is placed before the initial bot mention, after the second message comes through (as seen in the recording or screenshot).

Recording: https://www.loom.com/share/c37472b703184965ad9ee649cb9f17bc

enter image description here

Why is this happening? What can I do to make sure the order stays the same?

Thanks!

1

There are 1 best solutions below

8
On BEST ANSWER

Your code is being run onEvent

Thereby, the event types are:

  • UNSPECIFIED
  • MESSAGE
  • ADDED_TO_SPACE
  • REMOVED_FROM_SPACE
  • CARD_CLICKED

In other words:

Just adding the bot to the chatroom is already an event that will trigger him to send a message - even before the bot was mentioned.

How to avoid it:

Implement a conditional statement that checks the type of event before sending a message.

Sample:

if event_data['type'] == 'MESSAGE':
    message = {"text": "Thanks for your question! Let me check :)", "thread": thread}
    chat.spaces().messages().create(
        parent=event_data["space"]["name"], body=message
    ).execute()
else:
    return

Sample without chat.spaces().messages().create:

if event_data['type'] == 'MESSAGE':
    message = "Thanks for your question! Let me check :)"
else:
    return
return json.jsonify({'text': message})