Skip to content
This repository was archived by the owner on Aug 7, 2024. It is now read-only.

Commit 6452580

Browse files
committed
migrate api.PostDirectMessage to new twitter api
1 parent 96ccf1f commit 6452580

File tree

6 files changed

+55
-57
lines changed

6 files changed

+55
-57
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ htmlcov
3434
nosetests.xml
3535
htmlcov
3636
coverage.xml
37+
.hypothesis
3738

3839
# PyCharm data
3940
.idea
Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,22 @@
1-
{"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":[]}}
1+
{
2+
"event": {
3+
"created_timestamp": "1534347829024",
4+
"message_create": {
5+
"message_data": {
6+
"text": "test message",
7+
"entities": {
8+
"symbols": [],
9+
"user_mentions": [],
10+
"hashtags": [],
11+
"urls": []
12+
}
13+
},
14+
"sender_id": "4012966701",
15+
"target": {
16+
"recipient_id": "372018022"
17+
}
18+
},
19+
"type": "message_create",
20+
"id": "761517675243679747"
21+
}
22+
}

tests/test_api_30.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1643,16 +1643,10 @@ def testPostDirectMessage(self):
16431643
status=200)
16441644
resp = self.api.PostDirectMessage(text="test message", user_id=372018022)
16451645
self.assertEqual(resp.text, "test message")
1646-
1647-
resp = self.api.PostDirectMessage(text="test message", screen_name="__jcbl__")
1648-
self.assertEqual(resp.sender_id, 4012966701)
1649-
self.assertEqual(resp.recipient_id, 372018022)
1646+
self.assertEqual(resp.sender_id, "4012966701")
1647+
self.assertEqual(resp.recipient_id, "372018022")
16501648
self.assertTrue(resp._json)
16511649

1652-
self.assertRaises(
1653-
twitter.TwitterError,
1654-
lambda: self.api.PostDirectMessage(text="test message"))
1655-
16561650
@responses.activate
16571651
def testDestroyDirectMessage(self):
16581652
with open('testdata/post_destroy_direct_message.json') as f:

tests/test_models.py

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -58,28 +58,6 @@ def test_direct_message(self):
5858
self.assertTrue(dm.AsJsonString())
5959
self.assertTrue(dm.AsDict())
6060

61-
def test_direct_message_sender_is_user_model(self):
62-
"""Test that each Direct Message object contains a fully hydrated
63-
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``."""
64-
dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)
65-
66-
self.assertTrue(isinstance(dm.sender, twitter.models.User))
67-
self.assertEqual(dm.sender.id, 372018022)
68-
69-
# Let's make sure this doesn't break the construction of the DM object.
70-
self.assertEqual(dm.id, 678629245946433539)
71-
72-
def test_direct_message_recipient_is_user_model(self):
73-
"""Test that each Direct Message object contains a fully hydrated
74-
twitter.models.User object for both ``dm.sender`` & ``dm.recipient``."""
75-
dm = twitter.DirectMessage.NewFromJsonDict(self.DIRECT_MESSAGE_SAMPLE_JSON)
76-
77-
self.assertTrue(isinstance(dm.recipient, twitter.models.User))
78-
self.assertEqual(dm.recipient.id, 4012966701)
79-
80-
# Same as above.
81-
self.assertEqual(dm.id, 678629245946433539)
82-
8361
def test_hashtag(self):
8462
""" Test twitter.Hashtag object """
8563
ht = twitter.Hashtag.NewFromJsonDict(self.HASHTAG_SAMPLE_JSON)

twitter/api.py

100644100755
Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2997,38 +2997,50 @@ def GetSentDirectMessages(self,
29972997

29982998
def PostDirectMessage(self,
29992999
text,
3000-
user_id=None,
3001-
screen_name=None,
3000+
user_id,
30023001
return_json=False):
30033002
"""Post a twitter direct message from the authenticated user.
30043003
30053004
Args:
30063005
text: The message text to be posted.
30073006
user_id:
3008-
The ID of the user who should receive the direct message. [Optional]
3009-
screen_name:
3010-
The screen name of the user who should receive the direct message. [Optional]
3007+
The ID of the user who should receive the direct message.
30113008
return_json (bool, optional):
3012-
If True JSON data will be returned, instead of twitter.User
3009+
If True JSON data will be returned, instead of twitter.DirectMessage
30133010
Returns:
30143011
A twitter.DirectMessage instance representing the message posted
30153012
"""
3016-
url = '%s/direct_messages/new.json' % self.base_url
3017-
data = {'text': text}
3018-
if user_id:
3019-
data['user_id'] = user_id
3020-
elif screen_name:
3021-
data['screen_name'] = screen_name
3022-
else:
3023-
raise TwitterError({'message': "Specify at least one of user_id or screen_name."})
3013+
url = '%s/direct_messages/events/new.json' % self.base_url
3014+
3015+
event = {
3016+
'event': {
3017+
'type': 'message_create',
3018+
'message_create': {
3019+
'target': {
3020+
'recipient_id': user_id,
3021+
},
3022+
'message_data': {
3023+
'text': text
3024+
}
3025+
}
3026+
}
3027+
}
30243028

3025-
resp = self._RequestUrl(url, 'POST', data=data)
3026-
data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
3029+
resp = self._RequestUrl(url, 'POST', json=event)
3030+
data = resp.json()
30273031

30283032
if return_json:
30293033
return data
30303034
else:
3031-
return DirectMessage.NewFromJsonDict(data)
3035+
dm = DirectMessage(
3036+
created_at=data['event']['created_timestamp'],
3037+
id=data['event']['id'],
3038+
recipient_id=data['event']['message_create']['target']['recipient_id'],
3039+
sender_id=data['event']['message_create']['sender_id'],
3040+
text=data['event']['message_create']['message_data']['text'],
3041+
)
3042+
dm._json = data
3043+
return dm
30323044

30333045
def DestroyDirectMessage(self, message_id, include_entities=True, return_json=False):
30343046
"""Destroys the direct message specified in the required ID parameter.

twitter/models.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -185,21 +185,13 @@ def __init__(self, **kwargs):
185185
self.param_defaults = {
186186
'created_at': None,
187187
'id': None,
188-
'recipient': None,
189188
'recipient_id': None,
190-
'recipient_screen_name': None,
191-
'sender': None,
192189
'sender_id': None,
193-
'sender_screen_name': None,
194190
'text': None,
195191
}
196192

197193
for (param, default) in self.param_defaults.items():
198194
setattr(self, param, kwargs.get(param, default))
199-
if 'sender' in kwargs:
200-
self.sender = User.NewFromJsonDict(kwargs.get('sender', None))
201-
if 'recipient' in kwargs:
202-
self.recipient = User.NewFromJsonDict(kwargs.get('recipient', None))
203195

204196
def __repr__(self):
205197
if self.text and len(self.text) > 140:
@@ -208,7 +200,7 @@ def __repr__(self):
208200
text = self.text
209201
return "DirectMessage(ID={dm_id}, Sender={sender}, Created={time}, Text='{text!r}')".format(
210202
dm_id=self.id,
211-
sender=self.sender_screen_name,
203+
sender=self.sender_id,
212204
time=self.created_at,
213205
text=text)
214206

0 commit comments

Comments
 (0)