设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 7555|回复: 1
打印 上一主题 下一主题

新浪微博监听关注用户最新微博并转发至邮箱(含图)

[复制链接]

3

主题

0

好友

51

积分

注册会员

Rank: 2

跳转到指定楼层
楼主
发表于 2013-10-9 10:30:36 |只看该作者 |倒序浏览
本帖最后由 跑跑慢慢 于 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值. 缩进貌似有问题,自己解决.
  1. def get_code(url):
  2.     conn = httplib.HTTPSConnection('api.weibo.com')
  3.     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})
  4.     conn.request('POST','/oauth2/authorize',postdata,{'Referer':url,'Content-Type': 'application/x-www-form-urlencoded'})
  5.     res = conn.getresponse()
  6.     location = res.getheader('location')
  7.     code = location.split('=')[1]
  8.     conn.close()
  9.     return code
复制代码
  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-
  3. import weibo
  4. import webbrowser
  5. import json
  6. import os
  7. import sys
  8. import time
  9. """
  10. 获取授权信息
  11. 接口:
  12. statuses/user_timeline
  13. 调用方式:
  14. client.statuses.user_timeline.get(uid=自己的uid)
  15. """
  16. APP_KEY = '1111111111'#填写自己的app_key
  17. APP_SECRET ='aaaaaaaaaaaaaaaaaaaa'#填写自己的app_secret
  18. REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'#应用地址

  19. def getClient():
  20.     client = weibo.APIClient(APP_KEY,APP_SECRET)
  21.     authorize_url = client.get_authorize_url(REDIRECT_URL)

  22.     webbrowser.open(authorize_url)

  23.     code = raw_input('input the code: ').strip()

  24.     request = client.request_access_token(code,REDIRECT_URL)

  25.     access_token = request.access_token
  26.     expires_in = request.expires_in
  27.     uid = request.uid

  28.     client.set_access_token(access_token,expires_in)
  29.     return client
复制代码
代码2:listen.py
  1. #!/usr/bin/env python
  2. #-*- coding:utf-8 -*-

  3. import weibo
  4. import json
  5. import os
  6. import sys
  7. import time
  8. import mailimages
  9. import urllib
  10. """
  11. 获取uid 最新发表的微博列表(只能是自己的uid:微博id)
  12. 接口:
  13. statuses/user_timeline
  14. 调用方式:
  15. client.statuses.user_timeline.get(uid=自己的uid)
  16. """
  17. uid='**********'#更换自己的uid
  18. def eachCall(server,client,maxId):
  19.     """
  20.     获取自己关注列表发布的微博信息
  21.     """
  22.     if maxId==0:
  23.         callback = client.statuses.friends_timeline.get(count=100)#每次运行,第一次获得100条微博记录.100为最大值
  24.     else:
  25.         callback = client.statuses.friends_timeline.get(count=10)#之后每次获得10条记录,可随意修改,100为最大值
  26.     newMaxId = callback.statuses[0].id
  27.     file = open('e:/weibo/weibo2.txt','a')#保存至本地文件中,可以去掉.
  28.     for status in callback.statuses:
  29.         id = status.id
  30.         if id<=maxId:
  31.             break;
  32.         create_at = status.created_at
  33.         user = status.user.name
  34.         text = status.text
  35.         pic_urls = status.pic_urls
  36.         if 'retweeted_status' in status.keys():
  37.             retweeted_status = status.retweeted_status
  38.             retweeted_info = getNameText(retweeted_status,id)
  39.             mailContent = text+'['+retweeted_info[0]+':'+retweeted_info[1]+']'
  40.         else:
  41.             mailContent = text
  42.         #"""
  43.         images=[]
  44.         if 'original_pic' in status.keys():
  45.             pic = status.original_pic
  46.             print(pic)
  47.             type=os.path.splitext(pic)[1][1:]
  48.             urllib.urlretrieve(pic,'e:/weibo/%s.%s' % (str(id),type))
  49.             images.append('e:/weibo/%s.%s' % (str(id),type))
  50.         #"""
  51.         content = user+"\t"+create_at+"\n\t"+mailContent+"\n"
  52.         print(content)
  53.         file.write(content.encode('utf-8'))
  54.         file.flush()
  55.         mailimages.sendmail(server,user,mailContent,images)
  56.     file.close()
  57.     return newMaxId
  58. def run(client,maxId=0):
  59.     server = mailimages.login()
  60.     maxId = eachCall(server,client,maxId)
  61.     time.sleep(60)
  62.     while True:
  63.         maxId = eachCall(server,client,maxId)
  64.         print(maxId)
  65.         time.sleep(60)#每60秒获取一次最新微博
  66. def getNameText(status,id):
  67.     """
  68. 获取[name,text]
  69.     """
  70.     result = []
  71.     if 'user' in status.keys():
  72.         result.append(status.user.name)
  73.         result.append(status.text)
  74.     else:
  75.         result.append('')
  76.         result.append('')
  77.     #"""
  78.     if 'original_pic' in status.keys():
  79.         pic = status.original_pic
  80.         extension=os.path.splitext(pic)[1][1:]
  81.         path = 'e:/weibo/%s.%s' % (str(id),extension)
  82.         print(path)
  83.         urllib.urlretrieve(pic,path)
  84.         result.append(pic)
  85.     else:
  86.         result.append('')
  87.     #"""
  88.     return result
  89.         
复制代码
代码3:mailimages.py 用于发送邮件.请将#换行# 替换为html中的换行标签<br>
  1. #!/usr/bin/env python
  2. #-*-coding:utf-8 -*-
  3. import smtplib,mimetypes
  4. import time
  5. import os

  6. from email.MIMEMultipart import MIMEMultipart
  7. from email.MIMEText import MIMEText
  8. from email.MIMEImage import MIMEImage

  9. fromAddress = '***@***'
  10. toAddress = '***@qq.com'
  11. mail_host = 'smtp.exmail.qq.com'
  12. mail_user = '***@***'
  13. mail_pass = '******'

  14. def sendmail(server,nick,content,images=[]):
  15.     """
  16.     send a email with 微博内容
  17.     """
  18.     # Create the root message and fill in the from, to, and subject headers
  19.     msgRoot = MIMEMultipart('related')
  20.     msgRoot['From'] = "微博"
  21.     msgRoot['To'] = '******@qq.com'
  22.     msgRoot['Subject'] = nick #以用户昵称为标题
  23. #msgRoot.preamble = 'This is a multi-part message in MIME format.'
  24.    
  25.     # Encapsulate the plain and HTML versions of the message body in an
  26.     # 'alternative' part, so message agents can decide which they want to display.
  27.     msgAlternative = MIMEMultipart('alternative')
  28.     msgRoot.attach(msgAlternative)

  29.     msgText = MIMEText('This is the alternative plain text message.')
  30.     msgAlternative.attach(msgText)

  31.     # We reference the image in the IMG SRC attribute by the ID we give it below

  32.     msgImages=[]
  33.     if len(images)>0:
  34.         i=0
  35.         for image in images:
  36.             # This example assumes the image is in the current directory
  37.             fp = open(image, 'rb')
  38.             msgImage = MIMEImage(fp.read())
  39.             fp.close()
  40.             
  41.             # Define the image's ID as referenced above
  42.             msgImage.add_header('Content-ID', '<image'+str(i)+'>')
  43.             msgImages.append(msgImage)
  44.             
  45.             content+='#换行#<img src="cid:image'+str(i)+'">'#请将#换行# 替换为html中的换行标签.
  46.             i+=1

  47.     msgText = MIMEText(content,'html',_charset='utf-8')
  48.     msgAlternative.attach(msgText)
  49.     if len(msgImages)>0:
  50.         for msgImage in msgImages:
  51.             msgRoot.attach(msgImage)
  52.             
  53.     try:
  54.         server.sendmail(fromAddress,toAddress,msgRoot.as_string())
  55.         #print('Successfully')
  56.     except Exception , e:
  57.         print('=======Try to login on mail server again=======')
  58.         server = login()
  59.         try:
  60.             server.sendmail(fromAddress,toAddress,msgRoot.as_string())
  61.             print('Successfully')
  62.         except Exception , e:
  63.             print str(e)
  64. def flood():
  65.     while True:
  66.         sendmail()
  67.         time.sleep(30)

  68. def login():
  69.     try:
  70.         server = smtplib.SMTP()
  71.         server.connect(mail_host)
  72.         server.login(mail_user,mail_pass)
  73.         return server
  74.     except Exception , e:
  75.         print str(e)
  76. def logout(server):
  77.     try:
  78.         server.close()
  79.     except Exception , e:
  80.         print str(e)
复制代码
运行方式:
>>> import auth,listen
>>> c=auth.getClient()
input the code:
此时浏览器打开页面,登录自己的微博账户,浏览器跳转到一个地址,后面为code=******.
把=后面的数值输入
>>> listen.run(c)

每次监听后都会打印一个id值.
如果运行中断,可以加上id参数,从上次监听处继续监听.
>>> listen.run(c,id值)

-------------结束.
回复

使用道具 举报

0

主题

0

好友

62

积分

注册会员

Rank: 2

沙发
发表于 2013-10-9 10:49:28 |只看该作者
牛B 。。顶上去
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-19 10:38 , Processed in 0.017923 second(s), 23 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部