pythontwython

Updating Twython endpoints to the new api is erroring on send_direct_message


Having done some research and found that the latest release of Twython is still using the previous endpoints for some features, ( get and send direct messages so far ) I have updated the endpoint calls to the following.

def get_direct_messages(self, **params):
    return self.get('direct_messages/events/list', params=params)

and

def send_direct_message(self, **params):
    # return self.post('direct_messages/new', params=params)
    return self.post('direct_messages/events/new', params=params)

The former is now working as intended and retrieving my messages. The later on the other hand is still giving me the following non-descript error

TwythonError('An error occurred processing your request.')

Previous to that was the

twython.exceptions.TwythonError: Twitter API returned a 404 (Not Found), Sorry, that page does not exist.

This progression leads me to believe I am on the right path, and now I am wondering if it is just my request not being formed correctly?

class Messages:
keys = creds.set_keys()
twitter = Twython(keys["key_twitter"],
                  keys["secret_twitter"],
                  keys["token_twitter"],
                  keys["token_secret_twitter"])

    def send_test_msg(self):
        try:
            self.twitter.send_direct_message(type='message_create', recipient_id="raelonmasters", message_data="first test!")
        except Exception as e:
            pprint.pprint(e)

I have been referencing the official docs

https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event

in trying to track this down, and any help is greatly appreciated!

edit {I should add that my app credentials are set to read write and direct message}


Solution

  • After further research, and a nights sleep I rewrote the api function to allow me to send messages.

    twython/api.py

        def post_message(self, endpoint, userid, msg, version='1.1'):
        return self.request('direct_messages/events/new',
                            'POST', params='{"event": {"type": "message_create", '
                                           '"message_create": {"target": {"recipient_id": "'+userid+'"}, '
                                           '"message_data": {"text": "'+msg+'"}}}}', version=version)