migrate api.PostDirectMessage to new twitter api by jmingtan · Pull Request #579 · bear/python-twitter · GitHub
Skip to content
This repository was archived by the owner on Aug 7, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
23 changes: 22 additions & 1 deletion testdata/post_post_direct_message.json
Original file line number Diff line number Diff line change
@@ -1 +1,22 @@
{"id":761517675243679747,"id_str":"761517675243679747","text":"test message","sender":{"id":4012966701,"id_str":"4012966701","name":"notinourselves","screen_name":"notinourselves","location":"","description":"","url":null,"entities":{"description":{"urls":[]}},"protected":true,"followers_count":1,"friends_count":2,"listed_count":1,"created_at":"Wed Oct 21 23:53:04 +0000 2015","favourites_count":1,"utc_offset":null,"time_zone":null,"geo_enabled":true,"verified":false,"statuses_count":83,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"000000","profile_background_image_url":"http:\/\/pbs.twimg.com\/profile_background_images\/736320724164448256\/LgaAQoav.jpg","profile_background_image_url_https":"https:\/\/pbs.twimg.com\/profile_background_images\/736320724164448256\/LgaAQoav.jpg","profile_background_tile":false,"profile_image_url":"http:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_2_normal.png","profile_image_url_https":"https:\/\/abs.twimg.com\/sticky\/default_profile_images\/default_profile_2_normal.png","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/4012966701\/1453123196","profile_link_color":"000000","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":true,"has_extended_profile":false,"default_profile":false,"default_profile_image":true,"following":false,"follow_request_sent":false,"notifications":false},"sender_id":4012966701,"sender_id_str":"4012966701","sender_screen_name":"notinourselves","recipient":{"id":372018022,"id_str":"372018022","name":"jeremy","screen_name":"__jcbl__","location":"not a very good kingdom tbh","description":"my kingdom for a microwave that doesn't beep","url":"http:\/\/t.co\/wtg3XzqQTX","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/wtg3XzqQTX","expanded_url":"http:\/\/iseverythingstilltheworst.com","display_url":"iseverythingstilltheworst.com","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":79,"friends_count":423,"listed_count":8,"created_at":"Sun Sep 11 23:49:28 +0000 2011","favourites_count":2696,"utc_offset":-14400,"time_zone":"Eastern Time (US & Canada)","geo_enabled":false,"verified":false,"statuses_count":587,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"FFFFFF","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/755782670572027904\/L5YRsZAY_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/755782670572027904\/L5YRsZAY_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/372018022\/1469027675","profile_link_color":"EE3355","profile_sidebar_border_color":"000000","profile_sidebar_fill_color":"000000","profile_text_color":"000000","profile_use_background_image":false,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":true,"follow_request_sent":false,"notifications":false},"recipient_id":372018022,"recipient_id_str":"372018022","recipient_screen_name":"__jcbl__","created_at":"Fri Aug 05 11:02:16 +0000 2016","entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[]}}
{
"event": {
"created_timestamp": "1534347829024",
"message_create": {
"message_data": {
"text": "test message",
"entities": {
"symbols": [],
"user_mentions": [],
"hashtags": [],
"urls": []
}
},
"sender_id": "4012966701",
"target": {
"recipient_id": "372018022"
}
},
"type": "message_create",
"id": "761517675243679747"
}
}
10 changes: 2 additions & 8 deletions tests/test_api_30.py
Original file line number Diff line number Diff line change
Expand Up @@ -1643,16 +1643,10 @@ def testPostDirectMessage(self):
status=200)
resp = self.api.PostDirectMessage(text="test message", user_id=372018022)
self.assertEqual(resp.text, "test message")

resp = self.api.PostDirectMessage(text="test message", screen_name="__jcbl__")
self.assertEqual(resp.sender_id, 4012966701)
self.assertEqual(resp.recipient_id, 372018022)
self.assertEqual(resp.sender_id, "4012966701")
self.assertEqual(resp.recipient_id, "372018022")
self.assertTrue(resp._json)

self.assertRaises(
twitter.TwitterError,
lambda: self.api.PostDirectMessage(text="test message"))

@responses.activate
def testDestroyDirectMessage(self):
with open('testdata/post_destroy_direct_message.json') as f:
Expand Down
22 changes: 0 additions & 22 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,28 +58,6 @@ def test_direct_message(self):
self.assertTrue(dm.AsJsonString())
self.assertTrue(dm.AsDict())

def test_direct_message_sender_is_user_model(self):
"""Test that each Direct Message object contains a fully hydrated
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``."""
dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)

self.assertTrue(isinstance(dm.sender, twitter.models.User))
self.assertEqual(dm.sender.id, 372018022)

# Let's make sure this doesn't break the construction of the DM object.
self.assertEqual(dm.id, 678629245946433539)

def test_direct_message_recipient_is_user_model(self):
"""Test that each Direct Message object contains a fully hydrated
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``."""
dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)

self.assertTrue(isinstance(dm.recipient, twitter.models.User))
self.assertEqual(dm.recipient.id, 4012966701)

# Same as above.
self.assertEqual(dm.id, 678629245946433539)

def test_hashtag(self):
""" Test twitter.Hashtag object """
ht = twitter.Hashtag.NewFromJsonDict(self.HASHTAG_SAMPLE_JSON)
Expand Down
46 changes: 29 additions & 17 deletions twitter/api.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2997,38 +2997,50 @@ def GetSentDirectMessages(self,

def PostDirectMessage(self,
text,
user_id=None,
screen_name=None,
user_id,
return_json=False):
"""Post a twitter direct message from the authenticated user.

Args:
text: The message text to be posted.
user_id:
The ID of the user who should receive the direct message. [Optional]
screen_name:
The screen name of the user who should receive the direct message. [Optional]
The ID of the user who should receive the direct message.
return_json (bool, optional):
If True JSON data will be returned, instead of twitter.User
If True JSON data will be returned, instead of twitter.DirectMessage
Returns:
A twitter.DirectMessage instance representing the message posted
"""
url = '%s/direct_messages/new.json' % self.base_url
data = {'text': text}
if user_id:
data['user_id'] = user_id
elif screen_name:
data['screen_name'] = screen_name
else:
raise TwitterError({'message': "Specify at least one of user_id or screen_name."})
url = '%s/direct_messages/events/new.json' % self.base_url

event = {
'event': {
'type': 'message_create',
'message_create': {
'target': {
'recipient_id': user_id,
},
'message_data': {
'text': text
}
}
}
}

resp = self._RequestUrl(url, 'POST', data=data)
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
resp = self._RequestUrl(url, 'POST', json=event)
data = resp.json()

if return_json:
return data
else:
return DirectMessage.NewFromJsonDict(data)
dm = DirectMessage(
created_at=data['event']['created_timestamp'],
id=data['event']['id'],
recipient_id=data['event']['message_create']['target']['recipient_id'],
sender_id=data['event']['message_create']['sender_id'],
text=data['event']['message_create']['message_data']['text'],
)
dm._json = data
return dm

def DestroyDirectMessage(self, message_id, include_entities=True, return_json=False):
"""Destroys the direct message specified in the required ID parameter.
Expand Down
10 changes: 1 addition & 9 deletions twitter/models.py