1

由于 Twitter 更改了他们的 API,我必须控制原型自动售货机的脚本不再起作用,编写脚本的开发人员已经转向更环保的牧场。

该脚本每 15 秒扫描一次 Twitter,搜索包含指定主题标签(当前设置为 #sunshine)的最新推文,并过滤掉任何转发。

当它识别出一条新推文时,它会向 Arduino 发送一个信号,Arduino 会触发一个螺线管来分发免费的产品样品(目前是防晒霜)

这行代码似乎是问题/过时的:

j =json.loads(urllib.urlopen('http://search.twitter.com/search.json?q='+searchTerm+'&result_type=recent&rpp=1&filter:retweets').read())

我已经在 Twitter 上注册了一个开发者帐户,所以我有消费者密码和令牌代码等,但我仍然不知道如何使用这些 OAuth 代码修改旧代码以使其再次工作。我在下面完整复制了代码。任何人都可以帮助我并告诉我如何让这个脚本再次工作。

import twitter
import json
import urllib
from pprint import pprint
import time
from arduino import Arduino

##################SETUP AS REQUIRED###########################
##############################################################
#Change to suit the sample, currently at 0.2 of a second  #
vendtime = 0.2                                               #
                                                         #
#Delay Time Between each Search (never below 15 seconds)     #
delayTime = 15                                               #
#This is the search term for the URL. (%23 = #)              # 
searchTerm = '%23sunshine'                      #
                                                         #
A = Arduino('COM3') #This will need to be COM3              #
A.output([12]) #Output on pin 12                             #
A.output([13]) #to keep serial in use                        #
##############################################################


#to collect the first tweet without vending
countTweet = 0
#To test Twitter for consistancy 
tweet= 0
noTweet= 0



#the infinite loop
while True:

    #j contains the JSON we load from the URL
    j =json.loads(urllib.urlopen('http://search.twitter.com/search.json?q='+searchTerm+'&result_type=recent&rpp=1&filter:retweets').read())

    #Debug JSON from twitter (for faults on the Twitter end or possible GET limit id below 15 seconds per request)
    #pprint(j) #needed for debugging only

    #find the text and the tweet id
    if 'results' in j and j['results']:
        text = j['results'][0]['text']
        id = j['results'][0]['id']
        #how many times the Json is complete
        tweet+= 1
    else:
        #How many times the Json is incomplete (sometimes twitter malfunctions. About 0.1 in 100 are broken)
        noTweet += 1

    #print the text and id to the screen
    pprint(text) #needed for debugging only
    pprint(id)   #needed for debugging only

    #to get the existing tweet from before we power on, if the first ID has been stored already (count == 1)
    if countTweet != 0:  #if countTweet is not equal to 0 then it's not the first tweet
        #pprint ("new loop") #needed for debugging only

        #if lastID is not equal to ID
        if lastID != id:
        #Tell Arduino to Vend
            #pin 12 HIGH
            A.setHigh(12)
            #Sleep for the time specified in vendtime
            time.sleep(vendtime)
            #pin 12 LOW
            A.setLow(12)
            #Display the tweet that triggered the vend
            #pprint(text) #needed for debugging only
            #pprint(id)   #needed for debugging only
            #Make lastID equal to ID so that next time we can compare it 
            lastID = id
            #pprint ('lastID updated') #needed for debugging only
        #if no new tweets, print     
        else:  #needed for debugging only
            pprint ('no new tweets') #needed for debugging only
    #If it's the first loop, confirm by printing to the screen
    else:
        pprint("First loop complete")
        pprint(text)
        pprint(id)
        lastID = id
        pprint(lastID)
        countTweet += 1 #Add 1 to countTweet

    pprint ('Number of Tweets')
    pprint (countTweet)
    pprint('Working JSON')
    pprint(tweet)
    pprint('Broken JSON')
    pprint(noTweet)
    pprint('waiting')
    A.setHigh(13)
    time.sleep(delayTime)
    A.setLow(13)
4

1 回答 1

0

您发布的代码甚至没有使用twitter库。下面的代码已经过修改,实际上使用了 twitter 库,但您仍然需要将 twitter 键放入代码中。

from twitter import *
import time
from arduino import Arduino

##################SETUP AS REQUIRED###########################
##############################################################
#Change to suit the sample, currently at 0.2 of a second     #
vendtime = 0.2                                               #
                                                             #
#Delay Time Between each Search (never below 15 seconds)     #
delayTime = 15                                               #
#This is the search term                                     # 
searchTerm = "#sunshine"                                     #
                                                             #
A = Arduino("COM3") #This will need to be COM3               #
A.output([12]) #Output on pin 12                             #
A.output([13]) #to keep serial in use                        #
##############################################################

# Twitter keys
OAUTH_TOKEN = ""     # Access token
OAUTH_SECRET = ""    # Access token secret
CONSUMER_KEY = ""    # Consumer key
CONSUMER_SECRET = "" # Consumer secret

#to collect the first tweet without vending
first_tweet = True
#To test Twitter for consistancy 
tweet= 0
notweet= 0

# Start Twitter session
t = Twitter\
(
    auth = OAuth(OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
)

#the infinite loop
while True:
    # Print stats
    print("Number of Tweets: %d" % (tweet + notweet))
    print("Working JSON: %d" % tweet)
    print("Broken JSON: %d" % notweet)

    # Perform search
    search_results = t.search.tweets(q = searchTerm, _timeout = 60)

    #find the text and the tweet id
    tweet_failed = True
    if search_results:
        if search_results.has_key("statuses"):
            statuses = search_results["statuses"]
            if statuses:
                # Select first result
                status = statuses[0]
                if not bool(set(["id", "text"]) - set(status.keys())):
                    tweet_failed = False
                    tweet_text = status["text"]
                    tweet_id = status["id"]
                    #how many times the Json is complete
                    tweet+= 1
    if tweet_failed:
        #How many times the Json is incomplete (sometimes twitter malfunctions. About 0.1 in 100 are broken)
        notweet += 1
        continue
    else:
        if first_tweet:
            first_tweet = False
            print("First loop complete")
        else:
            #if last_id is not equal to tweet_id
            if last_id != tweet_id:
                #Tell Arduino to Vend
                #pin 12 HIGH
                A.setHigh(12)
                #Sleep for the time specified in vendtime
                time.sleep(vendtime)
                #pin 12 LOW
                A.setLow(12)

        #Make last_id equal to ID so that next time we can compare it 
        last_id = tweet_id
        #Display the tweet that triggered the vend
        print("Tweet: %s" % tweet_text)
        print("Id: %d" % tweet_id)

    print("waiting")
    A.setHigh(13)
    time.sleep(delayTime)
    A.setLow(13)
于 2013-06-24T12:49:15.700 回答