def post(self, post): """ Upload post to wp :type post: WordPressPost """ #TODO: maybe required to make counter and make not more then 10-15 attempts not to loop forever log.info(f"Publishing to {self.url}: {post.title} ...") is_error = True attempts_num = 0 while is_error and attempts_num <= ATTEMPTS_LIM: try: attempts_num += 1 self.get_client().call(posts.EditPost(post.id, post)) is_error = False log.info(f"Published to {self.url}: {post.title}") except (ServerConnectionError, ProtocolError, http.client.CannotSendRequest, http.client.ResponseNotReady, http.client.CannotSendHeader) as e: time.sleep(random.uniform(1, 3)) except socket.timeout as e: log.info("some error") if is_error and attempts_num > ATTEMPTS_LIM: log.error(f'Problem uploading post to {self.url}: {post.title}') raise ConnectionError( f'Problem uploading post to {self.url}: {post.title}')
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 send_to_wordpress(id, title, categories, tags, content, configuration): if len(content.strip()) == 0: return client = get_client(configuration) if id: post = client.call(posts.GetPost(id)) pass else: post = WordPressPost() post.content = content if title is not None: post.title = title if post.title is None: post.title = 'My post' post.terms_names = { 'post_tag': tags, 'category': categories, } if id: client.call(posts.EditPost(post.id, post)) else: post.id = client.call(posts.NewPost(post)) print("Blog post with id " + post.id + " was successfully sent to WordPress.") return post.id
def unpublishPost(self, post_id): ''' make the post draft, so it's not published ''' post = self.getThePost(post_id) post.post_status = 'draft' self.wordpress.call(posts.EditPost(post.id, post))
def update_authors_page(self): pages = self._client.call( posts.GetPosts({'post_type': 'page'}, results_class=wordpress_xmlrpc.WordPressPage)) authors_page = [page for page in pages if page.title == 'Authors'][0].id authors_count = {} for i in itertools.count(0, 10): some_posts = self._client.call( posts.GetPosts({ 'number': 10, 'offset': i })) if len(some_posts) == 0: break # no more posts returned for post in some_posts: for term in post.terms: if term.taxonomy == 'post_tag': author = term.name authors_count[author] = authors_count.get(author, 0) + 1 links = [ '<a href="https://mathematicaldeliberations.wordpress.com/tag/{}/">{} - {} posts</a>' .format(name.lower().replace(' ', '-'), name, count) for name, count in authors_count.items() ] rec = wordpress_xmlrpc.WordPressPage() rec.title = 'Authors' rec.content = '<div style="direction: ltr; text-align: left;"><ul>\n' + \ '\n'.join(['<li style="text-align: left;">{}</li>'.format(link) for link in links]) + \ '\n</ul></div>' self._client.call(posts.EditPost(authors_page, rec))
def editPost(filename, post_id): post = parseDocument(filename) client = initClient() oldRawFilename = filename[:-3] + '.raw.id-' newRawFilename = filename[:-3] + '.raw.id-' + str(post_id) os.rename(oldRawFilename, newRawFilename) return client.call(posts.EditPost(post_id, 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)
def pedir_datos_nueva_entrada(): limpiar_pantalla() nueva_entrada = WordPressPost() nueva_entrada.title = input("Ingresa el título de la entrada: ") nueva_entrada.content = input("Ingresa todo el contenido de la entrada: ") etiquetas = [] categorias = [] eleccion = input("¿Deseas agregar etiquetas? [S/N] ") if eleccion.lower() == "s": etiquetas = input("Ingresa las etiquetas separadas con comas: ").split(",") eleccion = input("¿Deseas agregar categorías? [S/N] ") if eleccion.lower() == "s": categorias = input("Ingresa las categorías separadas con comas: ").split(",") nueva_entrada.terms_names = { 'post_tag': etiquetas, 'category': categorias, } print("Publicando entrada...") id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada)) limpiar_pantalla() print("Correcto! Se guardó la entrada como borrador, y su id es {}".format(id_entrada_publicada)) eleccion = input("¿Publicar inmediatamente? [S/N] ") if eleccion.lower() == "s": print("Publicando entrada...") nueva_entrada.post_status = 'publish' resultado = cliente.call(posts.EditPost(id_entrada_publicada, nueva_entrada)) if resultado is True: input("Entrada publicada") else: input("Algo salió mal") imprimir_menu_opciones()
def callback(ch, method, properties, body): print(body) if str(body).startswith("[wordpress]") and len(str(body)) < 300: query = str(body)[11:] q = query.split('-') nueva_entrada = WordPressPost() nueva_entrada.title = q[0] nueva_entrada.content = q[1] id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada)) print("Correcto! Se guardó la entrada como borrador, y su id es {}". format(id_entrada_publicada)) print("Publicando entrada...") nueva_entrada.post_status = 'publish' resultado = cliente.call( posts.EditPost(id_entrada_publicada, nueva_entrada)) print(resultado) if resultado is True: print("Entrada publicada") else: print("Algo salió mal") ########## PUBLICA EL RESULTADO COMO EVENTO EN RABBITMQ ########## channel.basic_publish(exchange='donbot', routing_key="publicar_slack", body="publicado!")
async def normal_handler(event): post = WordPressPost() msg = event.message.to_dict() fwd_channel_name = (await client.get_entity( PeerChannel(msg['fwd_from']['channel_id']))).username title, content = tit_le(msg) post.title = '@' + fwd_channel_name + ': ' + title post.content = content post.id = wp.call(posts.NewPost(post)) post.post_status = 'publish' # add image # set to the path to your file try: filename = (await event.message.download_media()) data = { 'name': 'picture.jpg', 'type': 'image/jpeg', # mimetype } with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] post.thumbnail = attachment_id # delete pictures remove(filename) except: print("with out pictures") wp.call(posts.EditPost(post.id, post))
def test_revisions(self): original_title = 'Revisions test' post = WordPressPost() post.title = original_title post.slug = 'revisions-test' post.content = 'This is a test post using the XML-RPC API.' post_id = self.client.call(posts.NewPost(post)) self.assertTrue(post_id) post.title = 'Revisions test updated' post.content += ' This is a second revision.' response = self.client.call(posts.EditPost(post_id, post)) self.assertTrue(response) # test wp.getRevisions revision_list = self.client.call(posts.GetRevisions(post_id, ['post'])) self.assert_list_of_classes(revision_list, WordPressPost) # workaround for WP bug #22686/22687 # an auto-draft revision will survive wp.newPost, so pick the 2nd revision self.assertEqual(2, len(revision_list)) real_rev = revision_list[1] self.assertTrue(real_rev) self.assertNotEquals(post_id, real_rev.id) # test wp.restoreRevision response2 = self.client.call(posts.RestoreRevision(real_rev.id)) self.assertTrue(response2) post2 = self.client.call(posts.GetPost(post_id)) self.assertEquals(original_title, post2.title) # cleanup self.client.call(posts.DeletePost(post_id))
def publishPost(self, post_id): ''' publish the post with post id ''' post = self.wordpress.call(posts.GetPost(post_id)) post.post_status = 'publish' self.wordpress.call(posts.EditPost(post.id, post))
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 test_post_lifecycle(self): # create a post object post = WordPressPost() post.title = 'Test post' post.slug = 'test-post' post.content = 'This is test post using the XML-RPC API.' post.comment_status = 'open' post.user = self.userid # create the post as a draft post_id = self.client.call(posts.NewPost(post)) self.assertTrue(post_id) # fetch the newly-created post post2 = self.client.call(posts.GetPost(post_id)) self.assertTrue(isinstance(post2, WordPressPost)) self.assertEqual(str(post2.id), post_id) # update the post post2.content += '<br><b>Updated:</b> This post has been updated.' post2.post_status = 'publish' response = self.client.call(posts.EditPost(post_id, post2)) self.assertTrue(response) # delete the post response = self.client.call(posts.DeletePost(post_id)) self.assertTrue(response)
def updateBlog(self): with open('已发布的漫画列表.csv', 'r', encoding='UTF-8') as csv_file: csv_reader_lines = csv.reader(csv_file) for blog in csv_reader_lines: post = WordPressPost() post.post_status = 'draft' self.wp.call(posts.EditPost(blog[1], post))
def test_category_post(self): # create a test post post = WordPressPost() post.title = 'Test Post' post.slug = 'test-post' post.user = self.userid post.id = self.client.call(posts.NewPost(post)) # create a test category cat = WordPressTerm() cat.name = 'Test Category' cat.taxonomy = 'category' cat.id = self.client.call(taxonomies.NewTerm(cat)) # set category on post try: post.terms = [cat] response = self.client.call(posts.EditPost(post.id, post)) self.assertTrue(response) # fetch categories for the post to verify post2 = self.client.call(posts.GetPost(post.id, ['terms'])) post_cats = post2.terms self.assert_list_of_classes(post_cats, WordPressTerm) self.assertEqual(post_cats[0].id, cat.id) finally: # cleanup self.client.call(taxonomies.DeleteTerm(cat.taxonomy, cat.id)) self.client.call(posts.DeletePost(post.id))
def testEdit(): #testUpdate(2669) post = parseDocument('posts/binding-domain-to-plugin-of-mobile-theme.md') # post.id = 2659 # post.post_status = 'publish' client = initClient() #print client.call(posts.EditPost(2669, testReturnPost() )) print client.call(posts.EditPost(2659, post))
def testUpdate(pid): client = initClient() post = WordPressPost() post.title = 'My new title update 2' post.content = 'This is the body of my new post.' post.slug = 'helloword' post.post_type = 'post' post.post_status = 'draft' print client.call(posts.EditPost(pid, 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 prependToPage(self, page, theString): # put new content at the front. page.content = theString + page.content page.post_status = 'publish' page.thumbnail = None # magic : avoid 'Invalid attachment ID.' exception from EditPost try: self.client.call(posts.EditPost(page.id, page)) except Exception as inst: print 'uploadMedia: posts.EditPost() failed', inst
def add_post(self, title, text, category): post = WordPressPost() post.title = title post.content = text post.terms_names = { 'category': [category], } post.id = self._client.call(posts.NewPost(post)) post.post_status = 'publish' self._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 update_post_wp(self, wp_post_id): """ Update post with id in WordPress. :param wp_post_id: post id """ post = self.client.call(posts.GetPost(wp_post_id)) if not post: raise ResourceError("Post not found, id: {}.".format(wp_post_id)) key_assoc = { "city": "city_id", "coordinates_lat": "latitude", "coordinates_long": "longitude", "geo_hash_id": "geo_hash_id", "rate": "rate", "place_id": "place_id", "address": "address_coord" } post_custom_fields = CustomFields(post.custom_fields, key_assoc) custom_fields_unpacked = post_custom_fields.unpack() try: location = [] location_unserialized = custom_fields_unpacked["city_id"] for loc in location_unserialized: term = self.client.call( taxonomies.GetTerm("locations", int(loc))) location.append(term) break except KeyError: pass db_post = self.connection.get( InterestPoint, { "latitude": custom_fields_unpacked["latitude"], "longitude": custom_fields_unpacked["longitude"] }) if not db_post: db_post = self.connection.get(InterestPoint, {"title": post.title}) if not db_post: raise MissingResourceError( "InterestPoint not found for post with id: {}.".format( post.id)) dict_post = post.__dict__() post_diff = self.prejudice_diff(post, db_post) new_post_data = WordPressPost() new_post_data.custom_fields = [] self.client.call(posts.EditPost(post.id, new_post_data)) exit()
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 EditPost(WpPost=None): Bj = WpC.WB.Bj if WpPost.id <= 1 or not isinstance(WpPost.id, int): raise ValueError('EditPost: WpPost.id must be a positive integer!') # PrePost = Bj.WpCli.call(posts.GetPost( WpPost.id )) # L.info("\nWpPost.id:{}, Before Edit:", WpPost.id) # PrintPostDetails( PrePost ) # Better PPrint( vars( WpPost )) EditSuccess = Bj.WpCli.call(posts.EditPost(WpPost.id, WpPost)) L.info("\nWpPost.id= {}, Edit Success= {}", WpPost.id, EditSuccess) # EditedPost = Bj.WpCli.call(posts.GetPost (WpPost.id )) # PrintPostDetails( EditedPost ) # Better PPrint( vars(WpPost)) return EditSuccess
def post_page(wpUrl, wpUserName, wpPassword, articleTitle, articleContent, pageId): # This function updates/creates a page in a wordpress site client = Client(wpUrl, wpUserName, wpPassword) # Page page = WordPressPage() page.title = articleTitle page.content = articleContent # page.terms_names = {'post_tag': articleTags, 'category': articleCategories} page.post_status = 'publish' # post.thumbnail = attachment_id client.call(posts.EditPost(int(pageId), page)) return pageId
def _edit_post(self, page): try: self.getClient().call(posts.EditPost(page.id, page)) log.info("Updated wordpress page with id: " + page.id) except ConnectionResetError as e: log.critical("HTTP Wordpress Client: {msg}".format(msg=e)) sys.exit(4) except Exception as e: log.critical( "Unexpected error: {msg}".format(msg=sys.exc_info()[0])) log.debug("Skipping... {page_id}".format(page_id=page.id)) return False return True
def publish_posts(self, processed_posts: Iterable[WordPressPost]): post_id_by_title = self._get_post_id_by_title() operation = "null" for post in processed_posts: if post.title in post_id_by_title: post.id = post_id_by_title[post.title] operation = "creating" else: post.id = self._client.call(posts.NewPost(post)) operation = "updating" post.post_status = self._post_status LOG.info(f"{operation} post {post.title}, post id {post.id}") self._client.call(posts.EditPost(post.id, post))
def updatePost(self): blog_list = self.wp.call( posts.GetPosts({ 'offset': 0, 'number': 661, 'post_status': 'publish' })) for blog in blog_list: post = WordPressPost() post.title = blog.title post.post_status = 'draft' print('当前编辑文章:', blog.title) self.wp.call(posts.EditPost(blog.id, post))
def edit_post(wp_post_id): user = current_user client = check_login(user.wp_url, user.wp_username, login_session['pw']) if request.method == 'POST': edit_wp_post = WordPressPost() edit_wp_post.title = request.form['title'] edit_wp_post.content = request.form['content'] edit_wp_post.id = wp_post_id edit_wp_post.status = 'publish' client.call(posts.EditPost(edit_wp_post.id, edit_wp_post)) flash('Post edited successfully') return redirect(url_for('get_posts')) else: return render_template('posts/editpost.html', wp_post_id=wp_post_id)