Direct Message with Media #448

Open
opened 2017-08-03 06:44:34 -07:00 by HappyRobotProject · 5 comments
HappyRobotProject commented 2017-08-03 06:44:34 -07:00 (Migrated from github.com)

Twitter now supports leaving a direct message with a media id

See
https://dev.twitter.com/rest/reference/post/direct_messages/events/new
and
https://dev.twitter.com/rest/direct-messages/attaching-media

Using the api.post function doesn't seem to correctly handle a python dictionary that should be converted to a json object and sent with the post message.

Can you offer an example of the correct way to use api.post? or recommend a different approach?

Twitter now supports leaving a direct message with a media id See [https://dev.twitter.com/rest/reference/post/direct_messages/events/new](https://dev.twitter.com/rest/reference/post/direct_messages/events/new) and [https://dev.twitter.com/rest/direct-messages/attaching-media](https://dev.twitter.com/rest/direct-messages/attaching-media) Using the api.post function doesn't seem to correctly handle a python dictionary that should be converted to a json object and sent with the post message. Can you offer an example of the correct way to use api.post? or recommend a different approach?
michaelhelmick commented 2017-08-04 07:51:59 -07:00 (Migrated from github.com)

Looks like you can upload media or a video and then attach that media ID to the DM

from twython import Twython
twitter = Twython(APP_KEY, APP_SECRET,
                  OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

# video = open('/path/to/file/video.mp4', 'rb')
# response = twitter.upload_video(media=video, media_type='video/mp4', media_category='dm_video')

image = open('/path/to/file/image.jpg', 'rb')
response = twitter.upload_media(media=image ,media_type='image/jpeg', media_category='dm_image')

media_id = response['media_id_string']
params = {
    'event': {
        'type': 'message_create',
        'message_create': {
            'target': {
                'recipient_id': '844385345234',
            },
            'message_data': {
                'text': 'Check out this image!',
                'attachment': {
                    'type': 'media',
                    'media': {
                        'id': media_id,
                    }
                }
            }
        }
    }
}
twitter.post('direct_messages/events/new', params=params)
Looks like you can upload media or a video and then attach that media ID to the DM ```python from twython import Twython twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) # video = open('/path/to/file/video.mp4', 'rb') # response = twitter.upload_video(media=video, media_type='video/mp4', media_category='dm_video') image = open('/path/to/file/image.jpg', 'rb') response = twitter.upload_media(media=image ,media_type='image/jpeg', media_category='dm_image') media_id = response['media_id_string'] params = { 'event': { 'type': 'message_create', 'message_create': { 'target': { 'recipient_id': '844385345234', }, 'message_data': { 'text': 'Check out this image!', 'attachment': { 'type': 'media', 'media': { 'id': media_id, } } } } } } twitter.post('direct_messages/events/new', params=params) ```
michaelhelmick commented 2017-08-04 07:54:58 -07:00 (Migrated from github.com)

If that doesn't work, let me know. Looks like there is a json parameter that can be sent using requests that will automatically json encode this for you.

If that doesn't work, let me know. Looks like there is a `json` parameter that can be sent using requests that will automatically json encode this for you.
BarlowHall commented 2018-01-30 14:48:23 -08:00 (Migrated from github.com)

Hi, I've been trying to get this to work and not managed to so far. I've taken the example above and added my keys, tokens etc and the recipient. Has anyone got this working recently?

Any help appreciated.

Thanks

Neale

Hi, I've been trying to get this to work and not managed to so far. I've taken the example above and added my keys, tokens etc and the recipient. Has anyone got this working recently? Any help appreciated. Thanks Neale
gabe-camp commented 2018-03-18 16:30:42 -07:00 (Migrated from github.com)

I am trying the following

from twython import Twython

api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET)

photo = open('/path/to/image.jpg','rb')
response = api.upload_media(media=photo,media_type='image/jpeg',media_category='dm_image')
media_id = response['media_id_string']

response = api.lookup_user(screen_name='username')
recipient_id = response[0]['id']

params = {
        "event": {
                "type":"message_create",
                "message_create": {
                        "target": {
                                "recipient_id": str(recipient_id),
                        },
                        "message_data": {
                                "text":"Insert caption here",
                                "attachment": {
                                        "type":"media",
                                        "media" : {
                                                "id": str(media_id),
                                        }
                                }
                        }
                }
        }
}
response = api.post('direct_messages/events/new',params=params)

Unfortunately, I am getting back an error

Traceback (most recent call last):
File "twitbot.py", line 47, in
response = api.post('direct_messages/events/new',params=params)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 268, in post
return self.request(endpoint, 'POST', params=params, version=version)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 258, in request
api_call=url)
File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request
retry_after=response.headers.get('X-Rate-Limit-Reset'))
twython.exceptions.TwythonError: Twitter API returned a 422 (Unprocessable Entity), An error occurred processing your request.

I am trying the following ``` from twython import Twython api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_TOKEN,ACCESS_SECRET) photo = open('/path/to/image.jpg','rb') response = api.upload_media(media=photo,media_type='image/jpeg',media_category='dm_image') media_id = response['media_id_string'] response = api.lookup_user(screen_name='username') recipient_id = response[0]['id'] params = { "event": { "type":"message_create", "message_create": { "target": { "recipient_id": str(recipient_id), }, "message_data": { "text":"Insert caption here", "attachment": { "type":"media", "media" : { "id": str(media_id), } } } } } } response = api.post('direct_messages/events/new',params=params) ``` Unfortunately, I am getting back an error >Traceback (most recent call last): > File "twitbot.py", line 47, in <module> > response = api.post('direct_messages/events/new',params=params) > File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 268, in post > return self.request(endpoint, 'POST', params=params, version=version) > File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 258, in request > api_call=url) > File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request > retry_after=response.headers.get('X-Rate-Limit-Reset')) >twython.exceptions.TwythonError: Twitter API returned a 422 (Unprocessable Entity), An error occurred processing your request.
rjallbert commented 2018-08-28 11:46:43 -07:00 (Migrated from github.com)

I came across this today, and the code above is ok, but before you call api.post() you need to do

import json
params = json.dumps(params)

HTH

I came across this today, and the code above is ok, but before you call api.post() you need to do import json params = json.dumps(params) HTH
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: code/twython#448
No description provided.