class BlogPost: def __init__(self,user,password): self.wp = Client("http://dataslant.xyz/xmlrpc.php",user,password) def postDraft(self, title, body): ''' Creates a draft with title and graph Currently both title and graph are just strings ''' post = WordPressPost() post.title = title post.content = body # post,terms_names = { # 'post_tag': ['test'], # 'category': ['testCat']} self.wp.call(NewPost(post)) def uploadJPG(self, filePath): data = { 'name': filePath.split('/')[-1], 'type': 'image/jpeg', } with open(filePath, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = self.wp.call(media.UploadFile(data)) return response['id']
def load_file(self): fname = askopenfilename(filetypes=(("PNG Image", "*.png"), ("JPG Image", "*.jpg;*.jpeg"), ("GIF Image", "*.gif"), ("Bitmap Image", "*.bmp"), ("All Files", "*"))) print(mimetypes.guess_type(fname)[0]) try: wp = Client('https://your.wordpress.installation/xmlrpc.php', 'Username', 'password') except TimeoutError: self.status.delete(0, END) self.status.insert(0, 'Unable to connect to WP') except gaierror: self.status.config(state=NORMAL) self.status.delete(1.0, END) self.status.insert(1.0, 'DNS lookup failed') self.status.config(state=DISABLED) raise print(MyFrame.path_leaf(fname)) data = {'name': MyFrame.path_leaf(fname), 'type': mimetypes.guess_type(fname)[0]} with open(fname, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) print(response['url']) self.status.config(state=NORMAL) self.status.delete(1.0, END) self.status.insert(1.0, 'Link: '+response['url']) self.status.config(state=DISABLED)
def get_blog_subscribers(self): """ Gets WordPress Blog Subscribers """ config = SafeConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'config.ini')) try: url = config.get("wordpress", "url") username = config.get("wordpress", "username") password = config.get("wordpress", "password") except Error as error: msg = "Config section [wordpress] bad or missing: %s" % \ error.message logging.error(msg) raise Exception(msg) subs = [] wp = Client(url, username, password) users = wp.call(GetUsers()) logging.info("Found %d users." % len(users)) for u in users: logging.debug("User: %s" % u.email) logging.debug("Roles: %s" % u.roles) if 'subscriber' in u.roles: subs.append((u.email, u.first_name)) return subs
def media_upload(): print 'Media Upload' from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.compat import xmlrpc_client from wordpress_xmlrpc.methods import media, posts client = Client(xmlrpc_url, username, password) if len(param_list[2:]) == 0: print "Error: Please select Uploads file" sys.exit(0) else: for f in param_list[2:]: filepath = os.path.abspath(f) filename = os.path.basename(filepath.strip()) dirname = os.path.dirname(filepath.strip()) # prepare metadata data = { 'name': filename, 'type': mimetypes.guess_type(filename)[0] } # read the binary file and let the XMLRPC library encode it into base64 with open(filepath.strip(), 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) attachment_id = response['id'] media_info = client.call(media.GetMediaItem(attachment_id)) media_filename = os.path.basename(media_info.link.strip()) print '==========================\n' + 'Attachment ID : ' + attachment_id + '\nFile name : ' + media_filename + '\nFile url : ' + media_info.link
def post(self): from lxml import etree try: self.ui.label.setText("Importing necessary modules...") from wordpress_xmlrpc import Client, WordPressPost status = 1 except: status = 0 if(status==1): from wordpress_xmlrpc.methods.posts import GetPosts, NewPost from wordpress_xmlrpc.methods.users import GetUserInfo self.ui.label.setText("Imported modules...") data = etree.parse("config.xml") user = data.find("user").text url = data.find("url").text pwd = data.find("pass").text self.ui.label.setText("Imported data...") try: wp = Client(url+"/xmlrpc.php", user, pwd) except: status = 0 if (status == 1): post = WordPressPost() post.content = str(self.ui.BodyEdit.toPlainText()) post.title = str(self.ui.TitleEdit.text()) post.content = post.content + "<br><small><i>via QuickPress</i></small></br>" post.post_status = 'publish' wp.call(NewPost(post)) self.ui.label.setText("Published") else: self.ui.label.setText("Check Internet Connection and try again...") else: self.ui.label.setText("module(wordpress_xmlrpc) not found, you can install manually from terminal using pip install python-wordpress-xmlrpc")
def test_pages(user, password): from wordpress_xmlrpc import WordPressPage client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) pages = client.call(posts.GetPosts({'post_type': 'page'}, results_class=WordPressPage)) p = pages[0] print(p.id) print(p.title)
def upload_to_wordpress(xmlrpc_url,xmlrpc_user,xmlrpc_pass,inputfile,name): """upload to <xmlrpc_url> as <xmlrpc_user>, <xmlrpc_pass> the <inputfile> as <name>""" global path metadata = { 'name': name, 'type': mimetypes.guess_type(inputfile)[0] or 'audio/mpeg', } try: print xmlrpc_url,xmlrpc_user,xmlrpc_pass wpclient = Client(xmlrpc_url,xmlrpc_user,xmlrpc_pass) fh = open('/'.join([path,inputfile])) # Read input file and encode as base64 with open(filename, 'rb') as fh: data['bits'] = xmlrpc_client.Binary(fh.read()) response = wpclient.call(media.UploadFile(metadata)) # Expected response: # response == { # 'id': 6, # 'name': '2013.04.28_madison_whaley.mp3', # 'url': 'http://summitcrossing.org/wp-content/uploads/2013/04/28/2013.04.28_madison_whaley.mp3', # 'type': 'audio/mpeg', # } if response['id']: # If upload succeeded, rename input file: os.rename(inputfile,name) except IOError as e: print("({})".format(e)) return response
def post_article(self,wpUrl,wpUserName,wpPassword,articleTitle, articleCategories, articleContent, articleTags,PhotoUrl): self.path=os.getcwd()+"\\00000001.jpg" self.articlePhotoUrl=PhotoUrl self.wpUrl=wpUrl self.wpUserName=wpUserName self.wpPassword=wpPassword #Download File f = open(self.path,'wb') f.write(urllib.urlopen(self.articlePhotoUrl).read()) f.close() #Upload to WordPress client = Client(self.wpUrl,self.wpUserName,self.wpPassword) filename = self.path # prepare metadata data = {'name': 'picture.jpg','type': 'image/jpg',} # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) attachment_id = response['id'] #Post post = WordPressPost() post.title = articleTitle post.content = articleContent post.terms_names = { 'post_tag': articleTags,'category': articleCategories} post.post_status = 'publish' post.thumbnail = attachment_id post.id = client.call(posts.NewPost(post)) print 'Post Successfully posted. Its Id is: ',post.id
def PushToWeb(courses): if not pushToWordPress: return client = Client(url,user,pw) pages = GetWebPages() for course in courses: print("pushing to web", course) try: page = pages[course] f = open("raw/%s.html" % (course,),"r") page.content = f.read() f.close() except IOError as ioe: print("** no raw file found for",course) print(ioe) continue except KeyError as keyx: print("** no course found on blog",course) print(keyx) continue result = client.call(posts.EditPost(page.id, page)) if result: print("Successfully updated ", page.slug) else: print("******Warning********: could not update ", page.slug)
def wp_post(post_type, limit): from wordpress_xmlrpc import Client from wordpress_xmlrpc.methods import posts wp = Client('http://www.leedsdatamill.org/xmlrpc.php', 'USERNAME', 'PASSWORD') published_posts = wp.call(posts.GetPosts({'post_status': 'publish', 'number': limit, 'orderby': 'post_date', 'order': 'DESC', 'post_type': post_type })) return published_posts
def upload(pic): (_ , ext) = os.path.splitext(pic) wp_client = Client(rpc_service_url, user, password) data = {'name':str(uuid4()) + ext, 'type':mimetypes.guess_type(pic)[0]} with open(pic, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) rsp = wp_client.call(media.UploadFile(data)) return rsp
def _post_to_wp(post): # Keep 3rd party calls separate client = Client( url=settings.XML_RPC_URL, username=settings.XML_RPC_USERNAME, password=settings.XML_RPC_PW ) return client.call(post)
def share_on_facebook(post_ids, access_token, page_id=PAGE_ID): graph = facebook.GraphAPI(access_token) client = Client('http://domain.com/xmlrpc.php','username','password') for post_id in post_ids: post = client.call(GetPost(post_id)) link = post.link path = '/'+str(page_id)+'/feed' post = graph.request(path=path,post_args={'link':post.link}) print post
def getWordpressPostById(id): wpPost = [] try: wpClient = Client(app.config.get('BLOG_URL'), app.config.get('BLOG_USER'), app.config.get('BLOG_PASSWORD')) wpPost = wpClient.call(posts.GetPost(id)) except (ServerConnectionError, InvalidCredentialsError) as e: logging.warn(e.message) finally: return wpPost
class PublishPipeline(object): """ use xmlprc of wordpress to synchronize via push """ @classmethod def from_crawler(cls, crawler): return cls() def open_spider(self, spider): self.client = Client(os.getenv('SCRAPY_WP_RPCURL'), os.getenv('SCRAPY_WP_USERNAME'), os.getenv('SCRAPY_WP_PASSWORD')) pass def close_spider(self, spider): pass def process_item(self, item, spider): wp_filename = item.filename('wp') if os.path.exists(wp_filename): with open(wp_filename) as fh: post = pickle.load(fh) fh.close() # # # Here one might update or fix things if False: post.terms_names = { 'category': [item['source_name'].title()], 'post_tag': get_place_post_tag_names(item['place']) } self.client.call(posts.EditPost(post.id, post)) pass pass pass else: post = WordPressPost() post.title = item['headline'] try: post.content = item['body'] except KeyError: return None try: item['place'] except KeyError: item['place'] = "" post.terms_names = { 'category': [item['source_name'].title()], 'post_tag': get_place_post_tag_names(item['place']) } post.link = item['source_url'] post.date = item['time'] post.post_status = 'publish' post.id = self.client.call(posts.NewPost(post)) with open(wp_filename, 'wb') as fh: pickle.dump(post, fh) fh.close() pass return item pass pass
def getWordpressPosts(): allPosts = [] try: wpClient = Client(app.config.get('BLOG_URL'), app.config.get('BLOG_USER'), app.config.get('BLOG_PASSWORD')) allPosts = wpClient.call(posts.GetPosts({'post_status': 'publish'})) except (ServerConnectionError, InvalidCredentialsError) as e: logging.warn(e.message) finally: return allPosts
def getWordpressCategories(): wpCats = [] try: wpClient = Client(app.config.get('BLOG_URL'), app.config.get('BLOG_USER'), app.config.get('BLOG_PASSWORD')) wpCats = wpClient.call(taxonomies.GetTerms('category')) except (ServerConnectionError, InvalidCredentialsError) as e: logging.warn(e.message) finally: return wpCats
def __init__(self, user, password, archive, lfrom='pt', lto='pb'): client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) post = client.call(posts.GetPost(archive)) tagfrom = '[:%s]' % lfrom tagto = '[:%s]' % lto post.title = post.title.replace(tagfrom, tagto) post.content = post.content.replace(tagfrom, tagto) #print(post.title) #print(post.content) client.call(posts.EditPost(post.id, post))
def get_categories(site_id): ''' 获取site_id的所有category :param site_id: :return: ''' site = Site.objects.get(pk=site_id) client = Client(site.url + '/xmlrpc.php', site.username, site.password) categories = client.call(taxonomies.GetTerms('category')) return categories
def timezone(): from wordpress_xmlrpc import Client, WordPressOption from wordpress_xmlrpc.methods import options client = Client(xmlrpc_url, username, password) timezone = client.call(options.GetOptions('time_zone')) timezone_ = timezone[0] # print str(timezone_) timezone__ = re.search(r'time_zone="(.+)"', str(timezone_)).group(1).strip() global timezone___ timezone___ = float(timezone__)
def main(): client = Client("http://jonathanlurie.fr/xmlrpc.php", "jonathanlurie", "jo.270185") allPosts = client.call(posts.GetPosts()) for p in allPosts: try: print p except: None
def wp_truncate(): client = Client(os.getenv('SCRAPY_WP_RPCURL'), os.getenv('SCRAPY_WP_USERNAME'), os.getenv('SCRAPY_WP_PASSWORD')) while 1: posts_slice = client.call(posts.GetPosts()) if len(posts_slice): for p in posts_slice: client.call(posts.DeletePost(p.id)) else: break
def GetWebPages(): # the most stable way to access WordPress is to # hardcode the post IDs in here ids = [817,819,822,841,834,836,839,807,812,1156,1131,847,1428] pages = dict() client = Client(url,user,pw) for postId in ids: page = client.call(posts.GetPost(postId)) pages[page.slug] = page return pages
def post_to_wordpress(title, content): logger.debug('Logging to %s as %s...', WP_RPC_URL, WP_USER) wp = Client(WP_RPC_URL, WP_USER, WP_PASS) logger.debug('Logged in.') post = WordPressPost() post.title = title post.content = content logger.debug('Sending RPC call to %s wordpress as %s user...', WP_RPC_URL, WP_USER) post_id = wp.call(NewPost(post)) logger.debug('New post id = %s', post_id)
def run(self): self.logger.info("[%s] running" % self.name) # 验证地址是否可用 try: wp = Client(self.xmlrpc, self.user, self.passwd) para = {'number': (self.offset + 1) * 50} self.__wordpressitems = wp.call(posts.GetPosts(para)) except Exception, x: self.logger.info("[%s] xmlrpc connection or getinfor error" % self.name) self.logger.error(str(x))
def __init__(self, user, password, archive): client = Client('http://www.weeklyosm.eu/xmlrpc.php', user, password) post = client.call(posts.GetPost(archive)) tag1_from = '<!--:Ja-->' tag2_from = '[:Ja]' tag1_to = '<!--:ja-->' tag2_to = '[:ja]' post.title = post.title.replace(tag1_from, tag1_to) post.title = post.title.replace(tag2_from, tag2_to) post.content = post.content.replace(tag1_from, tag1_to) post.content = post.content.replace(tag2_from, tag2_to) client.call(posts.EditPost(post.id, post))
def create_wordpress_draft(publish_target, title, html, tags): post = WordPressPost() today = datetime.date.today() post.title = title post.content = html client = Client( publish_target["url"] + "/xmlrpc.php", publish_target["username"], publish_target["password"]) category = client.call(taxonomies.GetTerm('category', publish_target["default_category_id"])) post.terms.append(category) post.user = publish_target["default_user_id"] post.terms_names = {'post_tag': tags} post.comment_status = 'open' post.id = client.call(posts.NewPost(post)) return post
def authenticate_by_wordpress_site(username, password): """test password against external wordpress site via XML RPC call""" try: wp_client = WordPressClient( settings.WORDPRESS_SITE_URL, username, password ) wp_user = wp_client.call(WordPressGetUserInfo()) return '%s?user_id=%s' % (wp_client.url, wp_user.user_id) except InvalidCredentialsError: return None
def test(): client = Client( 'http://www.weeklyosm.eu/xmlrpc.php', 'alexandre', 'SENHA' ) posts = client.call(posts.GetPosts()) #for post in posts[:1]: #print(posts[1].id) #print(posts[1].title) #print(posts[1].link) print(posts[0].content)
def func_Create_WP_Post(atitle, acontent, category): wp = Client(WPPATH, WPUSER, WPPASS) my_category = category post = WordPressPost() post.title = atitle post.content = acontent post.post_format = "video" post.terms_names = {'category':[my_category]} print(category) print("---") my_posts = [] #my_posts = set() my_increment = 20 my_offset = 0 while True: wp_obj_posts = wp.call(posts.GetPosts({'number': my_increment, "offset": my_offset})) if len(wp_obj_posts) == 0: break for apost in wp_obj_posts: apost = apost.content apost = apost.split("embed/",1)[1] #my_posts.add(apost) my_posts.append(apost) #try: # print(apost.title) #except UnicodeEncodeError: # print("'ascii' codec can't encode character.") my_offset += my_increment #print(wp_obj_posts) #print("---") print(my_posts) print("---") post_id = post.content.split("embed/",1)[1] print(post_id) #my_posts = sorted(my_posts) if post_id in my_posts: print("Dublicate post!!!\n") print("---") else: print("Posted!\n") print("---") post.id = wp.call(posts.NewPost(post)) post.post_status = 'publish' wp.call(posts.EditPost(post.id, post))
def get_client(configuration): transport = get_proxy(configuration) client = Client(configuration['endpoint'], configuration["username"], configuration['password'], transport=transport) return client
def getClient(self): if not self._connection: self._connection = Client(self.url(), self.settings["username"], self.settings["password"]) return self._connection
def update_wiki(url, username, password, _page_title, _page_id, _markdown): wp = Client(url, username, password) # define pages variable page = WordPressPage() page.title = _page_title # page id can be found by viewing via wp-admin dashboard in URL page.id = _page_id # set local content file to read handle info into a string with open(_markdown, 'r') as _file: page.content = _file.read() # post new content to the page wp.call(EditPost(page.id, page))
def wpClient(): ''' Base class used to connect to Wordpress via XMLRPC. ''' return Client(settings.WORDPRESS_MIGRATR['server'], settings.WORDPRESS_MIGRATR['user'], settings.WORDPRESS_MIGRATR['pass'])
def updatePost(config, html): blog = Client(settings.blogXmlRpc, settings.blogUsername, settings.blogPassword) post = WordPressPost() post.title = config['post_title'] post.id = config['id'] post.terms_names = {} post.terms_names['category'] = config['category'] post.content = html # post.content = markdown.markdown(content) myposts = blog.call(EditPost(post.id, post))
def getWordpressPostsLimit(): wpPost = [] try: wpClient = Client(app.config.get('BLOG_URL'), app.config.get('BLOG_USER'), app.config.get('BLOG_PASSWORD')) wpPost = wpClient.call( posts.GetPosts({ 'number': 4, 'post_status': 'publish' })) except (ServerConnectionError, InvalidCredentialsError) as e: logging.warn(e.message) finally: return wpPost
def importNewUser(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) IMG_DIR = os.path.join(BASE_DIR, "images") site = Client('http://192.168.137.26/xmlrpc.php', '*****@*****.**', 'Bpl2 vF31 ePl6 Unoa rAcC kJGm') # This IP is dependent on the wordpress site being hosted on my laptop's hotspot. recently_modified = site.call(posts.GetPosts({'orderby': 'post_modified', 'number': 100})) # Get the most recent 100 posts (Would theoretically break if we did 100 random posts and then added a new user post, # can expand number if needed media_library = site.call(media.GetMediaLibrary([])) # Get media library of database new_users = [] added_new_user = False for post in recently_modified: terms = post.terms for term in terms: if 'New User' == term.name and post not in new_users: new_users.append(post) added_new_user = True # We are only interested in posts with the category "New User", so keep track of those # Should be deleting requests after each message # Or maybe add a tag that says "Processed" to keep history? That way it is ignored on a second call to this script post_id = new_users[0].id # In theory, we would only process 1 new user post at a time and then either delete the post or # add a tag that prevents future processing (i.e. the list will always have only 1 post in it) photo_links = re.findall("class=\"wp-image-([\d]+)\"", new_users[0].content) print(photo_links) # Get the media attachment ids for the post for m in media_library: if str(m.id)in photo_links: print(m) print(m.link) resp = requests.get(m.link, stream=True) local_name = "Temp_Pictures/get_image_test{}.jpeg".format(media_library.index(m)) local = open(local_name, "wb") resp.raw.decode_content = True shutil.copyfileobj(resp.raw, local) del resp # Using the attachment ids, get pictures from media library and use links to download pictures to a temporary folder # on the pi # Temp folder can be used by main.py to import the new images and create a new recognizer return added_new_user
def push_kuaijiwang(): try: # 检测是否登录成功 # 登录WordPress后台 client = Client("https://www.yebing.cn/xmlrpc.php", "yebing", "yeye910103") except ServerConnectionError: print('登录失败') else: print('登录成功') # wp = client.call(posts.GetPosts({'orderby': 'post_modified', 'number': 50})) # for w in wp: # print(w.link) for item in kuaijiwangarticle.find({"status": 0}): if item['fenlei'] in fenlei_catgory.keys(): if item['tags'].split(",")[0]: # 判断是否有标签,有标签的直接发布,没有的手工 # NewPost()方法,新建一篇文章 newpost = WordPressPost( ) # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例 newpost.title = item['title'] newpost.content = item['content'] newpost.excerpt = item['summay'] newpost.post_status = 'publish' # private表示私密的,draft表示草稿,publish表示发布 newpost.comment_status = "open" newpost.terms_names = { 'post_tag': item['tags'].split(",")[:2], # 文章所属标签,没有则自动创建 'category': fenlei_catgory.get(item['fenlei']) } # 文章所属分类,没有则自动创建} time.sleep(random.randint(30, 120)) aid = client.call(posts.NewPost(newpost)) if aid: kuaijiwangarticle.update_one({'_id': item['_id']}, {'$set': { 'status': 1 }}) ar_url = "https://www.yebing.cn/article_{}.html".format( aid) print(ar_url) flush(ar_url)
def post(filename): wp = Client('https://doricardo.com/images/xmlrpc.php', 'user', 'pass') # set to the path to your file filename = '/path/to/my/post.jpg' filename = 'post.jpg' # prepare metadata data = { 'name': 'post.jpg', 'type': 'image/jpeg', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) #response = { # 'id': 100, # 'file': 'StoriesBras18-1.jpg', # 'url': 'https://i1.wp.com/www.trisportmag.com.br/wp-content/uploads/2018/11/StoriesBras18-1.jpg', # 'type': 'image/jpeg' #} attachment_id = response['id'] #fonte = open('post.txt','r') #content = fonte.read() with open('post_model.json') as fonte: data = json.load(fonte) title = data['title'] description = data['description'] urlmedia = data['media'] category = data['category'] tags = data['tags'] print(title + " " + description) post = WordPressPost() post.title = title post.content = description post.post_status = 'publish' post.thumbnail = attachment_id wp.call(NewPost(post)) print("Conteúdo posta com sucesso")
def get_post(url): try: _url = "{}/{}".format(url.get('url'), "xmlrpc.php") user_name = url.get('userName') password = url.get('password') client = Client(_url, user_name, password) news = client.call(posts.GetPosts({ 'orderby': 'date', 'order': 'DESC' })) if news is None: return None else: return news[0] except Exception as e: print(e) return None
def sends(data): # print targeturl #u=content1[i][0] #链接WordPress,输入xmlrpc链接,后台账号密码 wp = Client('http://www.stock-t.com/wordpress/xmlrpc.php', 'jiehunt', 'yxpbl1982') post = WordPressPost() post.title = 'MyStockRecommend' # post.post_type='test' post.content = data post.post_status = 'publish' #发送到WordPress #print 'here3' wp.call(NewPost(post)) time.sleep(3) print('posts updates')
class WordPressXMLRPCPipeline(object): def __init__(self): self.client = Client(settings.get('WP_URL'), settings.get('WP_USER'), settings.get('WP_PASSWORD'), settings.get('WP_BLOGID')) def create_thumbnail(self, item): src = item['thumbnail_src'].encode('utf-8') img_name = 'wp-' + src.split('/')[-1] img_save_to = os.path.join('/tmp', img_name) remote_img = urllib.urlopen(src) with open(img_save_to, 'wb') as output: output.write(remote_img.read()) data = { 'name': img_name, 'type': 'image/jpeg', } with open(img_save_to, 'rb') as img_file: data['bits'] = xmlrpc_client.Binary(img_file.read()) response = self.client.call(media.UploadFile(data)) try: os.remove(img_save_to) except: pass return response['id'] def process_item(self, item, spider): post = WordPressPost() post.title = item['title'] post.content = item['content'] + settings.get('GOTO_SOURCE', "[%s]") % item['link'] post.date = datetime.datetime.strptime(item['publish_date'], "%Y-%m-%d %H:%M") post.terms_names = { 'post_tag': item['tag'], 'category': item['category'] if len(item['category']) > 0 else ['gist'], } post.post_status = 'publish' post.thumbnail = self.create_thumbnail(item) post.id = self.client.call(posts.NewPost(post)) return item
def wpsend(content, title, vido_info_kind): try: # 链接地址,登录用户名,密码 wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce', '12345678') # print(content) post = WordPressPost() # 设置标题内容 post.title = str(title) # 文章正文内容 post.content = " ''' " + content + " ''' " # 可见性,publish:全部可见; post.post_status = 'publish' # 设置标签,分类 post.terms_names = { 'post_tag': ['影视'], 'category': ['影视', '链接资源', vido_info_kind] } # 验证是否有相同标题 old_post = wp.call(GetPost(post.title)) # old_post = GetPost(post.title) print(old_post) if post.title == old_post: wp.call(DeletePost(post.title)) print('已经删除{}'.format(post.title)) else: # 新建文章 wp.call(NewPost(post)) localtime = time.localtime(time.time()) print('文档已上传 {}'.format( time.strftime("%Y-%m-%d %H:%M:%S", localtime))) except: print('没有上传成功')
def post_wp(d,usite,uname,upass): wp = Client(usite, uname, upass) # wp.call(GetPosts()) # wp.call(GetUserInfo()) post = WordPressPost() post.title = d[2] post.content = d[1] post.terms_names = {'post_tag': d[5],'category': d[4]} post.post_status = 'publish' try: wp.call(NewPost(post)) except Exception as ex: print(str(ex)) excw = open("exception.txt", "a+") excw.write(str(ex)+" : "+time.asctime()+"\n") excw.write("\n--------------------------------------------------------------------------------\n") excw.close() print ("----------------------Wordpress-Post-Done-----------------------")
def run_imports(importfile, user, pw): global DJANGO_DATA global API DJANGO_DATA = dp.load_website_data(importfile) API = Client('http://us-ignite.local/xmlrpc.php', user, pw) # import_applications(DJANGO_DATA) # import_blogposts(DJANGO_DATA) import_pages(DJANGO_DATA)
def __init__(self, site=SITE, user=SITE_USER, passwd=SITE_PASSWD): try: self.db=pymysql.connect(host=WP_HOST,port=WP_PORT,password=WP_PASSWD,user=WP_USER,database=WP_DB) self.cur=self.db.cursor() except Exception as e: print(e) sys.exit(0) self.wp = Client('{}/xmlrpc.php'.format(site), user, passwd) self.categories = Taxonomy() # self.wp.call(taxonomies.GetTerms('category')) self.tags = Taxonomy() # self.wp.call(taxonomies.GetTerms('post_tag')) _cat=self.wp.call(taxonomies.GetTerms('category')) _tag=self.wp.call(taxonomies.GetTerms('post_tag')) [self.categories.tax_list.append(i.name) for i in _cat] [self.tags.tax_list.append(i.name) for i in _tag] for i in _cat: self.categories.tax_dict.setdefault(i.name,i.taxonomy_id) for i in _tag: self.tags.tax_dict.setdefault(i.name,i.taxonomy_id)
def _connectToWP(self): """Establish the actual TCP connection to Flickr""" if self.connected_to_wp: logger.debug("Already connected to wp") return True # Load config from file info = json.load(open(WP_LOGIN_FILE, 'r')) self.wp = Client(info['url'],\ info['username'],\ info['password']) logger.debug("Connecting to wp") self.connected_to_wp = True return True
def wpclient(username, password, domain="box5880.temp.domains/~chaptrgl/codelab"): "Authenticate WordPress Login and Output Client" website_link = "http://" + domain + "/xmlrpc.php" wp = Client(website_link, username, password) return wp
def publish(results): try: print("%s invoked" % (inspect.stack()[1][3])) wp_client = Client('http://www.bbgo321.com/xmlrpc.php', 'jkdcdlly', 'mfYU6wnXuWBYSgOWVu') for result in results: time.sleep(5) id, origin_url, cate, title, imgs, content, rand = result print(id) word_press_post = WordPressPost() word_press_post.title = title word_press_post.content = content word_press_post.terms_names = {'category': [cate]} word_press_post.post_status = 'publish' word_press_post.id = wp_client.call(posts.NewPost(word_press_post)) update_post(id) except Exception as e: print(e)
def wpsend(content, title): try: # 链接地址,登录用户名,密码 wp = Client('http://magnetkey.xyz/xmlrpc.php', 'bruce', 'flzx3qc@ysyhl9t') # wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce','12345678') # print(content) post = WordPressPost() post.title = str(title) post.content = " ''' " + content + " ''' " post.post_status = 'publish' post.terms_names = { 'post_tag': ['magnet'], 'category': ['福利', 'magnet'] } wp.call(NewPost(post)) print('文档已上传 {}'.format(daytime)) except: print('没有上传成功')
def setUp(self): config = ConfigParser() with open('wp-config.cfg', 'r') as f: config.readfp(f) self.xmlrpc_url = config.get('wordpress', 'url') self.username = config.get('wordpress', 'username') self.userid = config.get('wordpress', 'userid') self.client = Client(self.xmlrpc_url, self.username, config.get('wordpress', 'password'))
def wpsend(content, title, vido_info_kind): try: # 链接地址,登录用户名,密码 wp = Client('http://magnetkey.xyz/xmlrpc.php', 'bruce', 'flzx3qc@ysyhl9t') # wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce','12345678') post = WordPressPost() post.title = str(title) post.content = " ''' " + content + " ''' " post.post_status = 'publish' post.terms_names = { 'post_tag': ['magnet', vido_info_kind], 'category': ['福利', 'magnet', vido_info_kind] } wp.call(NewPost(post)) localtime = time.localtime(time.time()) print('文档已上传 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", localtime))) except: print('没有上传成功')
def get_xmlrpc(self, blog=None): """ Fetch an XML-RPC client for a given blog (or the root blog). """ if blog: path = '/%s/xmlrpc.php' % blog else: path = '/xmlrpc.php' return Client(build_url(path), USERNAME, PASSWORD)
def wpsend(content, title, vido_info_kind): try: # 链接地址,登录用户名,密码 wp = Client('http://wh-nb6ulvw9jakg3k41rni.my3w.com/xmlrpc.php', 'bruce', 'flzx3qc@ysyhl9t') # print(content) post = WordPressPost() post.title = str(title) post.content = " ''' " + content + " ''' " post.post_status = 'publish' post.terms_names = { 'post_tag': ['影视'], 'category': ['影视', '链接资源', vido_info_kind] } wp.call(NewPost(post)) localtime = time.localtime(time.time()) print('文档已上传 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", localtime))) except: print('没有上传成功')
def post_wordpress(loginid, loginpw, domain, title, content, post_tag, category, post_status): """Word Pressへの簡易投稿 Args: loginid (str): Your login ID. loginpw (str): Your login PassWord. domain (str): Your WordPress domain name. title (str): Post title. content (str): Post contents. post_tag (str[]): Post tag. category (str[]): Post category. post_status (str): Post status. Returns: None """ url = "http://" + domain + "/xmlrpc.php" try: wp = Client('%s/xmlrpc.php' % url, loginid, loginpw) except ServerConnectionError: sys.exit("Cannot Connect to the server. Please check your network.") except: sys.exit("Cannot find configuration!") post = WordPressPost() post.title = title post.content = content post.terms_names = {"post_tag": post_tag, "category": category} post.status = post_status try: wp.call(NewPost(post)) except InvalidCredentialsError: sys.exit("Username or Password is incorrect") except XmlrpcDisabledError: sys.exit("XML-RPC services are disabled in WordPress") print("Finish post!")
def post_article(self, wpUrl, wpUserName, wpPassword, articleTitle, articleCategories, articleContent, articleTags, PhotoUrl): try: self.path = os.getcwd() + "\\images\\00000001.jpg" self.articlePhotoUrl = PhotoUrl self.wpUrl = wpUrl self.wpUserName = wpUserName self.wpPassword = wpPassword # Download File f = open(self.path, 'wb') f.write(urllib.urlopen(self.articlePhotoUrl).read()) f.close() # Upload to WordPress client = Client(self.wpUrl, self.wpUserName, self.wpPassword) filename = self.path # prepare metadata data = { 'name': 'picture.jpg', 'type': 'image/jpg', } # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) attachment_id = response['id'] # Post post = WordPressPost() post.title = articleTitle post.content = articleContent post.terms_names = { 'post_tag': articleTags, 'category': articleCategories } post.post_status = 'publish' post.thumbnail = attachment_id post.id = client.call(posts.NewPost(post)) #print 'Post Successfully posted. Its Id is: ', post.id except Exception as e: print traceback.format_exc() return 0 return post.id
def pagina_wordpres_old(site = '***************'): if site == '************': usuario = "*************" contraseña = "*************" sitio = "**************/xmlrpc.php" else: usuario = '**************' contraseña = '************' sitio = '************/xmlrpc.php' cliente = Client(sitio, usuario, contraseña) return cliente
def pagina_wordpres(site = 'Aprende Data Science'): if site == 'd************': usuario = "************" contraseña = "************" sitio = "************/xmlrpc.php" else: usuario = '************' contraseña = '************' sitio = '************//xmlrpc.php' cliente = Client(sitio, usuario, contraseña) return cliente
def tweetDailyNews(self): wp = Client(self.wp_xmlrpc_url, self.wp_username, self.wp_password) posts = wp.call(GetPosts()) post = posts[0] post_date = post.title[10:] match = re.search(r'<div class="tweetcenterbox">(.+)</div>', post.content) if match: text = match.group(1) logging.debug(text) lead = text[:50] logging.debug(lead) status = u'Tweets about [' + self.keyword + '] on ' + post_date + ' "' + lead + u'..." ' + post.link logging.info(status) self.tweet(status) return
def post_article(self, wpUrl, wpUserName, wpPassword, PhotoName, PhotoPath): self.wpUrl = wpUrl self.wpUserName = wpUserName self.wpPassword = wpPassword #Upload to WordPress client = Client(self.wpUrl, self.wpUserName, self.wpPassword) filename = PhotoPath + PhotoName # prepare metadata data = { 'name': PhotoName, 'type': 'image/gif', } # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) print 'Post Successfully posted. Its Id is: ', response['id']