Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

发文后自动分享到微博和Twitter-Python

$
0
0

我在每次发帖后都会把帖子手动分享到微博、Twitter等社交网络,但是很多时候我会忘,于是我就想自动化这个过程。

本站使用的是WordPress博客系统,不知道有没有现成的插件。我使用python做,原因是我有切换到Django的打算,使用Python做可以方便以后集成。还有就是,我对php不熟。

基本步骤:

通过RSS订阅获得最新文章 调用微博/推特api发微博/推

代码:

#!/usr/bin/env python3 import feedparser# http://blog.topspeedsnail.com/archives/8156 import sys import shelve import os from weiboimport Client# https://github.com/lxyu/weibo import socket import tweepy# http://blog.topspeedsnail.com/archives/3380 rss_uri = "http://blog.topspeedsnail.com/feed" entries_n = 7 # 获得文章数 # 保存发送过的文章 cache_max = 100 if not os.path.exists('cache.db'): db = shelve.open('cache.db', writeback=True) db['article_list'] = [] else: db = shelve.open('cache.db', writeback=True) # 判断是否联网 def is_connected(): try: REMOTE_SERVER = "www.baidu.com" host = socket.gethostbyname(REMOTE_SERVER) s = socket.create_connection((host, 80), 2) return True except: pass return False if is_connected() is False: print("检查网络连接") sys,exit(0) # 微博认证 API_KEY = '22795XXXXX' API_SECRET = '807297475bcca4b93d7bcxxxxxxxx' REDIRECT_URI = 'http://weibo.com/241589xxxxx' weibo_client = Client(API_KEY, API_SECRET, REDIRECT_URI) print("使用浏览器访问: ", weibo_client.authorize_url) code = input("输入返回的code: ") weibo_client.set_code(code) # 推特认证 consumer_key = 'qdte0pMyPvk6Puxxxxxxxx' consumer_secret = 'lQ4xTLhBmv4KaYlusBH04jppeo9Nfm6WudFxxxxxxxx' access_token = '909480547-Soz5w3N22gOkITEXUsvrlU41HkxsC5xxxxxxx' access_token_secret = '3j08IYs1pwPNnchmlcNK7wagGXuJcBtkjcsxxxxxxxx' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) auth.secure = True api = tweepy.API(auth) # 获得feed feed = feedparser.parse(rss_uri) if feed['status'] != 200: print("连接异常") sys.exit(0) entries = feed['entries'][0:entries_n] #entries.reverse() # 发送 for entryin entries: if entry['id'] not in db['article_list']: # 构造要发送的内容 """ # 带hashtag的推文 if 'tags' in entry: print('有hastag') else: print('没有hastag') """ # 只发送标题和链接 send_content = entry['title'] + ' - ' + entry['id'] #使用bitly短链接服务缩小链接所占字数 #short_link = bitly_api.Connection(access_token='cb3e9e1ce06f2b29852f0f83702e9xxxxxxxxx') #short_url = short_link.shorten(entry['id']) print(send_content) try: weibo_client.post('statuses/update', status=send_content) api.update_status(status=send_content) except Exception as e: print(str(e)) # 如果达到缓存上限,删除第一个元素,然后append if len(db['article_list']) == cache_max: del db['article_list'][0] db['article_list'].append(entry['id']) db.close() # 把脚本发送的服务器, 设置cronjob定时执行这个脚本 """ ###### facebook ###### import facebook cfg = { "page_id": "9605513040xxxxxx", "access_token" : "EAAYoBACzC5sBAInen1gctYAjb18AYAkkt2AOEeXNvcZARfyq2QS1TJLRtIue1OSym2dQ5azBSXMLL3cLRBrgB3y94e1tExYLi5fsx7ExK1FL3Yz7pMZCfeyif2AWpKZCMAvMEH3mxxxxxxxx" } def send(tilte, link): if title == None or link == None: return False attach ={ 'name': '', 'link': link, 'caption': '', 'description': '', 'picture': '' } #print(title) #print(link) api = get_api(cfg) status = api.put_wall_post(title, attachment = attach) return True def get_api(cfg): graph = facebook.GraphAPI(cfg['access_token']) # Get page token to post as the page. You can skip # the following if you want to post as yourself. resp = graph.get_object('me/accounts') page_access_token = None for page in resp['data']: if page['id'] == cfg['page_id']: page_access_token = page['access_token'] graph = facebook.GraphAPI(page_access_token) return graph """
发文后自动分享到微博和Twitter-Python

后续:提取、发送文章简介;添加hashtag;整理代码。

使用Python获取并解析 RSS feed-Feedparser 使用Tweepy发送推文-Python

Share the post "发文后自动分享到微博和Twitter-Python"

Google+ Weibo Email

Viewing all articles
Browse latest Browse all 9596

Trending Articles