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 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 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 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 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 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 pedir_datos_nueva_entrada(): limpiar_pantalla() nueva_entrada = WordPressPost() nueva_entrada.title = input("Ingresa el título de la entrada: ") nueva_entrada.content = input("Ingresa todo el contenido de la entrada: ") etiquetas = [] categorias = [] eleccion = input("¿Deseas agregar etiquetas? [S/N] ") if eleccion.lower() == "s": etiquetas = input("Ingresa las etiquetas separadas con comas: ").split(",") eleccion = input("¿Deseas agregar categorías? [S/N] ") if eleccion.lower() == "s": categorias = input("Ingresa las categorías separadas con comas: ").split(",") nueva_entrada.terms_names = { 'post_tag': etiquetas, 'category': categorias, } print("Publicando entrada...") id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada)) limpiar_pantalla() print("Correcto! Se guardó la entrada como borrador, y su id es {}".format(id_entrada_publicada)) eleccion = input("¿Publicar inmediatamente? [S/N] ") if eleccion.lower() == "s": print("Publicando entrada...") nueva_entrada.post_status = 'publish' resultado = cliente.call(posts.EditPost(id_entrada_publicada, nueva_entrada)) if resultado is True: input("Entrada publicada") else: input("Algo salió mal") imprimir_menu_opciones()
def 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 _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 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 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_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://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 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 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 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 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 wordpress_artice(wppost_status, wp_title, wp_slug_title, wp_content, wp_category, wp_post_tag, wp_host, wp_user, wp_password): # 如果遇到错误就出试5次 success_num = 0 while success_num < 5: try: client = Client(wp_host, wp_user, wp_password) newpost = WordPressPost() # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例 # newpost.post_status = 'draft' newpost.post_status = wppost_status newpost.slug = wp_slug_title # 文章别名,固定链接形式为文章标题时需要 # 设置发布目录(一篇文章可以属于多个分类目录) newpost.terms_names = { 'category': wp_category, # 目录 'post_tag': wp_post_tag # 标签 } newpost.title = wp_title newpost.content = wp_content client.call(posts.NewPost(newpost)) #发布新建的文章,返回的是文章id print("Wordpress发布成功:", wp_title) except Exception as e: print("正在重试:", e) success_num = success_num + 1 continue
def 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 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 postNewPostByXmlRpc(title, content, enterName, techField, techMaturity, contactName, contactTel, contactEmail, completeDate, applyStatus, cowork_type, apply_score, result_type, award_type, award_level, prospect_promotion, patent_name, postal_address, district, images, prov): print("postNewPostByXmlRpc") wp = Client('http://39.106.104.45/wordpress/xmlrpc.php', 'shikun', 'ShiKun001') post = WordPressPost() post.title = title post.content = gen_content(content, enterName, applyStatus, apply_score, result_type, award_type, award_level, prospect_promotion, patent_name, postal_address, images) post.terms_names = { 'category': ['成果展示'] } #post.custom_fields = { # 'enter-name':enterName, # 'tech-field': techField, # 'tech-maturity': techMaturity, # 'contact-name':contactName, # 'contact-tel':contactTel, # 'contact-email':contactEmail #}; post.id = wp.call(NewPost(post)) print("post.id = " + str(post.id)) postId = post.id insertOtherDataIntoDB(postId, enterName, techField, techMaturity, contactName, contactTel, contactEmail, completeDate, cowork_type, district) insertProvDataIntoDB(postId, prov, enterName) savePostId(postId)
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 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, 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://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 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(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 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 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 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 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 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 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 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 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 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 new_post(site_id, article_id, category=None, post_tag=None): site = Site.objects.get(pk=site_id) client = Client(site.url + '/xmlrpc.php', site.username, site.password) article = Article.objects.get(pk=article_id) post = WordPressPost() post.title = article.title post.content = article.context # ## post.post_status='publish' # ## 文章默认发布为草稿 post.post_status = 'publish' if category: post.terms_names = {'category': category} if post_tag: post.terms_names = {'post_tag': post_tag} post_id = client.call(NewPost(post)) return post_id
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 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))
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(post_title,post_content,post_tag): wp = Client(wprpcurl, username, password) print wp.call(GetPosts()) print wp.call(GetUserInfo()) post = WordPressPost() post.title = post_title post.content = post_content dict1 = {} for x in post_tag: dict1.setdefault('post_tag',[]).append(str(x)) dict1.setdefault('category',[]).append('vps') post.terms_names = dict1 post.post_status = 'publish' wp.call(NewPost(post)) print wp.call(GetPosts())
def blog_content(title,content,tage,category): passwd="" wp = Client('http://123.206.66.55/xmlrpc.php', 'admin', passwd) """ 发表博文 """ post = WordPressPost() post.title = title post.content = content post.post_status = 'publish' print tage post.terms_names = { 'post_tag': tage, 'category': category } wp.call(NewPost(post))
def posting(): wp = Client('<YOURWORDPRESSSIT>/xmlrpc.php','YOURUSERNAME','YOURPASSWORD') #publish_date = (publish, '%a %b %d %H:%M:%S %Y %z') post = WordPressPost() post.title = title #Commit Title post.content = description #Commit message post.post_status = 'publish' post.terms_names = { 'category': ['12SDD'] } #post.date = publish_date #Creates a new wordpress post and posts it on the site. wp.call(NewPost(post))
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 buildPost(self, item): post = WordPressPost() post.title = self.spin.spin(item['title']) post.content = self.spin.spin(item['content']) post.excerpt = self.spin.spin(item['excerpt']) terms = [] for x in item['tag'].split(','): x = x.strip() if len(x) != 0: terms.append(x) if len(terms) == 0: terms.append(item['category']) post.terms_names = { 'post_tag': terms, 'category': item['category'], } return post
def 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 parseDocument(filename): lines = open(filename, 'r').readlines() values = {'title':'', 'permalink':'', 'layout':'post', 'tags':'', 'categories':'default', 'published': 'false'} start = False config = False for i in range(len(lines)): line = lines[i].strip() if config == False: if line == '---': if (start == False): start = True else: # end if (values['title'] == '' or values['permalink'] == ''): printf('title and permalink should not be null!\n'); exit() else:# config ok config = True else: try: key = line[:line.find(':')] value = line[line.find(':')+1:] values[key] = value.strip() except: printf('config failed! (key, value) = (' + key + ', ' + value + ')\n');exit() else: #config ok while len(lines[i]) <= 1: #filter first blank lines i+=1 rawcontent = parseMedia(lines[i:]) rawfilename = filename[:-3] + '.raw.id-' open(rawfilename, 'w').writelines(rawcontent) post = WordPressPost() post.title = values['title'] post.slug = values['permalink'] post.content = pandocTool.md2html(rawfilename) post.post_type = values['layout'] post.post_status = 'publish' if values['published'].lower() == 'true' else 'draft' post.comment_status = 'open' #default post.pint_status = 'open' #default post.terms_names = {} #values['tags'] = values['tags'].replace(',', ',') compatible with jekyll, use blank #values['categories'] = values['categories'].replace(',', ',') if len(values['tags']) > 0: post.terms_names['post_tag'] = [ tag.strip() for tag in values['tags'].split() if len(tag) > 0] if len(values['categories']) > 0: post.terms_names['category'] = [ cate.strip() for cate in values['categories'].split() if len(cate) > 0] return post
def requests_digest(): c = conn.cursor() c.execute('select id, name, obit_headline, obit_url, requested_at from requests where request_blogged_at is null') unblogged = c.fetchall() post = WordPressPost() today = datetime.strftime(datetime.today(),'%B %-d, %Y') post.title = 'New requests for FBI files, ' + today post.terms_names = { 'category':['Requests'], 'post_tag':[] } post.content = """We've recently requested the FBI files of the following individuals: <ul>""" for entry in unblogged: name = entry[1] obit_headline = entry[2] obit_url = entry[3] post.content += "\n<li>{name} (<a href=\"{obit_url}\">New York Times obit</a>)</li>".format(**locals()) post.terms_names['post_tag'].append(name.lower()) post.post_status = 'publish' post_id = wp.call(NewPost(post)) post_url = wp.call(GetPost(post_id)).link.replace('http','https') post_date = str(wp.call(GetPost(post_id)).date) post_title = wp.call(GetPost(post_id)).title for entry in unblogged: entry_id = entry[0] c.execute('update requests set request_blogged_at = ?, request_blog_url = ? where id = ?',(post_date,post_url,entry_id)) conn.commit() conn.close() ftd_tweets.tweet_digest_post(post_title,post_url)
def _readMetaAndContent(self,fid): """Reads meta data and content from file into WordPressPost() class. Returns the class If error, returns None """ found_meta_separator=False d={} # Read lines until we find the meta separator while found_meta_separator is False: line = fid.readline() # Did we find the --- separator it? if line[0:len(self.META_SEPARATOR)]==self.META_SEPARATOR: found_meta_separator=True else: key=line.split(':')[0].strip().lower() if key in self.WP_META_KEYS: d[key]=line.split(':')[1].strip() else: logger.error("wp: Token '%s' not in list of known tokens %s"\ %(key,self.WP_META_KEYS)) return None if not d.has_key('title'): print("wp: A title: keyword is required!") d['content']=fid.readlines() d['content']=''.join(d['content']) # Let's transfer over to a wordpress post class post = WordPressPost() post.title=d['title'] post.content=d['content'] post.post_status='publish' post.terms_names={} if d.has_key('tags'): post.terms_names['post_tag']=d['tags'].split(',') if d.has_key('category'): post.terms_names['category']=d['category'].split(',') return post
def process_item(self, item, spider): wp_filename = item.filename('wp') if os.path.exists(wp_filename): with open(wp_filename) as fh: post = pickle.load(fh) fh.close() # # # Here one might update or fix things if False: post.terms_names = { 'category': [item['source_name'].title()], 'post_tag': get_place_post_tag_names(item['place']) } self.client.call(posts.EditPost(post.id, post)) pass pass pass else: post = WordPressPost() post.title = item['headline'] try: post.content = item['body'] except KeyError: return None try: item['place'] except KeyError: item['place'] = "" post.terms_names = { 'category': [item['source_name'].title()], 'post_tag': get_place_post_tag_names(item['place']) } post.link = item['source_url'] post.date = item['time'] post.post_status = 'publish' post.id = self.client.call(posts.NewPost(post)) with open(wp_filename, 'wb') as fh: pickle.dump(post, fh) fh.close() pass return item pass
def build_draft_post(title, content): post = WordPressPost() post.title = title post.content = content post.terms_names = { 'post_tag': config_keys['wordpress_tags'], 'category': config_keys['wordpress_categories'] } # Don't duplicate same year / week no; reuse current_posts = wp.call(posts.GetPosts()) dup_posts = filter(lambda p: p.title.split(':') == post.title.split(':'), current_posts) if dup_posts: # lets assume this returns in a sensible order dup_id = dup_posts[0].id wp.call(posts.EditPost(dup_id, post)) post.id = dup_id else: post.id = wp.call(posts.NewPost(post)) return post
def insertPostFromDB(): conn = sqlite3.connect('qtfy.db') c = conn.cursor() idx = 0 db = qtfy_db('qtfy.db') for row in c.execute("select mid, name, url, desc, info, img from movie"): if idx>2: break post = WordPressPost() print row[0] post.title = row[1] lk = db.get_movielnks(row[0]) post.content = gen_webpage(row[3], row[4], row[5], lk) # row[3] + row[4] post.terms_names={'post_tag':['liu', 'jing']} post.post_status = "publish" idx += 1 print wp.call(NewPost(post)) conn.commit() conn.close()