Python – API.send_direct_message() in Tweepy
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = 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 recipientrecipient_id = # text to be senttext = "This is a Direct Message." # sending the direct messagedirect_message = api.send_direct_message(recipient_id, text) # printing the text of the sent direct messageprint(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 recipientrecipient_id = # text to be senttext = "This is a Direct Message." # the ID of the mediaattachment_media_id = # sending the direct messagedirect_messages = api.send_direct_message(recipient_id, text, attachment_media_id = attachment_media_id) |
Output :


