class WordPressPostingRobot(object): def __init__(self, site, user, password=""): if password == "": password = raw_input( 'Please enter the password for the user %s: ' % user) self.additional_tags = raw_input( 'Please enter additional tags to give to all the posts: ') self.__wp = Client(site, user, password) #wp.call(GetUserInfo()) def post_new(self, title, content, categories=['Mac OS X'], individual_tags='', status='private', date=dt.datetime.now()): post = WordPressPost() post.title = title post.description = content tags = 'automatically posted' if ( self.additional_tags == '') else self.additional_tags + ', automatically posted' tags = individual_tags + tags post.tags = tags post.date_created = date post.post_status = status post.categories = categories self.__wp.call(NewPost(post, True))
def update(self, _page_title, _page_id, _markdown): """ Update an existing wordpress page with generated markdown. Assumes you have a markdown file with content you want published to an existing wordpress page. :param _page_title: post page title :param _page_id: post page id :param _markdown: path to markdown file for upload """ wp = Client(self.endpoint, self.username, self.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))
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 postToWP(title, article, url_bing): request = urllib2.Request(url_bing) request.add_header('Authorization', credentialBing) requestOpener = urllib2.build_opener() response = requestOpener.open(request) results = json.load(response) l = len(results['d']['results']) image = results['d']['results'][random.randint(0,l-1)]['Thumbnail']['MediaUrl'] response = requests.get(image, stream=True) with open('image'+h+m+s+'.jpg', 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response filename = 'image'+h+m+s+'.jpg' url = 'http://www.'+args.profile+'.com/xmlrpc.php' wp = Client(url, 'admin', 'wIn$j5vG$#NryzJGGlBMd20J') # prepare metadata data = { 'name': 'image'+h+m+s+'.jpg', 'type': 'image/jpeg', # mimetype } with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) img = '/wp-content/uploads/'+yr+'/'+mo+'/image'+h+m+s+'.jpg' post = WordPressPost() post.title = title post.content = '<img class="alignleft" src="'+img+'" width="341" height="341"/> \n' + article post.terms_names = { 'category': categories[:2] } post.post_status = 'publish' wp.call(NewPost(post)) return True
def wordpress_background_task(api): log("IOT background task") data1= "{" for key1, value in cbpi.cache.get("sensors").iteritems(): data1 += ", " if key1 >1 else "" data1 += "\"%s\":%s" % (value.name, value.instance.last_value) data1 += "}" data2= "{" for key2, value2 in cbpi.cache.get("actors").iteritems(): data2 += ", " if key2 >1 else "" data2 += "\"%s\":%s,%s" % (value2.name, value2.state, value2.power) data2 += "}" log("Wordpress Update") blog = Client(Wordpress_Domain + "xmlrpc.php", Wordpress_Username, Wordpress_Password) post = WordPressPost() # Create a title with some simple styling classes post.title = time.strftime("%y/%m/%d %H:%M:%S", time.localtime()) post.content = data1 + "<br />" + data2 post.terms_names = { 'post_tag': [Wordpress_Tag], 'category': [Wordpress_Category], } post.id = blog.call(posts.NewPost(post)) # Always publish these posts post.post_status = 'publish' blog.call(posts.EditPost(post.id, post))
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 remove_template_files(file_name): try: os.remove(sass_directory + '_'+ file_name + '.scss') except: print sass_directory + '_'+ file_name + '.scss already deleted' try: os.removedirs(image_directory + file_name) except: print image_directory + file_name + ' already deleted' try: os.remove(page_template_directory + file_name + '.php') except: print page_template_directory + file_name + '.php already deleted' file_lines = [] with open('assets/scss/foundation.scss') as f: content = f.readlines() for line in content: if('@import "templates/'+file_name+'"' in line): continue else: file_lines.append(line) f = open('assets/scss/foundation.scss','w') f.writelines(file_lines) f.close() page_id = find_id(file_name.capitalize()) client = Client(site_host + 'xmlrpc.php', username, password) client.call(posts.DeletePost(page_id))
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 make_post(content): wp = Client('https://yoursite.com/xmlrpc.php', 'user', 'pass') post = WordPressPost() post.title = content['title'] post.content = content['body'] post.terms_names = { 'post_tag': ['AutoBlogger', 'BotPosted'], 'category': ['News', 'Update'] } # Lets Now Check How To Upload Media Files filename = '1.jpg' data = { 'name': '1.jpg', 'type': 'image/jpeg' # Media Type } # Now We Have To Read Image From Our Local Directory ! with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] # Above Code Just Uploads The Image To Our Gallery # For Adding It In Our Main Post We Need To Save Attachment ID post.thumbnail = attachment_id post.post_status = 'publish' post.id = wp.call(posts.NewPost(post)) # Set Default Status For Post .i.e Publish Default Is Draft # We Are Done With This Part :) Lets Try To Run It print("Sucessfully Posted To Our Blog !")
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 sends(): print len(targeturl) for i in range(len(targeturl)): #u=content1[i][0] url = "http://whuhan2013.github.io" + targeturl[i] print url a = Article(url, language='zh') a.download() a.parse() title = a.title dst = a.text #链接WordPress,输入xmlrpc链接,后台账号密码 wp = Client('http://127.0.0.1:22222/xmlrpc.php', 'www', '!abc6') #示例:wp = Client('http://www.python-cn.com/xmlrpc.php','username','password') post = WordPressPost() post.title = title #post.post_type='test' #post.content = dst post.description = dst post.post_status = 'publish' #发送到WordPress wp.call(NewPost(post, True)) time.sleep(3) print 'posts updates'
def post(wp_url, wp_user, wp_pw, wp_title, wp_context, wp_thumbnail, wp_tags, wp_categorys): while True: try: client = Client(wp_url, wp_user, wp_pw) if wp_thumbnail != None: filename = wp_thumbnail # prepare metadata data = { 'name': 'picture.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 = client.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = wp_title post.content = wp_context post.post_status = 'publish' if wp_thumbnail != None: post.thumbnail = attachment_id post.terms_names = {'post_tag': wp_tags, 'category': wp_categorys} post.id = client.call(posts.NewPost(post)) return "https://weporn.tv/?p=" + str(post.id) except: pass
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') # print(content) post = WordPressPost() # 设置标题内容 post.title = str(title) # 文章正文内容 post.content = " ''' " + content + " ''' " # 可见性,publish:全部可见;'private':私有 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 sent_to_wp(filename,fullname,title,content): #prepare metadata data = { 'name': filename, 'type': 'image/jpeg', # mimetype } # # # read the binary file and let the XMLRPC library encode it into base64 wp = Client('http://www.abc.cn/xmlrpc.php', 'www', 'abc16') # sent_to_wp(title,content) with open(fullname, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) #print('response: %s' % response) attachment_id = response['id'] #print('attachment_id: %s %s' %(type(attachment_id),attachment_id)) post = WordPressPost() post.title = title post.content = content post.post_status = 'publish' post.thumbnail = attachment_id post.id = wp.call(posts.NewPost(post)) print('title:%s =>post success' % title) print('-----------------------------------------------------------------------------------')
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 setUp(self): wp = Client('http://lightcastletech.wordpress.com/xmlrpc.php', '*****@*****.**', settings.WORDPRESS_PASS) self.all_posts = wp.call( GetPosts({ 'number': 100, 'post_status': 'publish' })) self.authors = wp.call(GetAuthors()) self.all_posts = self.all_posts[:: -1] #reverse the list of posts so that the most recent are last in the list for post in self.all_posts: for author in self.authors: if author.id == post.user: post.author = author.display_name # following line sets the image variable so the posts index can display right if blog._get_first_image(post.content) != "None": post.image = blog._get_first_image(post.content) else: post.image = "" b = blog.Blog(title=post.title, author=post.author, initial_image=post.image, date=post.date, content=post.content) b.save()
def wordpress_artice(wppost_status, wp_title, wp_slug_title, wp_content, wp_category, wp_post_tag, wp_host, wp_user, wp_password): # 如果遇到错误就出试5次 success_num = 0 while success_num < 5: try: client = Client(wp_host, wp_user, wp_password) newpost = WordPressPost() # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例 # newpost.post_status = 'draft' newpost.post_status = wppost_status newpost.slug = wp_slug_title # 文章别名,固定链接形式为文章标题时需要 # 设置发布目录(一篇文章可以属于多个分类目录) newpost.terms_names = { 'category': wp_category, # 目录 'post_tag': wp_post_tag # 标签 } newpost.title = wp_title newpost.content = wp_content client.call(posts.NewPost(newpost)) #发布新建的文章,返回的是文章id print("Wordpress发布成功:", wp_title) except Exception as e: print("正在重试:", e) success_num = success_num + 1 continue
def createPost(self, title, description, size, tags, links, category): wp = Client(self.wp_url, self.wp_username, self.wp_password, transport=SpecialTransport()) post = WordPressPost() post.post_status = 'publish' title = title.replace('.', ' ') title = title.replace('_', ' ') post.title = title post.content = 'Size:<b> ' + size + '</b> <br /><br /><br />' post.content = post.content + description post.content = post.content + '<br /><div class=' "downLinks" '>Download Links:</div>' addLinks = '<textarea readonly>' for link in links: addLinks = addLinks + link + ' ' addLinks = addLinks + '</textarea>' post.content = post.content + addLinks post.terms_names = {'post_tag': tags, 'category': [category]} id = wp.call(NewPost(post)) postLink = WordPressPost() postLink = wp.call(GetPost(id)) return postLink.link
def showText(): title = title_entry.get() description = description_entry.get('1.0', END) isYes = messagebox.askyesno("Confirmation to post", "Are you sure you want to post?") if isYes: print("Title: {titleKey} \nDescrption: {descriptionKey}".format( titleKey=title, descriptionKey=description)) wp = Client('https://vijayatm.wordpress.com/xmlrpc.php', 'yourUserName', 'yourPassword') #replace your username and password here data = {'name': 'Python file Name.jpg', 'type': 'image/jpg'} with open(imgArg, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachmentURL = response['url'] attachmentID = response['attachment_id'] print(response) post = WordPressPost() post.title = title post.content = "<img src='{att1}'/><br>{description}".format( att1=attachmentURL, description=description) post.thumbnail = attachmentID post.terms_names = { 'post_tag': ['vijayatm', 'usingPython', 'tkinter', 'wordpress'] } post.post_status = 'publish' resp = wp.call(NewPost(post)) print(resp) root.destroy() else: messagebox.showinfo('Welcome Back', 'Update the description if you want to')
def main(): (options, args) = parse_options() # # Check if the file exists # if not os.path.exists(args[0]): print("File:%s does not exists, aborting!" % args[0]) sys.exit(1) new_post_file = open(args[0], 'r') new_post_content = new_post_file.read() new_post_file.close() client = Client('http://192.168.50.50/xmlrpc.php', 'tony', 'tony_wordpress_123') now = datetime.datetime.now() post = WordPressPost() post.title = 'My New Post - %s' % now.strftime("%Y-%m-%d_%H_%M_%S") post.content = new_post_content post.id = client.call(posts.NewPost(post)) post.post_status = 'publish' client.call(posts.EditPost(post.id, post))
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 postArticle(art, title, im, category, tags): host = "" user = "" password = "" conn = MySQLdb.connect(host=host, user=user, passwd=password, db="") cursor = conn.cursor() cursor.execute( "UPDATE scraped_articles SET paraphrase_flag = 0 WHERE title = %s", (title)) data = cursor.fetchall() cursor.close() conn.close() client = Client("wp url", "admin", "") # set to the path to your file if len(im) < 2: print im im = getPic.searchPic(title) else: print im im = getPic.savePic(im) filename = "google_images/" + im # prepare metadata data = { 'name': filename, 'type': "image/jpg", # 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 = client.call(media.UploadFile(data)) # response == { # 'id': 6, # 'file': 'picture.jpg' # 'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg', # 'type': 'image/jpg', # } print response attachment_id = response['id'] post = WordPressPost() post.title = str(title) post.terms_names = { 'post_tag': ["premium"], 'category': ['business'], } post.content = str(art) post.post_status = 'publish' post.thumbnail = attachment_id post.id = client.call(posts.NewPost(post)) print "uploaded!"
def make_post(content, categorys='0', tags='0', date=None): ''' :param content: dict() formatado corretamente :param categorys: lista com as categorias do post :param tags: lista com as tags do post :param date: data para o post ser publicado ( formato datetime.datetime()) :return: ''' #URL DO SITE, USUARIO , SENHA !!! wp = Client(authData['url'] + '/xmlrpc.php', authData['adminUsername'], authData['adminPassword']) post = WordPressPost() post.title = content['title'] post.content = content['body'] if tags[0] != '0': post.terms_names = {'post_tag': tags} try: categorys[0] == 0 except IndexError: pass else: if categorys[0] != '0': post.terms_names = {'category': categorys} # Lets Now Check How To Upload Media Files filename = content['image'] data = { 'name': content['title'] + '.jpeg', 'type': 'image/jpeg' # Media Type } # Now We Have To Read Image From Our Local Directory ! with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] # Above Code Just Uploads The Image To Our Gallery # For Adding It In Our Main Post We Need To Save Attachment ID post.thumbnail = attachment_id #deletando do pc a imagem remove(filename) #setando para o post ser publicado (nao ficar de rascunho) post.post_status = 'publish' # marcando p/ o post ser postado na data desejada if date != None: post.date = date post.id = wp.call(posts.NewPost(post)) # Set Default Status For Post .i.e Publish Default Is Draft # We Are Done With This Part :) Lets Try To Run It if not date: print(post.title, " Postado com sucesso !") if date: print(post.title, " Vai ser postado em ", date, '!')
def new_post(account, post): wp = Client(account['xmlrpc_url'], account['username'], account['password']) post.id = wp.call(NewPost(post)) tmp = wp.call(GetPost(post.id)) detail = "GetPost: %s - %s - %s" % (tmp.id, tmp.title, tmp.link) print(detail) result(detail)
def wordpress(self): wp = Client('http://localhost/xmlrpc.php', 'client', 'GJyh2vs(AT*He&F#WdEzgdnN') post = WordPressPost() post.title = str(self.end_day) + '盘后总结' post.content = self.content() post.post_status = 'publish' wp.call(NewPost(post))
def test_auth(host, port=80, path='', user='******', secret='admin'): try: client = Client(f'http://{host}:{port}/{path}/xmlrpc.php', user, secret) client.call(wordpress_xmlrpc.methods.users.GetUsers()) return True except InvalidCredentialsError: return False
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 send_news(yourwebsit, username, password, news): wp = Client(yourwebsit, username, password) attachment_id = upload_image(news.image_name, wp) post = WordPressPost() post.title = news.title post.content = news.content post.post_status = 'publish' post.thumbnail = attachment_id post.terms_names = {'post_tag': news.tags, 'category': [news.category]} wp.call(NewPost(post))
def new_page(username, password): client = Client(admin.url + 'xmlrpc.php', username, password) post = WordPressPost() post.title = '233' post.content = '233' post.id = client.call(posts.NewPost(post)) post.post_status = 'publish' client.call(posts.EditPost(post.id, post)) print "[-----Create new articles------]" return post.id, post.title, post.content
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 __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 PostWp(): poster = Client(url, username, password) post = WordPressPost() post.title = 'Teste XMLRPwn' post.content = 'Teste de XML-RPC feito com xmlrpwn.' post.post_status = 'publish' post.terms_names = { 'post_tag': ['teste', 'xmlrpwn'], 'category': ['Introducao', 'Teste'] } poster.call(NewPost(post))
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 send_news(yourwebsit,username,password,news): wp=Client(yourwebsit,username,password) post=WordPressPost() post.title=news.title post.content=news.content post.post_status ='publish' post.terms_names={ 'post_tag':news.tags, 'category':[news.category] } wp.call(NewPost(post))
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 parsePage(spider, url, response): html = response.content selector = etree.HTML(html) html = html.decode('utf-8') propertys = json.loads(spider.args['PagePropertyRegularExpression']) for key in propertys: item = propertys[key] if item.startswith('$'): p1 = r'%s' % item[1:] pattern = re.compile(p1) match = pattern.search(html) if match: propertys[key] = match.group(1) #对文章的内容进行特殊处理,提取图片 if key == 'content_raw': contentselector = etree.HTML(propertys[key]) etree.strip_elements(contentselector, 'script') etree.strip_tags(contentselector, 'a') propertys[key] = etree.tostring(contentselector).decode( 'utf-8') if spider.args['DownLoadImg'] == 1: for imgsrc in contentselector.xpath("//img/@src"): if imgsrc is not None and len(imgsrc) > 0: cache.rpush('link-img', imgsrc) proto, rest = splittype(imgsrc) res, rest = splithost(rest) propertys[key] = propertys[key].replace( imgsrc, imgsrc.replace(res, 'img.zyai.top')) logging.info('push a img link to queue %s .' % imgsrc) else: item = selector.xpath(item)[0] propertys[key] = item dataPersistenceType = spider.args['DataPersistenceType'] if dataPersistenceType == 'WPRPC': wp = Client('http://tech.cocopass.com/xmlrpc.php', 'admin', '19841204') """ 发表博文 """ post = WordPressPost() post.title = propertys['title'].encode('utf-8') post.content = propertys['content_raw'].encode('utf-8') post.post_status = 'publish' post.terms_names = {'post_tag': [post.title], 'category': ['爱好']} wp.call(NewPost(post)) logging.info('successfully post one article: %s .' % propertys['title']) elif dataPersistenceType == 'MYSQL': pass
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True): html = getPage(url, "page1.html") os.remove('pages/page1.html') title = html.select('h1')[0].text first_para = html.select('.story-content > p:nth-of-type(1)')[0].text second_para = html.select('.story-content > p:nth-of-type(2)')[0].text try: image = html.select('.image > img')[0].get('src') except Exception: image = None wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password') if image: filename = 'http://www.livemint.com' + image path = os.getcwd() + "\\00000001.jpg" f = open(path, 'wb') f.write(urllib.urlopen(filename).read()) f.close() # prepare metadata data = { 'name': 'picture.jpeg', 'type': 'image/jpeg', # mimetype } with open(path, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) post = WordPressPost() post.title = title post.user = 14 post.post_type = "post" post.content = first_para + '\n' + '\n' + second_para if d: post.post_status = "draft" else: post.post_status = "publish" if image: attachment_id = response['id'] post.thumbnail = attachment_id post.custom_fields = [] post.custom_fields.append({ 'key': 'custom_source_url', 'value': url }) if cat1: cat1 = wp.call(taxonomies.GetTerm('category', cat1)) post.terms.append(cat1) if cat2: cat2 = wp.call(taxonomies.GetTerm('category', cat2)) post.terms.append(cat2) if cat3: cat3 = wp.call(taxonomies.GetTerm('category', cat3)) post.terms.append(cat3) addpost = wp.call(posts.NewPost(post))
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 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 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 upload(name, title): client = Client("http://domain.com/xmlrpc.php", "username", "password") imgfile = os.path.join(DATA_DIR, name) # imgfile = 'op/%s'%name data = {"name": name, "type": "image/jpg"} with open(imgfile, "rb+") as imag: data["bits"] = xmlrpc_client.Binary(imag.read()) response = client.call(media.UploadFile(data)) attachment_id = response["id"] _title = lxml.html.fromstring(title).text post = WordPressPost() post.title = _title post.post_status = "publish" post.thumbnail = attachment_id post.comment_status = "open" post.id = client.call(posts.NewPost(post))
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)
class EzinearticlesPipeline(object): def __init__(self): super(EzinearticlesPipeline, self).__init__() self.wordpress = Client('http://www.aixs.me/xmlrpc.php', 'admin', '861122zlc') self.spin = ArticleSpin(settings.GLOSSARY_FILE) def process_item(self, item, spider): if spider.name != 'ezinearticles': return item cate_reg = re.compile(r'(Hair|Skin|Beauty|Back|Weight|Womens|Popular|Sleep|Fitness|Drug|Anti)', re.DOTALL) m = cate_reg.match(''.join(item['category'])) if not m: raise DropItem('no the category i want') postid = self.wordpress.call(NewPost(self.buildPost(item))) log.msg('Ohhh... has post the %s' % item['title']) return item def buildPost(self, item): post = WordPressPost() post.title = self.spin.spin(item['title']) post.content = self.spin.spin(item['content']) post.excerpt = self.spin.spin(item['excerpt']) terms = [] for x in item['tag'].split(','): x = x.strip() if len(x) != 0: terms.append(x) if len(terms) == 0: terms.append(item['category']) post.terms_names = { 'post_tag': terms, 'category': item['category'], } return post
def posting(): wp = Client('<YOURWORDPRESSSIT>/xmlrpc.php','YOURUSERNAME','YOURPASSWORD') #publish_date = (publish, '%a %b %d %H:%M:%S %Y %z') post = WordPressPost() post.title = title #Commit Title post.content = description #Commit message post.post_status = 'publish' post.terms_names = { 'category': ['12SDD'] } #post.date = publish_date #Creates a new wordpress post and posts it on the site. wp.call(NewPost(post))
class PostGrabber: def __init__(self): self.client = Client(settings.WORDPRESS_URL, settings.WORDPRESS_USER, settings.WORDPRESS_PASSWORD) self.wp_posts = [] self.posts = [] self.filter = [] def getAllWpPosts(self): self.wp_posts = self.client.call(GetPosts()) return self.wp_posts def getAllPosts(self, refresh=False): if len(self.wp_posts) == 0 or refresh == True: tempPosts = self.getAllWpPosts() self.posts = render_posts(tempPosts) return self.posts def getPostsByTag(self, tag, refresh=False): if len(self.wp_posts) == 0 or refresh == True: tempPosts = self.getAllWpPosts() else: tempPosts = self.wp_posts filteredWpPosts = [] for post in tempPosts: for term in post.terms: if term.name == tag: filteredWpPosts.append(post) break self.filter = render_posts(filteredWpPosts) return self.filter
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 blog_content(title,content,tage,category): passwd="" wp = Client('http://123.206.66.55/xmlrpc.php', 'admin', passwd) """ 发表博文 """ post = WordPressPost() post.title = title post.content = content post.post_status = 'publish' print tage post.terms_names = { 'post_tag': tage, 'category': category } wp.call(NewPost(post))
def publish(pic, title, content): ''' ''' attachment = upload(pic) wp_client = Client(rpc_service_url, user, password) post = WordPressPost() post.title = title post.content = '%s\n\n<a href="%s"><img class="alignnone size-full wp-image-%s" alt="%s" src="%s" /></a>' % (content, attachment["url"], attachment["id"], attachment["file"], attachment["url"]) #post.tags='test, test2' #post.categories=['pet','picture'] post.thumbnail = attachment["id"] #change status to publish post.id = wp_client.call(posts.NewPost(post)) post.post_status = 'publish' wp_client.call(posts.EditPost(post.id, post)) return post.id
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 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 _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 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 setUp(self): wp = Client('http://lightcastletech.wordpress.com/xmlrpc.php', '*****@*****.**', settings.WORDPRESS_PASS) self.all_posts = wp.call(GetPosts({'number': 100, 'post_status': 'publish'})) self.authors = wp.call(GetAuthors()) self.all_posts = self.all_posts[::-1] #reverse the list of posts so that the most recent are last in the list for post in self.all_posts: for author in self.authors: if author.id == post.user: post.author = author.display_name # following line sets the image variable so the posts index can display right if blog._get_first_image(post.content) != "None": post.image = blog._get_first_image(post.content) else: post.image = "" b = blog.Blog( title = post.title, author = post.author, initial_image = post.image, date = post.date, content = post.content) b.save()
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 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 WordPressPostingRobot(object): def __init__(self, site, user, password=""): if password == "": password = raw_input('Please enter the password for the user %s: ' % user) self.additional_tags = raw_input('Please enter additional tags to give to all the posts: ') self.__wp = Client(site, user, password) #wp.call(GetUserInfo()) def post_new(self, title, content, categories = ['Mac OS X'], individual_tags = '', status = 'private', date = dt.datetime.now()): post = WordPressPost() post.title = title post.description = content tags = 'automatically posted' if (self.additional_tags == '') else self.additional_tags + ', automatically posted' tags = individual_tags + tags post.tags = tags post.date_created = date post.post_status = status post.categories = categories self.__wp.call(NewPost(post, True))