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 make_wp_content(hotitem): format_cont = Template(post_template) # format_cont.substitute(shop = u"天猫", img=hotitem["goods_pic"]) post = WordPressPost() post.title = hotitem["goods_title"] post.content = hotitem["goods_introduce"] # post.post_type = "tbkitem" iteminfo = json.dumps(hotitem) post.custom_fields = [{"key": "iteminfo", "value": iteminfo}] # post.thumbnail = hotitem["goods_pic"] post.content = format_cont.substitute( shop=hotitem["platform"].decode("utf8"), introduce=hotitem["goods_introduce"], origin_price=hotitem["origin_price"], quan_price=hotitem["zhekou_price"], now_price=float(hotitem["origin_price"]) - float(hotitem["zhekou_price"]), tbk_link_quan=hotitem["tbk_link_quan"], img=hotitem["goods_pic"]) post.terms_names = { 'post_tag': hotitem["tag"], 'category': hotitem["category"], } post.post_status = "publish" return post
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 process_item(self, item, spider): wp = Client('https://www.along.party/xmlrpc.php', '', '') post = WordPressPost() post.title = item['title'] post.user = item['author'] post.link = item['url'] # post.date = item['publish_time'] post.content = item['body'] post.content = u"%s \n 本文转载自 <a href='%s'> %s</a> " % ( item['body'], item['url'], item['title']) post.post_status = 'publish' post.terms_names = {'post_tag': 'Python', 'category': 'Python'} wp.call(NewPost(post))
def post_article(self, wordpress_link, wordpress_id, wordpress_pass, articletitle, articlecategories, articlecontent, articletags, imagelink=None): if imagelink: self.path = os.getcwd() + "\\00000001.jpg" self.articlePhotoUrl = imagelink self.wpUrl = wordpress_link self.wpUserName = wordpress_id self.wpPassword = wordpress_pass # 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 else: self.wpUrl = wordpress_link self.wpUserName = wordpress_id self.wpPassword = wordpress_pass # Upload to WordPress client = Client(self.wpUrl, self.wpUserName, self.wpPassword) # Post post = WordPressPost() post.title = articletitle post.content = articlecontent post.terms_names = {'post_tag': articletags, 'category': articlecategories} post.post_status = 'publish' post.id = client.call(posts.NewPost(post)) print 'Post Successfully posted. Its Id is: ', post.id
def process_button(site, camera): # check github directories and make sure they match whats stored locally # if directories match: newFaceRecognizer._smile321() camera.capture('test_image.jpg') print("Picture taken!") filepath = 'test_image.jpg' data = {'name': 'test_image.jpg', 'type': 'image/jpeg'} with open(filepath, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = site.call(media.UploadFile(data)) attachment_id = response['id'] yay = WordPressPost() yay.title = 'Picture Time!' yay.content = 'Lookin\' snazzy' d = date.today().strftime("%b-%d-%Y") yay.terms_names = {'post_tag': [d], 'category': ['Successful Login']} yay.post_status = 'publish' yay.thumbnail = attachment_id site.call(posts.NewPost(yay)) camera.close() # call cv2 script for unlocking the box id, conf = newFaceRecognizer.checkUser() if conf >= 45 and id not in newFaceRecognizer.getBannedUsers(): # call servo unlock fxn unlock_servo()
def build_news_message(news): post = WordPressPost() post.title = news.brief_comment converted_video_url = None if news.video_url is not None: converted_video_url = convert_youku_video_url(news.video_url) content_items = {'content' : _normalize_content(news.recommended_reason)} if news.screenshot_path_1: content_items['screenshot_path_1'] = settings.MEDIA_URL + news.screenshot_path_1.name if news.screenshot_path_2: content_items['screenshot_path_2'] = settings.MEDIA_URL + news.screenshot_path_2.name if news.screenshot_path_3: content_items['screenshot_path_3'] = settings.MEDIA_URL + news.screenshot_path_3.name if news.screenshot_path_4: content_items['screenshot_path_4'] = settings.MEDIA_URL + news.screenshot_path_4.name content_items['video_url'] = converted_video_url post.content = str(render_to_string('news_web.tpl', content_items)) post.terms_names = { 'category' : [u'新游预告'] } if news.screenshot_path_1.name != '': post.custom_fields = [] post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + news.screenshot_path_1.name}) post.post_status = 'publish' return WebMessage(news.id, post)
def build_game_message(game): post = WordPressPost() post.title = '%s - %s' % (game.name, game.brief_comment) converted_video_url = None if game.video_url is not None: converted_video_url = convert_youku_video_url(game.video_url) post.content = str(render_to_string('game_web.tpl', { 'content' : _normalize_content(game.recommended_reason), 'icon' : settings.MEDIA_URL + game.icon.name, 'category' : game.category.name, 'size' : game.size, 'platforms' : _get_game_platforms(game), 'id' : game.id, 'android_download_url' : game.android_download_url, 'iOS_download_url' : game.iOS_download_url, 'screenshot_path_1' : settings.MEDIA_URL + game.screenshot_path_1.name, 'screenshot_path_2' : settings.MEDIA_URL + game.screenshot_path_2.name, 'screenshot_path_3' : settings.MEDIA_URL + game.screenshot_path_3.name, 'screenshot_path_4' : settings.MEDIA_URL + game.screenshot_path_4.name, 'video_url' : converted_video_url })) post.terms_names = { 'category' : [game.category.name], 'post_tag' : _get_game_tags(game) } if game.screenshot_path_1.name != '': post.custom_fields = [] post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + game.screenshot_path_1.name}) post.post_status = 'publish' return WebMessage(game.id, post)
def build_evaluation_message(evaluation): post = WordPressPost() post.title = evaluation.title post.content = str(render_to_string('evaluation_web.tpl', { 'id' : evaluation.id, 'content' : _normalize_content(evaluation.recommended_reason), 'icon' : settings.MEDIA_URL + evaluation.icon.name, 'platforms' : _get_game_evaluation_platforms(evaluation), 'android_download_url' : evaluation.android_download_url, 'iOS_download_url' : evaluation.iOS_download_url, 'evaluation_content' : evaluation.content, 'rating' : evaluation.rating, })) post.terms_names = { 'category' : [u'游戏测评'], 'post_tag' : _get_game_evaluation_tags(evaluation) } if evaluation.icon.name != '': post.custom_fields = [] post.custom_fields.append({'key':'post_image','value':settings.MEDIA_URL + evaluation.icon.name}) post.post_status = 'publish' return WebMessage(evaluation.id, post)
def build_collection_message(collection): post = WordPressPost() post.title = collection.title games = [] for game in collection.games.all(): games.append({ 'name' : game.name, 'brief_comment' : game.brief_comment, 'icon' : settings.MEDIA_URL + game.icon.name, 'category' : game.category.name, 'size' : game.size, 'platforms' : _get_game_platforms(game), 'id' : game.id, 'android_download_url' : game.android_download_url, 'iOS_download_url' : game.iOS_download_url, 'rating' : game.rating, 'recommended_reason' : _normalize_content(game.recommended_reason) }) post.content = str(render_to_string('collection_web.tpl', { 'content' : _normalize_content(collection.recommended_reason), 'cover' : settings.MEDIA_URL + collection.cover.name, 'games' : games })) post.terms_names = { 'category' : [u'游戏合集'] } post.post_status = 'publish' return WebMessage(collection.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 post_to_wordpress(self, story): # Get number of posts to number the story title, i.e. if this is the 6th story # that will get posted the title will be "Story 6" print "Retrieving posts" # get pages in batches of 20 num_of_post = 0 offset = 0 increment = 20 while True: posts_from_current_batch = self.wp.call(posts.GetPosts({'number': increment, 'offset': offset})) if len(posts_from_current_batch) == 0: break # no more posts returned else: num_of_post += len(posts_from_current_batch) offset = offset + increment print num_of_post # Create new post print "Creating new post..." post = WordPressPost() post.title = 'Story %d' % (num_of_post + 1) # incrementing the number of post by 1 # convert each sentence to string, and join separated by a space. post.content = " ".join(map(str, story)) post.id = self.wp.call(posts.NewPost(post)) # publish it print "Publishing" post.post_status = 'publish' self.wp.call(posts.EditPost(post.id, post)) print "Done!"
def Publish_Post(title,body): # Connect to Word Press POST API obj=setup('https://hackingjournalismtest.wordpress.com/xmlrpc.php', 'contentmagicalsystem','aA9&cG^%wqSkd7MxHU@PYT72c&h') post = WordPressPost() if len(title) == 0 : raise("Cant Process the request") return "Empty title requested" if len(body) == 0: rasie("Cant Process the request") return "Empty body requested" ''' Future or Next in line Better data validations Have some other quality checks for non ascii charecters and valdiate unicode letters if required Request type validation (old vs new) check if title already exist and update postif required ''' post.title=title post.content=body # Make post visible ,status should be publish post.post_status = 'publish' # API call to push it to word press post.id=wp.call(NewPost(post)) #return "Post created with id ",post.id return post.id
def postToWordpress(text, thisDay, wp): """Publishes the blog post to WordPress. Arguments: text -- HTML text body of the post. thisDay -- The date of the post, which will also become the title. Return: post.title -- The title of the WordPress post. True / False -- Whether or not the post was successfully posted. """ post = WordPressPost() post.title = dateToString(thisDay) post.content = text post.date = (thisDay + datetime.timedelta(0,0,0,0,30,23)) # 6:30pm, EST post.post_status = 'publish' post.terms_names = { 'post_tag': ['Journal Entry', 'Food'], 'category': ['Journal'] } try: wp.call(NewPost(post)) except: return (post.title,False) return (post.title, True)
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 insert_post(self, joomla_post, category_id): client = self.get_client() post = WordPressPost() post.title = joomla_post.get_title() text_to_replace = joomla_post.get_introtext() text_to_replace = str(text_to_replace).replace("href=\"images/", "href=\"/images/") post.content = str(text_to_replace).replace("src=\"images/", "src=\"/images/") post.date = joomla_post.get_created() post.thumbnail = self.post_thumbnail(joomla_post.get_id())['id'] post.post_status = "publish" category = client.call(taxonomies.GetTerm('category', category_id)) post.terms.append(category) client.call(NewPost(post)) return post
def create_post(title, text="", url="", image_url=""): shortened_url = shorten_link(url) if url else "" url_html = "<a href='{shortened_url}'>{url}</a><br/>".format(url=url, shortened_url=shortened_url) if url else "" image_html = "<img style='width: 100%; height: auto;' src='{image_url}'></img><br/>".format(image_url=image_url) if image_url else "" text_html = "<p>" + text + "</p>" + "<br/>" if text else "" content = url_html + image_html + text_html # https://developer.wordpress.com/docs/api/1.1/post/sites/%24site/posts/new/ # http://python-wordpress-xmlrpc.readthedocs.org/en/latest/examples/posts.html post = WordPressPost() post.title = title post.content = content post.author = "testaccount" post.post_status = "publish" # post.terms_names = { # 'post_tag': ['test', 'firstpost'], # 'category': ['Introductions', 'Tests'] # } try: redditsync.wordpress.wp.call(NewPost(post)) except Exception as err: logging.error(str(err)) sys.exit()
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 newPost(title, content, tags, cats): post = WordPressPost() post.title = title post.content = content #post.post_status = 'publish' post.terms_names = {'post_tag': tags, 'category': cats} wp.call(NewPost(post))
def postWordpress(item): post = WordPressPost() post.title = item.title post.content = item.movieUrl if item.category == "": post.terms_names = {'post_tag': item.tags} else: category = [] category.append(item.category) post.terms_names = {'post_tag': item.tags, 'category': category} post.slug = '[input your prameter]' # 投稿時間 # 現在時間で投稿 post.date = datetime.now() # 予約投稿の場合(例:2017年2月2日0時0分0秒0マイクロ秒) #month = random.randint(1,10) #day = random.randint(1,22) #post.date = datetime(2018, month, day, 0, 0, 0, 0) # 投稿する。 # ステータスを公開済にする。 post.post_status = 'publish' # これなら下書き指定 # post.post_status = 'draft' post.thumbnail = getMediaId(item) wp.call(NewPost(post))
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 createPost(image): localFilename = 'images/{0}'.format(image + '.jpg') print 'image is: {0}'.format(localFilename) imageTimestamp = getTimestamp(image) wpFilename = image + imageTimestamp + '.jpg' data = { 'name': '{0}'.format(wpFilename), 'type': 'image/jpeg', } with open(localFilename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) print 'response is: {0}'.format(response) month = strftime("%m", gmtime()) post = WordPressPost() post.title = country + city post.content = '[caption id="" align="alignnone" width ="640"]<img src="http://www.backdoored.io/wp-content/uploads/2016/' + month + '/' + wpFilename.replace(":", "") + '">' + ipAddress + hostnames + isp + timestamp + country + city + '[/caption]' post.id = client.call(NewPost(post)) post.post_status = 'publish' client.call(EditPost(post.id, post))
def publish(self, title, content): post = WordPressPost() post.title = title post.content = content post.post_status = 'publish' # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布 post.terms_names = { 'post_tag': ['news'], # 文章所属标签,没有则自动创建 'category': ['news'], # 文章所属分类,没有则自动创建 } post.custom_fields = [] post.custom_fields.append({ 'key': '_aioseop_keywords', 'value': self.keywords }) post.custom_fields.append({ 'key': '_aioseop_description', 'value': self.description }) post.custom_fields.append({ 'key': '_aioseop_title', 'value': self.title }) post.id = self.wp.call(posts.NewPost(post))
def post(self): filename = "linuxlogo.jpg" data = { 'name': 'linuxlogo.jpg', 'type': 'image/jpeg', } with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) r = self.wp_client.call(media.UploadFile(data)) attachment_id = r['id'] #Create random content in range of 1000 letters s = np.random.uniform(0, 1, size=2) s1 = int(s[0] * self.conf.post_nchars + 1) s2 = int(s[1] * self.conf.post_title_nchars + 1) content = "".join([random.choice(string.letters) for i in xrange(s1)]) random_title = "".join( [random.choice(string.letters) for i in xrange(s2)]) post = WordPressPost() post.title = 'Random title: ' + random_title post.content = content post.post_status = 'publish' post.thumbnail = attachment_id post.terms_names = { 'post_tag': ['test', 'firstpost'], 'category': ['Uncategorized'] } return self.wp_client.call(NewPost(post))
def create_post(self, title, content, post_format='image', tag=None, category=None, thumnnail_path=None): post = WordPressPost() post.title = title post.content = content post.comment_status = 'open' post.post_format = post_format # image,video,0 post.post_status = 'publish' # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布 post.terms_names = { 'post_tag': tag #['test', 'beauty'], 文章所属标签,没有则自动创建 , 'category': category #['校园美女'] 文章所属分类,没有则自动创建 } if thumnnail_path is None: post.thumbnail = None elif thumnnail_path.startswith('http'): post.thumbnail = self.add_external_image(thumnnail_path) else: post.thumbnail = self._find_media(thumnnail_path) # 缩略图的id try: self.wp.call(posts.NewPost(post)) except Exception as e: print(e)
def createMP3Post(self, presenter, title, reference, date_str, media_url, verbose=False): if verbose: print 'createMP3Post starting' post = WordPressPost() titleTemplate = u"""Podcast : {0} : {1} - {2}""" title = title.encode('ascii','ignore') post.title = titleTemplate.format(date_str, presenter, title) template = u"""[audio "{4}" ]<p>{0} : {1} - {2} - {3}</p>""" post.content = template.format(date_str, presenter, title, reference, media_url) post.post_status = 'publish' # set the category so this Post is inserted into our 'podcast' feed post.terms_names = {'category': [self.feed_category,]} post.post_format = 'Link' retval = None try: print ' post = ', post print 'post.content =', post.content retVal = self.client.call(posts.NewPost(post)) except Exception as inst: print 'createMP3Post: posts.NewPost() failed', inst else: if verbose: print 'createMP3Post complete' return retVal
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()
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 detail_page(self, response): title = response.doc('h1').text(), texts = str(response.doc('.loadimg.fadeInUp > p')) #获取所有的HTML标签和内容 texts = texts.replace("https://www.ttfhvip.com/d/file", "/downimages") texts = texts.replace("下面我们一起来看看她最新的番号作品吧!", "") texts = texts.replace("点击查看更多番号作品", "") for each in response.doc('.loadimg.fadeInUp > p > img').items(): img_url = each.attr.src if ("ttfhvip" in img_url): #过滤掉不在ttfhvip站点上的图片连接 split_url = img_url.split('/') dir_name = split_url[-2] + '/' dir_path = self.deal.mkDir(dir_name) file_name = split_url[-1] self.crawl(img_url, callback=self.save_img, save={ 'dir_path': dir_path, 'file_name': file_name }) title = ''.join(str(title)) title = title.replace("('", "") title = title.replace("',)", "") wp = Client('http://192.168.2.98/xmlrpc.php', '东京不热郎', 'qaz78963') post = WordPressPost() post.title = title post.content = texts post.post_status = 'draft' #publish-发布,draft-草稿,private-私密 post.terms_names = { 'category': ['素人'] #文章所属分类,没有则自动创建 } post.id = wp.call(posts.NewPost(post))
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 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!")
def new_post(dir_str, photo_name): # prepare metadata category = '未分类' if photo_name.startswith('1__'): category = '清纯' if photo_name.startswith('2__'): category = '性感' data = { 'name': photo_name, 'type': 'image/jpeg', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open('{}/{}'.format(dir_str, photo_name), 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp_clt.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = photo_name[3:-4] post.content = '' post.post_status = 'publish' # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布 post.comment_status = 'open' # 不开启评论则设置成closed post.terms_names = { 'post_tag': ['haole', category], # 文章所属标签,没有则自动创建 'category': ['haole', category] # 文章所属分类,没有则自动创建 } post.thumbnail = attachment_id # 缩略图的id post.id = wp_clt.call(posts.NewPost(post))
def sent_to_wp(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://abc/xmlrpc.php', 'link', '!@#abc') if wp: print('wp link ok') else: print('wp link false') # 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 _unlockPost(user): post = WordPressPost() post.title = 'Box Unlocked' post.content = 'Unlocked by {}'.format(user) post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Successful Login']} post.post_status = 'publish' site.call(posts.NewPost(post))
def doPost(self): post = WordPressPost() # get all post properties post.title = str(unicode(self.lnEdit_PostTitle.text())) post.content = str(unicode(self.txtEdit_PostContent.toPlainText())) tag = unicode(self.lnEditPostTags.text()) category = unicode(self.lnEditPostCategories.text()) # use ',' split multi-tag or category if ',' in tag: tag = tag.split(',') if ',' in category: category = category.split(',') post.terms_names = { 'post_tag': tag, 'category': category } post.post_status = str(self.cb_post_status.currentText()) try: # new post or page-type post if (self._newPost_): post.id = self.wp.call(posts.NewPost(post)) QtGui.QMessageBox.information(self, 'info', "Post success!", QtGui.QMessageBox.Ok) else: print 'edit...' # edit a post if self._postId_ != None: self.wp.call(posts.EditPost(self._postId_, post)) QtGui.QMessageBox.information(self, 'info', "Edit success!", QtGui.QMessageBox.Ok) except Exception, e: QtGui.QMessageBox.information(self, 'err', str(e), QtGui.QMessageBox.Ok)
def post_article(self, wpUrl, wpUserName, wpPassword, articleCategories, path): self.path = path self.wpUrl = wpUrl self.wpUserName = wpUserName self.wpPassword = wpPassword client = Client(self.wpUrl, self.wpUserName, self.wpPassword) filename = self.path try: myFile = open(filename, "r") rawText = myFile.read() rawText = rawText.decode('latin-1') myFile.close() articleTitle = remove_tags(rawText) articleContent = rawText post = WordPressPost() post.title = articleTitle[:90] post.content = articleContent post.terms_names = {'category': articleCategories} post.post_status = 'publish' post.mime_type = "text/html" post.id = client.call(posts.NewPost(post)) print("success : " + os.path.basename(path)) os.remove(path) except (Exception, e): print("error : " + os.path.basename(path)) print(e)
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 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 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 createPost(image): localFilename = 'images/{0}'.format(image + '.jpg') print 'image is: {0}'.format(localFilename) imageTimestamp = getTimestamp(image) wpFilename = image + imageTimestamp + '.jpg' data = { 'name': '{0}'.format(wpFilename), 'type': 'image/jpeg', } with open(localFilename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) print 'response is: {0}'.format(response) month = strftime("%m", gmtime()) post = WordPressPost() post.title = country + city post.content = '[caption id="" align="alignnone" width ="640"]<img src="http://www.backdoored.io/wp-content/uploads/2016/' + month + '/' + wpFilename.replace( ":", "" ) + '">' + ipAddress + hostnames + isp + timestamp + country + city + '[/caption]' post.id = client.call(NewPost(post)) post.post_status = 'publish' client.call(EditPost(post.id, post))
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 _removedUserPost(user): post = WordPressPost() post.title = 'User removed' post.content = 'New User {}'.format(user) post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Remove User']} post.post_status = 'publish' site.call(posts.NewPost(post))
def create_post_from_file(a_file): post = WordPressPost() file_content = get_content_for_file(a_file) match = yaml_match_from_post_data(file_content) yaml_data = extract_yaml_data_using_match(file_content, match) add_meta_info_from_yaml_to_post(yaml_data, post, a_file) post.content = file_content[match.end():].strip() return post
def process_comment(wp, video_id, parent_post_id, comment): post = WordPressPost() post.title = comment['text'][6:50] post.content = get_post_content(video_id,comment) post.post_type = 'video-highlight' post.post_status = 'publish' post.parent_id = parent_post_id #logger.info("Created post with ID [%s]", wp.call(NewPost(post))) print "Created post with ID [%s]" % wp.call(NewPost(post))
def make_post(content, wp): start = datetime.datetime.utcnow() end = start + datetime.timedelta(7) dates = (start.strftime('%b %d'), end.strftime('%b %d')) post = WordPressPost() post.title = "This week's schedule (%s - %s)" % dates post.content = content post.post_status = 'draft' wp.call(NewPost(post))
def postInWordpress(self, title, content, ): post = WordPressPost() post.title = title post.content = content post.post_status = 'publish' post.terms_names = {'post_tag': ['leak', 'pastebin leak', 'hack leak', 'hack'],'category': ['Leaks']} post.id = self.wordpress.call(NewPost(post)) p = self.wordpress.call(GetPosts())[0] return p.link
def prepare_post(event): post = WordPressPost() post.title = event['Headline'] body_string = '''<p id="pagekeeper"><img src='http://free.pagepeeker.com/v2/thumbs.php?size=x&url={}'><br/>{}</p><p>{}</p>'''.format(event["Media"], event["Media Credit"].replace("\n", ""), event["Text"]) post.content = body_string post.date = parser.parse(event['Start Date']) post.terms_names = {'post_tag': [event['Tag']]} post.post_status = 'publish' return 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 build(self, title, content, categories=[], tags=[]): post = WordPressPost() post.title = title post.content = content post.terms_names = { 'post_tag': tags, 'category': categories, } post.post_status = 'publish' return NewPost(post)
def add_post(wp, title, body, category, date): date = datetime.strptime("%s 12:00:00 AM" % date, "%d-%b-%y %I:%M:%S %p") post = WordPressPost() post.title = title post.content = body post.terms_names = { 'category': [category,] } post.date = date post.post_status = 'publish' wp.call(NewPost(post))
def post_file(wp, f, t, y, m, d): p = WordPressPost() p.title = t p.content = slurp(f) # 9am zulu is early Eastern-Pacific p.date = p.date_modified = datetime(y,m,d,9) p.post_status = 'publish' p.comment_status = 'closed' if wp: wp.call(NewPost(p))
def newPost(title, content, tags, cats): post = WordPressPost() post.title = title post.content = content #post.post_status = 'publish' post.terms_names = { 'post_tag': tags, 'category': cats } wp.call(NewPost(post))
def toWordPressPost(self): post = WordPressPost() if self.title: post.title = self.title if self.content: post.content = self.content post.post_status = 'publish' return post
def createPost(self, post_title, post_content): # create draft post = WordPressPost() post.title = post_title post.content = post_content post.id = self.wordpress.call(posts.NewPost(post)) # set status to be update #post.post_status = 'publish' #self.wordpress.call(posts.EditPost(post.id, post)) return post
def create_new_empty_wp_post(component, event_category, event_map_location, location_gps): summary = component.get('SUMMARY').encode('UTF-8', 'backslashreplace') start_event = component.get('DTSTART').dt.strftime('%Y-%m-%d %H:%M') end_event = component.get('DTEND').dt.strftime('%Y-%m-%d %H:%M') end_frequency_event = component.get('DTEND').dt.strftime('%Y-%m-%d') uid = component.get('UID').encode('UTF-8', 'backslashreplace') event_description = component.get('DESCRIPTION') if event_description is None: event_description = " " else: event_description = component.get('DESCRIPTION').encode('UTF-8', 'backslashreplace') # Create a new post new_post = WordPressPost() new_post.title = summary new_post.content = event_description new_post.post_type = "event" new_post.post_status = "publish" new_post.terms_names = {'event-category': [event_category]} new_post.custom_fields = [] meta_adds = (['imic_event_start_dt', start_event], ['imic_event_end_dt', end_event], ['imic_event_frequency_end', end_frequency_event], ['imic_featured_event', 'no'], ['slide_template', 'default'], ['imic_event_day_month', 'first'], ['imic_event_week_day', 'sunday'], ['imic_event_frequency_type', '0'], ['imic_event_frequency', '35'], ['imic_event_registration', '0'], ['imic_custom_event_registration_target', '0'], ['imic_sidebar_columns_layout', '3'], ['imic_google_map_track', '1'], ['imic_event_address2', event_map_location], ['imic_event_map_location', location_gps], ['imic_pages_banner_overlay', '0'], ['imic_pages_banner_animation', '0'], ['imic_pages_select_revolution_from_list', '[rev_slider fsl]'], ['imic_pages_slider_pagination', 'no'], ['imic_pages_slider_auto_slide', 'no'], ['imic_pages_slider_direction_arrows', 'no'], ['imic_pages_slider_interval', '7000'], ['imic_pages_slider_effects', 'fade'], ['imic_pages_nivo_effects', 'sliceDown'], ['imic_import_uid', uid]) # Iterate over array creating meta in post for i in meta_adds: new_post.custom_fields.append({'key': i[0], 'value': i[1]}) return new_post
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 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 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 _make_post(client, title, content): """ Make a post on the wordpress site for this content item. """ print 'MAKING POST FOR:', title post = WordPressPost() post.title = title post.content = content post.terms_names = { 'post_tag': ['test', 'firstpost'], 'category': ['Introductions', 'Tests'] } post.publish = True client.call(NewPost(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))