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


Python Twython.create_favorite方法代码示例

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


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

示例1: RT

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
def RT(ID, name):
    """Function that actually retweets tweet"""
    """Takes a ID and username parameter"""
    """Once tweeted log is updated in overall and to date tweetlog"""
    
    config = config_create()
    print("RT")
    #Tid = int(float(ID))
    Tweetusername = config.get('Auth', 'botname')
    #TweetText = 'https://twitter.com/'+Tweetusername+'/status/'+ID
    #ReTweet = 'Hi I am ComicTweetBot!('+tim+') I Retweet Comics! Use #comicretweetbot '+TweetText
    x2 = config.get('Latest_Log', 'currenttweetlog')
    x3 = config.get('Latest_Log', 'overalllog')
    CONSUMER_KEY =  config.get('Auth', 'CONSUMER_KEY') 
    CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET')
    ACCESS_KEY = config.get('Auth', 'ACCESS_KEY')
    ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET')
    api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    tMax = int(float(config.get('Tweet_Delay', 'Max')))
    tMin = int(float(config.get('Tweet_Delay', 'Min')))
    tStep = int(float(config.get('Tweet_Delay', 'Step')))
    Log = open(x2, 'w')
    enterlog = ID+' '+name+ '\n'
    Log.write(enterlog)
    Log2 = open(x3, 'w')
    Log2.write(ID+'\n')
    #api.update_status(status= ReTweet)
    api.retweet(id = ID)
    api.create_favorite(id=ID, include_entities = True)
    #randomize the time for sleep 1.5mins to 5 mins
    rant = random.randrange(tMin, tMax, tStep)
    time.sleep(rant)
开发者ID:MichaelJRanglin,项目名称:Python_TwitterComicBot,代码行数:34,代码来源:comicbot.py

示例2: twitter

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
def twitter():
    tpath = os.path.join(os.path.dirname(os.path.realpath('fiverr.exe')), 'tweets.txt')
    tweetstosend = open(tpath).readlines()
    newUsers = []
    config = ConfigParser.ConfigParser()
    config.read(path)
    current_action = config.get("Settings", "Action")
# --------------------------------Twython Authorization-----------------------------------   
    t = Twython(app_key=consumer_key, 
        app_secret=consumer_secret, 
        oauth_token=access_token_key, 
        oauth_token_secret=access_token_secret)
# --------------------------------Hashtag Parsing-----------------------------------
    actions = []
    current_hashtag = config.get("Settings", "Hashtag")
    current_action = config.get("Settings", "Action")
    current_action = current_action[1:len(current_action)-1].split(',')
    #current_action = current_action.split(',')
    for i in current_action:
        actions.append(i.lstrip())
    print actions
    search = t.search(q='#'+current_hashtag,count=100)
    tweets = search['statuses']
    for tweet in tweets:
        username = str(tweet['user']['screen_name'])
        if username not in users and username not in newUsers: #Has the user been accounted for?
                newUsers.append(username)
                print 'User added: ' + username
                print actions
                try:
                    for action in actions:
                        print action
                        if action == ("'Retweet'"):
                            t.retweet(id = tweet['id_str'])
                            print 'retweeted'
                        if action == "'Favorite'":
                            t.create_favorite(id = tweet['id_str'])
                            print 'favorited'
                        if action == "'Tweet'":
                            t.update_status(status="@{0} {1}".format(username, random.choice(tweetstosend)))
                            print 'tweeted'
                        if action == "'Follow'":
                            t.create_friendship(screen_name = username)
                            print 'followed'
                except:
                    print "NULL"
    tweetedUsers = "\n".join(newUsers)
    file = open(uLpath, 'a')
    file.write(tweetedUsers + '\n')
    file.close()
    time.sleep(1800)
开发者ID:justinpoiroux,项目名称:Python-Scripts,代码行数:53,代码来源:twitterbot.py

示例3: TmBot

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

