本文整理汇总了Python中twython.Twython.create_friendship方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.create_friendship方法的具体用法?Python Twython.create_friendship怎么用?Python Twython.create_friendship使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.create_friendship方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: twitteradd
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
def twitteradd(request, usertoadd):
#usertoadd = User.get(username=uidtofollow)
twitterauth = UserSocialAuth.objects.get(user=request.user, provider="twitter")
if twitterauth is None:
return False
oauth_consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY
oauth_token = twitterauth.extra_data['access_token']['oauth_token']
#oauth_nonce = "91227c2566963d6ae01eb72f974e964a"
oauth_nonce = "".join([random.choice(string.letters) for i in xrange(32)])
oauth_signature = "eGxVJXIYoG%2B9ay0A4E7QxnBHHrI%3D"
#currenttime = "1381017251"
currenttime = str(int(time.time()))
#user_to_follow = "15378324"
from twython import Twython
twitter = Twython(settings.SOCIAL_AUTH_TWITTER_KEY,
settings.SOCIAL_AUTH_TWITTER_SECRET,
twitterauth.extra_data['access_token']['oauth_token'],
twitterauth.extra_data['access_token']['oauth_token_secret'])
try:
useridtofollow = UserSocialAuth.objects.get(user=usertoadd, provider="twitter").extra_data['id']
except:
return False
try:
twitter.create_friendship(user_id=useridtofollow)
except:
return False
return True
示例2: on_success
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
def on_success(self, data):
if 'event' in data and 'target' in data and 'source' in data:
if data['event'] == 'follow' and data['target']['screen_name'] == 'FutureDiaryBot':
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.create_friendship(user_id = data['source']['id'])
print 'auto followed @' + data['source']['screen_name']
except TwythonError as error:
print error
示例3: on_success
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
def on_success(self, data):
if "event" in data and "target" in data and "source" in data:
if data["event"] == "follow" and data["target"]["screen_name"] == "FutureDiaryBot":
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.create_friendship(user_id=data["source"]["id"])
print "auto followed @" + data["source"]["screen_name"]
except TwythonError as error:
print error
示例4: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [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_tweets = ''
tweet = '#Tatort Twitter-SEK: '
with con:
cur = con.cursor()
command = 'SELECT screen_name, count(tweet) FROM tatorttweets WHERE lfd = ' + str(episodenumber) + ' GROUP BY screen_name ORDER BY count(tweet) desc LIMIT 10 '
cur.execute(command)
rows = cur.fetchall()
for row in rows:
try:
twitter.create_friendship(screen_name=row[0])
except Exception as e:
if testmode: print e
stringrow = '<a href="http://twitter.com/' + row[0] + '">@' + row[0] + '</a>' + ' (' + str(row[1]) + ')'
top_tweets += stringrow + " <br />\n"
newtweet = tweet + ' \[email protected]' + row[0]
if not len(newtweet) > 140:
tweet = newtweet
toptweetsfilename = os.path.join(dir, "../FlaskWebProject/templates/top_tweets/top_tweets_" + str(episodenumber) + ".txt")
toptweetsfile = open(toptweetsfilename, "w")
if testmode: print top_tweets
print >> toptweetsfile, top_tweets
toptweetsfile.close()
# cmd = "scp -P 50001 " + toptweetsfilename + " [email protected]ssh.raumopol.de:../public/tatorttweets//FlaskWebProject/templates/top_tweets/top_tweets_" + str(episodenumber) + ".txt"
# print cmd
# os.system(cmd)
if testmode: print
if testmode: print tweet
if testmode: print len(tweet)
if live_tweet:
try:
twitter.update_status(status=tweet)
except Exception as e:
if testmode: print e
示例5: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
def main(argv):
os.system('clear')
print 'Queue Processor v.'+VERSION+'\n'
print 'Starting the "friending" procedure for:'
for q in Queue.objects.filter(is_processed=False):
q.processing = True
q.save()
user = q.user
profile = Profile.objects.get(user=user)
target = q.requested_twitter_user_handle
processing = q.processing
is_processed = q.is_processed
if(is_processed): continue
print '\nOur target:',color.BOLD + '@' + target + color.END + '\n'
oauth_token = profile.oauth_token
oauth_token_secret = profile.oauth_secret
twitter = Twython(APP_KEY, APP_SECRET, oauth_token, oauth_token_secret)
try:
followers = twitter.get_followers_ids(screen_name = target, count=300)
except:
print 'Skipping this one...'
q.is_processed = True
q.save()
continue
count = 1
for follower_id in followers['ids']:
print count, '..befriending', color.GREEN + 'id_' + str(follower_id) + color.END
try:
twitter.create_friendship(screen_name=target, follow="true")
except TwythonError as e:
print target
print '\n', e
sleep_time = random.randint(12,90)
print '..sleeping for',sleep_time,'seconds (180 request in 15 mins = 1 request at minimum of 12 seconds)'
time.sleep(sleep_time)
count+=1
q.is_processed = 1
q.save()
示例6: twitter
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [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)
示例7: follow_twitter_user
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
def follow_twitter_user(log, id):
log.debug(" Following %s", id)
check_twitter_config()
logging.captureWarnings(True)
old_level = log.getEffectiveLevel()
log.setLevel(logging.ERROR)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.create_friendship(screen_name=id)
except TwythonAuthError, e:
log.setLevel(old_level)
log.exception(" Problem trying to follow twitter user")
twitter_auth_issue(e)
raise
示例8: Command
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
class Command(BaseCommand):
def __init__(self):
self.twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET)
def handle(self, *args, **options):
current_users = [user.twitter_id for user in TwitterUser.objects.all()]
# Update DB with latest followers
for user_id in self.twitter.get_followers_ids(screen_name='John_DM')["ids"]:
if user_id not in current_users:
TwitterUser.objects.create(twitter_id = user_id)
# Prioritises users who signed up most recently
# Should work through backlog if we dont get > 100 followers/day
users_to_follow = TwitterUser.objects.filter(created__lte=timezone.now() - timedelta(days=3), followed__isnull=True).order_by('-created')[:100]
for target in users_to_follow:
self.twitter.create_friendship(user_id=target.twitter_id, follow="true")
target.follow()
time.sleep(61) # Is there a better way to do rate limiting?
示例9: TwitterHelper
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
#.........这里部分代码省略.........
@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)
@retry(**retry_args)
def unblock_users(self):
user_ids = self.twitter.list_block_ids(stringify_ids=True)
for user_id in user_ids["ids"]:
self.twitter.destroy_block(user_id=user_id)
@retry(**retry_args)
def show_owned_lists(self):
return self.twitter.show_owned_lists()["lists"]
@retry(**retry_args)
def get_list_members(self, list_id):
return self.twitter.get_list_members(list_id=list_id, count=5000, include_entities=False)
@blocked
@retry(**retry_args)
def create_list(self, **kwargs):
return self.twitter.create_list(**kwargs)
@retry(**retry_args)
def follow(self, user_id, screen_name):
logger.info("following user id {} @{}".format(user_id, screen_name))
self.twitter.create_friendship(user_id=user_id, screen_name=screen_name)
self.identity.statistics.increment("Follows")
@retry(**retry_args)
def unfollow(self, user_id, screen_name):
logger.info("unfollowing user id {} @{}".format(user_id, screen_name))
self.twitter.destroy_friendship(user_id=user_id, screen_name=screen_name)
self.identity.statistics.increment("Unfollows")
@retry(**retry_args)
def block(self, user_id, screen_name):
logger.info("blocking user id {} @{}".format(user_id, screen_name))
self.twitter.create_block(user_id=user_id, screen_name=screen_name)
self.identity.statistics.increment("Blocks")
@retry(**retry_args)
def report(self, user_id, screen_name):
logger.info("reporting user id {} @{}".format(user_id, screen_name))
self.twitter.report_spam(user_id=user_id, screen_name=screen_name)
self.identity.statistics.increment("Reports")
@retry(**retry_args)
def lookup_user(self, user_id):
return self._rate_limit("/users/lookup", self.twitter.lookup_user, user_id=user_id)
def sing_song(self, song, target=None, inbox_item=None, text=None, hashtag=None):
if not text:
text = random.choice(["All together now!", "Sing along!"])
text += ' ' + song["video"]
if hashtag:
text += ' ' + hashtag
in_reply_to_id_str = self._send_to(
示例10: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
#.........这里部分代码省略.........
# 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()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
"""Test returning ids of users the authenticated user and then a random
user are followed by succeeds"""
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
"""Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds"""
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
"""Test returning incoming friendship ids succeeds"""
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
"""Test returning outgoing friendship ids succeeds"""
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
"""Test creating a friendship succeeds"""
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
"""Test destroying a friendship succeeds"""
self.api.destroy_friendship(screen_name='justinbieber')
def test_update_friendship(self):
"""Test updating friendships succeeds"""
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='true')
self.api.update_friendship(screen_name=protected_twitter_1,
retweets=False)
def test_show_friendships(self):
"""Test showing specific friendship succeeds"""
self.api.show_friendship(target_screen_name=protected_twitter_1)
def test_get_friends_list(self):
"""Test getting list of users authenticated user then random user is
following succeeds"""
self.api.get_friends_list()
self.api.get_friends_list(screen_name='twitter')
def test_get_followers_list(self):
"""Test getting list of users authenticated user then random user are
followed by succeeds"""
self.api.get_followers_list()
self.api.get_followers_list(screen_name='twitter')
# Users
示例11: line
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
from twython import Twython, TwythonError
# Optionally accept user data from the command line (or elsewhere).
#
# Usage: follow_user.py ryanmcgrath
import sys
if len(sys.argv) >= 2:
target = sys.argv[1]
else:
target = raw_input("User to follow: ") # For Python 3.x use: target = input("User to follow: ")
# Requires Authentication as of Twitter API v1.1
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
try:
twitter.create_friendship(screen_name=target, follow="true")
except TwythonError as e:
print(e)
示例12: TwythonEndpointsTestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
#.........这里部分代码省略.........
@unittest.skip('skipping non-updated test')
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()
self.api.get_friends_ids(screen_name='twitter')
@unittest.skip('skipping non-updated test')
def test_get_followers_ids(self):
"""Test returning ids of users the authenticated user and then a random
user are followed by succeeds"""
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
@unittest.skip('skipping non-updated test')
def test_lookup_friendships(self):
"""Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds"""
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
@unittest.skip('skipping non-updated test')
def test_get_incoming_friendship_ids(self):
"""Test returning incoming friendship ids succeeds"""
self.api.get_incoming_friendship_ids()
@unittest.skip('skipping non-updated test')
def test_get_outgoing_friendship_ids(self):
"""Test returning outgoing friendship ids succeeds"""
self.api.get_outgoing_friendship_ids()
@unittest.skip('skipping non-updated test')
def test_create_friendship(self):
"""Test creating a friendship succeeds"""
self.api.create_friendship(screen_name='justinbieber')
@unittest.skip('skipping non-updated test')
def test_destroy_friendship(self):
"""Test destroying a friendship succeeds"""
self.api.destroy_friendship(screen_name='justinbieber')
@unittest.skip('skipping non-updated test')
def test_update_friendship(self):
"""Test updating friendships succeeds"""
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='true')
self.api.update_friendship(screen_name=protected_twitter_1,
retweets=False)
@unittest.skip('skipping non-updated test')
def test_show_friendships(self):
"""Test showing specific friendship succeeds"""
self.api.show_friendship(target_screen_name=protected_twitter_1)
@unittest.skip('skipping non-updated test')
def test_get_friends_list(self):
"""Test getting list of users authenticated user then random user is
following succeeds"""
self.api.get_friends_list()
self.api.get_friends_list(screen_name='twitter')
@unittest.skip('skipping non-updated test')
def test_get_followers_list(self):
"""Test getting list of users authenticated user then random user are
示例13: raw_input
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
twitter.verify_credentials()
twitter.update_status(status="Test Twerter post.")
# 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
示例14: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
count = 0
# your twitter consumer and access information goes here
apiKey = '****'
apiSecret = '****'
accessToken = '****'
accessTokenSecret = '****'
twitter = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
while True:
#auto follow back function
try:
followers = twitter.get_followers_ids(screen_name = "Botrack Obama") #Enter twitter handle here
for followers_ids in followers['ids']:
twitter.create_friendship(user_id=followers_ids)
except TwythonError as e:
print(e)
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")
示例15: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import create_friendship [as 别名]
#.........这里部分代码省略.........
# 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()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
'''Test returning ids of users the authenticated user and then a random
user are followed by succeeds'''
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
'''Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds'''
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
'''Test returning incoming friendship ids succeeds'''
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
'''Test returning outgoing friendship ids succeeds'''
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
'''Test creating a friendship succeeds'''
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
'''Test destroying a friendship succeeds'''
self.api.destroy_friendship(screen_name='justinbieber')
def test_update_friendship(self):
'''Test updating friendships succeeds'''
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='true')
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='false')
def test_show_friendships(self):
'''Test showing specific friendship succeeds'''
self.api.show_friendship(target_screen_name=protected_twitter_1)
def test_get_friends_list(self):
'''Test getting list of users authenticated user then random user is
following succeeds'''
self.api.get_friends_list()
self.api.get_friends_list(screen_name='twitter')
def test_get_followers_list(self):
'''Test getting list of users authenticated user then random user are
followed by succeeds'''
self.api.get_followers_list()
self.api.get_followers_list(screen_name='twitter')
# Users