pystackexchange polling issue
So, I'm fairly new to python and I had an idea today to make a script that polls stackoverflow for my rep, and when it changes, it sends an email, which gets sent to my phone as a text.
The emailing part works, but for some reason I can't get the polling right, so I decided I'd see if maybe you guys wanted to take a stab at it.
Here's my code:
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 开发者_Go百科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)
Currently if you print REP it is right at first, but doesnt update if my rep changes. Ideally it would. Any help is greatly appreciated. Thanks in advance.
This is a simplified example that will loop properly:
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)
I added a line to filter the accounts so it will only check your rep on the proper site. You were using the index, I have no idea if that's stable or not, I'd guess not. Polling every 10 seconds (like in the original example) might be a bit much, maybe do something more reasonable like every 5 minutes? Do you really need an up to the minute update of your rep? Consider just writing this as a cron job and having it run every 5, 10, 15 minutes whatever.
精彩评论