Python – Tweepy 中的 API.send_direct_message()
Twitter是一个流行的社交网络,用户在其中分享称为推文的消息。 Twitter 允许我们使用 Twitter API 或Tweepy挖掘任何用户的数据。数据将是从用户那里提取的推文。首先要做的是从 twitter 开发人员那里轻松获得每个用户可用的消费者密钥、消费者密钥、访问密钥和访问密钥。这些密钥将帮助 API 进行身份验证。
API.send_direct_message()
Tweepy 模块中API
类的send_direct_message()
方法用于作为认证用户发送直接消息。
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
示例 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'])
输出 :
This is a Direct Message.
示例 2:发送带有以下媒体附件的直接消息:
# 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)
输出 :
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。