def TranslateBatchPosts(batch_posts): for post in batch_posts: translated_post = TranslatePost(post) try: wp.call(EditPost(translated_post.id, translated_post)) print("Uploaded: " + translated_post.id) except: try: post.thumbnail=post.thumbnail['attachment_id'] wp.call(EditPost(translated_post.id, translated_post)) print("Uploaded: " + translated_post.id) except: error.append([post.id, "upload"]) error_file.write("Upload, " + translated_post.id)
def publish_post(podcast_and_config, wp_details, wp, settings): '''copies the podcast object, updates it according to the supplied details dict and edits the one on the blog''' podcastcopy = copy.copy(podcast_and_config[0]) podcastcopy.title = wp_details['title'] podcastcopy.content = wp_details['content'] podcastcopy.date = wp_details['date'] podcastcopy.post_status = wp_details['post_status'] if type(podcast_and_config[0].thumbnail) == types.DictType: podcastcopy.thumbnail = podcast_and_config[0].thumbnail[ 'attachment_id'] fields_of_interest = [ 'audio_file', 'bible_passage', 'duration', 'episode_number', 'filesize_raw', 'preacher', 'publish_now', 'date_recorded' ] for custom_fields in podcastcopy.custom_fields: if custom_fields['key'] in fields_of_interest and custom_fields[ 'key'] in wp_details: custom_fields['value'] = wp_details[custom_fields['key']] fields_of_interest.remove(custom_fields['key']) for custom_field in fields_of_interest: if custom_field in wp_details: podcastcopy.custom_fields.append({ 'key': custom_field, 'value': wp_details[custom_field] }) if 'tags' in wp_details and wp_details['tags'] != []: podcastcopy.terms.extend(wp_details['tags']) if wp.call(EditPost(podcastcopy.id, podcastcopy)): return wp.call(GetPost(podcastcopy.id)) else: print('Could not update podcast ' + podcastcopy.id + ': ' + podcastcopy.title)
def createPost(image): localFilename = 'images/{0}'.format(image + '.jpg') print 'image is: {0}'.format(localFilename) imageTimestamp = getTimestamp(image) wpFilename = image + imageTimestamp + '.jpg' data = { 'name': '{0}'.format(wpFilename), 'type': 'image/jpeg', } with open(localFilename, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = client.call(media.UploadFile(data)) print 'response is: {0}'.format(response) month = strftime("%m", gmtime()) post = WordPressPost() post.title = country + city post.content = '[caption id="" align="alignnone" width ="640"]<img src="http://www.backdoored.io/wp-content/uploads/2016/' + month + '/' + wpFilename.replace( ":", "" ) + '">' + ipAddress + hostnames + isp + timestamp + country + city + '[/caption]' post.id = client.call(NewPost(post)) post.post_status = 'publish' client.call(EditPost(post.id, post))
def update(self, _page_title, _page_id, _markdown): """ Update an existing wordpress page with generated markdown. Assumes you have a markdown file with content you want published to an existing wordpress page. :param _page_title: post page title :param _page_id: post page id :param _markdown: path to markdown file for upload """ wp = Client(self.endpoint, self.username, self.password) # define pages variable page = WordPressPage() page.title = _page_title # page id can be found by viewing via wp-admin dashboard in URL page.id = _page_id # set local content file to read handle info into a string with open(_markdown, "r") as _file: page.content = _file.read() # post new content to the page wp.call(EditPost(page.id, page))
def edit_post(self, blog, post_id): """ Edit a post. """ xmlrpc = self.get_xmlrpc(blog) post = WordPressPost() post.title = 'Edited post from api' post.description = 'Edited description' return xmlrpc.call(EditPost(post_id, post, True))
def editPost(self, title, content, id): try: post = WordPressPost() post.title = title post.content = content post.id = id post.post_status = 'publish' self.client.call(EditPost(post.id, post)) except Exception as e: print(e) print("Unable to edit post!")
def trashPost(self, postIDs): for postID in postIDs: post = WordPressPost() #根据ID查看文章 try: plot = self.wp.call(GetPost(postID)) # print('删除文章:',plot,type(plot),plot.title) post.title = plot.title post.post_status = 'trash' self.wp.call(EditPost(postID, post)) print('已删除文章[ID]:[%s],[标题]:%s' % (postID, plot.title)) except: print('文章[ID]:[%s],已经被删除,请不要重复删' % postID)
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 main(): blog_settings = yaml.load(Path('./blog.yml').read_text()) wp = Client(blog_settings['xmlrpc-url'], blog_settings['username'], blog_settings['password']) articles = wp.call(GetPosts()) [article.title for article in articles] post = WordPressPost() post.title = 'My new title' post.content = 'This is the body of my new post.' wp.call(NewPost(post)) post.post_status = 'publish' wp.call(EditPost(post.id, post))
def upload (self): wp_url = 'http://www.py4seo.com/xmlrpc.php' login = '******' passw = '123456' client = Client(wp_url, login, passw) posts = client.call(GetPosts({'number': 10000})) post = WordPressPost() for ttl, content in self.trans_posts.items(): post.title = ttl post.content = content post.id = client.call(NewPost(post)) post.post_status = 'publish' client.call(EditPost(post.id, post)) url = f'http://py4seo.com/?p={post.id}' print(f'ЗАПОСТИЛИ СТАТЬЮ С ТАЙТЛОМ {ttl}' + ' - ' + url)
def updatePost(config, html): blog = Client(settings.blogXmlRpc, settings.blogUsername, settings.blogPassword) post = WordPressPost() post.title = config['post_title'] post.id = config['id'] post.terms_names = {} post.terms_names['category'] = config['category'] post.content = html # post.content = markdown.markdown(content) myposts = blog.call(EditPost(post.id, post))
def update_wiki(url, username, password, _page_title, _page_id, _markdown): wp = Client(url, username, password) # define pages variable page = WordPressPage() page.title = _page_title # page id can be found by viewing via wp-admin dashboard in URL page.id = _page_id # set local content file to read handle info into a string with open(_markdown, 'r') as _file: page.content = _file.read() # post new content to the page wp.call(EditPost(page.id, page))
def create_new_post(wp_instance, title='', content='', author='', tags=[], category=['USAF']): post = WordPressPost() post.title = title content = reformat_url_with_htmltag(content) post.content = content tags.append(author) tags = tags + generate_tags(content) category.append(author) # By far, only classify the 'Kadena' and 'Andersen' AFB if 'Kadena' in tags: category.append('Kadena') if 'Andersen' in tags: category.append('Andersen') post.terms_names = { 'post_tag': tags, 'category': category } post.post_status = 'publish' # insert the new post post_id = wp_instance.call(NewPost(post)) # update the published date to the tweet datetime re_object = re.compile('(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s.*\s\d{4}') original_time = re_object.search(content).group() post.date = parse_post_formated_time(original_time) post.date_modified = post.date # update the post author to the tweet screen name post.post_author = 2 wp_instance.call(EditPost(post_id, post)) return post_id
def Upload(self, directory, filename): """Uploads/Updates/Replaces files""" db = self._loadDB(directory) logger.debug("wp: Attempting upload of %s" % (filename)) # See if this already exists in our DB if db.has_key(filename): pid = db[filename] logger.debug('wp: Found %s in DB with post id %s' % (filename, pid)) else: pid = None fullfile = os.path.join(directory, filename) fid = open(fullfile, 'r') # Read meta data and content into dictionary post = self._readMetaAndContent(fid) #Connect to WP self._connectToWP() # If no pid, it means post is fresh off the press # and not uploaded yet! if not pid: # Get a PID by uploading pid = self.wp.call(NewPost(post)) if pid: logger.debug("wp: Uploaded post with pid %s", pid) db[filename] = pid self._saveDB(directory, db) return True else: logger.error("wp: Couldn't upload post") return False else: # Already has PID, replace post logger.debug("wp: Replacing post with pid %s", pid) #FIXME: Check return value?! self.wp.call(EditPost(pid, post)) return True return False
def _update_an_article(self, postid): afile, aname = self.conf.get_article(postid, self.args.type) # If output is provided, write the html to a file and abort. if self.args.output: self._write_html_file(afile) return html, meta, txt, medias = self._get_and_update_article_content(afile) if not html: return resultclass = WordPressPost if self.args.type == 'page': postid = meta.postid resultclass = WordPressPage post = self.wpcall(GetPost(postid, result_class=resultclass)) if not post: slog.warning('No post "%s"!'%postid) return slog.info('Old article:') self.print_results(post) post.title = meta.title post.user = meta.author post.slug = meta.nicename post.date = meta.date post.content = html post.post_status = meta.poststatus if meta.modified: post.date_modified = meta.modified terms = self.cache.get_terms_from_meta(meta.category, meta.tags) if terms: post.terms = terms elif self.args.type == 'post': slog.warning('Please provide some terms.') return succ = self.wpcall(EditPost(postid, post)) if succ == None: return if succ: slog.info('Update %s successfully!'%postid) else: slog.info('Update %s fail!'%postid)
def edit_post(self, post_id, title, content, categrory, post_tag, img_list): post = WordPressPost() post.title = title post.content = content post.categrory = [] post.categrory.append(categrory) if post_tag is not None: post.terms_names = { 'post_tag': post_tag, 'category': post.categrory } else: post.terms_names = {'post_tag': '', 'category': post.categrory} post.post_status = 'publish' self.wp.call(EditPost(post_id, post)) print('正在修正[ID]:%s,[标题]:%s' % (post_id, post.title)) return post_id, len(post.content)
def sync_post(self, estate): try: wp_meta = estate.wp_meta old_post = self.get_post_by_estate(estate) wp_meta.post_id = old_post.id if old_post else None if wp_meta.post_id == -1: wp_meta.status = EstateWordpressMeta.MULTIKEYS wp_meta.save() return False post = self.assemble_post(estate, old_post, True) if not wp_meta.post_id: wp_meta.post_id = self.client.call(NewPost(post)) else: self.client.call(EditPost(wp_meta.post_id, post)) wp_meta.status = EstateWordpressMeta.UPTODATE wp_meta.save() return True except xmlrpclib.ProtocolError as err: wp_meta.error_message = prepare_err_msg(err) wp_meta.save() except Exception, err: wp_meta.error_message = prepare_err_msg(err) wp_meta.status = EstateWordpressMeta.ERROR wp_meta.save()
def edit_post(id, title, content, link, post_status, terms_names_post_tag, terms_names_category): post_obj = create_post_obj(title, content, link, post_status, terms_names_post_tag, terms_names_category) res = wp.call(EditPost(id, post_obj)) print(res)
key = input("Enter key: ") text = ' '.join(parse_google(key)) parse_image(key) image_path = f"images\\{listdir('images')[0]}" post = WordPressPost() post.title = f'Dz29 Vertinskyi Post For Key: {key}' post.content = text post.terms_names = {'post_tag': ['dz29', key], 'category': ['vertinskyi', key]} new_post = wp_client.call(NewPost(post)) post.post_status = 'publish' wp_client.call(EditPost(new_post, post)) data = { 'name': image_path, 'type': 'image/jpeg', } with open(image_path, 'rb') as img: data['bits'] = xmlrpc_client.Binary(img.read()) response = wp_client.call(media.UploadFile(data)) my_post = wp_client.call(GetPost(new_post)) my_post.thumbnail = response['id']
def postNews(self, tweets): wp = Client(self.wp_xmlrpc_url, self.wp_username, self.wp_password) posts = wp.call(GetPosts()) post = posts[0] post_date = post.title[10:] # Assuming Asia/Tokyo. now_tokyo = datetime.now() + timedelta(hours=9) today_date = now_tokyo.isoformat().decode('utf-8')[10:] if (post_date != today_date): post = WordPressPost() post.title = u'Tweets on ' + today_date post.content = '<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>' post.id = wp.call(NewPost(post)) logging.info(post.id) htmls = post.content.split('<hr class="tweetboxdelimiter" />') # logging.debug(htmls) tweet_ids = [] for html in htmls: match = re.search(r'/status/(\d+)', html) if match: tweet_ids.append(int(match.group(1))) logging.info(tweet_ids) tmpl = u''' <div class="tweetbox"> <div class="tweetheaderbox"> <a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorprofile"><img src="%s" /></a> <a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorname">%s</a> <a href="https://twitter.com/intent/user?user_id=%s" class="tweetauthorscreenname">@%s</a> <a href="https://twitter.com/intent/user?user_id=%s" class="tweetfollow"><img src="/wp-content/themes/slight/images/twitter/bird_gray_16.png" alt="Follow" title="Follow" /></a> </div> <div class="tweetcenterbox">%s</div> <div class="tweetfooterbox"> <a href="https://twitter.com/%s/status/%s" class="tweettimestamp">%s</a> <div class="tweetactionbox"> <a href="https://twitter.com/intent/tweet?in_reply_to=%s" class="tweetreply"><img src="/wp-content/themes/slight/images/twitter/reply.png" alt="Reply" title="Reply" /></a> <a href="https://twitter.com/intent/retweet?tweet_id=%s" class="tweetretweet"><img src="/wp-content/themes/slight/images/twitter/retweet.png" alt="Retweet" title="Retweet" /></a> <a href="https://twitter.com/intent/favorite?tweet_id=%s" class="tweetfavorite"><img src="/wp-content/themes/slight/images/twitter/favorite.png" alt="Favorite" title="Favorite" /></a> </div> </div> </div> '''.replace("\n", "") new_htmls = [] for tweet in tweets: if tweet.author.screen_name != u'your_twitter_username': if not tweet.id in tweet_ids: if re.match(r'.*' + self.keyword + '.*', tweet.text): logging.info(tweet.text) html = tmpl % ( tweet.author.id, tweet.author.profile_image_url, tweet.author.id, tweet.author.name, tweet.author.id, tweet.author.screen_name, tweet.author.id, tweet.text, tweet.author.screen_name, tweet.id, tweet.created_at + timedelta(hours=9), tweet.id, tweet.id, tweet.id) new_htmls.append(html) if new_htmls: htmls = htmls + new_htmls html = '<hr class="tweetboxdelimiter" />'.join(htmls) # logging.debug(html) post.content = html post.post_status = 'publish' wp.call(EditPost(post.id, post)) return
def main(): # look for command line arguments args = sys.argv[1:] if '-h' in args or '--help' in args or '-?' in args: helptext() sys.exit(0) if '-l' in args: logging = True logfilename = args[args.index('-l') + 1] trimlogfile(logfilename) logfile = open(logfilename, 'a') oldstdout = sys.stdout oldstderr = sys.stderr logsplit = LogFileSplitter(sys.stdout, logfile) sys.stdout = logsplit sys.stderr = logsplit print('Logging started.') if '-c' in args: configfile = args[args.index('-c') + 1] if not os.path.isfile(configfile): print(configfile + ' does not exist, create it? (Y/N):') if not raw_input().lower() == 'y': print('OK, config file will not be created') if logging == True: sys.stdout = oldstdout sys.stderr = oldstderr logfile.close() sys.exit(0) else: configfile = '/etc/ssp_sermon_podcast.xml' if ('--config' in args) or not os.path.isfile(configfile): edit_config_file(configfile) print('Config file created and will be used on next run.') if logging: sys.stdout = oldstdout sys.stderr = oldstderr logfile.close() sys.exit(0) #load the config file if os.path.isfile(configfile): try: configET = ET.parse(configfile) except: print('Can\'t parse config file ' + configfile) sys.exit(1) config = configET.getroot() if not ((config.tag == 'config') and (config.attrib['description'] == 'Seriously Simple Podcasting Sermon Podcast settings')): print(configfile + ' is not a SSP Sermon Podcast config file.') if logging: sys.stdout = oldstdout sys.stderr = oldstderr logfile.close() sys.exit(1) #get the settings from the config settings = config.find('settings') #open the wordpress object wordpress_url = settings.find('wordpress_url').text if wordpress_url.endswith('/'): xmlrpc_url = wordpress_url + 'xmlrpc.php' else: xmlrpc_url = wordpress_url + '/xmlrpc.php' wp = Client(xmlrpc_url, settings.find('wordpress_user').text, decryptpassword(settings.find('wordpress_pass').text)) #get a list of podcast objects allpodcasts = [] interval = 20 offset = 0 while True: podcastbatch = wp.call( GetPosts({ 'post_type': 'podcast', 'number': interval, 'offset': offset })) if len(podcastbatch) == 0: break allpodcasts.extend(podcastbatch) offset += interval print('Retrieved ' + str(len(allpodcasts)) + ' podcasts from WordPress site.') #get the series settings from the config and find out which series will be podcast allseriesconfigs = config.findall('series_config') termids_to_podcast = [] for seriesconfig in allseriesconfigs: termids_to_podcast.append(seriesconfig.attrib['term_id']) #get a list of series from the blog listofseriesterms = [] interval = 20 offset = 0 while True: termsbatch = wp.call( GetTerms('series', { 'number': interval, 'offset': offset })) if len(termsbatch) == 0: break listofseriesterms.extend(termsbatch) offset += interval print('Found ' + str(len(listofseriesterms)) + ' podcast series on the WordPress site.') #find out the hierarchy of the series so we can do the lowest children first termpriority = {} term_parents = {} for term in listofseriesterms: term_parents[term.id] = term.parent order = 0 parentid = term.parent while parentid != '0': order += 1 for parentterm in listofseriesterms: if parentid == parentterm.id: parentid = parentterm.parent break termpriority[term.id] = order #so the order to approach term.ids is termid_order = [] for termid, order in sorted(termpriority.iteritems(), key=lambda x: x[1], reverse=True): termid_order.append(termid) print('This is the order the series terms will be published:') print(', '.join(termid_order)) #find which series config the posts should be published with (if any) podcasts_to_do = {} extension = extension_dot(settings.findtext('source_audio_type')) for termid in termid_order: if termid in termids_to_podcast: for podcast in allpodcasts: #check whether the podcast is flagged to be published and has a date: date_recorded = get_post_custom_field(podcast, 'date_recorded') if get_post_custom_field(podcast, 'publish_now') and date_recorded: podcast_termids = ['0'] for podcastterm in podcast.terms: podcast_termids.append(podcastterm.id) for podcast_termid in podcast_termids: if podcast_termid in term_parents: podcast_termids.append( term_parents[podcast_termid]) if termid in podcast_termids and not podcast.id in podcasts_to_do: #work out what the start of the source file name will be: termid_seriesconfig = seriescfg_from_term_id( allseriesconfigs, termid) source_date_format = termid_seriesconfig.find( 'source_date_format').text date_recorded_format = settings.find( 'date_recorded_format').text sourcefile_name_start = getdatetime( date_recorded, user_format=date_recorded_format ).strftime( source_date_format) + termid_seriesconfig.findtext( 'source_file_code', default='') sourcepath = termid_seriesconfig.findtext( 'source_path') #and does it exist? directorylist = [] if os.path.exists(sourcepath): #this seems to timeout sometimes, so will loop if need be: retrycount = 3 while retrycount: try: directorylist = os.listdir(sourcepath) retrycount = 0 except OSError as errmsg: print(errmsg) retrycount -= 1 if retrycount: print('Retrying directory list...') for filename in directorylist: if filename[:len(sourcefile_name_start )] == sourcefile_name_start: if extension: extposn = -len(extension) if filename[ extposn:] == extension or extension == None: ordered_podcast_termids = [] for termid_again in termid_order: if termid_again in podcast_termids: ordered_podcast_termids.append( termid_again) ordered_podcast_termids.append('0') podcasts_to_do[podcast.id] = [ podcast, termid_seriesconfig, os.path.abspath( os.path.join(sourcepath, filename)), ordered_podcast_termids ] print('There are ' + str(len(podcasts_to_do)) + ' podcasts to process in this pass.') if len(podcasts_to_do) != 0: listofposttags = [] interval = 20 offset = 0 while True: termsbatch = wp.call( GetTerms('post_tag', { 'number': interval, 'offset': offset })) if len(termsbatch) == 0: break listofposttags.extend(termsbatch) offset += interval posttagsdict = {} for posttag in listofposttags: posttagsdict[posttag.name.lower()] = posttag print('Retrieved ' + str(len(posttagsdict)) + ' post tags from WordPress site.') #iterate over the podcasts for podcast_id, podcast_and_config in podcasts_to_do.iteritems(): #open the audio file print('\n') print('Now processing file ' + podcast_and_config[2]) backuppodcast = copy.deepcopy(podcast_and_config[0]) try: sourceaudio = audiotools.open(podcast_and_config[2]) sourcepcm = sourceaudio.to_pcm() #calculate its loudness loudness = audiotools.calculate_replay_gain([sourceaudio]) for loudnesstuple in loudness: gain = loudnesstuple[1] peak = loudnesstuple[2] if peak == 0: print('This audio file is silent, ignoring it.') continue #mix it to the specified number of channels gaincorrection = 0 if settings.findtext('audiochannels') == '1': print('Converting to mono.') sourcepcm_mixed = audiotools.pcmconverter.Averager(sourcepcm) elif settings.findtext('audiochannels') == '2': print('Converting to stereo.') sourcepcm_mixed = audiotools.pcmconverter.Downmixer(sourcepcm) if sourceaudio.channels() == 1: gaincorrection = 6.0 else: sourcepcm_mixed = sourcepcm #adjust the gain to the users' preference instead of replaygain's target -20 target_loudness = float( settings.findtext('target_loudness', default='-24')) newgain = gain + (target_loudness + 20.0) + gaincorrection newpeak = 1.0 / (10.0**(newgain / 20.0)) if (peak / (10.0**(gaincorrection / 20.0))) > newpeak: newpeak = peak / (10.0**(gaincorrection / 20.0)) print( 'Normalising for gain: ' + str(round(newgain, 2)) + 'dB, peak = ' + str( round( (20.0 * log10(peak / (10.0**(gaincorrection / 20.0)))), 2)) + 'dBFS.') #normalise the audio to the target loudness sourcepcm_normalised = audiotools.replaygain.ReplayGainReader( sourcepcm_mixed, newgain, newpeak) try: bitspersample = int(settings.findtext('bitspersample')) except: bitspersample = None if bitspersample: print('Quantising to ' + str(bitspersample) + '-bit.') sourcepcm_resampled = audiotools.pcmconverter.BPSConverter( sourcepcm_normalised, bitspersample) #make some tempfiles: process_tempfile = tempfile.mkstemp( suffix='.wav', prefix='sermon_process_tempfile') processed_tempfile = tempfile.mkstemp( suffix='.wav', prefix='sermon_processed_tempfile') encoded_tempfile = tempfile.mkstemp( suffix=extension_dot(settings.findtext('encoded_audio_type')), prefix='sermon_encoded_tempfile') print('tempfiles: ' + process_tempfile[1] + ', ' + processed_tempfile[1] + ', ' + encoded_tempfile[1]) #write the audio back out to a wave file for processing audiotools.WaveAudio.from_pcm(process_tempfile[1], sourcepcm_resampled) sourcepcm_normalised.close() sourcepcm_mixed.close() sourcepcm.close() sourceaudio = None audioparams = getaudioparams(sourcepcm_resampled) sourcepcm_resampled.close() subprocess_args = [settings.findtext('processing_utility')] for argsubelement in settings.findall('processing_utility_arg'): subprocess_args.append( Template(argsubelement.text).substitute(audioparams)) tempstring = settings.findtext('processing_utility_infile') if tempstring: subprocess_args.append(tempstring) subprocess_args.append(process_tempfile[1]) tempstring = settings.findtext('processing_utility_outfile') if tempstring: subprocess_args.append(tempstring) subprocess_args.append(processed_tempfile[1]) print('Now processing audio ...') print( subprocess.Popen(subprocess_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True).communicate()[0]) os.remove(process_tempfile[1]) processedfile = audiotools.open(processed_tempfile[1]) audioparams = getaudioparams(processedfile.to_pcm()) subprocess_args = [settings.findtext('encoding_utility')] for argsubelement in settings.findall('encoding_utility_arg'): subprocess_args.append( Template(argsubelement.text).substitute(audioparams)) tempstring = settings.findtext('encoding_utility_infile') if tempstring: subprocess_args.append(tempstring) subprocess_args.append(processed_tempfile[1]) tempstring = settings.findtext('encoding_utility_outfile') if tempstring: subprocess_args.append(tempstring) subprocess_args.append(encoded_tempfile[1]) print('Now encoding audio ...') print( subprocess.Popen(subprocess_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True).communicate()[0]) os.remove(processed_tempfile[1]) wp_details = make_podcast_dict(podcast_and_config, wp, settings) wp_details['post_status'] = 'publish' wp_details['publish_now'] = '' updated_podcast = publish_post(podcast_and_config, wp_details, wp, settings) podcast_and_config[0] = updated_podcast updated_details = make_podcast_dict(podcast_and_config, wp, settings, final_pass=True) try: imageurl = urllib2.urlopen(updated_details['image']) podcastimage = imageurl.read() except: podcastimage = False try: audioimage = [ audiotools.Image.new(podcastimage, u'Artwork', 0) ] except: audioimage = [] outputmetadata = audiotools.MetaData( track_name=updated_details['title'], track_number=int(updated_details['episode_number']), album_name=updated_details['series'], artist_name=updated_details['preacher'], copyright=updated_details['copyright'], publisher=updated_details['publisher'], year=updated_details['date'].strftime('%Y'), date=updated_details['date_recorded'], comment=updated_details['content'], images=audioimage) outputfile = audiotools.open(encoded_tempfile[1]) outputfile.set_metadata(outputmetadata) outputfile_seconds = int(outputfile.seconds_length()) outputfile_name = updated_details[ 'output_file_template'] + extension_dot( settings.findtext('encoded_audio_type')) outputfile_size = ftp_encodedfile(encoded_tempfile[1], outputfile_name, podcast_and_config[1]) if outputfile_size == None: raise Exception('FTP appears not to have worked.') print('\n') print('Output file size = ' + str(outputfile_size)) print('Output file duration = ' + str(outputfile_seconds)) print('\n') os.remove(encoded_tempfile[1]) urlpath = podcast_and_config[1].findtext('download_path') if not urlpath[-1] == '/': urlpath = urlpath + '/' updated_details['audio_file'] = urlpath + outputfile_name updated_details['filesize_raw'] = str(outputfile_size) mins = str(outputfile_seconds / 60) secs = str(outputfile_seconds % 60) if len(secs) == 1: secs = '0' + secs updated_details['duration'] = mins + ':' + secs #put the preacher in as a tag: updated_details['tags'] = [] if updated_details['preacher'].lower() in posttagsdict: updated_details['tags'].append( posttagsdict[updated_details['preacher'].lower()]) else: tag = WordPressTerm() tag.taxonomy = 'post_tag' tag.name = updated_details['preacher'] tag.id = wp.call(NewTerm(tag)) updated_details['tags'].append(tag) posttagsdict[tag.name.lower()] = tag #put the book(s) of the bible in as tags: #This bit is really messy and I should try to write my own scripture regular expressions, but in the interest of speed: listofpassages = scriptures.extract( updated_details['bible_passage']) if 'song of songs' in updated_details['bible_passage'].lower(): listofpassages.append(('Song of Songs', 1, 1, 1, 1)) for passage in listofpassages: book = passage[0] if book[:4] == 'III ': bookname = '3 ' + book[4:] elif book[:3] == 'II ': bookname = '2 ' + book[3:] elif book[:2] == 'I ': bookname = '1 ' + book[2:] elif book == 'Song of Solomon': bookname = 'Song of Songs' else: bookname = book if bookname.lower() in posttagsdict: updated_details['tags'].append( posttagsdict[bookname.lower()]) else: tag = WordPressTerm() tag.taxonomy = 'post_tag' tag.name = bookname tag.id = wp.call(NewTerm(tag)) updated_details['tags'].append(tag) posttagsdict[tag.name.lower()] = tag finalpost = publish_post(podcast_and_config, updated_details, wp, settings) print('Final Post details are as follows:\n') for field, contents in finalpost.struct.iteritems(): try: if type(contents) == types.StringType: print(field + ' : ' + contents) elif type(contents) == types.ListType: for subcontents in contents: print(field + ' : ' + str(subcontents)) elif type(contents) == types.DictType: for subfield, subcontents in contents.iteritems(): print(field + ' : ' + subfield + ' : ' + str(subcontents)) elif type(contents) == types.UnicodeType: print(field + ' : ' + contents.encode('ascii', 'ignore')) else: print(field + ' : ' + str(contents)) except: print('Can\'t print field') except Exception as message: print('ERROR: Exception raised while processing that podcast:') print(message) print( 'Attempting to restore original post prior to modification...') try: if wp.call(EditPost(backuppodcast.id, backuppodcast)): print('Post restored.') else: print('Unable to restore original post.') except Exception as message: print('Unable to restore original post: ') print(message) try: os.remove(encoded_tempfile[1]) except: pass try: os.remove(processed_tempfile[1]) except: pass try: os.remove(process_tempfile[1]) except: pass logsplit.write('Completed with normal exit\n\n\n') if logging: sys.stdout = oldstdout sys.stderr = oldstderr logfile.close()
def sendPostToWordpress(post, wp, txt): # Check if there is no id. idregex = re.compile('\<ID\>\s*(?P<id>\d+)\s*\</ID\>', re.IGNORECASE | re.DOTALL) m = idregex.search(txt) if not m: print("This looks like a new post, use --post option") return else: id = m.groupdict()['id'] post.id = id title = getTitle(txt) post.title = title print("[I] Sending post : {0} : {1}.".format(id, title)) # content contentRegex = re.compile("\<CONTENT\>(?P<content>.+)\<\/CONTENT\>", re.IGNORECASE | re.DOTALL) m = contentRegex.search(txt) if m: content = m.groupdict()['content'] if len(content.strip()) == 0: print("[E] : No content in file.") return content = formatContent(content) else: print("[W] Post with empty content.") content = "" post.content = content # status statusRegex = re.compile("\<STATUS\>\s*(?P<status>\w+)\s*\</STATUS\>", re.IGNORECASE | re.DOTALL) m = statusRegex.search(txt) if m: status = m.groupdict()['status'] post.post_status = status else: print("[W] Post with uncertain status. Default to publish") pagepost.post_status = "publish" termsAndCats = dict() # tags tagRegex = re.compile("\<POST_TAG\s+ID\=\"(?P<id>\d*)\"\>\s*"+\ "(?P<tag>[\s\w]+)\s*\</POST_TAG\>", re.IGNORECASE | re.DOTALL) ms = tagRegex.findall(txt) tags = list() for m in ms: id, name = m tags.append(name) termsAndCats['post_tag'] = tags # categories catRegex = re.compile("\<CATEGORY\s+ID\=\"(?P<id>\d*)\"\>\s*"+\ "(?P<cat>[\s\w]+)\s*\</CATEGORY\>", re.IGNORECASE | re.DOTALL) mm = catRegex.findall(txt) cats = list() for m in mm: id, cat = m cats.append(cat) termsAndCats['category'] = cats post.terms_names = termsAndCats wp.call(EditPost(post.id, post)) return
def publishPost(self, post_id): post = self.wp.call(GetPost(post_id)) post.post_status = 'publish' self.wp.call(EditPost(post_id, post)) return post_id
def editPost(self, postID, sourceUrl, title, featureImg, content, category, tags, customField): post = WordPressPost() post.title = title #标题 post.content = content #内容 post.post_status = 'publish' #文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布 imgList = [] #图片列表 if customField != {}: try: if customField["imgList"]: imgList = customField["imgList"] else: imgList = str(imgList) except KeyError: print("customField中没有imgList这个图片列表") if not category: category = [ 'other', ] post.category = category print(post.category, type(post.category)) if tags: post.terms_names = { 'post_tag': tags, #文章所属标签,没有则自动创建 'category': post.category #文章所属分类,没有则自动创建 } else: post.terms_names = {'post_tag': '', 'category': post.category} #自定义字段列表 post.custom_fields = [] #添加自定义字段内容 if postID == '0': for key in customField: post.custom_fields.append({ 'key': key, 'value': customField[key] }) #print('post.custom_fields',type(post.custom_fields),post.custom_fields) else: for n in range(len(post.custom_fields)): for key in customField: if post.custom_fields[n][ 'key'] == key and post.custom_fields[n][ 'value'] != customField[key]: post.custom_fields[n]['value'] = customField[key] #如果特色图片存在,上传特色图片 if featureImg: img_name = featureImg.split('/')[-1] filename = featureImg data = {'name': img_name, 'type': 'image/jpeg'} 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 if postID == '0': postID = self.wp.call(NewPost(post)) print('正在发布[ID]:%s,[标题]:%s' % (postID, post.title)) else: self.wp.call(EditPost(postID, post)) print('正在修正[ID]:%s,[标题]:%s' % (postID, post.title)) return postID
def robo_tempo(): import requests import os token = # token de acesso do Climatempo login = # login conta wordpress senha = # senha wordpress dados_maceio = requests.get(f'http://apiadvisor.climatempo.com.br/api/v1/forecast/locale/6809/days/15?token={token}').json() dados_tempo = dados_maceio["data"] proximo_dia = dados_tempo[1] texto = proximo_dia['text_icon'] texto_longo = texto['text'] texto_longo2 = texto_longo['phrase'] texto_resumido = texto_longo2['afternoon'] texto_detalhado = texto_longo2['reduced'] texto_detalhado1, texto_detalhado2, texto_detalhado3 = texto_detalhado.split('.') if texto_detalhado3.isalpha() == False: textinho = (f'{texto_detalhado1} e{texto_detalhado2}') else: textinho = (f'{texto_detalhado1},{texto_detalhado2} e{texto_detalhado3}') data_completa = proximo_dia['date_br'] dia, mes, ano = data_completa.split('/') # datas atuais data_atual = dados_tempo[0] data_atual = data_atual['date'] ano_atual, mes_atual, dia_atual = data_atual.split('-') if mes_atual == '01': mes_atual = 'January' if mes_atual == '02': mes_atual = 'February' if mes_atual == '03': mes_atual = 'March' if mes_atual == '04': mes_atual = 'April' if mes_atual == '05': mes_atual = 'May' if mes_atual == '06': mes_atual = 'June' if mes_atual == '07': mes_atual = 'July' if mes_atual == '08': mes_atual = 'August' if mes_atual == '09': mes_atual = 'September' if mes_atual == '10': mes_atual = 'October' if mes_atual == '11': mes_atual = 'November' if mes_atual == '12': mes_atual = 'December' temperatura = proximo_dia['temperature'] maxima = temperatura['max'] minima = temperatura['min'] chuva = proximo_dia['rain'] pro_chuva = chuva['probability'] from datetime import date from datetime import datetime hj = date.today() dias = ('terça-feira', 'quarta-feira', 'quinta-feira', 'sexta-feira', 'sábado', 'domingo', 'segunda-feira') dia_semana = (dias[hj.weekday()]) if dia_semana == "sábado" or dia_semana == "domingo": pronome = 'este' else: pronome = 'esta' # Imprimindo matéria final titulo = (f"'{texto_resumido.capitalize()}', indica previsão do tempo para amanhã em Maceió") lide = (f"A previsão do tempo para a cidade de Maceió para {pronome} {dia_semana}, dia {dia}, indica {textinho.lower()}. A máxima registrada será de {maxima}ºC e a mínima de {minima}ºC. A probabilidade de chuva para amanhã é de {pro_chuva}%.") sublide = ("As informações desta matéria foram coletadas pela nossa robô do tempo <strong>Malu</strong>, de modo automatizado, no Portal Climatempo. Para saber mais sobre a Malu <strong><a href='http://www.agenciatatu.com.br/malu'>clique aqui</a></strong>.") corpo = (lide + '\n' + '\n' + sublide) print(titulo) print(lide) print(sublide) # Atualizar post from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost wp = Client('http://www.sitewordpress.com.br/xmlrpc.php', f'{login}', f'{senha}') # substituir url do site def atualizar_post(): def find_id(title): offset = 0 increment = 10 while True: filter = { 'offset' : offset } p = wp.call(GetPosts(filter)) if len(p) == 0: break for post in p: if post.title == title: return(post.id) offset = offset + increment return(False) # postando matéria final post = WordPressPost() post.id = XX # substituir XX pelo id do post a ser modificado post.title = titulo # título da matéria post.content = corpo # corpo da matéria post.date = datetime.strptime(f'{dia_atual} {mes_atual} {ano_atual}','%d %B %Y') post.post_status = 'publish' post.terms_names = { 'post_tag': ['Previsão do Tempo', 'Maceió'], 'category': ['Previsão do Tempo'] } if post.id: wp.call(EditPost(post.id, post)) else: post_id=find_id(post.title) if post_id: print("Ops, algo deu errado", post_id) else: wp.call(NewPost(post))
def delet_post(self,post_id): post=WordPressPost() post.post_status='trash' self.wp.call(EditPost(post_id, post)) print('正在删除[ID]:%s 的文章;' %(post_id,post.title))
from wordpress_xmlrpc import Client, WordPressPost from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost from wordpress_xmlrpc.methods.users import GetUserInfo url = 'http://www.py4seo.com/xmlrpc.php' login = '******' passw = '1234567' client = Client(url, login, passw) posts = client.call(GetPosts({'number': 10000})) post = WordPressPost() post.title = 'My post' post.content = 'This is a wonderful blog post about XML-RPC.' post.id = client.call(NewPost(post)) # whoops, I forgot to publish it! post.post_status = 'publish' client.call(EditPost(post.id, post))