1

我对 Python 和 Raspberry Pi 非常陌生。

我的目标:作为构建 Raspberry Pi 并学习一些 Python 的一部分,我计划构建一个气象站。作为其中的一部分,它会在推特上发布天气信息。虽然这可能不是将要使用的最终代码。这有助于我学习。这就是我发布这个问题的原因。

我已经整理了来自各种来源的代码,以便与 Twython 一起发布到 Twitter。代码(见下文)运行良好。我必须使用 python3 才不会出现 SSL 错误。

#!/usr/bin/env python3
import sys
from twython import Twython, TwythonError

#tweetStr = "Tweet goes here, limit 140 characters"
tweetStr = input("Type your Tweet: ")


#Your Twitter Application keys
apiKey = 'apiKey'
apiSecret = 'apiSecret'
accessToken = 'accessToken'
accessTokenSecret = 'accessTokenSecret'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
try:
    api.update_status(status=tweetStr)
except TwythonError as Error:
    print (Error)

print ("Tweeted: ", tweetStr)

这是我喜欢的方式。要求输入。如果它有效,它会打印以筛选推文作为它有效的确认。但是,我想添加检查用户输入以验证它是否为 140 个字符或更少的功能。如果小于 141,则继续,如果超过 140,则返回错误,说明您输入的字符过多。我将只使用文本推文,没有链接。

我可以让以下内容自行工作。但是,我不确定如何让它与上述内容一起使用。(注意:我使用 <15 而不是 <141 进行测试,并且不必输入超过 140 个字符)。我不希望它删除超过 140 的内容,而只是返回错误以重试。

tweetStr = input("Tweet: ")
if len(tweetStr) < 10:
  print (tweetStr)
else:
  print ('too long')

我尝试了以下方法,但没有运气:

#!/usr/bin/env python3
import sys
from twython import Twython, TwythonError

#tweetStr = "Tweet goes here, limit 140 character"
tweetStr = input("Type your Tweet: ")

#Your Twitter Application keys
apiKey = 'apiKey'
apiSecret = 'apiSecret'
accessToken = 'accessToken'
accessTokenSecret = 'accessTokenSecret'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)

if len(tweetStr) < 15:
    try:
        api.update_status(status=tweetStr)
    except TwythonError as Error:
        print (Error)
else:
      print ('Too long use less than 141 characters')

print ("Tweeted: ", tweetStr)

任何帮助将非常感激。也许有一种完全不同且更简单的方法可以用 Twython 做同样的事情。

4

1 回答 1

1

我设法自己拼凑了一个答案。

#! /usr/bin/ python3
import sys
from twython import Twython, TwythonError

#Your tweet, ask for user input
tweetStr = input('Type your Tweet: ')

#check for twitter input limit, return error if over 140
if len(tweetStr) > 140:
    print('Error! You exceeded 140 Characters. Please try again.')
    sys.exit()

# Your Twitter Application keys
apiKey = 'apiKey'
apiSecret = 'apiSecret'
accessToken = 'accessToken'
accessTokenSecret = 'accessTokenSecret'

api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)

#send your tweet or return Twython error
try:
    api.update_status(status=tweetStr)
except TwythonError as Error:
    print (Error)
#print back your tweet, likely succeeded
print ('Tweeted: ',tweetStr)

尽管我在 #! 中调用了 python3,但由于某种原因,我的 Pi 发生了一些变化,我必须运行:

python3 filename.py

最初,我可以运行:

python filename.py

感谢您的关注。

于 2015-04-16T23:13:33.607 回答