Skip to content

Instantly share code, notes, and snippets.

Forked from liberize/
Last active Dec 11, 2016
What would you like to do?
short_name = your_short_name
secret = xxxxxxxxxxxxxxxxxxxxx
host =
name = sendername
password = xxxxxxxx
to =
from =
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import smtplib
import ConfigParser
import json
import os
from email.mime.text import MIMEText
last_log_id = 0
last_log_id_path = ''
content_template = '''
<head><meta http-equiv=Content-Type content="text/html;charset=utf-8"><title>{title}</title></head>
comment_template = '''
<p><a href="mailto:{email}">{name}</a> 于 {time} 在文章《<a href="{url}">{title}</a>》下发表了评论:</p>
def render_content(comments):
global content_template, comment_template
comments = [comment_template.format(**comment) for comment in comments]
content = content_template.format(title='多说', body=''.join(comments))
return content
def convert(input_string):
if isinstance(input_string, dict):
return {convert(key): convert(value) for key, value in input_string.iteritems()}
elif isinstance(input_string, list):
return [convert(element) for element in input_string]
elif isinstance(input_string, unicode):
return input_string.encode('utf-8')
return input_string
def get_response(base_url, params):
url = '{}?{}'.format(base_url, urllib.urlencode(params))
data = urllib.urlopen(url).read()
resp = convert(json.loads(data))
if resp['code'] != 0:
return None
return resp
except Exception, e:
print str(e)
return None
def check(duoshuo):
global last_log_id
log_data = get_response('', {
'short_name': duoshuo['short_name'],
'secret': duoshuo['secret'],
'order': 'desc'
if log_data is None:
return None
comments = []
for log in log_data['response']:
if int(log['log_id']) <= last_log_id:
if log['action'] == 'create':
thread_data = get_response('', {
'short_name': duoshuo['short_name'],
'thread_key': log['meta']['thread_key']
'title': log['meta']['thread_key'],
'url': thread_data['thread']['url'] if thread_data else '',
'name': log['meta']['author_name'],
'email': log['meta']['author_email'],
'content': log['meta']['message'],
'time': log['meta']['created_at'].split('+')[0].replace('T', ' ')
print last_log_id, '->', log_data['response'][0]['log_id']
if str(last_log_id) != str(log_data['response'][0]['log_id']):
last_log_id = int(log_data['response'][0]['log_id'])
with open(last_log_id_path, 'w') as f:
return comments
def send_email(email, content):
msg = MIMEText(content, _subtype='html', _charset='utf-8')
msg['Subject'] = '多说评论通知'
msg['From'] = email['from']
msg['To'] = email['to']
msg['X-Mailer'] = 'Microsoft Outlook 14.0'
server = smtplib.SMTP()
server.login(email['name'], email['password'])
server.sendmail(email['from'], [email['to']], msg.as_string())
return True
except Exception, e:
print str(e)
return False
def read_conf():
global last_log_id
global last_log_id_path
conf = ConfigParser.ConfigParser()
path = os.path.dirname(__file__)
conf_file = os.path.join(path, 'duoshuo.conf')
last_log_id_path = os.path.join(path, 'last_log_id')
duoshuo = dict(conf.items('duoshuo'))
email = dict(conf.items('email'))
others = dict(conf.items('others'))
if os.path.exists(last_log_id_path):
with open(last_log_id_path, 'r') as f:
last_log_id =
last_log_id = int(last_log_id)
last_log_id = 0
return duoshuo, email, others
def run():
duoshuo, email, others = read_conf()
print '=> checking comments ...'
comments = check(duoshuo)
if comments:
print '{} new comments found.'.format(len(comments))
content = render_content(comments)
print '=> sending email ...'
send_email(email, content)
if __name__ == '__main__':
Copy link

coderzh commented Sep 13, 2015

$ crontab -e

*/5 * * * * python /root/tools/

$ /etc/init.d/cron restart

Copy link

LooEv commented Dec 11, 2016


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment