0

所以,我对 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,一开始是正确的,但如果我的代表发生变化,则不会更新。理想情况下会。任何帮助是极大的赞赏。提前致谢。

4

1 回答 1

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 分钟运行一次。

于 2011-05-07T02:13:14.507 回答