Open In App

Python – API.get_direct_message() in Tweepy

Last Updated : 12 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.

API.get_direct_message()

The get_direct_message() method of the API class in Tweepy module is used to fetch a direct message as the authenticated user.

Syntax : API.get_direct_message(id, full_text)

Parameters :

  • id : ID of the direct message.
  • full_text : boolean indicating whether or not the full text of a message should be returned or not.

Returns : an object of class DirectMessage

Example 1 :




# import the module
import tweepy
  
# assign the values accordingly
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
  
# authorization of consumer key and consumer secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
  
# set access to user's access key and access secret 
auth.set_access_token(access_token, access_token_secret)
  
# calling the api 
api = tweepy.API(auth)
  
# ID of the direct message
id = 
  
# fetching the direct message
direct_message = api.get_direct_message(id)
  
print(direct_message.message_create['message_data']['text'])


Output :

This is a Direct Message.

Example 2 : Exception is raised when the ID is invalid.




# invalid ID of the direct message
id = 12345
  
# fetching the direct message
direct_message = api.get_direct_message(id)


Output :

    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{'code': 34, 'message': 'Sorry, that page does not exist.'}]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads