Crossin的编程教室
标题:
新浪微博监听关注用户最新微博并转发至邮箱(含图)
[打印本页]
作者:
跑跑慢慢
时间:
2013-10-9 10:30
标题:
新浪微博监听关注用户最新微博并转发至邮箱(含图)
本帖最后由 跑跑慢慢 于 2013-10-27 21:32 编辑
关注了一些账户,不过经常遇见发布没多久就删除的,所以尝试写了该工具.经过逐步完善,现在已经可以发布带图片的邮件内容,不过图片只有一张,有时间稍微加一些代码就可更新.
准备工作:
新浪微博开发平台SDK python版:
https://github.com/michaelliao/sinaweibopy/zipball/master
自己在开发平台创建一个自己的应用: 我的应用类型:普通应用 - 客户端.
邮件中图片是先下载到本地e:/weibo/中,再发送到邮件.
另外注意:mailimages.py 中,
请将#换行# 替换为html中的换行标签<br>
代码:auth.py
更新get_code()方法,使用code = get_code(authorize_url),不需要手动输入code值. 缩进貌似有问题,自己解决.
def get_code(url):
conn = httplib.HTTPSConnection('api.weibo.com')
postdata = urllib.urlencode({'client_id':APP_KEY,'response_type':'code','redirect_uri':REDIRECT_URL,'action':'submit','userId':ACCOUNT,'passwd':PASSWORD,'isLoginSina':0,'from':'','regCallback':'','state':'','ticket':'','withOfficalFlag':0})
conn.request('POST','/oauth2/authorize',postdata,{'Referer':url,'Content-Type': 'application/x-www-form-urlencoded'})
res = conn.getresponse()
location = res.getheader('location')
code = location.split('=')[1]
conn.close()
return code
复制代码
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import weibo
import webbrowser
import json
import os
import sys
import time
"""
获取授权信息
接口:
statuses/user_timeline
调用方式:
client.statuses.user_timeline.get(uid=自己的uid)
"""
APP_KEY = '1111111111'#填写自己的app_key
APP_SECRET ='aaaaaaaaaaaaaaaaaaaa'#填写自己的app_secret
REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'#应用地址
def getClient():
client = weibo.APIClient(APP_KEY,APP_SECRET)
authorize_url = client.get_authorize_url(REDIRECT_URL)
webbrowser.open(authorize_url)
code = raw_input('input the code: ').strip()
request = client.request_access_token(code,REDIRECT_URL)
access_token = request.access_token
expires_in = request.expires_in
uid = request.uid
client.set_access_token(access_token,expires_in)
return client
复制代码
代码2:listen.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import weibo
import json
import os
import sys
import time
import mailimages
import urllib
"""
获取uid 最新发表的微博列表(只能是自己的uid:微博id)
接口:
statuses/user_timeline
调用方式:
client.statuses.user_timeline.get(uid=自己的uid)
"""
uid='**********'#更换自己的uid
def eachCall(server,client,maxId):
"""
获取自己关注列表发布的微博信息
"""
if maxId==0:
callback = client.statuses.friends_timeline.get(count=100)#每次运行,第一次获得100条微博记录.100为最大值
else:
callback = client.statuses.friends_timeline.get(count=10)#之后每次获得10条记录,可随意修改,100为最大值
newMaxId = callback.statuses[0].id
file = open('e:/weibo/weibo2.txt','a')#保存至本地文件中,可以去掉.
for status in callback.statuses:
id = status.id
if id<=maxId:
break;
create_at = status.created_at
user = status.user.name
text = status.text
pic_urls = status.pic_urls
if 'retweeted_status' in status.keys():
retweeted_status = status.retweeted_status
retweeted_info = getNameText(retweeted_status,id)
mailContent = text+'['+retweeted_info[0]+':'+retweeted_info[1]+']'
else:
mailContent = text
#"""
images=[]
if 'original_pic' in status.keys():
pic = status.original_pic
print(pic)
type=os.path.splitext(pic)[1][1:]
urllib.urlretrieve(pic,'e:/weibo/%s.%s' % (str(id),type))
images.append('e:/weibo/%s.%s' % (str(id),type))
#"""
content = user+"\t"+create_at+"\n\t"+mailContent+"\n"
print(content)
file.write(content.encode('utf-8'))
file.flush()
mailimages.sendmail(server,user,mailContent,images)
file.close()
return newMaxId
def run(client,maxId=0):
server = mailimages.login()
maxId = eachCall(server,client,maxId)
time.sleep(60)
while True:
maxId = eachCall(server,client,maxId)
print(maxId)
time.sleep(60)#每60秒获取一次最新微博
def getNameText(status,id):
"""
获取[name,text]
"""
result = []
if 'user' in status.keys():
result.append(status.user.name)
result.append(status.text)
else:
result.append('')
result.append('')
#"""
if 'original_pic' in status.keys():
pic = status.original_pic
extension=os.path.splitext(pic)[1][1:]
path = 'e:/weibo/%s.%s' % (str(id),extension)
print(path)
urllib.urlretrieve(pic,path)
result.append(pic)
else:
result.append('')
#"""
return result
复制代码
代码3:mailimages.py 用于发送邮件.
请将#换行# 替换为html中的换行标签<br>
#!/usr/bin/env python
#-*-coding:utf-8 -*-
import smtplib,mimetypes
import time
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
fromAddress = '***@***'
toAddress = '***@qq.com'
mail_host = 'smtp.exmail.qq.com'
mail_user = '***@***'
mail_pass = '******'
def sendmail(server,nick,content,images=[]):
"""
send a email with 微博内容
"""
# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['From'] = "微博"
msgRoot['To'] = '******@qq.com'
msgRoot['Subject'] = nick #以用户昵称为标题
#msgRoot.preamble = 'This is a multi-part message in MIME format.'
# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)
# We reference the image in the IMG SRC attribute by the ID we give it below
msgImages=[]
if len(images)>0:
i=0
for image in images:
# This example assumes the image is in the current directory
fp = open(image, 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# Define the image's ID as referenced above
msgImage.add_header('Content-ID', '<image'+str(i)+'>')
msgImages.append(msgImage)
content+='#换行#<img src="cid:image'+str(i)+'">'#请将#换行# 替换为html中的换行标签.
i+=1
msgText = MIMEText(content,'html',_charset='utf-8')
msgAlternative.attach(msgText)
if len(msgImages)>0:
for msgImage in msgImages:
msgRoot.attach(msgImage)
try:
server.sendmail(fromAddress,toAddress,msgRoot.as_string())
#print('Successfully')
except Exception , e:
print('=======Try to login on mail server again=======')
server = login()
try:
server.sendmail(fromAddress,toAddress,msgRoot.as_string())
print('Successfully')
except Exception , e:
print str(e)
def flood():
while True:
sendmail()
time.sleep(30)
def login():
try:
server = smtplib.SMTP()
server.connect(mail_host)
server.login(mail_user,mail_pass)
return server
except Exception , e:
print str(e)
def logout(server):
try:
server.close()
except Exception , e:
print str(e)
复制代码
运行方式:
>>> import auth,listen
>>> c=auth.getClient()
input the code:
此时浏览器打开页面,登录自己的微博账户,浏览器跳转到一个地址,后面为code=******.
把=后面的数值输入
>>> listen.run(c)
每次监听后都会打印一个id值.
如果运行中断,可以加上id参数,从上次监听处继续监听.
>>> listen.run(c,id值)
-------------结束.
作者:
simple
时间:
2013-10-9 10:49
牛B 。。顶上去
欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/)
Powered by Discuz! X2.5