#.........这里部分代码省略.........
         try:
            # Occasionally force some short(er) updates so they're not all
            # paragraph-length.. (these values arbitrarily chosen)
            maxLen = choice([120, 120, 120, 120, 100, 100, 100, 80, 80, 40])
            album, track, msg = self.GetLyric(maxLen)
            self.tweets.append({'status' : msg})
            self.settings.lastUpdate = int(time())
            # we'll log album name, track name, number of lines, number of characters
            self.Log("Tweet", [album, track, str(1 + msg.count("\n")), str(len(msg))])
         except NoLyricError:
            self.Log("NoLyric", [])
            pass

   def HandleMentions(self):
      '''
         Get all the tweets that mention us since the last time we ran and process each
         one.
         Any time we're mentioned in someone's tweet, we favorite it. If they ask
         us a question, we reply to them.
      '''
      mentions = self.twitter.get_mentions_timeline(since_id=self.settings.lastMentionId)
      if mentions:
         # Remember the most recent tweet id, which will be the one at index zero.
         self.settings.lastMentionId = mentions[0]['id_str']
         for mention in mentions:
            who = mention['user']['screen_name']
            text = mention['text']
            theId = mention['id_str']

            # we favorite every mention that we see
            if self.debug:
               print "Faving tweet {0} by {1}:\n {2}".format(theId, who, text.encode("utf-8"))
            else:
               self.twitter.create_favorite(id=theId)

            eventType = 'Mention'
            # if they asked us a question, reply to them.
            if "?" in text:
               # create a reply to them.
               maxReplyLen = 120 - len(who)
               album, track, msg = self.GetLyric(maxReplyLen)
               # get just the first line
               msg = msg.split('\n')[0]
               # In order to post a reply, you need to be sure to include their username
               # in the body of the tweet.
               replyMsg = "@{0} {1}".format(who, msg)
               self.tweets.append({'status': replyMsg, "in_reply_to_status_id" : theId})
               eventType = "Reply"

            self.Log(eventType, [who])



   def HandleQuotes(self):
      ''' The streaming version of the bot may have detected some quoted tweets
         that we want to respond to. Look for files with the .fav extension, and 
         if we find any, handle them. 
      '''
      faves = glob(self.GetPath("*.fav"))
      for fileName in faves:
         with open(fileName, "rt") as f:
            tweetId = f.readline().strip()
            if self.debug:
               print "Faving quoted tweet {0}".format(tweetId)
            else:
               try:
开发者ID:gausie,项目名称:ajjthebot,代码行数:70,代码来源:ajjthebot.py

示例4: TwythonAPITestCase

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

#.........这里部分代码省略.........
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    def test_remove_profile_banner(self):
        '''Test removing profile banner succeeds'''
        self.api.remove_profile_banner()

    def test_get_profile_banner_sizes(self):
        '''Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner'''
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    def test_get_user_suggestions_by_slug(self):
        '''Test getting user suggestions by slug succeeds'''
        self.api.get_user_suggestions_by_slug(slug='twitter')

    def test_get_user_suggestions(self):
        '''Test getting user suggestions succeeds'''
        self.api.get_user_suggestions()

    def test_get_user_suggestions_statuses_by_slug(self):
        '''Test getting status of suggested users succeeds'''
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    def test_get_favorites(self):
        '''Test getting list of favorites for the authenticated
        user succeeds'''
        self.api.get_favorites()

    def test_create_and_destroy_favorite(self):
        '''Test creating and destroying a favorite on a tweet succeeds'''
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    def test_show_lists(self):
        '''Test show lists for specified user'''
        self.api.show_lists(screen_name='twitter')

    def test_get_list_statuses(self):
        '''Test timeline of tweets authored by members of the
        specified list succeeds'''
        self.api.get_list_statuses(list_id=test_list_id)

    def test_create_update_destroy_list_add_remove_list_members(self):
        '''Test create a list, adding and removing members then
        deleting the list succeeds'''
        the_list = self.api.create_list(name='Stuff')
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed')

        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name='johncena,xbox')
        self.api.delete_list_members(list_id=list_id,
                                     screen_name='johncena,xbox')

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id, screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)
开发者ID:chrisbol,项目名称:twython,代码行数:69,代码来源:test_twython.py

