如何循环这样我可以添加更多的Twitter帐户

时间:2014-08-17 00:40:34

标签: python loops twitter

import time
from TwitterAPI import TwitterAPI
import requests
from requests_oauthlib import OAuth1
from urlparse import parse_qs

# application's key and key secret
ck = ''
cs = ''

# obtain request token
oauth = OAuth1(ck, cs)
r = requests.post(url='https://api.twitter.com/oauth/request_token', auth=oauth)
credentials = parse_qs(r.content)
request_key = credentials.get('oauth_token')[0]
request_secret = credentials.get('oauth_token_secret')[0]

#obtain authorization from twitter user
print('Visit this link to authorize the TweetBot:\n https://api.twitter.com/oauth/authorize?oauth_token=%s' % request_key)
verifier = raw_input('Enter your verification code: ')

# obtain access token
oauth = OAuth1(ck, cs, request_key, request_secret, verifier=verifier)
r = requests.get(url='https://api.twitter.com/oauth/access_token', auth=oauth)
credentials = parse_qs(r.content)
tk = credentials.get('oauth_token')[0]
ts = credentials.get('oauth_token_secret')[0]

# access TwitterAPI with the obtained access
api = TwitterAPI(ck, cs, tk, ts)
f = open('tweetbot.txt', 'rU')
for line in f:
    r = api.request('statuses/update', {'status' : line})
    print line,
    print r.status_code
    time.sleep(600)

我有这个代码,但我希望它添加多个Twitter帐户。我想我需要循环输入并将它们存储在不同的变量中?请给我最好的解决方案。我不是那么先进的python。

1 个答案:

答案 0 :(得分:0)

好的@ user3392493,你需要的是一个while循环,但里面有几个if语句和一个计数器变量,所以根据计数器所在的数字来设置变量:

enoughaccounts = False
counter = 0
while not enoughaccounts:
    counter += 1
    if counter == 1:
        # Do Everything
        account1 = .....
    if counter == 2:
        # Do Everything
        account2 = .....       
    if counter == 3:
        # Do Everything
        account3 = .....
    if counter == 4:
        # Do Everything
        account4 = .....
    moreaccounts = input('Add another account? (type yes or no)')
    if moreaccounts == 'no' or moreaccounts == 'No' or moreaccounts == 'NO':
        enoughaccounts = True

这应该按照你的意愿行事,如果你还需要其他任何东西,请问:)