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 insert_pipop_wordpress(filename, data): kan = "" en = "\n\n" for x in data["lyric"]: kan = kan + x["furigana"] + "\n" + x["roman"] + "\n\n" en = en + x["en"] + "\n\n" data_image = { 'name': str(time.time()) + '.jpg', 'type': 'image/jpeg', } if "http" in data["thumbnail"]: dow(data["thumb_max"], filename) else: filename = "image_des_wp_pipop/" + image_thum[random.randint(0, 390)] # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data_image['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data_image)) attachment_id = response['id'] post = WordPressPost() cate = [] cate.append("Jpop Lyrics") post.terms_names = { 'category': cate, } post.title = "FULL lyric and english translation of " + data[ "name"] + " - " + data["singer"] post.content = form( data["name"], data["singer"], kan, en, "https://www.youtube.com/embed/" + data["link_youtube"].split("v=")[-1], data["name_ro"]) post.post_status = 'publish' post.thumbnail = attachment_id post.id = client.call(posts.NewPost(post)) now_1 = datetime.now() # print((post.id, -1, 1, random.randint(45, 50) / 10, now_1, "X.X.X.X")) # # print((attachment_id, # "{0} lyric, {0} english translation, {0} {1} lyrics".format(data["name"], # data["singer"]))) ctn = connect.connect(user="******", password="******", host="103.253.145.165", database="admin_songlyrics") cusor = ctn.cursor() insert_rate( (post.id, -1, 1, random.randint(45, 50) / 10, now_1, "X.X.X.X"), cusor, ctn) update_des_image( attachment_id, "{0} lyric, {0} english translation, {0} {1} lyrics".format( data["name"], data["singer"]), cusor, ctn) # admin_score(post.id,random.randint(45,50)/10) print("ok pipop_wp!")
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
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 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 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(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 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 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 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 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 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 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(self, title, content, tags, attachment_id): post = WordPressPost() post.title = title post.content = content post.terms = tags post.thumbnail = attachment_id post.post_status = 'publish' post.id = self.client.call(posts.NewPost(post))
def post(wp, old_post, title, content, rtcprof, img_info): from wordpress_xmlrpc import WordPressPost from wordpress_xmlrpc.methods.posts import NewPost, EditPost if old_post: post = old_post else: post = WordPressPost() post.title = title post.content = content post.terms_names = { 'post_tag': [rtcprof.name, 'RTC'], 'category': ['RTComponents', rtcprof.basicInfo.category] } post.slug = rtcprof.name n = datetime.datetime.now() year = n.year month = n.month day = n.day hour = n.hour if n.hour < 9: day = day - 1 hour = hour + 24 if day == 0: month = month - 1 if month == 0: month = 12 year = year -1 if month in [4, 6, 9, 11]: day = 30 elif month == 2: day = 28 else: day = 31 hour = hour - 9 post.date = datetime.datetime(year, month, day, hour, n.minute, n.second) post.post_status = 'publish' if img_info: post.thumbnail = img_info['id'] else: post.thumbnail = old_post.thumbnail if old_post: # Edit Mode wp.call(EditPost(post.id, post)) else: wp.call(NewPost(post))
def new_post(self, title, content, image_id): post = WordPressPost() post.title = title post.content = content post.thumbnail = image_id post.post_status = 'publish' post.id = self._wp.call(NewPost(post)) return post.id
def get_urls(url): try: user_agent = {'User-agent': 'Mozilla/5.0'} r = requests.get(url,headers = user_agent) data = r.text soup = BeautifulSoup(data) div = soup.find('div', class_="panel-content") links = div.findAll('a') for a in links: try: if 'deccanchronicle.com' in a['href']: r = requests.get(a['href'],headers = user_agent) data = r.text soup = BeautifulSoup(data) title = soup.find('h1', class_="title") imgurl = soup.find('div',class_="field-item even") orgimgurl = imgurl['resource'] data = data[data.index('<div class="field field-name-field-image'):] data = data[:data.index('<div class="field field-name-field-tags')] soup = BeautifulSoup(data) texts = soup.find_all('p') content = "" for text in texts: content = content+"<p>"+text.getText() wai = WordAi('*****@*****.**','passhere') print(content) print(wai.unique_variation(content)) input("Press Enter to continue...") content = content + "<p>" + "Credits : deccanchronicle.com" post = WordPressPost() post.title = title.get_text() #Setting Post Title urllib.request.urlretrieve(orgimgurl, os.path.basename(orgimgurl)) filename = os.path.basename(orgimgurl) data = { 'name': os.path.basename(orgimgurl), 'type': mimetypes.guess_type(filename)[0], # 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 #Setting Feautured Image post.content = content #Setting Content Up post.terms_names = { 'post_tag': ['tech', 'techonology'], #Change Tags here 'category': ['Techie Stuff'] #Change Category Here } post.post_status = 'publish' wp.call(NewPost(post)) #print ("Post Id is %s" %(wp.call(NewPost(post)))) print("%s is Posted!" %(title.get_text())) #input("Press Enter to continue...") except: print('Some Error On This Post %s ' %(title.get_text())) raise except: raise
def post_article(self, articleTitle, articleCategories, articleContent, articleTags, imageUrl, tempDir, imageName, dirDelimiter, postStatus): # --- Get image extension imgExt = imageUrl.split('.')[-1].lower() # -------------------------------------------------------------- self.imgPath = tempDir + dirDelimiter + imageName + "." + imgExt self.articleImageUrl = imageUrl # --- Download image file f = open(self.imgPath, 'wb') try: f.write(urllib.request.urlopen(self.articleImageUrl).read()) except: print("Error downloading image") return -1 f.close() # -------------------------------------------------------------- # --- Upload image to WordPress filename = self.imgPath # prepare metadata data = { 'name': imageName + '.' + imgExt, 'type': 'image/' + imgExt, } # read the binary file and let the XMLRPC library encode it into base64 try: with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) except: print("Error while reading downloaded image file") return -2 try: response = self.wpClient.call(media.UploadFile(data)) except: print("Error while uploading image file") return -3 attachment_id = response['id'] # -------------------------------------------------------------- # --- Post article post = WordPressPost() post.title = articleTitle post.content = articleContent post.terms_names = { 'post_tag': articleTags, 'category': articleCategories } # More about post statuses: https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.posts.GetPostStatusList post.post_status = postStatus post.thumbnail = attachment_id try: post.id = self.wpClient.call(posts.NewPost(post)) except: print("Error while posting article") return -4 print('Post Successfully posted. Its Id is: ', post.id) # -------------------------------------------------------------- return post.id
def makeWpPost(prod_title, description, attachment_id): post = WordPressPost() post.title = prod_title post.content = description post.post_type = "product" post.post_status = "draft" post.thumbnail = attachment_id addpost = client.call(posts.NewPost(post)) print 'Product added: ' + prod_title print '\n'
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 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 post_article(title, content, first_img, author, source_url, source_name, delivery_url, delivery_name, class_, tmpdir): client = Client(WP_XMLRPC_URL, WP_XMLRPC_USER, WP_XMLRPC_PASS) retry = 5 if first_img: logger.debug('Download image %s' % first_img) img_path = get_img(first_img, tmpdir) logger.debug('Download article\'s first image to %s' % img_path) ret = None if first_img: for i in xrange(retry): ret = upload_file_to_wp(client, img_path) if ret: break else: raise CanNotUploadException('upload %s' % img_path) attachment_id = ret # Download all image file, and put it into static directory in web server, # and replace URL in the article content. content_obj = BeautifulSoup(content) img_tags = content_obj.find_all('img', recursive=True) from hashlib import md5 hex_dir = md5(title.encode('utf-8')).hexdigest() for img in img_tags: if img and img.has_attr('src'): img_path = get_img(img.attrs['src'], tmpdir) img_path2 = copy_to_web_server(img_path, hex_dir) img.attrs['src'] = img_path2 post = WordPressPost() post.title = title post.content = str(content_obj) #post.post_status = 'publish' if first_img: post.thumbnail = attachment_id post.terms_names = { # TODO: add tags #'post_tag': ['tagA', 'another tag'], 'category': [ 'Web-Crawler/新闻资讯', ], } post.custom_fields = [] post.custom_fields.append({'key': 'source_url', 'value': source_url}) post.custom_fields.append({'key': 'source_name', 'value': source_name}) post.custom_fields.append({'key': 'delivery_name', 'value': delivery_name}) post.custom_fields.append({'key': 'delivery_url', 'value': delivery_url}) post.id = client.call(posts.NewPost(post))
def send_news(user, news): wp = Client(user['website'], user['username'], user['password']) post = WordPressPost() if news.image_name != '': print news.title for image in news.image_name: attachment_id = upload_image(image, wp) post.thumbnail = attachment_id post.title = news.title post.content = str(news.content) post.post_status = 'publish' post.terms_names = {'post_tag': news.tags, 'category': [news.category]} wp.call(NewPost(post))
def edit_posts(self, post_id, title, feature_img, staff, content, img_list, tag_list, categrory): post = WordPressPost() post.title = title if staff: content = staff + '<br>' + content post.content = content post.categrory = [] post.categrory.append(categrory) if tag_list: post.terms_names = { 'post_tag': tag_list, 'category': post.categrory } else: post.terms_names = {'post_tag': '', 'category': post.categrory} #img_list设置为空,避免图片重复上传 img_list = [] if img_list: img_name = img_list[-1].split('/')[-1] filename = img_list[-1].replace('http://', '/www/wwwroot/') data = {'name': img_name, 'type': 'image/jpeg'} try: with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = self.wp.call(media.UploadFile(data)) attachment_id = response['id'] post.thumbnail = attachment_id except: print('最后一张图片不存在:', img_list[-1]) # for i in range(len(img_list)): # img_name=img_list[i].split('/')[-1] # filename = './'+img_name #上传的图片本地文件路径 # prepare metadata # data = {'name': 'picture.jpg','type': 'image/jpeg',} # data['name']=img_name # 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=self.wp.call(media.UploadFile(data)) # if i ==len(img_list)-1: # attachment_id = response['id'] # post.thumbnail=attachment_id post.post_status = 'publish' self.wp.call(EditPost(post_id, post)) print('正在修正[ID]:%s,[标题]:%s' % (post_id, post.title)) if os.path.isfile(self.wp_log): with open(self.wp_log, 'a+') as f: f.writelines(str(post_id) + '\n') return post_id, len(post.content)
def process_item(self, item, spider): post = WordPressPost() post.title = item['title'] post.content = item['content'] + settings.get('GOTO_SOURCE', "[%s]") % item['link'] post.date = datetime.datetime.strptime(item['publish_date'], "%Y-%m-%d %H:%M") post.terms_names = { 'post_tag': item['tag'], 'category': item['category'] if len(item['category']) > 0 else ['gist'], } post.post_status = 'publish' post.thumbnail = self.create_thumbnail(item) post.id = self.client.call(posts.NewPost(post)) return item
def wp_post_update(request, post_id): """ Update WordPress post using Post object and HTML Primarily for 'Update This Post' button AJAX function in :view:`post_generator.views.post.post_view` :param post_id: :model:`post_generator.Post` to update WP post with :type post_id: :model:`post_generator.Post` """ # TODO: add case for GET request if request.method == 'POST': client = Client(os.environ['POSTGEN_WP_TARGET'], os.environ['POSTGEN_WP_USER'], os.environ['POSTGEN_WP_PASS']) post_obj = Post.objects.get(pk=post_id) # Generate Multilingual title post_title = post_obj.title.english if post_obj.title.somali: post_title += ' (' + post_obj.title.somali + ')' if post_obj.title.french or post_obj.title.french_feminine: post_title += ' ' + (post_obj.title.french or post_obj.title.french_feminine) if post_obj.title.arabic: post_title += ' ' + post_obj.title.arabic post_title += ' - PostGen' # Pull WP post ID from stored link matches = re.search('.*=(\d+)$', post_obj.link) wp_post_id = matches.group(1) # Create new WP post object with data wp_post = WordPressPost() wp_post.title = post_title wp_post.content = request.POST['post-content'] wp_post.date = post_obj.pub_date # Retrieve current post data via WP XML-RPC API # - Used to determine whether featured_image_id data should be included # - Avoids error from setting featured_image_id to the one already attached current_post = client.call(posts.GetPost(wp_post_id)) if not current_post.thumbnail or current_post.thumbnail[ 'attachment_id'] != str(post_obj.featured_image_id): wp_post.thumbnail = str(post_obj.featured_image_id) # Update WP post and return status=True via JSON client.call(posts.EditPost(wp_post_id, wp_post)) return HttpResponse(json.dumps({'status': True}), content_type='application/json')
def _intruderPost(image): data = {'name': image, 'type': 'image/jpeg'} with open(image, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = site.call(WordpressMedia.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = 'Unauthorized Access Attempt' post.content = 'Face not recognized' post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Unsuccessful Login']} post.post_status = 'publish' post.thumbnail = attachment_id site.call(posts.NewPost(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 crear_nueva_entrada_automatica(): limpiar_pantalla() nueva_entrada = WordPressPost() num = int(input("Introduce el ID del post que quieres publicar: ")) articulos = [] articulos = pd.read_csv('travel_translated.csv',sep = ';') nueva_entrada.title = articulos.titulo_traducido[num] nueva_entrada.content = articulos.cuerpo_traducido[num] ############ AUTOMATIZAR LA SUBIDA DE IMAGENES ############ filename = 'downloads/travel_images_2/travel_' + str(num) + '.jpg' # prepare metadata data = {'name': 'picture.jpg', 'type': 'image/jpeg',} # 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 = cliente.call(media.UploadFile(data)) attachment_id = response['id'] nueva_entrada.thumbnail = attachment_id ####################### ####################### ####################### etiquetas = [] categorias = [] eleccion = input("¿Deseas agregar etiquetas? [S/N] ") if eleccion.lower() == "s": #etiquetas = input("Ingresa las etiquetas separadas con comas: ").split(",") etiquetas = ["viajar,carrefour,baratos,viajeros piratas,halcon,viaje al cuarto de una madre,barcelo,viaje al centro de la tierra,sorpresa,viaje sorpresa,viaje a cuba,viaje a nueva york,viaje a egipto,viajera del tiempo,viajem,todo incluido,viajera soledad,viajera,agencia,viaje en el tiempo,corte ingles,viaje largo,viaje barato,viaje budapest,viaje bali,viaje berlin,viaje barcelona,viaje bora bora,viaje bruselas brujas gante,viaje barato a roma,viaje bahamas,viaje barato semana santa,the travel brand pamplona,viajeras b,viajeras con b,viaje b alfa romeo,mundo,the travel brand valladolid,viajeros b travel brand,viaje canarias,viaje costa oeste eeuu,viaje cuba,viaje costa rica,viaje corte ingles,viaje croacia,viaje cerdeña,viaje caribe,viaje con niños,viaje con nosotros,viajeros c,m&c turismo quilmes,jota c ,d.c. y turismo s.a,at&c mar del plata,viaje de chihiro,viaje de novios,viaje disney,viaje del heroe,viaje disneyland,viaje de magallanes,viaje disney paris,viaje de arlo,viaje destino sorpresa,viaje dubai,viaje destinos,san juan,viaje club,gaitan,san juan estafa,de viaje destinos san juan,turismo,tour.com,d-viaje vitoria,viaje egipto,viaje en el tiempo,viaje en globo madrid,viaje eurodisney,viaje en ingles,viaje en globo segovia,viaje en tren,viaje express,viajero,viaje de chihiro,viaje mas largo,viaje del heroe,viaje de arlo,operadora sa de cv veracruz,ideas,el tiempo,viaje fin desemana,playa,montaña"] 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 push_posts(self, title, feature_img, staff, content, img_list, tag_list, categrory): post = WordPressPost() post.title = title post.content = content post.categrory = [] post.categrory.append(categrory) if tag_list: post.terms_names = { 'post_tag': tag_list, 'category': post.categrory } else: post.terms_names = {'post_tag': '', 'category': post.categrory} post.post_status = 'publish' #如果特色图片存在,那么加到图片列表最后一张 if feature_img: img_list.append(feature_img) #上传图片到wp if img_list: for i in range(len(img_list)): img_name = img_list[i].split('/')[-1] filename = img_list[i] #上传的图片本地文件路径 # prepare metadata data = {'name': img_name, 'type': 'image/jpeg'} #data['name']=img_name # 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 = self.wp.call(media.UploadFile(data)) #取最后一张图片作为特色图片 if i == len(img_list) - 1: attachment_id = response['id'] post.thumbnail = attachment_id ''' response == { 'id': 6, 'file': 'picture.jpg' 'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg', 'type': 'image/jpeg', } ''' postid = self.wp.call(NewPost(post)) print('正在发布[ID]:%s,[标题]:%s' % (postid, post.title)) # if os.path.isfile(self.wp_log): # with open(self.wp_log,'a+') as f: # f.writelines(str(postid)+'\n') return postid
def addItem(self, item): # 跳转链作为唯一标识去重 # exist_posts = self.rpcClient.call(posts.GetPosts({'custom_fields':{'key':'link_value', 'value' : item.link}})) if self.itemExist(item.link): return print 'item.link = ' + item.link res = urlparse.urlparse(item.thumb) if len(res.query) > 0: qs = urlparse.parse_qs(res.query) # huihui图片ID des = qs['id'][0] filename = des + '.png' destfile = 'temp/' + filename else: filename = item.thumb[item.thumb.rfind('/'):] destfile = 'temp' + filename downloadimage(item.thumb, destfile) # prepare metadata data = { 'name': filename, 'type': 'image/png', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open(destfile, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = self.rpcClient.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = item.title post.content = item.content post.thumbnail = attachment_id post.custom_fields = [{'key': 'link_value', 'value': item.link}] post.id = self.rpcClient.call(posts.NewPost(post)) # # attachment_id.parentid = post.id # # whoops, I forgot to publish it! post.post_status = 'publish' # cats = self.rpcClient.call(taxonomies.GetTerms('category')) for cat in self.categorys: if cat.name == item.category: post.terms = [cat] break self.rpcClient.call(posts.EditPost(post.id, post))
def addItem(self, item): # 跳转链作为唯一标识去重 # exist_posts = self.rpcClient.call(posts.GetPosts({'custom_fields':{'key':'link_value', 'value' : item.link}})) if self.itemExist(item.link): return print 'item.link = '+item.link res = urlparse.urlparse(item.thumb) if len(res.query) > 0: qs = urlparse.parse_qs(res.query) # huihui图片ID des = qs['id'][0] filename = des+'.png' destfile = 'temp/'+filename else: filename = item.thumb[item.thumb.rfind('/'):] destfile = 'temp'+filename downloadimage(item.thumb,destfile) # prepare metadata data = { 'name': filename, 'type': 'image/png', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open(destfile, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = self.rpcClient.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = item.title post.content = item.content post.thumbnail = attachment_id post.custom_fields = [{'key':'link_value', 'value' : item.link}] post.id = self.rpcClient.call(posts.NewPost(post)) # # attachment_id.parentid = post.id # # whoops, I forgot to publish it! post.post_status = 'publish' # cats = self.rpcClient.call(taxonomies.GetTerms('category')) for cat in self.categorys: if cat.name == item.category: post.terms = [cat] break self.rpcClient.call(posts.EditPost(post.id, 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 post_picture(image_url): fileImg = urlopen(image_url) imageName = fileImg.url.split('/')[-1]+'.jpg' data = { 'name': imageName, 'type': 'image/jpeg', } data['bits'] = xmlrpc_client.Binary(fileImg.read()) response = client.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = 'Picture of the Day' post.post_status = 'publish' post.thumbnail = attachment_id post.id = client.call(posts.NewPost(post))
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 upload_article(self, article, img_url, tags, categories): """ Create a post object, initialize its properties and upload it. :param article: HTML string :param img_url: the url to img :param tags: list with tags :param categories: list with categories """ post = WordPressPost() post.title = self.title post.content = article post.thumbnail = self._upload_image(img_url) post.terms_names = {'post_tag': tags, 'category': categories} # post.post_status = 'publish' post.id = self.client.call(NewPost(post))
def post_to_wordpress( self, title, content, detail_url, image_upload_id, retry, ): # now post the post and the image post = WordPressPost() post.post_type = 'portfolio' post.title = title post.content = content post.post_status = 'publish' post.thumbnail = image_upload_id if self.wp.call(NewPost(post)): return True
def post_data_to_site(titles, filenames): post_ids = [] client = Client('http://domain.com/xmlrpc.php','username','password') for i in range(0,len(titles)): post_title, filename = titles[i], filenames[i] imgfile = os.path.join(DATA_DIR, filename) data = {'name':filename, 'type':'image/jpg'} with open(imgfile, 'rb+') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) attachment_id = response['id'] post = WordPressPost() post.title = post_title post.post_status = 'publish' post.thumbnail = attachment_id post.comment_status = 'open' post.id = client.call(posts.NewPost(post)) post_ids.append(post.id) print post.id return post_ids
def publish(pic, title, content): ''' publish a post and set to open to comment and ping(trackback) ''' 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' post.comment_status = 'open' post.ping_status = 'open' post.user = account_ids[r.randint(0, len(account_ids)-1)] wp_client.call(posts.EditPost(post.id, post)) return post.id
def addItemsToWordpress( self ): items = self.items if items: wp = Client('http://' + self.wpinfo['website'] + '/xmlrpc.php', self.wpinfo['user'], self.wpinfo['pass']) pass for item in items: self.log.info("[ Scrapper {} ] - [ Publishing \"{}\" into WP ]".format( self.table, item["title"] )) now = time.strftime("%c") post = WordPressPost() post.terms_names = { 'category': ['Scrapped'] # This need to be changed in next release } post.title = '{}'.format(item['title']) if item['slug']: post.slug = item['slug'] if item['image_url']: call(['curl',item['image_url'].replace(' ','%20'),'-o','image.jpg.scrapper_data']) filename = 'image.jpg.scrapper_data' data = { 'name': 'image.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 content = '' if item['content']: content += '{}'.format(item['content']) content += 'Source: <a href="{}">{}</a>\n\n'.format(item['url'],item['referer']) post.content = content wp.call(NewPost(post))
def add_or_edit_wp_post(title, content, slug, more_info_url, local_img_file): # first upload the image if local_img_file: data = { 'name': local_img_file.split('/')[-1], 'type': 'image/jpg', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open(local_img_file, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] # now post the post and the image post = WordPressPost() post.post_type = 'post' # stupid effing theme post.title = title post.content = content post.post_status = 'publish' post.slug = slug if local_img_file: post.thumbnail = attachment_id if not get_wp_post_id(slug): # this is a new post wp.call(NewPost(post)) msg = "posted" else: # this post exists, update it post.id = get_wp_post_id(slug) wp.call(EditPost(post.id, post)) msg = "edited" print "%s %s as %s" % (msg, title, post.slug)
def wordpress_post(config): print("Connecting to: " + config.wordpress['xmlrpc']) wp = Client(config.wordpress['xmlrpc'], config.wordpress['username'], config.wordpress['password']) if config.attach_header: print("Uploading header image...") # Upload header image data = { 'name': os.path.basename(config.png_header_file), 'type': 'image/png', } # Read the image and let the XMLRPC library encode it to base64 with open(config.png_header_file, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) attachment_id = response['id'] print("Posting blog...") post = WordPressPost() post.title = config.wordpress['title'] post.content = config.wordpress['content'] post.post_format = config.wordpress['post_format'] post.post_status = config.wordpress['post_status'] post.comment_status = config.wordpress['comment_status'] if config.attach_header: post.thumbnail = attachment_id post.terms_names = { 'post_tag': [config.wordpress['tags']], 'category': [config.wordpress['category']] } post.id = wp.call(NewPost(post)) if config.wordpress['podcast_plugin'] == 'Powerpress': get_audio_size_and_duration(config)
def _post_newpost_to_wordpress(self, item, attachment_id): post = WordPressPost() post.title = item['title'] post.content = item['content'] post.post_type = "post" post.post_status = "publish" post.terms_names = { 'post_tag': item['tags'], 'category': [item['url_from']] } post.custom_fields = [] post.custom_fields.append({ 'key': 'custom_source_url', 'value': item['url'] }) # cat1 = self.wp.call(taxonomies.GetTerm('category', 'wanghao')) # post.terms.append(cat1) if attachment_id: post.thumbnail = attachment_id addpost = self.wp.call(posts.NewPost(post)) return addpost
post.content = post.content + '});' post.content = post.content + '});' post.content = post.content + '</script>\n' # set to the path to your file filename = s3IconURL + 'chap' + str(chapNum) + '.png' # prepare metadata data = { 'name': 'chap' + str(chapNum) + '.png', 'type': 'image/png', # mimetype } IconResponse = urllib2.urlopen(filename) #html = response.read() data['bits'] = xmlrpc_client.Binary(IconResponse.read()) #with open(filename, 'rb') as img: # data['bits'] = xmlrpc_clent.Binary(img.read()) the_response = wp.call(media.UploadFile(data)) attachment_id = the_response['id'] post.thumbnail = attachment_id #publish it post.post_status = 'publish' wp.call(posts.NewPost(post)) print("Posted!")
def post_article(self, content_path, files_path): ''' in : - content_path : content link - files_path : files link in a tuple out : string with success or error with information ''' from unidecode import unidecode try : for f in files_path : self._file_updater(f) except Exception as e : return 'Error while uploading images : ' + str(e) try : if len(content_path) == 1 : title, categories, tags,thumbnail, content, = self._content_extract(content_path[0]) else : return 'Error with the content : upload one text file' except Exception as e : return 'Error while extracting title, categories, tages, content : ' + str(e) try : html_content = markdown2.markdown(content) post = WordPressPost() post.title = title for upd in self.all_upd_response : if upd['file'] == thumbnail : post.thumbnail = upd['id'] except Exception as e : return 'Error while converting in markdown : ' + str(e) try : # convert unicode in string str_content = unicodedata.normalize('NFKD', html_content).encode('ascii', 'ignore') # justify paragraphs str_content = str_content.replace ('<p>', '<p align=\"justify\">') # center images str_content = str_content.replace ('<p align=\"justify\"><img', '<p align=\"center\"><img') post.content = str_content post.post_status = 'publish' if isinstance(tags, str): tags = tags.split() if isinstance(categories, str): categories = categories.split() post.terms_names = { 'post_tag': tags, 'category': categories, } except Exception as e : return 'Erro while normalizing html : ' + str(e) try : erno = self.wp.call(NewPost(post)) except : return "Erro while posting content" if erno is not 401 or erno is not 403 or erno is not 404 : ret_value = 'Post successful!' else : ret_value = 'Error while posting : ' + erno return ret_value
def post(): #get id post_id = re.search(':wp_id:((.*)|\n)', asc_file_read_str).group(1).strip() #get status post_status = re.search(':wp_status:((.*)|\n)', asc_file_read_str) #get title post_title = re.search(':wp_title:((.*)|\n)', asc_file_read_str) #get slug post_slug = re.search(':wp_slug:((.*)|\n)', asc_file_read_str) #get category post_category = re.search(':wp_category:((.*)|\n)', asc_file_read_str) post_category_str = post_category.group(1).strip().split(", ") if len(post_category_str) == 0: post_category_str = [] elif post_category.group(1).strip() == '': post_category_str = [] elif len(post_category_str) == 1: post_category_str = post_category.group(1).strip(), #get tag post_tag = re.search(':wp_tag:((.*)|\n)', asc_file_read_str) post_tag_str = post_tag.group(1).strip().split(", ") if len(post_tag_str) == 0: post_tag_str = [] elif post_tag.group(1).strip() == '': post_tag_str = [] elif len(post_tag_str) == 1: post_tag_str = post_tag.group(1).strip(), #get excerpt post_excerpt = re.search(':wp_excerpt:((.*)|\n)', asc_file_read_str) #get thumbnail post_thumbnail = re.search(':wp_thumbnail:((.*)|\n)', asc_file_read_str) #post to wordpress from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods import posts client = Client(xmlrpc_url, username, password) post = WordPressPost() date_ = datetime.now() #id New or Edit if not post_id: post.date = date_.strftime("%s") post.id = client.call(posts.NewPost(post)) mode = "New" asc_file_re = re.sub(r':wp_id:((.*)|\n)', ':wp_id: ' + post.id , asc_file_read_str) asc_file_write = open(filepath, 'w') try: asc_file_write.write( asc_file_re ) finally: asc_file_write.close() else: post.date_modified = date_.strftime("%s") post.id = post_id mode = "Edit" post.post_status = post_status.group(1).strip() try: post.title = post_title.group(1).strip() except: print 'Title is not exist' try: post.slug = post_slug.group(1).strip() except: print 'Slug is not exist' post.content = html try: post.excerpt = post_excerpt.group(1).strip() except: post.excerpt = '' post.terms_names = { 'category': post_category_str, 'post_tag': post_tag_str, } try: post.thumbnail = post_thumbnail.group(1).strip() except: post.thumbnail = '' client.call(posts.EditPost(post.id, post)) post_info = client.call(posts.GetPost(post.id, post)) #get post info from wordpress asc_file_read_slug = open(filepath, 'r') asc_file_read_slug_str = asc_file_read_slug.read() if post_info: asc_file_read_slug_str = re.sub(r':wp_slug:((.*)|\n)', ':wp_slug: ' + post_info.slug, asc_file_read_slug_str) if mode == "New": new_date = int(post_info.date.strftime("%s"))+(timezone___*60*60) new_date = datetime.fromtimestamp(new_date).strftime("%Y-%m-%d %H:%M:%S") asc_file_read_slug_str = re.sub(r':wp_date:((.*)|\n)', ':wp_date: ' + new_date, asc_file_read_slug_str) elif mode == "Edit": edit_date = int(post_info.date_modified.strftime("%s"))+(timezone___*60*60) edit_date = datetime.fromtimestamp(edit_date).strftime("%Y-%m-%d %H:%M:%S") asc_file_read_slug_str = re.sub(r':wp_modified:((.*)|\n)', ':wp_modified: ' + edit_date, asc_file_read_slug_str) asc_file_re_slug_write = open(filepath, 'w') try: asc_file_re_slug_write.write( asc_file_read_slug_str ) finally: asc_file_re_slug_write.close() print '==========================\n' + mode + ' Post ID: ' + post.id + ' \nStatus: ' + post.post_status + '\nTitle: ' + post.title + '\nSlug: ' + post_info.slug + '\nCategory: ' + post_category.group(1).strip() + '\nTag: ' + post_tag.group(1).strip() + '\n'
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 main(series_name, playlist_id, wordpress_host, wordpress_username, wordpress_password): host_rpc_url = "http://%s/xmlrpc.php" % wordpress_host playlist_url = "https://www.youtube.com/playlist?list=%s" % playlist_id logger.debug("-- INPUTS --------------------------------------------------") logger.debug("YouTube Playlist ID: %s" % playlist_id) logger.debug("Wordpress Host: %s" % wordpress_host) logger.debug("Wordpress Username: %s" % wordpress_username) logger.debug("Wordpress Password: %s" % wordpress_password) logger.debug("------------------------------------------------------------") logger.debug(" + Host RPC URL: %s" % host_rpc_url) logger.debug(" + Playlist URL: %s" % playlist_url) logger.debug("------------------------------------------------------------") # wordpress client client = Client(host_rpc_url, wordpress_username, wordpress_password) # get the playlist playlist = pafy.get_playlist(playlist_url) videos = playlist['items'] logger.debug("Playlist URL: %s" % playlist_url) for v in videos: video = v['pafy'] # retrieve contents from the pafy object title = video.title description = video.description category = "Videos" tags = video.keywords video_id = video.videoid image_url = video.bigthumb if video.bigthumb else video.thumb # save the file to disk filename = os.path.basename(image_url) f, path = tempfile.mkstemp(suffix=filename) r = requests.get(image_url, stream=True) if r.status_code == 200: with open(path, 'wb') as imgfile: for chunk in r: imgfile.write(chunk) # prepare to upload featured image data = { 'name': os.path.basename(image_url), 'type': 'image/jpeg' } with open(path, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) # import ipdb; ipdb.set_trace() response = client.call(UploadFile(data)) featured_image_id = response['id'] embed = """ <iframe width="560" height="315" src="https://www.youtube.com/embed/%s" frameborder="0" allowfullscreen> </iframe> """ % (video_id,) # create a WordPressPost object post = WordPressPost() post.title = title post.terms_names = { 'post_tag': tags, 'category': [category, series_name] } post.thumbnail = featured_image_id post.content = """ <p>%s</p> <p>%s</p> """ % (embed, description) logger.info("Processing '%s'" % title) logger.debug(" - Description: %s..." % description) logger.debug(" - Category: %s" % category) logger.debug(" - Tags: %s" % tags) logger.debug(" - Video ID: %s" % video_id) client.call(NewPost(post))
# Take markdown, convert to HTML and put it as post content # Makes intermediate convertion to Panflute AST to apply the filters. postdocument = pf.convert_text(postcontent, input_format='markdown', output_format='panflute', standalone=True) pf.run_filters( [ imageURLs, codeBlocks ], doc = postdocument ) content = pf.convert_text(postdocument, input_format='panflute', output_format='html') # Set post metadata post.title = title post.content = content post.post_status = post_status post.terms_names = terms_names if not thumb_url == None: thumb_mime = checkImage(thumb_url) if not thumb_mime == None: response = uploadFile(thumb_url, thumb_mime) post.thumbnail = response['id'] post.id = WP.call(NewPost(post)) # Post it! print( "Posted: " + post.title ) print( "\nWith Status: " + post.post_status ) print( "\nAnd ID: " + post.id )
def upload_text(wp, repo_name, rtcprof, html, img_info = None, test=False, build_report_filename="build_report.yaml"): from wordpress_xmlrpc.methods import posts, taxonomies, media sys.stdout.write(' - Uploading %s\n' % rtcprof.name) editFlag = False post = None for p in all_posts: if p.title == title: editFlag = True post = p break html = update_build_status(html, build_report_filename) if not editFlag: post = WordPressPost() post.title = title post.content = apply_language_setting(html) post.terms_names = { 'post_tag': [rtcprof.name, 'RTC'], 'category': ['RTComponents', rtcprof.basicInfo.category] } post.slug = rtcprof.name n = datetime.datetime.now() year = n.year month = n.month day = n.day hour = n.hour if n.hour < 9: day = day - 1 hour = hour + 24 if day == 0: month = month - 1 if month == 0: month = 12 year = year -1 if month in [4, 6, 9, 11]: day = 30 elif month == 2: day = 28 else: day = 31 hour = hour - 9 post.date = datetime.datetime(year, month, day, hour, n.minute, n.second) post.post_status = 'publish' post.thumbnail = img_info['id'] post.id = wp.call(NewPost(post)) return else: # Edit Flag #post = WordPressPost() post.title = title post.content = apply_language_setting(html) post.terms_names = { 'post_tag': [rtcprof.name, 'RTC'], 'category': ['RTComponents'] } post.slug = rtcprof.name n = datetime.datetime.now() year = n.year month = n.month day = n.day hour = n.hour if n.hour < 9: day = day - 1 hour = hour + 24 if day == 0: month = month - 1 if month == 0: month = 12 year = year -1 if month in [4, 6, 9, 11]: day = 30 elif month == 2: day = 28 else: day = 31 hour = hour - 9 post.date = datetime.datetime(year, month, day, hour, n.minute, n.second) post.post_status = 'publish' post.thumbnail = img_info['id'] wp.call(posts.EditPost(post.id, post))
def post_to_wp(title, content, datetime_local): """ :param title: Title for post, used to guess post URL :param content: Body for post :param datetime_local: local time of earthquake, assumed to be the sames of WordPress instalation. Used to guess post URL :return: post_url """ msg = "\nYou need to set up your WordPress credentials: \n" \ "Use:\n" \ " salvitobot.config.wordpress_client = 'https://mydomain.wordpress.com/xmlrpc.php'\n" \ " salvitobot.config.wordpress_username = '******'\n" \ " salvitobot.config.wordpress_password = '******'\n" if config.wordpress_client == '': raise WordPressNotConfigured(msg) if config.wordpress_username == '': raise WordPressNotConfigured(msg) if config.wordpress_password == '': raise WordPressNotConfigured(msg) wp = Client(config.wordpress_client, config.wordpress_username, config.wordpress_password) # set to the path to your file filename = os.path.join(config.base_folder, 'img', 'salvitobot.png') # prepare metadata data = { 'name': 'salvitobot.png', 'type': 'image/png', # mimetype } # read the binary file and let the XMLRPC library encode it into base64 with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp.call(media.UploadFile(data)) # response == { # 'id': 6, # 'file': 'picture.jpg' # 'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg', # 'type': 'image/jpeg', # } attachment_id = response['id'] post = WordPressPost() post.title = title post.content = content post.id = wp.call(posts.NewPost(post)) post.terms_names = { 'post_tag': ['salvitobot', 'temblor', 'sismo'], 'category': ['noticias'] } post.thumbnail = attachment_id # whoops, I forgot to publish it! post.post_status = 'publish' wp.call(posts.EditPost(post.id, post)) # return post url based on config wp_client and datetime_local return make_url(title, datetime_local)
def post_article(title, content, first_img, author, source_url, source_name, delivery_url, delivery_name, class_, tmpdir): client = Client(LF_XMLRPC_URL, LF_XMLRPC_USER, LF_XMLRPC_PASS) retry = 5 if first_img: logger.debug('Download image %s' % first_img) img_path = get_img(first_img, tmpdir) logger.debug('Download article\'s first image to %s' % img_path) ret = None if first_img: for i in xrange(retry): ret = upload_file_to_wp(client, img_path) if ret: break else: raise CanNotUploadException('xmlrpc upload %s' % img_path) attachment_id = ret # Download all image file, and put it into static directory in web server, # and replace URL in the article content. content_obj = BeautifulSoup(content) img_tags = content_obj.find_all('img', recursive=True) from hashlib import md5 hex_dir = md5(title.encode('utf-8')).hexdigest() img_paths = [] img_src_list = [] for img in img_tags: if img and img.has_attr('src'): img_path = get_img(img.attrs['src'], tmpdir) img_paths.append(img_path) img_src_list.append(img.attrs['src']) img_host_list = copy_to_web_server(img_paths, hex_dir) if len(img_host_list) != len(img_src_list): raise CanNotUploadException('ftp upload file length not match, local(%s), remote(%s)' % (len(img_src_list), len(img_host_list))) for x in xrange(len(img_src_list)): img_src_list[x] = img_host_list[x] post = WordPressPost() post.title = title post.content = str(content_obj) #post.post_status = 'publish' if first_img: post.thumbnail = attachment_id post.terms_names = { # TODO: add tags #'post_tag': ['tagA', 'another tag'], 'category': ['公社推送', ], } post.custom_fields = [] post.custom_fields.append({ 'key': 'source_url', 'value': source_url }) post.custom_fields.append({ 'key': 'source_name', 'value': source_name }) post.custom_fields.append({ 'key': 'delivery_name', 'value': delivery_name }) post.custom_fields.append({ 'key': 'delivery_url', 'value': delivery_url }) post.id = client.call(posts.NewPost(post))