示例5: TwitterHelper

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

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

        }
        self.twitter.post(url, finalize_params)

        return media_id

    def get_trending_topics_for(self, woeids):
        trending_topics = []
        for woeid in woeids:
            trends = self.twitter.get_place_trends(id=woeid)[0].get('trends', [])
            for trend in trends:
                trending_topics.append(trend['name'])
        return trending_topics

    def get_saved_searches(self):
        saved_searches = []
        searches = self.twitter.get_saved_searches()
        for srch in searches:
            saved_searches.append(srch['name'])
        return saved_searches

    def delete_saved_searches(self):
        searches = self.twitter.get_saved_searches()
        for srch in searches:
            self.twitter.destroy_saved_search(id=srch["id_str"])

    def search(self, text, result_type="popular"):
        query = quote_plus(text)
        return self.twitter.search(q=query, result_type=result_type)["statuses"]

    @retry(**retry_args)
    def favourite(self, id_str):
        try:
            self.twitter.create_favorite(id=id_str)
            self.identity.statistics.record_favourite()
        except TwythonError as ex:
            if "You have already favourited this tweet" in str(ex):
                logger.warning(ex)
            else:
                raise

    @retry(**retry_args)
    def retweet(self, id_str):
        try:
            self.twitter.retweet(id=id_str)
            self.identity.statistics.record_retweet()
        except TwythonError as ex:
            if "You have already retweeted this tweet" in str(ex):
                logger.warning(ex)
            else:
                raise

    @retry(**retry_args)
    def add_user_to_list(self, list_id, user_id, screen_name):
        self.twitter.create_list_members(list_id=list_id, user_id=user_id, screen_name=screen_name)

    @retry(**retry_args)
    def block_user(self, user_id, user_screen_name=None):
        self.twitter.create_block(user_id=user_id, screen_name=user_screen_name)

    @retry(**retry_args)
    def get_user_timeline(self, **kwargs):
        return self._rate_limit("/statuses/user_timeline", self.twitter.get_user_timeline, **kwargs)

    def unblock_user(self, user):
        self.twitter.destroy_block(user_id=user.id, screen_name=user.screen_name)
开发者ID:andrewtatham,项目名称:twitterpibot,代码行数:70,代码来源:twitterhelper.py

示例6: Twython

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
    'Miauuuu Miaau',
    'Miau Mateo que te veo']

#sacamos la hora
hora = time.strftime("%H")
print hora
if hora >= "09" and hora < "19":
    print "dentro del tiempo permitido para mandar el tuit"
    api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    api.update_status_with_media(status=random.choice(texto), media=photo)
    print "tuit enviado enviado a las "+time.strftime("%H:%M")

else:
    print "fuera de hora porque son las "+time.strftime("%H:%M")+ "pero empezamos a favear"
    api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    naughty_words = [" -RT", "SEX", "sexo", "muerto"]
    good_words = [" gato ", "miauu", " gatos ", "LaGataSoka", "@lagatasoka", "gatito", "gatitos"]
    filter = " OR ".join(good_words)
    blacklist = " -".join(naughty_words)
    keywords = filter + blacklist

    search_results = api.search(q=keywords, count=30)
    print "resultados"+str(search_results)
    for tweet in search_results["statuses"]:
        print tweet["id_str"]
        #twitter.retweet(id = tweet["id_str"])
        api.create_favorite(id = tweet["id_str"])

print "Bye, Bye...."
sys.exit()
开发者ID:jaunje,项目名称:twitter-lagatasoka,代码行数:32,代码来源:twithief.py

示例7: TwythonAPITestCase

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

#.........这里部分代码省略.........
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    def test_remove_profile_banner(self):
        """Test removing profile banner succeeds"""
        self.api.remove_profile_banner()

    def test_get_profile_banner_sizes(self):
        """Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner"""
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(list_id=test_list_id)

    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff')
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed')

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id,
                                     screen_name=screen_names)

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id, screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)
开发者ID:hungtrv,项目名称:twython,代码行数:70,代码来源:test_core.py

示例8: MainWindow

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

