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 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 post_file(wp, f, t, y, m, d): p = WordPressPost() p.title = t p.content = slurp(f) # 9am zulu is early Eastern-Pacific p.date = p.date_modified = datetime(y,m,d,9) p.post_status = 'publish' p.comment_status = 'closed' if wp: wp.call(NewPost(p))
def 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 post_file(wp, f, t, y, m, d): p = WordPressPost() p.title = t p.content = slurp(f) # All 3 sites are configured to UTC if re.search('deutsche', f): p.date = datetime(y, m, d, 4) # 4am UTC is 5am in UTC+1=Berlin else: p.date = datetime(y, m, d, 10) # 10am UTC is 5am eastern, 2am pacific p.date_modified = p.date p.post_status = 'publish' p.comment_status = 'closed' if wp: wp.call(NewPost(p))
def post_article(title, body, category, tag): """发布一篇文章""" try: post = WordPressPost() post.title = title post.content = body post.post_status = "publish" # draft草稿 post.post_type = "post" # page页面 post.comment_status = 'open' # 允许评论 post.date_modified = datetime.datetime.now() post.terms_names = {'category': category, 'post_tag': tag} wp.call(NewPost(post)) log("发布文章:%s..." % title[0:20]) except Exception as e: log_error("文章发布失败!", e)
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 toWordPressPost(self): post = WordPressPost() if self.title: post.title = self.title if self.content: post.content = self.content post.date = self.published post.date_modified = self.updated post.comment_status = True post.post_status = 'publish' return post
def post_event(self, indico_event): post_view = IndicoEventWordpressPostView(indico_event) post = WordPressPost() post.title = post_view.get_title() post.date = post_view.get_date() post.content = post_view.get_content() post.post_status = 'publish' post.comment_status = 'closed' post_id = self.client.call(NewPost(post)) return post_id
def toWordPressPost(self): post = WordPressPost() if self.title: post.title = self.title if self.content: post.content = self.content post.date = self.published post.date_modified = self.updated post.comment_status = True post.post_status = 'publish' return post
def post_wordpress(title, content, post_status, comment_status, post_tags, categories): wp = get_wordpress_client() post = WordPressPost() post.title = title post.content = content post.post_status = post_status post.comment_status = comment_status post.terms_names = { # 'post_tag': ['test', 'firstpost'], # 'category': ['Introductions', 'Tests'] 'post_tag': post_tags, 'category': categories } return wp.call(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 _create_wp_post(song, content): # Create the NewPost object - see docs at # http://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/wordpress.html # We're missing some fields but ehhhh who knows if they even exist anymore post = WordPressPost() post.title = str(song) post.content = content post.comment_status = 'open' post.ping_status = 'closed' post.post_status = 'publish' post.post_type = 'post' post.excerpt = song.tagline post.date = datetime.now(tz=timezone.utc) post.date_modified = datetime.now(tz=timezone.utc) return NewPost(post)
def push_kuaijiwang(): try: # 检测是否登录成功 # 登录WordPress后台 client = Client("https://www.yebing.cn/xmlrpc.php", "yebing", "yeye910103") except ServerConnectionError: print('登录失败') else: print('登录成功') # wp = client.call(posts.GetPosts({'orderby': 'post_modified', 'number': 50})) # for w in wp: # print(w.link) for item in kuaijiwangarticle.find({"status": 0}): if item['fenlei'] in fenlei_catgory.keys(): if item['tags'].split(",")[0]: # 判断是否有标签,有标签的直接发布,没有的手工 # NewPost()方法,新建一篇文章 newpost = WordPressPost( ) # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例 newpost.title = item['title'] newpost.content = item['content'] newpost.excerpt = item['summay'] newpost.post_status = 'publish' # private表示私密的,draft表示草稿,publish表示发布 newpost.comment_status = "open" newpost.terms_names = { 'post_tag': item['tags'].split(",")[:2], # 文章所属标签,没有则自动创建 'category': fenlei_catgory.get(item['fenlei']) } # 文章所属分类,没有则自动创建} time.sleep(random.randint(30, 120)) aid = client.call(posts.NewPost(newpost)) if aid: kuaijiwangarticle.update_one({'_id': item['_id']}, {'$set': { 'status': 1 }}) ar_url = "https://www.yebing.cn/article_{}.html".format( aid) print(ar_url) flush(ar_url)
def create_post_obj(title, content, link, post_status, terms_names_post_tag, terms_names_category): post_obj = WordPressPost() post_obj.title = title post_obj.content = content post_obj.link = link post_obj.post_status = post_status post_obj.comment_status = "open" print(post_obj.link) post_obj.terms_names = { #文章所属标签,没有则自动创建 'post_tag': terms_names_post_tag, #文章所属分类,没有则自动创建 'category': terms_names_category } return post_obj
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 post_article(title, content, thumbnail_id=None, excerpt='', tags=[], categories=[], comment_status='open', post_status='publish'): article = WordPressPost() article.title = title article.content = content article.excerpt = excerpt article.terms_names = {"post_tag": tags, "category": categories} article.comment_status = comment_status if thumbnail_id: article.thumbnail = thumbnail_id article.post_status = post_status article.id = _client.call(posts.NewPost(article)) return article.id
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 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(self, title, content, image_url, keywords): try: post = WordPressPost() post.title = title post.comment_status = 'approve' post.content = content post.status = 'draft' attachment_id = self.upload_pic(image_url) post.thumbnail = attachment_id post.terms_names = { 'post_tag': keywords, 'category': ['To review'] } self.client.call(NewPost(post)) except Exception as e: print( 'Some errors trying to publish to Wordpress (Wordpress.py): ' + str(e)) return False return True
def wordpress_artice(wppost_status,wp_title,wp_slug_title,wp_content,wp_category,wp_post_tag, wp_host,wp_user,wp_password): 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.comment_status = 'open' newpost.title= wp_title newpost.content= wp_content post_id = client.call(posts.NewPost(newpost)) #发布新建的文章,返回的是文章id print("Wordpress发布成功:",wp_title) return post_id except ServerConnectionError: print('WordPress登录失败')
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 push_wp(): try: # 检测是否登录成功 # 登录WordPress后台 client = Client("https://www.yebing.cn/xmlrpc.php", "yebing", "yeye910103") except ServerConnectionError: print('登录失败') else: print('登录成功') # wp = client.call(posts.GetPosts({'orderby': 'post_modified', 'number': 50})) # for w in wp: # print(w.link) for item in article.find({"status": 0}): # NewPost()方法,新建一篇文章 newpost = WordPressPost() # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例 newpost.title = item['title'] newpost.content = item['content'] newpost.excerpt = item['summary'] newpost.post_status = 'draft' # private表示私密的,draft表示草稿,publish表示发布 newpost.comment_status = "open" newpost.terms_names = { 'post_tag': item['keyword'].split(","), # 文章所属标签,没有则自动创建 'category': ["会计实务"] } # 文章所属分类,没有则自动创建} print(item['keyword'].split(",")) time.sleep(random.randint(30, 80)) aid = client.call(posts.NewPost(newpost)) if aid: article.update_one({'_id': item['_id']}, {'$set': { 'status': 1 }}) print(aid) # 发布新建的文章,返回的是文章id
def upload_file(): if request.method == 'POST': url1=request.form['url'] #return(url1) ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320', }], 'outtmpl':'%(title)s-%(id)s.%(ext)s' } with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url1, download=True) mp3FileName = ydl.prepare_filename(info).replace(info['ext'], 'mp3') print(mp3FileName) newfile=mp3FileName.split(" ",1)[0] identify=newfile + "mp3file" newFileName=newfile + ".mp3" os.rename(mp3FileName,newFileName) audiofile=eyed3.load(newFileName) Title= request.form['title'] if not (Title==""): Title=Title else: Title="kanniyam" Artist = request.form['artist'] if not (Artist==""): Artist=Artist else: Artist="Kanniyam" Album = request.form['album'] if not (Album==""): Album=Album else: Album="Kanniyam" Genre = request.form['genre'] if not (Genre==""): Genre=Genre else: Genre="Podcast" Source_url = bytes(request.form['source_url'],'utf-8') if not (Source_url==""): Source_url=Source_url else: Source_url="" License = str(request.form['license']) if not (License==""): License=License else: License="https://creativecommons.org/licenses/by/4.0/" Comments = str(request.form['comments']) if not (Comments==""): Comments=Comments else: Comments="" Language = str(request.form['language']) if not (Language==""): Language=Language else: Language="Tamil" Art_name = request.form['art_name'] if not (Art_name==""): Art_name=Art_name else: Art_name="Kanniyam" Publisher_url = bytes(request.form['publisher_url'],'utf-8') if not (Publisher_url==""): Publisher_url=Publisher_url else: Publisher_url="http://www.kaniyam.com" print (type(Publisher_url)) print ("ssss") audiofile.tag.title = u""+Title audiofile.tag.artist = u""+Artist audiofile.tag.album = u""+Album audiofile.tag.genre = u""+Genre audiofile.tag.source_url = b""+Source_url audiofile.tag.license = u""+License audiofile.tag.comments.set(u""+Comments, description=u"") audiofile.tag.language = u""+Language audiofile.tag.art_name = u""+Art_name audiofile.tag.publisher_url = b""+Publisher_url audiofile.tag.save() print ("after save") ia_upload = "ia upload " + identify + \ " -m collection:opensource -m mediatype:audio -m sponsor:Kaniyam -m language:ta " + \ newFileName os.system(ia_upload) audioURL = "https://archive.org/download/%s/%s" % (identify, newFileName) print ("file uploaded") print("Posting into WordPress") client = Client(blog url,username,password) post = WordPressPost() content = "%s \n %s"% (audioURL, Comments) post.title = Title post.content = content post.post_status = 'publish' post.comment_status = 'open' post.terms_names = {'category': ['Podcast']} post.slug = newfile post.id = client.call(posts.NewPost(post)) print("Posted into WordPress") return "File updated"
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 # FIXME: Make sure tags and category are defined. Don't assume they are. post.terms_names = { 'post_tag': [config.wordpress['tags']], 'category': [config.wordpress['category']] } url = config.wordpress['uploads_url'].format(config.season, config.episode, config.mp3_file) if config.wordpress['podcast_plugin'] == 'Powerpress': config = get_audio_size_and_duration(config) enclosureData = { 'duration': config.mp3['duration'], 'size': config.mp3['size'], ### Below items are best left undefined unless we really ### want to force their settings per upload. # 'embed': True, # 'keywords': '', # 'subtitle': '', # 'summary': '', # 'gp_desc': '', # 'gp_explicit': False, # 'gp_block': '', # 'author': '', # 'no_player': False, # 'no_links': False, # 'explicit': False, # 'cc': '', # 'order': 0, # 'always': '', # 'block': '', # 'image': '', # 'ishd': False, # Is an HD Video # 'height': 0, # Video Height # 'width': 0, # Video Width # 'webm_src': '', # 'feed_title': '', } post.custom_fields = [] post.custom_fields.append({ 'key': 'enclosure', 'value': "{}\n{}\n{}\n{}".format(url, config.mp3['size'], config.tags['podcast_type'] or 'episodic', dumps(enclosureData).decode('ascii')), }) post.id = wp.call(NewPost(post))
args = parser.parse_args() zim_parser = get_parser('wiki') wiki_text = open(args.file).read() tree = zim_parser.parse(wiki_text) if args.wordpress: wp = Client('http://%s/xmlrpc.php' % args.wordpress, args.username, args.password) else: wp = None source_dir = os.path.splitext(args.file)[0] linker = WordPressLinker(source_dir, wp) dumper = WordPressPostDumper(linker=linker) lines = dumper.dump(tree) wordpress_text = ''.join(lines).encode('utf-8') #print wordpress_text assert dumper.wp_title is not None post = WordPressPost() post.title = dumper.wp_title post.content = wordpress_text post.comment_status = 'open' # allow comments post.terms_names = {'post_tag': dumper.wp_tags, 'category': []} if wp: wp.call(NewPost(post)) else: print post.content
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
புத்தக எண் - ''' + str(book_number) + ''' ''' print("Publising the Ebook") content = content + extra post.title = book_title + " - " + category + " - " + author post.slug = book_title_in_english post.post_type = 'ebooks' post.content = content post.thumbnail = attachment_id post.comment_status = 'open' post.post_status = 'publish' #post.post_status = 'draft' if artist: post.terms_names = { 'genres': [category], 'contributors': [artist, ebook_maker], 'authors': [author] } else: post.terms_names = { 'genres': [category], 'contributors': [ebook_maker],
def add_movies(page_num, choice): while True: if (choice == 'a' or choice == 'upcoming'): term_tag = 'upcoming' term_cat = 'upcoming' get_url = "/3/movie/upcoming?page=" + str( page_num ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a" if (choice == 'b' or choice == 'nowplaying'): term_tag = 'Now playing' term_cat = 'now_playing' get_url = "/3/movie/now_playing?page=" + str( page_num ) + "&language=en-US&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a" if (choice == 'c' or choice == 'archives' or choice == 'archive'): term_tag = 'archives' term_cat = 'archives' get_url = "/3/discover/movie?page=" + str( page_num) + "&language=en-US&primary_release_date.lte=" + str( date) + "&api_key=eedcd0a42e1921c7f3da84ad5fdeaa2a" try: #making the connection to the api print("making the connection") conn = http.client.HTTPSConnection("api.themoviedb.org") payload = "{}" print("getting all the movies from page " + str(page_num)) #getting the movies data , key = now playing print("making the api req") #print(get_url , term_cat , term_tag) conn.request("GET", get_url, payload) res = conn.getresponse() data = res.read() response = json.loads(data.decode("utf-8")) #connecting to wordpress wp = Client('http://172.104.189.102/xmlrpc.php', 'octraves', 'octraves') # THE MAIN LOOP FOR ADDING ALL THE MOVIES TO THE WP DATABASE counter = 1 for movie in response['results']: try: print("Adding movie number = " + str(counter) + "id : " + str(movie['id'])) #download and upload the image to wordpress url = "http://image.tmdb.org/t/p/w200" + movie[ 'poster_path'] image_name = str(movie['id']) + '.jpg' image_location = '/Users/user/Desktop/wordpress_images/' + image_name urllib.request.urlretrieve( url, image_location) # download the image image = image_location imageType = mimetypes.guess_type(str(image))[0] img_data = { 'name': image_name, 'type': imageType, } with open(image, 'rb') as img: img_data['bits'] = xmlrpc_client.Binary(img.read()) img_response = wp.call(media.UploadFile(img_data)) attachment_id = img_response[ 'id'] # id to be appended in post #getting the trailer try: link = details.get_trailer(movie['id']) except: link = "" pass # Creating custom fields fields = [['Languages', movie['original_language']], ['Release Date', movie['release_date']]] # Creating the post post = WordPressPost() post.title = movie['title'] post.post_type = 'post' post.mime_type = "text/html" post.content = genres.get_primary_info( movie['id'] ) + """<h3> Overview </h3> """ + movie[ 'overview'] + """<h3> Trailer </h3> """ + " \n" + link + " \n" + " \n" + " \n" + """<h3> Credits </h3> """ + " \n" + " \n" + " \n" + str( details.get_credits(movie['id'], 'cast')) + details.get_poster( movie['id']) post.thumbnail = attachment_id post.terms_names = { 'post_tag': [term_tag], term_cat: genres.get_genres(movie['genre_ids']), 'category': genres.get_genres(movie['genre_ids']) } post.custom_fields = [] for field in fields: post.custom_fields.append({ 'key': field[0], 'value': field[1] }) post.post_status = 'publish' post.comment_status = 'open' #finally publish the post !! post.id = wp.call(posts.NewPost(post)) #add comments reviews = details.get_reviews(movie['id']) for review in reviews: comment = WordPressComment() comment.author = review['author'] comment.content = review['content'] wp.call(comments.NewComment(post.id, comment)) counter += 1 except Exception as e: print( "All the pages have been processed or there is a error!! " + str(e)) pass print("Page number " + str(page_num) + " is completed ! Loading another page.") page_num += 1 except Exception as e: print(str(e))
response = wordpress.call(media.UploadFile(data)) # substitute picture placeholders in content with WP loaded URL if response['url'] is not None: parsed_url = urlparse.urlparse(response['url']) html_img='<a href=' + response['url'] + ' target=_blank><img class=aligncenter src=' + response['url'] + ' /></a>' content = content.replace('[IMG' + str(filecount) + ']', html_img) else: print "DBG File '" + filename +"' cannot be found." sys.exit(1) # assemble post object (as draft first) new_post = WordPressPost() new_post.status = 'draft' new_post.title = title new_post.content = content new_post.comment_status = 'open' new_post.ping_status = 'open' if post_date is not None and len(post_date.strip()) > 0: #new_post.date = dateutil.parser.parse(post_date + " " + datetime.now(tzlocal()).tzname()) new_post.date = dateutil.parser.parse(post_date) # categorise post if categories is not None and len(categories.strip()) > 0: for category in categories.split(','): category_objects = wordpress.call(taxonomies.GetTerms('category', {'search': category, 'orderby': 'count', 'number': 1})) if category_objects != None: for category_object in category_objects: new_post.terms.append(category_object) # dump out post object
def wp_post(anime_title, track_name, track_id, artists, img_url, release_date, flag): wp = Client(hiddenInfo.wp_URL, hiddenInfo.wp_author, hiddenInfo.wp_pass) post = WordPressPost() #Title title = "「{}」が配信が開始".format(track_name) #Content img_source = "<img src=\"{}\" />".format(img_url) article_top = "アニメ「{}」の「 {}」 がSpotifyにて配信が開始されました!".format( anime_title, track_name) #Artists list to string artists_str = ','.join(artists) #Table table_template = "<table style=\"width: 100%; background-color: #fff5f5;\">\ <tbody>\ <tr>\ <td style=\"background-color: #ffd4d4;\"><span style=\"font-size: 8pt;\">アニメタイトル</span></td>\ </tr>\ <tr>\ <td><span style=\"font-size: 14pt;\"><strong>{}</strong></span></td>\ </tr>\ <tr>\ <td style=\"background-color: #ffd4d4;\"><span style=\"font-size: 8pt;\">トラック名</span></td>\ </tr>\ <tr>\ <td><span style=\"font-size: 14pt;\"><strong>{}</strong></span></td>\ </tr>\ <tr>\ <td style=\"background-color: #ffd4d4;\"><span style=\"font-size: 8pt;\">アーティスト</span></td>\ </tr>\ <tr>\ <td><span style=\"font-size: 14pt;\"><strong>{}</strong></span></td>\ </tr>\ <tr>\ <td style=\"background-color: #ffd4d4;\"><span style=\"font-size: 8pt;\">リリース日</span></td>\ </tr>\ <tr>\ <td><span style=\"font-size: 14pt;\"><strong>{}</strong></span></td>\ </tr>\ </tbody>\ </table>".format(anime_title, track_name, artists_str, release_date) #Spotify_HTML_Player player = "<h3>視聴</h3><iframe src=\"https://open.spotify.com/embed/track/{}\" width=\"100%\" height=\"80\" frameborder=\"0\"></iframe><br><br>".format( track_id) #URL link = "Spotify URL (Webプレイヤーが開きます)<br><a href=\"https://open.spotify.com/track/{}\">https://open.spotify.com/track/{}</a>".format( track_id, track_id) body = img_source + article_top + table_template + player + link #Post status if (flag == 1): post_status = 'draft' else: post_status = 'publish' #Tag and category tag = artists cat = [] year = release_date.split('-')[0] month = int(release_date.split('-')[1]) if (month >= 9): season = "秋アニメ" elif (month >= 7): season = "夏アニメ" elif (month >= 4): season = "春アニメ" elif (month >= 1): season = "冬アニメ" cat_set = year + season cat.append(cat_set) #Add child category add_child_category(cat_set, anime_title) cat.append(anime_title) tag_cat = {'post_tag': tag, 'category': cat} #Custom field # customFields = [{'key': 'fifu_image_url','value': img_url}] # set param---------- post.title = title post.content = body post.terms_names = tag_cat datetime.now() post.post_status = post_status post.comment_status = 'open' # post.custom_fields = customFields #-------------------- wp.call(NewPost(post))
def post_article(self, wpUrl, wpUserName, wpPassword, articleTitle, articleCategories, articleContent, articleTags, PhotoUrl, date, logo_name, post_name): self.path = os.path.join(os.getcwd(), "00000001.jpg") self.articlePhotoUrl = PhotoUrl self.wpUrl = wpUrl self.wpUserName = wpUserName self.wpPassword = wpPassword #Download File print self.articlePhotoUrl #r = requests.get(self.articlePhotoUrl,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)'}) #with open('test.jpg', "wb") as f: # f.write(r.content) from PIL import Image from StringIO import StringIO import urllib2 #content = r.content self.articlePhotoUrl = self.articlePhotoUrl.replace( 'www.macappdownload.net', 'www.macbed.com') print self.articlePhotoUrl print 'vvvvvvvvvvvvvvvvvvvvv' r = requests.get( self.articlePhotoUrl, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:16.0) Gecko/20100101 Firefox/16.0,gzip(gfe)' }) #content = urllib2.urlopen(self.articlePhotoUrl).read() im = Image.open(StringIO(r.content)) #im.seek(0) #im.verify() rgb_im = im.convert('RGB') self.path = os.path.join(os.getcwd(), 'image', logo_name) print self.path rgb_im.save(self.path) #Upload to WordPress client = Client(self.wpUrl, self.wpUserName, self.wpPassword) filename = self.path # prepare metadata data = {'name': logo_name, 'type': 'image/jpeg'} # read the binary file and let the XMLRPC library encode it into base64 print filename with open(filename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) print 'aaaaaaaaaaaa' attachment_id = response['id'] #Post post = WordPressPost() post.title = articleTitle try: post.date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M") post.date_modified = datetime.datetime.strptime( date, "%Y-%m-%d %H:%M") except: post.date = datetime.datetime.strptime(date, "%Y-%m-%d") post.date_modified = datetime.datetime.strptime(date, "%Y-%m-%d") post.slug = post_name post.comment_status = "open" 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 if post.content.find('https://nmac.to') != -1: image = client.call(media.GetMediaItem(attachment_id)) import re post.content = re.sub(r'https://nmac.to(\S+).png', image.link, post.content) client.call(posts.EditPost(post.id, post)) print 'Post Successfully updated. Its Id is: ', post.id
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/jpeg', # } #print (response) testing1234 =raw_input("hit enter when ready") attachment_id = response['id'] post = WordPressPost() post.thumbnail = attachment_id post.title = "some title" #add some title text here post.content = "some content" # add some context text here post.comment_status = 'open' #turn on comments or closed for off post.terms_names = { #'post_tag': ['blog'], #add your tags 'category': ['blog'] #add your category } #publish or draft draft is the default #post.post_status = 'publish' wp.call(NewPost(post)) print ("new post, posted")