所以,我对python还不熟悉,今天我有一个想法,就是为我的代表制作一个轮询stackoverflow的脚本,当它发生变化时,会发送一封电子邮件,然后将其作为文本发送到我的手机。
电子邮件部分有效,但由于某种原因我无法正确进行投票,所以我决定看看是否有人想要对它进行一次尝试。
这是我的代码:
import sys
from stackauth import StackAuth
from stackexchange import Site, StackOverflow
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
import time
gmail_user = "email@gmail.com"
gmail_pwd = "password"
def mail(to, subject, text):
msg = MIMEMultipart()
msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
old_rep = None
while True:
user_id = 731221 if len(sys.argv) < 2 else int(sys.argv[1])
print 'StackOverflow user %d\'s accounts:' % user_id
stack_auth = StackAuth()
so = Site(StackOverflow)
accounts = stack_auth.associated(so, user_id)
REP = accounts[3].reputation
print REP
if REP != old_rep:
old_rep = REP
mail("email@email.com","REP",str(REP))
time.sleep(10)
目前,如果您打印REP,它首先是正确的,但如果我的代表更改,则不会更新。 理想情况下会。 任何帮助是极大的赞赏。提前致谢。
答案 0 :(得分:1)
这是一个能够正确循环的简化示例:
import time
from stackauth import StackAuth
from stackexchange import Site, StackOverflow
rep = None
while True:
stack_auth = StackAuth()
so = Site(StackOverflow)
accounts = stack_auth.associated(so, 641766) # using my id
so_acct = filter(lambda x: x.on_site.api_endpoint.endswith('api.stackoverflow.com'), accounts)[0] # filtering my accounts so I only check rep on stackoverflow
if rep != so_acct.reputation:
rep = so_acct.reputation
print rep
# send e-mail
time.sleep(30)
我添加了一行来过滤帐户,因此它只会在适当的网站上检查您的代表。你在使用索引,我不知道这是否稳定,我猜不会。每10秒轮询一次(如原始示例中所示)可能有点多,也许每5分钟做一些更合理的事情?你真的需要最新的代表更新吗?考虑把它写成一个cron作业并让它每5,10,15分钟运行一次。