#.........这里部分代码省略.........
        while 1:
            key = self.cmdbar.getkey()

            if key == "q":
                break
            
            if key in self.key_bind:
                name, func = self.key_bind[key]
                self.change_modename(name)
                func(self.mwin)
                self.change_modename("Waiting")

                curses.curs_set(0)

            self.show_timeline()

        curses.nocbreak()
        curses.echo()
        curses.endwin()

    def add_plugin(self, cls):
        self.plugin.append(cls)
        for name, func, bind in cls.cmd_list:
            self.key_bind[bind] = (name, func)
        
    def get_home_timeline(self, num=-1):
        if num == -1:
            statuses = self.api.get_home_timeline(since_id = self.latest_id)
        else:
            statuses = self.api.get_home_timeline(count = num)
            
        for status in statuses[::-1]:
            self.on_status(status)
            self.latest_id = status['id']

    def get_loaded_status(self):
        return self.loaded_statuses
            
    def user_input(self):
        self.cmdbar.erase()
        self.cmdbar.refresh()
        curses.echo()
        input = self.cmdbar.getstr()
        curses.noecho()
        return input

    def fit_window(self):
        self.max_y, self.max_x = self.win.getmaxyx()
        self.mwin.resize(self.max_y-2, self.max_x)
        self.mwin.mvwin(0,0)
        self.statbar.resize(1,self.max_x)
        self.statbar.mvwin(self.max_y-2, 0)
        self.cmdbar.resize(1, self.max_x)
        self.cmdbar.mvwin(self.max_y-1, 0)
        self.win.refresh()
        
    def show_timeline(self, all=False):
        self.fit_window()
        self.mwin.erase()
        length = len(self.loaded_statuses)
        if all == True:
            show_range = range(length)
        else:
            show_range = range(max(0, length-self.max_y), length)

        for i in show_range:
            status = self.loaded_statuses[i]
            self.mwin.addstr("\n%s:%s" % (status['user']['screen_name'], status['text']))
        self.mwin.refresh()
    
    def tweet(self, content, in_reply_to=None):
        if in_reply_to == None:
            self.api.update_status(status=content)
        else:
            self.api.update_status(status=content, in_reply_to_status_id=in_reply_to) 

    def retweet(self, id):
        self.api.retweet(id=id)

    def create_favorite(self, id):
        self.api.create_favorite(id=id)
        
    def change_modename(self, name):
        self.modename = name
        self.statbar_refresh()

    def statbar_refresh(self):
        self.statbar.erase()
        self.statbar.addstr("  (%s)" % self.modename)
        self.statbar.refresh()

    def cmdbar_output(self, text):
        self.cmdbar.erase()
        self.cmdbar.addnstr(text, self.max_x)
        self.cmdbar.refresh()
        
    def on_status(self, status):
        self.mwin.addstr("%s: %s\n" % (status['user']['screen_name'], status['text']))
        self.mwin.refresh()
        self.loaded_statuses.append(status)
开发者ID:maleic1618,项目名称:cmaletter,代码行数:104,代码来源:main.py

示例9: main

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
def main(episodenumber, live_tweet, testmode):
    
    import sqlite3 as lite
    from twython import Twython    
    import os
    import warnings
    warnings.filterwarnings("ignore")

    dir = os.path.dirname(__file__)
    filename = os.path.join(dir, '../tweets.db')
    con = lite.connect(filename)
    
    import twitterconfig 
    twitter = Twython(twitterconfig.APP_KEY, twitterconfig.APP_SECRET, twitterconfig.OAUTH_TOKEN, twitterconfig.OAUTH_TOKEN_SECRET)

    
    top_retweets = '' 
    striketweet = '#Tatort - Ins Schwarze getwittert: '
    top_tweeters = [] 
    
    
    with con:
        
        cur = con.cursor()
        command = 'SELECT * FROM tatorttweets WHERE lfd =  ' + str(episodenumber) + ' ORDER BY retweet_count DESC LIMIT 10' 

        cur.execute(command)
        rows = cur.fetchall()
        for row in rows:
            if testmode: print row[2]
            
            newtweet = striketweet + ' \[email protected]' + row[2] 
            if not ((len(newtweet) > 140) or (row[2] in top_tweeters)): 
                striketweet = newtweet 
                top_tweeters.append(row[2])
            try: 
                twitter.create_friendship(screen_name=row[2])
            except Exception as e: 
                if testmode: print e

            if testmode: print row[4]

            searchstring = '"' + row[4] + '"'

            response = twitter.search(q=searchstring, include_entities=1, count=100)
            for tweet in response['statuses']: 
                if 'RT @' not in tweet['text'] and (row[2] == tweet['user']['screen_name']): 
                    oembed = twitter.get_oembed_tweet(id=tweet['id'])
#                     print oembed['html']
                    try: 
                        twitter.create_favorite(id=tweet['id'])
                        twitter.retweet(id=tweet['id'])
                    except Exception as e: 
                        if testmode: print e

                    top_retweets += oembed['html'].encode('utf-8') + " <br />\n"
                
        
        topretweetsfilename = os.path.join(dir, "../FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt")
        topretweetsfile = open(topretweetsfilename, "w")
#         print top_retweets 
        print >> topretweetsfile, top_retweets
        topretweetsfile.close()
        
#         cmd = "scp -P 50001 " + topretweetsfilename + " [email protected]:../public/tatorttweets/FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt"
#         print cmd
#         os.system(cmd)
        
        if testmode: print 
        if testmode: print striketweet
        if testmode: print len(striketweet)
        
        
        
        if live_tweet: 
            try:
                twitter.update_status(status=striketweet)
                twitter.update_status(status="Die meist-retweeted #Tatort tweets: http://tatort.mash-it.net/" + str(episodenumber) + "#Strike")
            except Exception as e: 
                if testmode: print e
开发者ID:nulllogicone,项目名称:tatorttweets,代码行数:82,代码来源:generate_top_retweets.py

示例10: __init__

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
class TweetBot:
	def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret):
		self.account = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
		self.step = 15 

	def verify_credentials(self):
		# https://dev.twitter.com/rest/reference/get/account/verify_credentials
		info = self.account.verify_credentials(include_entities=False, skip_status=True, include_email=False)
		name = info.get('name', None)
		if name is None:
			log.error('Could not verify credentials')
		else:
			log.info('Logged in as @{name}, tweets: {tweets}, followers: {followers}'.format(
				name = name,
				tweets = info['statuses_count'],
				followers = info['followers_count']))
		return info

	def upload_twitter_picture(self, picture_path):
		photo = open(picture_path, 'rb')
		log.debug("Uploading '{}'".format(picture_path))
		response = self.account.upload_media(media=photo)
		return response['media_id']

	def reply_media_tweet(self, status, reply_id, media_path):
		media_id = self.upload_twitter_picture(media_path)
		tweet = self.account.update_status(status=status, media_ids=[media_id], in_reply_to_status_id=reply_id)
		return tweet

	def reply_text_tweet(self, status, reply_id):
		tweet = self.account.update_status(status=status, in_reply_to_status_id=reply_id)
		log.info('Responded with text to {}'.format(reply_id))
		return tweet

	def rate_limit_remaining(self):
		rate_limit = self.account.get_lastfunction_header('x-rate-limit-remaining')
		log.info('Rate limit remaining: {}'.format(rate_limit))
		return rate_limit

	def favorite(self, status_id):
		tweet = self.account.create_favorite(id=status_id)
		log.debug('Favorited tweet {}'.format(status_id))
		return tweet

	# Find first tweet mentioning any element of query_list_OR
	# in the tweet text (excluding user names).
	# Only tweets for which predicate_func(tweet) is truthy are returned.
	# Returns a tuple of the found status/tweet and what element of
	# the query_list_OR was identified.
	# Returns (None, None) if no matching tweets were found.
	def find_single_tweet(self, query_list_OR, predicate_func):
		counter = 0
		while counter <= len(query_list_OR):
			current_query = query_list_OR[counter:counter+self.step]
			log.debug("Searching for '{}'".format(', '.join(current_query)))
			statuses = self.account.search(q=' OR '.join(current_query), count=50)['statuses']
			log.debug("Found {} matching tweets".format(len(statuses)))
			self.rate_limit_remaining()
			counter += self.step
			for status in statuses:
				# Should be able to identify which part of the query list was mentioned
				text = status['text'].lower()
				found = None
				for query_item in current_query:
					if text.rfind(query_item.lower()) > -1:
						found = query_item
						break
				if found is None:
					continue
				# Identified query part should not be part of tweeting user's name
				if found.lower() in status['user']['screen_name'].lower():
					continue
				# Identified query part should not be part of a mentioned user's name
				mentions = status['entities'].get('user_mentions')
				for m in mentions:
					if found.lower() in m['screen_name'].lower():
						continue
				# Identified query part should not be in user name being replied to
				if found.lower() in (status['in_reply_to_screen_name'] or '').lower():
					continue
				# Should return True for the passed predicate_func
				if not predicate_func(status):
					continue
				log.info(TWITTER_STATUS_URL_TEMPLATE.format(id=status['id']))
				log.info(status['text'].replace('\n',' '))
				return (status, found)
		log.warn("No tweets matching '{}' were found".format(query_list_OR))
		return (None, None)
开发者ID:chrisma,项目名称:yourpokedex,代码行数:90,代码来源:tweeter.py

示例11: Twython

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
# Options and notes:
#
# Usage:  
#
##

from license import __author__
from license import __copyright__
from license import __copyrighta__
from license import __license__
__version__ = "0.0.1"
from license import __bitcoin__

import sys
from twython import Twython, TwythonError
from config import *

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

l = len(sys.argv)

if l == 1:
    twid = input("Enter ID number of tweet to favourite: ")
elif l >= 2:
    twid = sys.argv[1]

try:
    twitter.create_favorite(id=twid)
except TwythonError as e:
    print(e)
开发者ID:Hasimir,项目名称:twython-tools,代码行数:32,代码来源:tweet-favourite.py

示例12: TwythonEndpointsTestCase

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

#.........这里部分代码省略.........
        self.api.create_mute(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_mute(self):
        """Test muting a user succeeds"""
        self.api.destroy_mute(screen_name='justinbieber')

    # Suggested Users
    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    @unittest.skip('skipping non-updated test')
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    @unittest.skip('skipping non-updated test')
    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    @unittest.skip('skipping non-updated test')
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff %s' % int(time.time()))
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed \
                             %s' % int(time.time()))

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id,
                                     screen_name=screen_names)
开发者ID:nouvak,项目名称:twython,代码行数:69,代码来源:test_endpoints.py

示例13: raw_input

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
# Post
post = raw_input("Write your tweet: ")
twitter.update_status(status=post)

# Get timelines
print twitter.get_user_timeline(screen_name = "name")
print twitter.get_home_timeline(count = 5)

# Search
print twitter.search(q="linux", result_type="popular")

# Follow
twitter.create_friendship(screen_name = "LinuxUserMag")

# Retweet
twitter.retweet(id = "12345")

# Favouriting
twitter.create_favorite(id = "12345")
print twitter.get_favorites()

# Mentions
print twitter.get_mentions_timeline(count="5")

# Trending
print twitter.get_place_trends(id="1")

# Retrieve lists
print twitter.get_list_statuses(id = "12345")
开发者ID:codefitz,项目名称:twerter,代码行数:31,代码来源:Twerter.py

示例14: print

# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_favorite [as 别名]
    search_results = twitter.search(q="thanksobama", since_id = idnum, count=20)
    #searchs a hashtag from after a certian tweet with a max of 20 results
    count = 0
    for tweet in search_results["statuses"]:
        try:
            rannum = random.randrange(1,5)
            print(rannum)
            if rannum == 2:
                #Below line retweets the statuses
                twitter.retweet(id = tweet["id_str"])
                print ("Retweeted")

            if rannum == 1:
                #Below line favorites the statuses
                twitter.create_favorite(id = tweet["id_str"])
                print ("Favorited")

            if rannum == 3:
                #Below line retweets the statuses
                twitter.retweet(id = tweet["id_str"])
                twitter.create_favorite(id = tweet["id_str"])
                print ("Retweeted and Favorited")

            if rannum == 4:
              print("did nothing")

            if count == 0:
                #checks to see if its the first tweet in the list and gets ID so there are no double ups.
                idnum = tweet["id_str"]
                print(idnum)
开发者ID:theferris,项目名称:Botrack-Obama,代码行数:32,代码来源:botrackobama2.py


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