bear / python-twitter

A Python wrapper around the Twitter API.
Apache License 2.0
3.41k stars 957 forks source link

DirectMessage: KeyError: 'event' #600

Closed webtweakers closed 5 years ago

webtweakers commented 5 years ago

In reference to issue: https://github.com/bear/python-twitter/issues/587

A little follow-up on this... It is possible that the Twitter API returns in error and that 'event' is not returned in the response. Trying to create the DirectMessage object as the response of the PostDirectMessage call will then fail:

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'],
)

This code fails with a KeyError: 'event'.

This happens, for example, when attempting to send a direct message to a user that is not following you.

When setting return_json=True, the returned data will then be something like this:

{'errors': [{'code': 150,
   'message': 'You cannot send messages to users who are not following you.'}]}

Clearly 'event' is missing.

I think the return data of the call to the Twitter API needs to be checked for cases like this, before naively trying to create the DirectMessage object.

UPDATE: actually it looks like this line is simply missing after calling the Twitter API:

data = self._ParseAndCheckTwitter(resp.content.decode('utf-8'))
jeremylow commented 5 years ago

Yeah i was going to say that's usually what we do. if you want to submit a PR, i can get it approved or I'll take care of it after the holiday

webtweakers commented 5 years ago

Happy holidays! :)