Open In App

Python – API.send_direct_message() in Tweepy

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.send_direct_message()

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

Syntax : API.send_direct_message(parameters)

Parameters :

  • recipient_id : ID of the recipient.
  • text : text of the direct message.
  • attachment_type : attachment media or location to be sent.
  • attachment_media_id : ID of the attachment media to be sent.

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 recipient
recipient_id = 
  
# text to be sent
text = "This is a Direct Message."
  
# sending the direct message
direct_message = api.send_direct_message(recipient_id, text)
  
# printing the text of the sent direct message
print(direct_message.message_create['message_data']['text'])


Output :

This is a Direct Message.

Example 2 : Sending a direct message with the following media attachment :




# ID of the recipient
recipient_id = 
  
# text to be sent
text = "This is a Direct Message."
  
# the ID of the media
attachment_media_id = 
  
# sending the direct message
direct_messages = api.send_direct_message(recipient_id, text,
                    attachment_media_id = attachment_media_id)


Output :



Last Updated : 12 Jun, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads