Open In App

Python – API.list_direct_messages() 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.list_direct_messages()

The list_direct_messages() method of the API class in Tweepy module is used to fetch all the direct messages within the last 30 days the authenticated user.

Syntax : API.list_direct_messages(count)

Parameters :

  • count : number of direct messages to be fetched.
  • full_text : boolean indicating whether or not the full text of a message should be returned or not.

Returns : list of objects 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)
  
# fetching the direct messages
direct_messages = api.list_direct_messages()
  
# printing the timestamps
for direct_message in direct_messages:
    print(direct_message.created_timestamp)


Output :

1591868314610
1591868289514
1591868232626
1591867665376
1591867346546
1591867323014

Example 2 : Counting the number of direct messages in the last 30 days.




# fetching the direct messages
direct_messages = api.list_direct_messages()
  
print(len(direct_messages))


Output :

6


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads