当前位置: 首页>>代码示例>>Python>>正文


Python Twython.get_direct_messages方法代码示例

本文整理汇总了Python中twython.Twython.get_direct_messages方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_direct_messages方法的具体用法?Python Twython.get_direct_messages怎么用?Python Twython.get_direct_messages使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twython.Twython的用法示例。


在下文中一共展示了Twython.get_direct_messages方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: updateSched

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
def updateSched(pipe):
    # KeyboardInterrupt is not a good thing to catch in here.
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    config = ConfigParser.RawConfigParser()
    config.read("impetus.conf")
    creds = dict(config.items("twitter"))
    pipe.send(creds)

    t = Twython(creds["con_key"], creds["con_secret"], creds["access_token"], creds["access_secret"])

    lastUpdate = safeConfGet(config, "alarm", "last_time")
    if lastUpdate:
        lastUpdate = dt.strptime(lastUpdate, "%Y-%m-%d %H:%M:%S.%f")
    else:
        lastUpdate = dt.min

    lastId = safeConfGet(config, "alarm", "last_id")

    while 1:
        if pipe.poll():
            obj = pipe.recv()
            if isinstance(obj, dt):
                pipe.send(nextAlarm(obj, config))
            elif obj == "teardown":
                break
        if dt.now() > lastUpdate + td(minutes=3):
            try:
                dms = t.get_direct_messages(since_id=lastId)
                if dms:
                    dms.reverse()
                    for dm in dms:
                        processed = processDm(config, dm)
                        if processed:
                            lastId = processed
                            config.set("alarm", "last_id", lastId)
                            t.send_direct_message(
                                screen_name=dm["sender_screen_name"],
                                text="Command sent on %s has been processed." % dm["created_at"],
                            )
            except TwythonError:
                pass  # Hrm.
            lastUpdate = dt.now()
            config.set("alarm", "last_time", lastUpdate)
            saveConfig(config)
        sleep(1)

    config.set("alarm", "last_id", lastId)
    config.set("alarm", "last_time", lastUpdate)

    cfg = open("impetus.conf", "w")
    config.write(cfg)
    cfg.close()
    pipe.close()
开发者ID:seandw,项目名称:impetus-clock,代码行数:55,代码来源:impetus.py

示例2: __init__

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
class TwitterBot:

    def __init__(self, name, con_k, con_s, acc_k, acc_s):
        self.name = name
        self.con_k = con_k
        self.con_s = con_s
        self.acc_k = acc_k
        self.acc_s = acc_s
        self.twitter = Twython(self.con_k, self.con_s, self.acc_k, self.acc_s)
        self.last_intervals = []
        self.last_tweet = ''

    def get_dms(self):
        if self.twitter is not None:
            dms = self.twitter.get_direct_messages()
            return dms
        
    def update_image(self):
        if self.twitter is not None:
            with open('zf.png', 'rb') as image_file:
                encoded_string = base64.b64encode(image_file.read())
                results = self.twitter.update_profile_image(image=encoded_string)
                return results

    def change_name(self, name):
        if self.twitter is not None:
            name = name.replace('"','')
            results = self.twitter.update_profile(name=name)
            return results

    def tweet(self, msg):
        if self.twitter is not None:
            # > 140 char detection
            if len(msg) > 140:
                msg = msg[0:139]
            syslog.syslog('%s is tweeting %s' % (self.name, msg))
            try:
                self.twitter.update_status(status=msg)
                self.last_tweet = msg
            except Exception as e:
                syslog.syslog('%s error tweeting -> %s' % (self.name, str(e)))
开发者ID:zmallen,项目名称:flock,代码行数:43,代码来源:ircbot.py

示例3: receive

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
    def receive(self):
        dm_enable = self.param('receiving', 'dm')
        ids = self.param('receiving', 'ids')
        tweets = list()
        user_timeline = list()

        APP_KEY = self.param('receiving', 'key')
        APP_SECRET = self.param('receiving', 'secret')
        OAUTH_TOKEN = self.param('receiving', 'token')
        OAUTH_TOKEN_SECRET = self.param('receiving', 'tsecret')
        SCREEN_NAME = self.param('receiving', 'name')

        twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

        try:
            if dm_enable:
                if len(ids) > 0:
                    for dm_id in ids:
                        dm = twitter.get_direct_message(id=dm_id)
                        user_timeline.append(dm)
                else:
                    user_timeline = twitter.get_direct_messages()
            else:
                if len(ids) > 0:
                    for t_id in ids:
                        tweet = twitter.show_status({'id': t_id})
                        user_timeline.append(tweet)
                else:
                    user_timeline = twitter.get_user_timeline(screen_name=SCREEN_NAME)

            for x in user_timeline:
                if 'text' in x:
                    tweets.append(x['text'])

        except Exception as err:
            raise ExfilChannel("Error retrieving tweets: {0}".format(err))

        return tweets
开发者ID:davinerd,项目名称:sneaky-creeper,代码行数:40,代码来源:twitter.py

示例4: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
class TwythonAPITestCase(unittest.TestCase):
    def setUp(self):
        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret)

    # Timelines
    def test_get_mentions_timeline(self):
        '''Test returning mentions timeline for authenticated user succeeds'''
        self.api.get_mentions_timeline()

    def test_get_user_timeline(self):
        '''Test returning timeline for authenticated user and random user
        succeeds'''
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')  # Random User Timeline

    def test_get_protected_user_timeline_following(self):
        '''Test returning a protected user timeline who you are following
        succeeds'''
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    def test_get_protected_user_timeline_not_following(self):
        '''Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError'''
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    def test_get_home_timeline(self):
        '''Test returning home timeline for authenticated user succeeds'''
        self.api.get_home_timeline()

    # Tweets
    def test_get_retweets(self):
        '''Test getting retweets of a specific tweet succeeds'''
        self.api.get_retweets(id=test_tweet_id)

    def test_show_status(self):
        '''Test returning a single status details succeeds'''
        self.api.show_status(id=test_tweet_id)

    def test_update_and_destroy_status(self):
        '''Test updating and deleting a status succeeds'''
        status = self.api.update_status(status='Test post just to get deleted :(')
        self.api.destroy_status(id=status['id_str'])

    def test_retweet(self):
        '''Test retweeting a status succeeds'''
        retweet = self.api.retweet(id='99530515043983360')
        self.api.destroy_status(id=retweet['id_str'])

    def test_retweet_twice(self):
        '''Test that trying to retweet a tweet twice raises a TwythonError'''
        retweet = self.api.retweet(id='99530515043983360')
        self.assertRaises(TwythonError, self.api.retweet,
                          id='99530515043983360')

        # Then clean up
        self.api.destroy_status(id=retweet['id_str'])

    def test_get_oembed_tweet(self):
        '''Test getting info to embed tweet on Third Party site succeeds'''
        self.api.get_oembed_tweet(id='99530515043983360')

    def test_get_retweeters_ids(self):
        '''Test getting ids for people who retweeted a tweet succeeds'''
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    def test_search(self):
        '''Test searching tweets succeeds'''
        self.api.search(q='twitter')

    # Direct Messages
    def test_get_direct_messages(self):
        '''Test getting the authenticated users direct messages succeeds'''
        self.api.get_direct_messages()

    def test_get_sent_messages(self):
        '''Test getting the authenticated users direct messages they've
        sent succeeds'''
        self.api.get_sent_messages()

    def test_send_get_and_destroy_direct_message(self):
        '''Test sending, getting, then destory a direct message succeeds'''
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d!')

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    def test_send_direct_message_to_non_follower(self):
        '''Test sending a direct message to someone who doesn't follow you
        fails'''
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man!')

    # Friends & Followers
    def test_get_user_ids_of_blocked_retweets(self):
        '''Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds'''
#.........这里部分代码省略.........
开发者ID:chrisbol,项目名称:twython,代码行数:103,代码来源:test_twython.py

示例5: Twython

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
from twython import Twython, TwythonError
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)


get_list = twitter.get_direct_messages()
#Returns All Twitter DM information which is a lot in a list format

dm_dict = get_list[0]
#Sets get_list to a dictionary, the number in the list is the direct message retrieved
#That means that 0 is the most recent and n-1 is the last DM revieved.
#You can cycle through all the numbers and it will return the text and the sender id of each

print dm_dict['text']
#Gets the text from the dictionary

print dm_dict['sender']['id']
#Gets the ID of the sender
开发者ID:Hasimir,项目名称:twython,代码行数:19,代码来源:get_direct_messages.py

示例6: TwythonAPITestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]

#.........这里部分代码省略.........

    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(status='Test post just to get deleted :(')
        self.api.destroy_status(id=status['id_str'])

    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()

    def test_get_sent_messages(self):
        """Test getting the authenticated users direct messages they've
        sent succeeds"""
        self.api.get_sent_messages()

    def test_send_get_and_destroy_direct_message(self):
        """Test sending, getting, then destory a direct message succeeds"""
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d! %s' % int(time.time()))

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    def test_send_direct_message_to_non_follower(self):
        """Test sending a direct message to someone who doesn't follow you
        fails"""
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man!')

    # Friends & Followers
    def test_get_user_ids_of_blocked_retweets(self):
        """Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds"""
        self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)

    def test_get_friends_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user is following succeeds"""
        self.api.get_friends_ids()
开发者ID:hungtrv,项目名称:twython,代码行数:70,代码来源:test_core.py

示例7: print

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
                # keep sleep mode on
                sleep_status = True
                psql.sendSQL("UPDATE sleep SET active = true;")
                print('sleep mode start activated')
            if sleep_status and now.hour == sleep_end.hour and now.minute == sleep_end.minute:
                # we are at the sleep end time, so turn on the heat
                rc.onAll(twitter)
                # turn off sleep mode
                sleep_status = 0
                psql.sendSQL("UPDATE sleep SET active = false;")
                twitter.send_direct_message(text='Sleep Mode Off', screen_name=tc.ok_user_id)
                print('sleep mode end activated')

        # read direct messages
        try:
            direct_messages = twitter.get_direct_messages()
            direct_messages = direct_messages['events']
        except:
            print('twitter GET rate limit error')
            direct_messages = []

        num_messages = len(direct_messages)
        # see if there is a new direct message
        # print('found ' + str(num_messages) + ' messages')
        for i in range(num_messages):
            #sender_name = direct_messages[num_messages - i - 1]['sender_screen_name']
            sender_name = direct_messages[num_messages - i -1]['message_create']['sender_id']
            message_id = direct_messages[num_messages - i - 1]['id']
            if sender_name == ok_user_name:
                #message = direct_messages[num_messages - i - 1]['text'].upper()
                message = direct_messages[num_messages - i - 1]['message_create']['message_data']['text'].upper()
开发者ID:gsugar87,项目名称:thermostat,代码行数:33,代码来源:tweet_monitor.py

示例8: TwythonEndpointsTestCase

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
class TwythonEndpointsTestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        # This is so we can hit coverage that Twython sets
        # User-Agent for us if none is supplied
        oauth2_client_args = {
            'headers': {}
        }

        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key, access_token=access_token,
                                  client_args=oauth2_client_args)

    # Timelines
    @unittest.skip('skipping non-updated test')
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

    @unittest.skip('skipping non-updated test')
    def test_get_user_timeline(self):
        """Test returning timeline for authenticated user and random user
        succeeds"""
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')
        # Random User Timeline

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_following(self):
        """Test returning a protected user timeline who you are following
        succeeds"""
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_not_following(self):
        """Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError"""
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    @unittest.skip('skipping non-updated test')
    def test_retweeted_of_me(self):
        """Test that getting recent tweets by authenticated user that have
        been retweeted by others succeeds"""
        self.api.retweeted_of_me()

    @unittest.skip('skipping non-updated test')
    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    @unittest.skip('skipping non-updated test')
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(status='Test post just to get \
                    deleted :( %s' % int(time.time()))
        self.api.destroy_status(id=status['id_str'])

    @unittest.skip('skipping non-updated test')
    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    @unittest.skip('skipping non-updated test')
    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    @unittest.skip('skipping non-updated test')
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    @unittest.skip('skipping non-updated test')
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()
#.........这里部分代码省略.........
开发者ID:nouvak,项目名称:twython,代码行数:103,代码来源:test_endpoints.py

示例9: exit

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
 print '---> Listen <---'
 if config.get('Enviroment','LAST_DM_ID'):
     # pedir somente os itens maiores que o id existente...
     current_val = config.get('Enviroment','LAST_DM_ID')
     print '--> variavel atual: '+str(current_val)+' <--'
     #print 'Valor atual = '+current_val
 else:
     # variavel nao existe.
     config.set('Enviroment','LAST_DM_ID',0)
     config.write(open(fileDefaults,'w'))
     #abort script.
     print '--> Nao existe variavel! <--'
     exit()
 #pegando pacote com as mensagens enviadas
 #print 'seguindo...'
 pkgReturnDM = api.get_direct_messages(since_id=current_val)
 print '--> Tamanho do pacote: '+str(len(pkgReturnDM))+' <--'
 for returnDM in pkgReturnDM:
     senderData = returnDM['sender']
     entities = returnDM['entities']
     print 'Sender ---->' + config.get('Enviroment','allow_sender')
     print 'senderData:' + str(senderData['id'])
     if str(senderData['id']) == config.get('Enviroment','allow_sender'):
         print returnDM['created_at']
         print '--> Usuario OK! <--'
         command =  returnDM['entities']['hashtags'][0]['text']
         print '-> comando recebido: '+command+' <-'
         #Executar o comando da hashtag
         full_path = '/home/raspbot/raspLab/tweetBot/'
         cmd = 'python '+full_path+'raspTweet.py '+command
         print '[ '+cmd+' ]'
开发者ID:rom232,项目名称:raspLab,代码行数:33,代码来源:raspTweet.py

示例10: get_user_messages

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
def get_user_messages(consumer_key, consumer_sec, access_tok, access_token_sec, username='heteroT1'):
    twitter = Twython(consumer_key, consumer_sec, access_tok, access_token_sec)
    # user_timeline = twitter.get_user_timeline(screen_name='HeteroT1')
    user_messages = twitter.get_direct_messages(screen_name=username)
    for message in user_messages:
        print("message - ", message)
开发者ID:Shi3A,项目名称:Public-Key-Twitter,代码行数:8,代码来源:messaging.py

示例11: Tweety

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
class Tweety(object):
    """
    Twitter client using Twython
    """

    def __init__(self, app_key=TWITTER_APP_KEY, app_secret=TWITTER_APP_SECRET,
                 oauth_token=TWITTER_OAUTH_TOKEN, oauth_token_secret=TWITTER_OAUTH_SECRET):
        try:
            self.twitter = Twython(
            app_key,
            app_secret,
            oauth_token,
            oauth_token_secret)
            self.cache = RedisCache({
            'server': REDIS_SERVER,
            'port': REDIS_PORT,
            'database': REDIS_DATABASE,
            'key_prefix': 'domus-twitter'
            })
        except TwythonAuthError:
            raise Exception("Unable to connect to twitter")

    def __get_friends(self):
        """
        Using twitter get_friends and redis, gets a list of screen names
        :return:a list of twitter users
        """
        results = self.cache.get('twitter_friends')
        if not results:
            try:
                results = [a['screen_name'] for a in self.twitter.get_friends_list()['users']]
                self.cache.store('twitter_friends',json.dumps(results), expires=120)
            except (TwythonError, TwythonRateLimitError):
                raise Exception('Unable to get followers list')
        else:
            results = json.loads(results)
        return results

    def tweet(self, message,to_friends=False):
        """
        Writtes a twit
        :param message: what to tweet
        :param to_friends: send to all friends?
        :return:
        """
        try:
            if to_friends:
                for a_friend in self.__get_friends():
                    mention = "@{} ".format(a_friend)
                    available_chars = 140 - len(mention)
                    self.twitter.update_status(
                        status=(mention+message)[:available_chars] + ((mention+message)[(available_chars-2):] and '..'))
            else:
                self.twitter.update_status(
                        status=message[:140] + (message[138:] and '..'))
        except (TwythonError, TwythonRateLimitError):
            raise Exception("Unable to post update")

    def dm(self, user, message):
        try:
            self.twitter.send_direct_message(screen_name=user, text=message)
        except TwythonError:
            raise Exception("Unable to send dm to {}".format(user))

    def get_dms(self):
        """
        Gets a list of dms. Stores the last id seen so the next request is for the new messages only.
        :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}}
        """
        results = {}
        dms = []
        last_id = self.cache.get('twitter_last_dm')
        if last_id:
            dms = self.twitter.get_direct_messages(count=100,since_id = last_id)
        else:
            dms = self.twitter.get_direct_messages(count=100)
        if dms:
            last_id = 0
            for a_dm in dms:
                results[a_dm['id']] = {'from':a_dm['sender_screen_name'],'text': a_dm['text']}
                last_id = a_dm['id'] if a_dm['id'] > last_id else last_id
            self.cache.store('twitter_last_dm', last_id)
        return results

    def get_mentions(self):
        """
        Gets a list of mentions.  Stores the last id seen so the next request is for the new messages only.
        :return: a dict of the form {tweet_id:{sender:screen_name,text:the_message}}
        """
        results = {}
        mentions = []
        last_id = self.cache.get('twitter_last_mention')
        if last_id:
            mentions = self.twitter.get_mentions_timeline(count=100,since_id = last_id)
        else:
            mentions = self.twitter.get_mentions_timeline(count=100)
        if mentions:
            last_id = 0
            for a_mention in mentions:
                results[a_mention['id']] = {'from':a_mention['user']['screen_name'],'text': a_mention['text']}
#.........这里部分代码省略.........
开发者ID:Esiravegna,项目名称:domus,代码行数:103,代码来源:tweety.py

示例12: TwitterPlotBot

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_direct_messages [as 别名]
class TwitterPlotBot(Thread):
    """ Blueprint for the plot bot """
    def __init__(self, apiKey, apiSecret, accessToken, accessTokenSecret, \
                 pauseCommand, resumeCommand, plotter, stopEvent, \
                 targetHandle='', tweetInterval=1000,  maxCnt=10,  \
                 dm=False):
        """ The ctor for 'PlotBot'
        apiKey, apiSecret    Your application's twitter 
        accessToken          auth credentials
        accessTokenSecret 
        pauseEvent           Toggels the tweeting
        stopEvent            Stops the tweeting (end of application)
        plotter              The plotter object that will be used to generate
                             graphs
        targetHandle         Twitter handle to be included in the tweet
        tweetInterval        Will tweet adter every 'tweetInterval'
        maxCnt               Maximum number of direct messages to be read
        dm                   Send a direct message?
        """
        super(TwitterPlotBot, self).__init__()
        self.apiKey = apiKey
        self.apiSecret = apiSecret
        self.accessToken = accessToken
        self.accessTokenSecret = accessTokenSecret
        self.plotter = plotter
        self.targetHandle = targetHandle
        self.tweetInterval = tweetInterval
        #if targetHandle != "":
        #    self.dm = dm   # Do direct messaging only if we have target handle
        #else:
        #    self.dm = False
        # Sadly image upload does not seem to work (not supported by twitter API?)
        # Hence direct messaging stays disabled for now
        self.dm = False
        
        self.api = None
        self.pauseCommand = pauseCommand
        self.resumeCommand = resumeCommand
        self.stopEvent = stopEvent
        # Try and log in to twitter
        self.twitter = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
        # Start the DataLogger thread and make the plotter ready
        self.plotter.begin()
        self.keepTweeting = True     # Flag to indicate whether we want to tweet or not
        self.latestTweetCheck = datetime.datetime.utcnow()       # Used check for the latest DM 
        
        

    def __tweetPlot__(self, twtStr):
        """ This function is directly taken from the twython doc """
        photo = Image.open(self.plotter.getOutPutFileName())

        basewidth = 1000
        #wpercent = (basewidth / float(photo.size[0]))
        #height = int((float(photo.size[1]) * float(wpercent)))
        height = 500
        photo = photo.resize((basewidth, height), Image.ANTIALIAS)

        image_io = StringIO.StringIO()
        photo.save(image_io, format='PNG')

        # If you do not seek(0), the image will be at the end of the file and
        # unable to be read
        image_io.seek(0)


        response = self.twitter.upload_media(media=image_io)
        if self.dm == False:
            self.twitter.update_status(status=twtStr, media_ids=[response['media_id']])
        else:
            self.twitter.send_direct_message(screen_name=self.targetHandle, text = twtStr, 
                                              media_ids=[response['media_id']])

    def run(self):
        """ The thread that tweets updates periodically """
        while 1:
            if self.stopEvent.isSet():
                self.plotter.stop()
                return
            # Check if we need to tweet or not
            if self.targetHandle != '':
                # Get the personal message from the master
                try:
                    msgs = self.twitter.get_direct_messages(screen_id = self.targetHandle, count=10)
                except Exception, ex:
                    print "Could not receive direct messages "
                    print str(ex)
                    self.keepTweeting = True
                    continue
                    
                # Below code is to make sure that the tweet that we interpret is the latest
                if len(msgs) != 0:
                    # Check if any of the message is latest
                    temp = time.strptime(msgs[0]['created_at'],'%a %b %d %H:%M:%S +0000 %Y')
                    temp = mktime(temp)
                    tweetTime = datetime.datetime.fromtimestamp(temp)
                    # if not, just pass
                    if tweetTime > self.latestTweetCheck:
                        for msg in msgs:
                            if msg['sender']['screen_name'].find(self.targetHandle.replace('@','')) >= 0:  # Tweet from the master
#.........这里部分代码省略.........
开发者ID:navin-bhaskar,项目名称:TwitterPlotBot,代码行数:103,代码来源:TwitterPlotBot.py


注:本文中的twython.Twython.get_direct_messages方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。