本文整理汇总了Python中tweepy.API.send_direct_message方法的典型用法代码示例。如果您正苦于以下问题:Python API.send_direct_message方法的具体用法?Python API.send_direct_message怎么用?Python API.send_direct_message使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tweepy.API
的用法示例。
在下文中一共展示了API.send_direct_message方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TwitterBackend
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
class TwitterBackend(ShareBackend):
"""Implements Tweepy API
Backends Settings:
api_token -- a valid oauth api token. This is your app's token.
api_secret -- a valid oauth api secret. This is your app's secret.
consumer_token -- optional consumer token.
consumer_secret -- optional consumer secret.
Twitter Specific Settings:
use_tco -- True or False, use Twitter's t.co shortner.
"""
def __init__(self, *args, **kwargs):
super(TwitterBackend, self).__init__(*args, **kwargs)
# handle twitter custom parameters
self.use_tco= kwargs.get('use_tco') or True
# create a tweepy API
from tweepy import API, OAuthHandler
auth = OAuthHandler(self.consumer_token, self.consumer_secret)
auth.set_access_token(self.api_token, self.api_secret)
# Set up API
self.api = API(auth)
def send_message(self, use_tco = 'true'):
"""Processes and sends direct message.
parameters:
use_tco -- use the t.co url shortner
"""
self.subject = subject.strip()
self.message = message.strip()
self.url = url.strip()
# Use url t.co url shortner?
if self.tweet != '':
self.tweet = _clean_tweet(use_tco=use_tco or False)
_send_message()
def _send_message(self):
"""Implemets tweepy send direct message.
Note: to is a list of Twitter IDs or Twitter usernames.
Twitter usernames can change, Twitter IDs do not.
"""
# Loop throught the to's
from tweepy.error import TweepError
for t in self.to:
self.api.send_direct_message(user=t, text=self.tweet)
def _clean_tweet(self, use_tco=True):
"""Creates tweets by truncating subject at appropriate length.
Length is calculated using the length of a t.co URL or the provided URL
depending the use_tco parameter.
"""
if use_tco:
length = 160 - 19
tweet = u'%s %s' % self.subject[0:length], self.url
else:
length = 160-len(self.url)-1
tweet = u'%s %s' % self.subject[0:length], self.url
return tweet
def _share(self):
"""Implements "sharing" on twitter which is exactly like tweeting.
Note: Tweeting is the same as "updating your status".
"""
result = self.api.update_status(status=self.tweet)
示例2: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
#.........这里部分代码省略.........
@to_direct_message
@include_entities
def get_direct_messages(self, **kwargs):
dms = self._api.direct_messages(**kwargs)
sent = self._api.sent_direct_messages(**kwargs)
dms.extend(sent)
return dms
# NOTE:
# `get_thread` is not decorated with `to_status` because
# it uses `TweepyApi.get_user_timeline` which is already
# decorated
@include_entities
def get_thread(self, status, **kwargs):
"""
Get the conversation to which `status` belongs.
It filters the last tweets by the participanting users and
based on mentions to each other.
"""
author = status.authors_username
mentioned = status.mentioned_usernames
if author not in mentioned:
mentioned.append(author)
tweets = []
for username in mentioned:
tweets.extend(self.get_user_timeline(username, **kwargs))
def belongs_to_conversation(status):
for username in mentioned:
if username in status.text:
return True
return filter(belongs_to_conversation, tweets)
@to_status_from_search
@include_entities
def search(self, text, **kwargs):
return self._api.search(text, **kwargs)
def update(self, text):
self._api.update_status(text)
def destroy_status(self, status):
self._api.destroy_status(status.id)
def retweet(self, status):
self._api.retweet(status.id)
def direct_message(self, username, text):
self._api.send_direct_message(user=username, text=text)
def destroy_direct_message(self, dm):
self._api.destroy_direct_message(dm.id)
def create_friendship(self, screen_name):
self._api.create_friendship(screen_name=screen_name)
def destroy_friendship(self, screen_name):
self._api.destroy_friendship(screen_name=screen_name)
def create_favorite(self, status):
self._api.create_favorite(status.id)
def destroy_favorite(self, status):
self._api.destroy_favorite(status.id)
# list methods
def get_lists(self, screen_name):
raise NotImplementedError
def get_own_lists(self):
raise NotImplementedError
def get_list_memberships(self):
raise NotImplementedError
def get_list_subscriptions(self):
raise NotImplementedError
def get_list_timeline(self, list):
raise NotImplementedError
def get_list_members(self, list):
raise NotImplementedError
def is_list_member(self, user, list):
raise NotImplementedError
def subscribe_to_list(self, list):
raise NotImplementedError
def get_list_subscribers(self, list):
raise NotImplementedError
def is_list_subscriber(self, user, list):
raise NotImplementedError
示例3: TwitterHandler
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
class TwitterHandler( StreamListener ):
def __init__( self ):
self.logger = logging.getLogger(__name__)
try:
self.auth = OAuthHandler(twitter_secrets.APP_KEY, twitter_secrets.APP_SECRET)
self.auth.secure = True
self.auth.set_access_token(twitter_secrets.OAUTH_TOKEN, twitter_secrets.OAUTH_TOKEN_SECRET)
self.api = API(self.auth)
# If the authentication was successful, you should
# see the name of the account self.logger.info out
self.logger.info(self.api.me().name)
self.stream = Stream(self.auth, self)
self.stream.userstream(async = True)
except BaseException as e:
self.logger.info("Error in __init__", e)
def on_connect( self ):
self.logger.info("Connection established!!")
def on_disconnect( self, notice ):
self.logger.info("Connection lost!! : ", notice)
def on_data( self, status ):
self.logger.info("Entered on_data()")
data = json.loads(status)
if 'direct_message' in data:
name = data['direct_message']['sender_screen_name']
text = data['direct_message']['text']
m = models.Message(source = "twitter", name = name, message = text, rec_by = "", response = "")
m.save()
self.logger.info("Name: " + name + " Text: " + text)
return True
def on_error( self, status ):
self.logger.info(status)
def sendMessage( self, name, message):
if(self.api.me().screen_name != name):
self.api.send_direct_message(screen_name = name, text = message)
self.logger.info("successfully sent " + message + " to " + name)
else:
self.logger.info("Cannot send message to yourself")
示例4: send_dm
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
def send_dm(username, text):
try:
consumer_key = environ['TWITTER_CONSUMER_KEY']
access_token = environ['TWITTER_ACCESS_TOKEN']
consumer_secret = environ['TWITTER_CONSUMER_SECRET']
access_secret = environ['TWITTER_ACCESS_SECRET']
except KeyError:
error("No Twitter credentials were found.")
# We don't have login stuff, bail.
return
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = API(auth_handler=auth)
api.send_direct_message(screen_name=username, text=text)
示例5: open
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
from __future__ import absolute_import, print_function
import json
from pprint import pprint
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import API
if __name__ == '__main__':
with open('api_secret_token.json') as data_file:
authdata = json.load(data_file)
#pprint(authdata)
auth = OAuthHandler(authdata['consumer_key'], authdata['consumer_secret'])
auth.set_access_token(authdata['access_token'], authdata['access_token_secret'])
api = API(auth)
print(api.me().name)
# If the application settings are set for "Read and Write" then
# this line should tweet out a direct message
# The "Read and Write" setting is on https://dev.twitter.com/apps
api.send_direct_message(user="hrishikesh_date", text="Hello From Pi :)")
示例6: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
#.........这里部分代码省略.........
if dm.sender_screen_name == me.screen_name:
with_user = dm.recipient_screen_name
else:
with_user = dm.sender_screen_name
def belongs_to_conversation(message):
return (message.sender_screen_name == with_user or
message.recipient_screen_name == with_user)
return filter(belongs_to_conversation, messages)
@to_status_from_search
@include_entities
def search(self, text, **kwargs):
return self._api.search(text, **kwargs)
@to_status
@include_entities
def get_retweets_of_me(self, **kwargs):
return self._api.retweets_of_me(**kwargs)
def update(self, text):
self._api.update_status(text)
def reply(self, status, text):
self._api.update_status(text, in_reply_to_status_id=status.id)
def destroy_status(self, status):
self._api.destroy_status(status.id)
def retweet(self, status):
self._api.retweet(status.id)
def direct_message(self, username, text):
self._api.send_direct_message(user=username, text=text)
def destroy_direct_message(self, dm):
self._api.destroy_direct_message(dm.id)
def create_friendship(self, screen_name):
self._api.create_friendship(screen_name=screen_name)
def destroy_friendship(self, screen_name):
self._api.destroy_friendship(screen_name=screen_name)
def create_favorite(self, status):
self._api.create_favorite(status.id)
def destroy_favorite(self, status):
self._api.destroy_favorite(status.id)
# list methods
@to_list
def get_lists(self, screen_name):
return self._api.lists(screen_name)
@to_list
def get_own_lists(self):
return self._api.lists()
@to_list
def get_list_memberships(self):
return self._api.lists_memberships()
@to_list
def get_list_subscriptions(self):
return self._api.lists_subscriptions()
@to_status
def get_list_timeline(self, a_list):
owner = a_list.owner.screen_name
return self._api.list_timeline(owner=owner, slug=a_list.slug)
@to_user
def get_list_members(self, a_list):
owner = a_list.owner.screen_name
return self._api.list_members(owner=owner, slug=a_list.slug)
def is_list_member(self, user, a_list):
return bool(self._api.is_list_member(owner=user.screen_name,
slug=a_list.slug,
user_id=user.id,))
@to_list
def subscribe_to_list(self, a_list):
owner = a_list.owner
return self._api.subscribe_list(owner=owner.screen_name,
slug=a_list.slug)
@to_user
def get_list_subscribers(self, a_list):
owner = a_list.owner
return self._api.list_subscribers(owner=owner.screen_name,
slug=a_list.slug,)
def is_list_subscriber(self, user, a_list):
return bool(self._api.is_subscribed_list(owner=user.screen_name,
slug=a_list.slug,
user_id=user.id,))
示例7: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
class TweepyAPITests(unittest.TestCase):
def setUp(self):
auth = OAuthHandler(oauth_consumer_key, oauth_consumer_secret)
auth.set_access_token(oauth_token, oauth_token_secret)
self.api = API(auth)
self.api.retry_count = 2
self.api.retry_delay = 5
def testhometimeline(self):
self.api.home_timeline()
def testfriendstimeline(self):
self.api.friends_timeline()
def testusertimeline(self):
self.api.user_timeline()
self.api.user_timeline('twitter')
def testmentions(self):
self.api.mentions()
def testretweetedbyme(self):
self.api.retweeted_by_me()
def testretweetedbyuser(self):
self.api.retweeted_by_user('twitter')
def testretweetedtome(self):
self.api.retweeted_to_me()
def testretweetsofme(self):
self.api.retweets_of_me()
def testretweet(self):
s = self.api.retweet(test_tweet_id)
s.destroy()
def testretweets(self):
self.api.retweets(test_tweet_id)
def testgetstatus(self):
self.api.get_status(id=test_tweet_id)
def testupdateanddestroystatus(self):
# test update
text = 'testing %i' % random.randint(0, 1000)
update = self.api.update_status(status=text)
self.assertEqual(update.text, text)
# test destroy
deleted = self.api.destroy_status(id=update.id)
self.assertEqual(deleted.id, update.id)
def testgetuser(self):
u = self.api.get_user('twitter')
self.assertEqual(u.screen_name, 'twitter')
u = self.api.get_user(783214)
self.assertEqual(u.screen_name, 'twitter')
def testsearchusers(self):
self.api.search_users('twitter')
def testme(self):
me = self.api.me()
self.assertEqual(me.screen_name, username)
def testfriends(self):
self.api.friends()
def testfollowers(self):
self.api.followers()
def testdirectmessages(self):
self.api.direct_messages()
def testsentdirectmessages(self):
self.api.sent_direct_messages()
def testsendanddestroydirectmessage(self):
# send
sent_dm = self.api.send_direct_message(username, text='test message')
self.assertEqual(sent_dm.text, 'test message')
self.assertEqual(sent_dm.sender.screen_name, username)
self.assertEqual(sent_dm.recipient.screen_name, username)
# destroy
destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
self.assertEqual(destroyed_dm.text, sent_dm.text)
self.assertEqual(destroyed_dm.id, sent_dm.id)
self.assertEqual(destroyed_dm.sender.screen_name, username)
self.assertEqual(destroyed_dm.recipient.screen_name, username)
def testcreatedestroyfriendship(self):
enemy = self.api.destroy_friendship('twitter')
self.assertEqual(enemy.screen_name, 'twitter')
# Wait 5 seconds to allow Twitter time
# to process the friendship destroy request.
#.........这里部分代码省略.........
示例8: TweepyApi
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
#.........这里部分代码省略.........
return self._to_status(self._api.favorites(**kwargs))
def get_direct_messages(self, **kwargs):
dms = self._api.direct_messages(**kwargs)
sent = self._api.sent_direct_messages(**kwargs)
dms.extend(sent)
return self._to_direct_message(dms)
def get_thread(self, status, **kwargs):
author = get_authors_username(status)
mentioned = get_mentioned_usernames(status)
if author not in mentioned:
mentioned.append(author)
tweets = []
for username in mentioned:
tweets.extend(self.get_user_timeline(username, **kwargs))
def belongs_to_conversation(status):
for username in mentioned:
if username in status.text:
return True
return filter(belongs_to_conversation, tweets)
def get_search(self, text, **kwargs):
# `tweepy.API.search` returns `tweepy.models.SearchResult` objects instead
# `tweepy.models.Status` so we have to convert them differently
def to_status(status):
kwargs = {
'id': status.id,
'created_at': status.created_at,
'user': status.from_user,
'text': status.text,
}
return Status(**kwargs)
results = self._api.search(text, **kwargs)
return [to_status(result) for result in results]
def update(self, text):
return self._api.update_status(text)
def destroy_status(self, status):
return self._to_status(self._api.destroy_status(status.id))
def retweet(self, status):
return self._to_status(self._api.retweet(status.id))
def direct_message(self, username, text):
return self._to_direct_message(self._api.send_direct_message(user=username,
text=text))
def destroy_direct_message(self, dm):
return self._to_direct_message(self._api.destroy_direct_message(dm.id))
# TODO: convert to `turses.models.User`
def create_friendship(self, screen_name):
self._api.create_friendship(screen_name=screen_name)
def destroy_friendship(self, screen_name):
self._api.destroy_friendship(screen_name=screen_name)
def create_favorite(self, status):
self._to_status(self._api.create_favorite(status.id))
def destroy_favorite(self, status):
self._to_status(self._api.destroy_favorite(status.id))
# list methods
def get_lists(self, screen_name):
raise NotImplementedError
def get_own_lists(self):
raise NotImplementedError
def get_list_memberships(self):
raise NotImplementedError
def get_list_subscriptions(self):
raise NotImplementedError
def get_list_timeline(self, list):
raise NotImplementedError
def get_list_members(self, list):
raise NotImplementedError
def is_list_member(self, user, list):
raise NotImplementedError
def subscribe_to_list(self, list):
raise NotImplementedError
def get_list_subscribers(self, list):
raise NotImplementedError
def is_list_subscriber(self, user, list):
raise NotImplementedError
示例9: __init__
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
class NestBot:
def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret, watermarkFilePath):
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
self.api = API(auth)
self.watermarkFilePath = watermarkFilePath
# 'example: 278910647155179520'
self.last_message_id = self.ReadAllText(watermarkFilePath)
def ReadAllText(self, filePath):
if os.path.exists(filePath):
f = open(filePath, 'r')
text = f.read().strip()
f.close()
if (len(text) == 0):
text = None
else:
text = None
return text;
def WriteAllText(self, filePath, text):
f = open(filePath, 'w')
f.write(text)
f.close()
def shouldExecute(self, sender):
return sender == 'vboctor'
def printMessage(self, id, message, sender, sentAt):
print id, message, sender, sentAt
def executeMessage(self, id, message, sender, sentAt):
if (not self.shouldExecute(sender)):
print 'Skipping "' + message + '" from "' + sender + '"'
elif (message == 'status'):
print 'getting status... not implemented.'
self.api.send_direct_message(user = sender, text = 'Here is your status!!! - ' + str(id))
elif (message == 'away'):
print 'setting away... not implemented.'
self.api.send_direct_message(user = sender, text = 'Your nest is now set to away.' + str(id))
def updateWatermark(self, messageId):
self.last_message_id = str(messageId)
self.WriteAllText(self.watermarkFilePath, self.last_message_id)
def run(self):
while (True):
print 'checking queue...'
messages = self.api.direct_messages(since_id = self.last_message_id)
if (len(messages) == 0):
print ' no work, sleep for a while.'
time.sleep(20)
else:
# reverse the list of messages to process them in chronological order
# this is import to make the last command win and for watermarking to work
messages = reversed(messages)
for message in messages:
self.printMessage(message.id, message.text, message.sender.screen_name, message.created_at)
self.executeMessage(message.id, message.text, message.sender.screen_name, message.created_at)
self.updateWatermark(message.id)
示例10: TweepyAPITests
# 需要导入模块: from tweepy import API [as 别名]
# 或者: from tweepy.API import send_direct_message [as 别名]
class TweepyAPITests(unittest.TestCase):
def setUp(self):
auths = []
for consumer_key, consumer_secret, access_key, access_secret in oauth_keys:
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
auths.append(auth)
self.api = API(auths)
self.api.retry_count = 2
self.api.retry_delay = 5
# TODO: Actually have some sort of better assertion
def testgetoembed(self):
data = self.api.get_oembed(test_tweet_id)
self.assertEqual(data["author_name"], "Twitter")
def testhometimeline(self):
self.api.home_timeline()
def testusertimeline(self):
self.api.user_timeline()
self.api.user_timeline("twitter")
def testmentionstimeline(self):
self.api.mentions_timeline()
def testretweetsofme(self):
self.api.retweets_of_me()
def testretweet(self):
# TODO(josh): Need a way to get random tweets to retweet.
raise SkipTest()
def testretweets(self):
self.api.retweets(test_tweet_id)
def testgetstatus(self):
self.api.get_status(id=test_tweet_id)
def testupdateanddestroystatus(self):
# test update
text = "testing %i" % random.randint(0, 1000)
update = self.api.update_status(status=text)
self.assertEqual(update.text, text)
# test destroy
deleted = self.api.destroy_status(id=update.id)
self.assertEqual(deleted.id, update.id)
def testgetuser(self):
u = self.api.get_user("twitter")
self.assertEqual(u.screen_name, "twitter")
u = self.api.get_user(783214)
self.assertEqual(u.screen_name, "twitter")
def testsearchusers(self):
self.api.search_users("twitter")
def testsuggestedcategories(self):
self.api.suggested_categories()
def testsuggestedusers(self):
categories = self.api.suggested_categories()
if len(categories) != 0:
self.api.suggested_users(categories[0].slug)
def testsuggesteduserstweets(self):
categories = self.api.suggested_categories()
if len(categories) != 0:
self.api.suggested_users_tweets(categories[0].slug)
def testme(self):
me = self.api.me()
self.assertEqual(me.screen_name, username)
def testdirectmessages(self):
self.api.direct_messages()
def testsentdirectmessages(self):
self.api.sent_direct_messages()
def testsendanddestroydirectmessage(self):
# send
sent_dm = self.api.send_direct_message(username, text="test message")
self.assertEqual(sent_dm.text, "test message")
self.assertEqual(sent_dm.sender.screen_name, username)
self.assertEqual(sent_dm.recipient.screen_name, username)
# destroy
destroyed_dm = self.api.destroy_direct_message(sent_dm.id)
self.assertEqual(destroyed_dm.text, sent_dm.text)
self.assertEqual(destroyed_dm.id, sent_dm.id)
self.assertEqual(destroyed_dm.sender.screen_name, username)
self.assertEqual(destroyed_dm.recipient.screen_name, username)
def testcreatedestroyfriendship(self):
enemy = self.api.destroy_friendship("twitter")
self.assertEqual(enemy.screen_name, "twitter")
#.........这里部分代码省略.........