WebexPythonSDK icon indicating copy to clipboard operation
WebexPythonSDK copied to clipboard

Add Support for Editing a Message

Open cpissay opened this issue 4 years ago • 7 comments

Version 1.6

Problem

Currently there is no method in the MessagesAPI class which can edit a message . This is a really useful feature to have to keep the space uncluttered of unnecessary bot messages and that annoying "deleted their message" messages.

Edit Message API

As per the documentation in developer.cisco.com, to edit a message, we need to send a HTTP PUT to /v1/messages/{messageId} with the following body parameters:

  • roomId
  • text
  • markdown
  • attachment (the guide doesn't have this, but I have tested this and it works)

But editing messages with files are not supported, so file is not an allowed parameter

Potential python syntax

from webexteamssdk import WebexTeamsAPI
api = WebexTeamsAPI()
api.messages.edit(messageId="string", text="string", markdown="string",attachment=[list])

cpissay avatar May 31 '21 03:05 cpissay

Hi @cpissay, this would definitely be useful and I made a start with a fork but realised when reviewing the contributing guidelines that I lack the experience to create a test case.

Additionally, I noted that (as you pointed out) attachments aren't supported (thus cards) but curious that it worked for you - I haven't tried yet... might play around with Extending the API with bound methods while these issues are addressed...

leighmhart avatar Sep 28 '21 22:09 leighmhart

thanks @leighmhart for suggesting extending the API. I was also looking for a way to edit messages what is currently not available. If anyone is interested, I'm sharing the following code that would allow you to edit your messages in a similar fashion as per the SDK.

webexapi = WebexTeamsAPI()

def _edit(messageId, roomId=None, text=None, markdown=None,
           attachments=None, **request_parameters):
  """Post a message to a room.

  The files parameter is a list, which accepts multiple values to allow
  for future expansion, but currently only one file may be included with
  the message.

  Args:
      messageId(basestring): The ID of the message to be edited.
      roomId(basestring): The room ID.
      text(basestring): The message, in plain text. If `markdown` is
          specified this parameter may be optionally used to provide
          alternate text for UI clients that do not support rich text.
      markdown(basestring): The message, in markdown format.
      attachments(list): Content attachments to attach to the message.
          See the Cards Guide for more information.
      **request_parameters: Additional request parameters (provides
          support for parameters that may be added in the future).

  Returns:
      Message: A Message object with the details of the created message.

  Raises:
      TypeError: If the parameter types are incorrect.
      ApiError: If the Webex Teams cloud returns an error.
      ValueError: If the files parameter is a list of length > 1, or if
          the string in the list (the only element in the list) does not
          contain a valid URL or path to a local file.

  """
  from past.builtins import basestring
  from webexteamssdk.models.cards import AdaptiveCard
  from webexteamssdk.utils import (
    check_type, dict_from_items_with_values,make_attachment
  )
  API_ENDPOINT = 'messages'
  OBJECT_TYPE = 'message'
  self = webexapi.messages

  check_type(messageId, basestring)
  check_type(roomId, basestring, optional=True)
  check_type(text, basestring, optional=True)
  check_type(markdown, basestring, optional=True)
  check_type(attachments, list, optional=True)

  if attachments:
    for item, attachment in enumerate(attachments):
      check_type(attachment, (dict, AdaptiveCard))

      if isinstance(attachment, AdaptiveCard):
        attachments[item] = make_attachment(attachment)

  post_data = dict_from_items_with_values(
    request_parameters,
    roomId=roomId,
    text=text,
    markdown=markdown,
    attachments=attachments
  )

  json_data = self._session.put(API_ENDPOINT+ '/' + messageId, json=post_data)


webexapi.messages.edit = _edit

The codes are largely referencing the write method, and references all existing object. To use it, you can simply call the webexapi.messages.edit() method.

I hope this is useful to anyone who is searching for them.

erqiyang avatar Oct 06 '21 05:10 erqiyang

@erqiyang thank you for sharing! I almost have it working but I am getting:

[ERROR: app.py:265 -         send_message() ] Error sending message to Webex: 
[400] Bad Request - Support for editing messages with files via Developer APIs
 currently disabled [Tracking ID: ROUTER_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx]

my original message is sent as follows:

            message = bot.messages.create(
                roomId=room, markdown=markdown, attachments=attachments
            )

without any files per se - attachments is defined as

        attachments = [
            {
                "contentType": "application/vnd.microsoft.card.adaptive",
                "content": json.loads(card),
            }

Looks like the API is now true to the API docs:

Please note edits of messages containing files or attachments are not currently supported. If a user attempts to edit a message containing files or attachments a 400 Bad Request will be returned by the API with a message stating that the feature is currently unsupported.

leighmhart avatar Oct 17 '21 16:10 leighmhart

@leighmhart @erqiyang Thanks a lot for your efforts!

With regards to the ability to edit cards, I have implemented it in a project (directly via REST API) and it's working absolutely fine.

Here is a snippet of what the documentation for cards say:

You could edit the content of the card as a result of the action (currently available only for the cards that doesn't include images, either pre or post edit). Edit message is the driving force behind editing a card.

This can be found under the header "Card Abilities" here : https://developer.webex.com/docs/api/guides/cards

cpissay avatar Oct 21 '21 00:10 cpissay

Ah I will double check my card tomorrow to make sure there are no images… thanks again

leighmhart avatar Oct 21 '21 01:10 leighmhart

yes.. @cpissay is right. The API is working fine. @leighmhart , the response you are getting back from the API is likely because of images in your card (if you are using cards) or other file attachment. Also, the current limit for editing messages is a max of 10 edits. Any more than that, you will also get a 400 Bad Request response.

You can read more about it here: https://developer.webex.com/docs/api/v1/messages/edit-a-message

erqiyang avatar Oct 22 '21 01:10 erqiyang

yes.. @cpissay is right. The API is working fine. @leighmhart , the response you are getting back from the API is likely because of images in your card (if you are using cards) or other file attachment. Also, the current limit for editing messages is a max of 10 edits. Any more than that, you will also get a 400 Bad Request response.

You can read more about it here: https://developer.webex.com/docs/api/v1/messages/edit-a-message

You are indeed correct - I removed the image reference and edit card now works - however, there was one missing piece to the _edit overload function - returning the json message object :). @erqiyang FYI

    # Return a message object created from the response JSON data
    return self._object_factory(OBJECT_TYPE, json_data)

leighmhart avatar Nov 09 '21 12:11 leighmhart

Closing this issue; it looks like the functionality was added in #190.

cmlccie avatar Feb 19 '24 18:02 cmlccie