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
Exemple #2
0
	def post(self):    
                from lxml import etree
		try:
                  self.ui.label.setText("Importing necessary modules...")
                  from wordpress_xmlrpc import Client, WordPressPost
                  status = 1  		
                except:
                  status = 0
                if(status==1):
                  from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
		  from wordpress_xmlrpc.methods.users import GetUserInfo
                  self.ui.label.setText("Imported modules...")
		  data = etree.parse("config.xml")
		  user = data.find("user").text	
		  url = data.find("url").text
		  pwd = data.find("pass").text
                  self.ui.label.setText("Imported data...")
                  try:  
                    wp = Client(url+"/xmlrpc.php", user, pwd)
	            	  
                  except:
                    status = 0
                  if (status == 1):  
                    post = WordPressPost()
		    post.content = str(self.ui.BodyEdit.toPlainText())
		    post.title = str(self.ui.TitleEdit.text())
                    post.content = post.content + "<br><small><i>via QuickPress</i></small></br>"
                    post.post_status = 'publish'
		    wp.call(NewPost(post))	
                    self.ui.label.setText("Published") 
                  else:
                    self.ui.label.setText("Check Internet Connection and try again...")
                else:
		  self.ui.label.setText("module(wordpress_xmlrpc) not found, you can install manually from terminal using pip install python-wordpress-xmlrpc")                
def 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 createPost(image):
    localFilename = 'images/{0}'.format(image + '.jpg')
    print 'image is: {0}'.format(localFilename)

    imageTimestamp = getTimestamp(image)

    wpFilename = image + imageTimestamp + '.jpg'

    data = {
            'name': '{0}'.format(wpFilename),
            'type': 'image/jpeg',
    }

    with open(localFilename, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

    response = client.call(media.UploadFile(data))

    print 'response is: {0}'.format(response)

    month = strftime("%m", gmtime())

    post = WordPressPost()
    post.title = country + city
    post.content = '[caption id="" align="alignnone" width ="640"]<img src="http://www.backdoored.io/wp-content/uploads/2016/' + month + '/' + wpFilename.replace(":", "") + '">' + ipAddress + hostnames + isp + timestamp + country + city + '[/caption]'
    post.id = client.call(NewPost(post))
    post.post_status = 'publish'
    client.call(EditPost(post.id, post))
def Publish_Post(title,body):
    # Connect to Word Press POST API
    obj=setup('https://hackingjournalismtest.wordpress.com/xmlrpc.php', 'contentmagicalsystem','aA9&cG^%wqSkd7MxHU@PYT72c&h')
    post = WordPressPost()

    if len(title) == 0 :
        raise("Cant Process the request")
        return "Empty title requested"

    if len(body) == 0:
        rasie("Cant Process the request")
        return "Empty body requested"
    '''
    Future or Next in line
    Better data validations
    Have some other quality checks for non ascii charecters and valdiate unicode letters if required
    Request type validation (old vs new)
    check if title already exist and update postif required
    '''

    post.title=title
    post.content=body
    # Make post visible ,status should be  publish
    post.post_status = 'publish'

    # API call to push it to word press
    post.id=wp.call(NewPost(post))
    #return "Post created with id ",post.id
    return post.id
def 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)
Exemple #7
0
def create_post(title, text="", url="", image_url=""):

    shortened_url = shorten_link(url) if url else ""

    url_html = "<a href='{shortened_url}'>{url}</a><br/>".format(url=url, shortened_url=shortened_url) if url else ""
    image_html = "<img style='width: 100%; height: auto;' src='{image_url}'></img><br/>".format(image_url=image_url) if image_url else ""
    text_html = "<p>" + text + "</p>" + "<br/>" if text else ""
    content = url_html + image_html + text_html

    # https://developer.wordpress.com/docs/api/1.1/post/sites/%24site/posts/new/
    # http://python-wordpress-xmlrpc.readthedocs.org/en/latest/examples/posts.html

    post = WordPressPost()
    post.title = title
    post.content = content
    post.author = "testaccount"
    post.post_status = "publish"
    # post.terms_names = {
    #   'post_tag': ['test', 'firstpost'],
    #   'category': ['Introductions', 'Tests']
    # }

    try:
        redditsync.wordpress.wp.call(NewPost(post))
    except Exception as err:
        logging.error(str(err))
        sys.exit()
	def post_to_wordpress(self, story):
		# Get number of posts to number the story title, i.e. if this is the 6th story
		# that will get posted the title will be "Story 6"
		print "Retrieving posts"

		# get pages in batches of 20
		num_of_post = 0
		offset = 0
		increment = 20
		while True:
				posts_from_current_batch = self.wp.call(posts.GetPosts({'number': increment, 'offset': offset}))
				if len(posts_from_current_batch) == 0:
						break  # no more posts returned
				else:
					num_of_post += len(posts_from_current_batch)
				offset = offset + increment
		print num_of_post

		# Create new post
		print "Creating new post..."
		post = WordPressPost()
		post.title = 'Story %d' % (num_of_post + 1) # incrementing the number of post by 1
		# convert each sentence to string, and join separated by a space.
		post.content = " ".join(map(str, story))
		post.id = self.wp.call(posts.NewPost(post))

		# publish it
		print "Publishing"
		post.post_status = 'publish'
		self.wp.call(posts.EditPost(post.id, post))
		print "Done!"
def 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)
Exemple #10
0
 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 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_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)
Exemple #13
0
def testUpdate(pid):
    client = initClient()
    post = WordPressPost()
    post.title = 'My new title update 2'
    post.content = 'This is the body of my new post.'
    post.slug= 'helloword'
    post.post_type = 'post'
    post.post_status = 'draft'
    print client.call(posts.EditPost(pid, post))
Exemple #14
0
def make_post(content, wp):
    start = datetime.datetime.utcnow()
    end = start + datetime.timedelta(7)
    dates = (start.strftime('%b %d'), end.strftime('%b %d'))
    post = WordPressPost()
    post.title = "This week's schedule (%s - %s)" % dates
    post.content = content
    post.post_status = 'draft'
    wp.call(NewPost(post))
def 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 process_comment(wp, video_id, parent_post_id, comment):
    post = WordPressPost()
    post.title = comment['text'][6:50]
    post.content = get_post_content(video_id,comment)
    post.post_type = 'video-highlight'
    post.post_status = 'publish'
    post.parent_id = parent_post_id
    #logger.info("Created post with ID [%s]", wp.call(NewPost(post)))
    print "Created post with ID [%s]" % wp.call(NewPost(post))
 def 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
Exemple #18
0
 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)
Exemple #19
0
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 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))
Exemple #21
0
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 post_new(self, title, content, categories = ['Mac OS X'], individual_tags = '', status = 'private', date = dt.datetime.now()):
     post = WordPressPost()
     post.title = title
     post.description = content
     tags = 'automatically posted' if (self.additional_tags == '')  else self.additional_tags + ', automatically posted'
     tags = individual_tags + tags
     post.tags = tags
     post.date_created = date
     post.post_status = status
     post.categories = categories
     self.__wp.call(NewPost(post, True))
    def toWordPressPost(self):
        post = WordPressPost()

        if self.title:
            post.title = self.title

        if self.content:
            post.content = self.content

        post.post_status = 'publish'
        return post
    def createPost(self, post_title, post_content):
        # create draft
        post = WordPressPost()
        post.title = post_title
        post.content = post_content
        post.id = self.wordpress.call(posts.NewPost(post))
        # set status to be update
        #post.post_status = 'publish'
        #self.wordpress.call(posts.EditPost(post.id, post))

        return post
Exemple #25
0
def create_new_empty_wp_post(component, event_category, event_map_location, location_gps):

    summary = component.get('SUMMARY').encode('UTF-8', 'backslashreplace')
    start_event = component.get('DTSTART').dt.strftime('%Y-%m-%d %H:%M')
    end_event = component.get('DTEND').dt.strftime('%Y-%m-%d %H:%M')
    end_frequency_event = component.get('DTEND').dt.strftime('%Y-%m-%d')
    uid = component.get('UID').encode('UTF-8', 'backslashreplace')
    event_description = component.get('DESCRIPTION')
    if event_description is None:
        event_description = " "
    else:
        event_description = component.get('DESCRIPTION').encode('UTF-8', 'backslashreplace')

    # Create a new post
    new_post = WordPressPost()
    new_post.title = summary
    new_post.content = event_description
    new_post.post_type = "event"
    new_post.post_status = "publish"
    new_post.terms_names = {'event-category': [event_category]}
    new_post.custom_fields = []

    meta_adds = (['imic_event_start_dt', start_event],
                 ['imic_event_end_dt', end_event],
                 ['imic_event_frequency_end', end_frequency_event],
                 ['imic_featured_event', 'no'],
                 ['slide_template', 'default'],
                 ['imic_event_day_month', 'first'],
                 ['imic_event_week_day', 'sunday'],
                 ['imic_event_frequency_type', '0'],
                 ['imic_event_frequency', '35'],
                 ['imic_event_registration', '0'],
                 ['imic_custom_event_registration_target', '0'],
                 ['imic_sidebar_columns_layout', '3'],
                 ['imic_google_map_track', '1'],
                 ['imic_event_address2', event_map_location],
                 ['imic_event_map_location', location_gps],
                 ['imic_pages_banner_overlay', '0'],
                 ['imic_pages_banner_animation', '0'],
                 ['imic_pages_select_revolution_from_list', '[rev_slider fsl]'],
                 ['imic_pages_slider_pagination', 'no'],
                 ['imic_pages_slider_auto_slide', 'no'],
                 ['imic_pages_slider_direction_arrows', 'no'],
                 ['imic_pages_slider_interval', '7000'],
                 ['imic_pages_slider_effects', 'fade'],
                 ['imic_pages_nivo_effects', 'sliceDown'],
                 ['imic_import_uid', uid])

    # Iterate over array creating meta in post
    for i in meta_adds:
        new_post.custom_fields.append({'key': i[0], 'value': i[1]})

    return new_post
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({
        'key': 'custom_source_url',
        'value': url
    })
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Exemple #27
0
def get_urls(url):
    user_agent = {'User-agent': 'Mozilla/5.0'}
    r = requests.get(url,headers = user_agent)
    data = r.text
    soup = BeautifulSoup(data)
    div = soup.find('div', class_="panel-content")
    links = div.findAll('a')
    for a in links:
        try:
            if 'deccanchronicle.com' in a['href']:
                r = requests.get(a['href'],headers = user_agent)
                data = r.text
                soup = BeautifulSoup(data)
                title = soup.find('h1', class_="title")
                imgurl = soup.find('div',class_="field-item even")
                orgimgurl = imgurl['resource']
                data = data[data.index('<div class="field field-name-field-image'):]
                data = data[:data.index('<div class="field field-name-field-tags')]
                soup = BeautifulSoup(data)
                texts = soup.find_all('p')
                content = ""
                if(len(texts)==0):
                    raise
                for text in texts:
                    content = content+"<p>"+text.getText()
                content = content + "<p>" + a['href']
                post = WordPressPost()
                post.title = title.get_text() #Setting Post Title
                urllib.request.urlretrieve(orgimgurl, os.path.basename(orgimgurl))
                filename = os.path.basename(orgimgurl)
                data = {
                    'name': os.path.basename(orgimgurl),
                    'type': mimetypes.guess_type(filename)[0],  # mimetype
                    }
                with open(filename, 'rb') as img:
                    data['bits'] = xmlrpc_client.Binary(img.read())
                response = wp.call(media.UploadFile(data))
                attachment_id = response['id']
                post.thumbnail = attachment_id #Setting Feautured Image
                post.content = content #Setting Content Up
                post.terms_names = {
                    'post_tag': ['snews', 'andhrapradesh'], #Change Tags here
                    'category': ['State News'] #Change Category Here
                    }
                post.post_status = 'publish'
                wp.call(NewPost(post))
                #print ("Post Id is %s" %(wp.call(NewPost(post))))
                print("%s is Posted!" %(title.get_text()))
                #input("Press Enter to continue...")
        except:
            print('Some Error On This Post %s ' %(title.get_text()))
            pass
Exemple #28
0
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
Exemple #29
0
    def postDraft(self, title, body):
        '''
        Creates a draft with title and graph
        
        Currently both title and graph are just strings
        '''
        post = WordPressPost()
        post.title = title
        post.content = body
#        post,terms_names = {
#            'post_tag': ['test'],
#            'category': ['testCat']}
        self.wp.call(NewPost(post))
Exemple #30
0
def send_news(user, news):
    wp = Client(user['website'], user['username'], user['password'])
    post = WordPressPost()
    if news.image_name != '':
        print news.title
        for image in news.image_name:
            attachment_id = upload_image(image, wp)
            post.thumbnail = attachment_id
    post.title = news.title
    post.content = str(news.content)
    post.post_status = 'publish'
    post.terms_names = {'post_tag': news.tags, 'category': [news.category]}
    wp.call(NewPost(post))
def postwpchallenge(title, content, tags, categories, wp, type="challenge"):
    #title (string), content (string/html), tags (list), categories (list), wp (Client Class), type (string)

    post = WordPressPost()
    post.post_type = type

    post.title = title
    post.content = content

    post.terms_names = {'post_tag': tags, 'category': categories}
    wp.call(NewPost(post))

    print("Challenge Posted to WordPress")
Exemple #32
0
 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)
Exemple #33
0
 def updatePost(self):
     blog_list = self.wp.call(
         posts.GetPosts({
             'offset': 0,
             'number': 661,
             'post_status': 'publish'
         }))
     for blog in blog_list:
         post = WordPressPost()
         post.title = blog.title
         post.post_status = 'draft'
         print('当前编辑文章:', blog.title)
         self.wp.call(posts.EditPost(blog.id, post))
Exemple #34
0
def newPost():
    print("newPost")
    wp = Client('http://39.106.104.45/wordpress/xmlrpc.php', 'shikun',
                'ShiKun001')
    post = WordPressPost()
    post.title = 'Lichuan Test5'
    post.content = 'This is the body of Lichuan Test5.'
    post.terms_names = {
        'post_tag': ['test', 'lichuan'],
        'category': ['Introductions', 'Tests']
    }
    post.id = wp.call(NewPost(post))
    print("post.id = " + str(post.id))
def add_post():
    post = WordPressPost()
    ts = time.time()
    title = 'Test Title' + datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')
    post.title = title
    post.content = 'This is a test post to see if the RPC call works.'
    post.terms_names = {
        'post_tag': ['test', 'firstpost'],
        'category': ['Introductions', 'Test']
    }
    post.slug = slugify(title)  # note this if final part of slug only
    API.call(NewPost(post))
Exemple #36
0
def send_news(yourwebsit,username,password,news):
	wp=Client(yourwebsit,username,password)
	attachment_id=upload_image(news.image_name,wp)
	post=WordPressPost()
	post.title=news.title
	post.content=news.content
	post.post_status ='publish'
	post.thumbnail = attachment_id
	post.terms_names={
		'post_tag':news.tags,
		'category':[news.category]
	}
	wp.call(NewPost(post))
Exemple #37
0
def new_post():
    user = current_user
    client = check_login(user.wp_url, user.wp_username, login_session['pw'])
    if request.method == 'POST':
        new_wp_post = WordPressPost()
        new_wp_post.title = request.form['title']
        new_wp_post.content = request.form['content']
        new_wp_post.status = 'publish'
        new_wp_post.id = client.call(posts.NewPost(new_wp_post))
        flash('New post successfully added')
        return redirect(url_for('get_posts'))
    else:
        return render_template('posts/newpost.html')
Exemple #38
0
 def process_item(self, item, spider):
     wp = Client('https://www.along.party/xmlrpc.php', '', '')
     post = WordPressPost()
     post.title = item['title']
     post.user = item['author']
     post.link = item['url']
     # post.date = item['publish_time']
     post.content = item['body']
     post.content = u"%s \n 本文转载自 <a href='%s'> %s</a> " % (
         item['body'], item['url'], item['title'])
     post.post_status = 'publish'
     post.terms_names = {'post_tag': 'Python', 'category': 'Python'}
     wp.call(NewPost(post))
Exemple #39
0
 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 wordpress_public(domain="如:www.domain.com ",
                     username="******",
                     password='******',
                     title='文章标题',
                     content="文章内容",
                     tags='标签,多个标签用逗号隔开如’标签1,标签2',
                     category='分类名称'):
    import urllib, urllib2, cookielib, requests
    headers = {
        "Host":
        "%s" % domain,
        "User-Agent":
        "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
    }
    cookieJar = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
    urllib2.install_opener(opener)
    login_data = {
        "log": "%s" % username,
        "pwd": "%s" % password,
    }
    login_data = urllib.urlencode(login_data)
    login_url = 'http://%s/wp-login.php' % domain
    req = urllib2.Request(url=login_url, data=login_data, headers=headers)
    html = urllib2.urlopen(req).read()
    url = 'http://%s/wp-admin/edit.php?s=%s' % (domain, title)
    html = opener.open(url).read()
    if 'post-title page-title column-title' in html:
        print '标题已经已经存在,跳过不发布'.decode('utf8')
    else:
        tag = []
        categorys = []
        tag.append(tags)
        categorys.append(category)
        wp = Client('http://%s/xmlrpc.php' % domain, '%s' % username,
                    '%s' % password)  #登陆后台

        wp.call(GetPosts())
        wp.call(GetUserInfo())
        post = WordPressPost()
        post.title = """%s""" % title  #文章标题
        post.content = """%s""" % content  #文章内容
        post.terms_names = {
            'post_tag':
            tag,  #标签    如果有多个标签的话需要以列表形式,如: 'post_tag': ['eo ', 'discuz'],
            'category':
            categorys,  #分类    如果是有多个分类的话需要以列表形式,如:'category': ['Introductions', 'Tests']
        }
        post.post_status = 'publish'
        wp.call(NewPost(post))
        print '发布成功,标题是:'.decode('utf8'), title.decode('utf8')
Exemple #41
0
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))
Exemple #42
0
 def submit(self, content):
     client = Client('http://域名或ip/xmlrpc.php', '用户名', '密码')
     post = WordPressPost()
     # 设置标题
     title = '{} - 今日更新'.format(self.today)
     post.title = title
     post.content = content
     post.date = datetime.datetime.now() - datetime.timedelta(hours=8)
     # 添加标签设置分类目录
     post.terms_names = {'post_tag': ['知乎', '每日更新'], 'category': ['知乎']}
     post.id = client.call(posts.NewPost(post))
     post.post_status = 'publish'
     status = client.call(posts.EditPost(post.id, post))
     return status
Exemple #43
0
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))
Exemple #44
0
def edit_post(wp_post_id):
    user = current_user
    client = check_login(user.wp_url, user.wp_username, login_session['pw'])
    if request.method == 'POST':
        edit_wp_post = WordPressPost()
        edit_wp_post.title = request.form['title']
        edit_wp_post.content = request.form['content']
        edit_wp_post.id = wp_post_id
        edit_wp_post.status = 'publish'
        client.call(posts.EditPost(edit_wp_post.id, edit_wp_post))
        flash('Post edited successfully')
        return redirect(url_for('get_posts'))
    else:
        return render_template('posts/editpost.html', wp_post_id=wp_post_id)
Exemple #45
0
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))
Exemple #46
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({'key': 'custom_source_url', 'value': url})
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Exemple #47
0
def wp_post_update(request, post_id):
    """
    Update WordPress post using Post object and HTML
    
    Primarily for 'Update This Post' button AJAX function in :view:`post_generator.views.post.post_view`
    
    :param post_id: :model:`post_generator.Post` to update WP post with
    :type post_id: :model:`post_generator.Post`
    """

    # TODO: add case for GET request
    if request.method == 'POST':
        client = Client(os.environ['POSTGEN_WP_TARGET'],
                        os.environ['POSTGEN_WP_USER'],
                        os.environ['POSTGEN_WP_PASS'])
        post_obj = Post.objects.get(pk=post_id)

        # Generate Multilingual title
        post_title = post_obj.title.english
        if post_obj.title.somali:
            post_title += ' (' + post_obj.title.somali + ')'
        if post_obj.title.french or post_obj.title.french_feminine:
            post_title += ' ' + (post_obj.title.french
                                 or post_obj.title.french_feminine)
        if post_obj.title.arabic:
            post_title += ' ' + post_obj.title.arabic
        post_title += ' - PostGen'

        # Pull WP post ID from stored link
        matches = re.search('.*=(\d+)$', post_obj.link)
        wp_post_id = matches.group(1)

        # Create new WP post object with data
        wp_post = WordPressPost()
        wp_post.title = post_title
        wp_post.content = request.POST['post-content']
        wp_post.date = post_obj.pub_date

        # Retrieve current post data via WP XML-RPC API
        # - Used to determine whether featured_image_id data should be included
        #   - Avoids error from setting featured_image_id to the one already attached
        current_post = client.call(posts.GetPost(wp_post_id))
        if not current_post.thumbnail or current_post.thumbnail[
                'attachment_id'] != str(post_obj.featured_image_id):
            wp_post.thumbnail = str(post_obj.featured_image_id)

        # Update WP post and return status=True via JSON
        client.call(posts.EditPost(wp_post_id, wp_post))
        return HttpResponse(json.dumps({'status': True}),
                            content_type='application/json')
Exemple #48
0
def _intruderPost(image):

    data = {'name': image, 'type': 'image/jpeg'}
    with open(image, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = site.call(WordpressMedia.UploadFile(data))
    attachment_id = response['id']
    post = WordPressPost()
    post.title = 'Unauthorized Access Attempt'
    post.content = 'Face not recognized'
    post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Unsuccessful Login']}
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    site.call(posts.NewPost(post))
Exemple #49
0
 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
Exemple #50
0
 def postBlog(self, new_blog):
     print('正在发布:', new_blog[1])
     post = WordPressPost()
     # post.id = new_blog[0]
     post.title = new_blog[1]
     post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
     post.content = new_blog[7]
     post.terms_names = {
         'post_tag': [new_blog[3]],  # 文章所属标签,没有则自动创建
         # 'category': ['日韩漫画']  # 文章所属分类,没有则自动创建
         'category': [self.category]
     }
     post.custom_fields = []  # 自定义字段列表
     # 资源价格
     post.custom_fields.append({'key': 'cao_price', 'value': 2})
     # VIP折扣
     post.custom_fields.append({'key': 'cao_vip_rate', 'value': 0})
     # 仅限永久VIP免费
     post.custom_fields.append({'key': 'cao_is_boosvip', 'value': 0})
     # 启用付费下载资源
     post.custom_fields.append({'key': 'cao_status', 'value': 1})
     post.custom_fields.append({'key': 'wppay_type', 'value': 4})
     # 资源下载地址
     post.custom_fields.append({'key': 'cao_downurl', 'value': new_blog[5]})
     # 资源下载密码
     post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[6]})
     # 资源下载次数
     post.custom_fields.append({
         'key': 'cao_paynum',
         'value': random.randint(1, 50)
     })
     post.custom_fields.append({  # 资源其他信息
         'key':
         'cao_info',
         'value': [{
             'title': '作   者',
             'desc': new_blog[2]
         }, {
             'title': '题材类型',
             'desc': new_blog[3]
         }, {
             'title': '是否完结',
             'desc': new_blog[4]
         }]
     })
     try:
         self.wp.call(posts.NewPost(post))
     except:
         pass
Exemple #51
0
def crear_nueva_entrada_automatica():

    limpiar_pantalla()
    nueva_entrada = WordPressPost()
    num = int(input("Introduce el ID del post que quieres publicar: "))
    articulos = []
    articulos = pd.read_csv('travel_translated.csv',sep = ';')
    nueva_entrada.title = articulos.titulo_traducido[num]
    nueva_entrada.content = articulos.cuerpo_traducido[num]

    ############       AUTOMATIZAR LA SUBIDA DE IMAGENES      ############
    filename = 'downloads/travel_images_2/travel_' + str(num) + '.jpg'
    # prepare metadata
    data = {'name': 'picture.jpg', 'type': 'image/jpeg',}
    # read the binary file and let the XMLRPC library encode it into base64
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = cliente.call(media.UploadFile(data))
    attachment_id = response['id']
    nueva_entrada.thumbnail = attachment_id
    ####################### ####################### #######################

    etiquetas = []
    categorias = []
    eleccion = input("¿Deseas agregar etiquetas? [S/N] ")
    if eleccion.lower() == "s":
        #etiquetas = input("Ingresa las etiquetas separadas con comas: ").split(",")
        etiquetas = ["viajar,carrefour,baratos,viajeros piratas,halcon,viaje al cuarto de una madre,barcelo,viaje al centro de la tierra,sorpresa,viaje sorpresa,viaje a cuba,viaje a nueva york,viaje a egipto,viajera del tiempo,viajem,todo incluido,viajera soledad,viajera,agencia,viaje en el tiempo,corte ingles,viaje largo,viaje barato,viaje budapest,viaje bali,viaje berlin,viaje barcelona,viaje bora bora,viaje bruselas brujas gante,viaje barato a roma,viaje bahamas,viaje barato semana santa,the travel brand pamplona,viajeras b,viajeras con b,viaje b alfa romeo,mundo,the travel brand valladolid,viajeros b travel brand,viaje canarias,viaje costa oeste eeuu,viaje cuba,viaje costa rica,viaje corte ingles,viaje croacia,viaje cerdeña,viaje caribe,viaje con niños,viaje con nosotros,viajeros c,m&c  turismo quilmes,jota c ,d.c.  y turismo s.a,at&c  mar del plata,viaje de chihiro,viaje de novios,viaje disney,viaje del heroe,viaje disneyland,viaje de magallanes,viaje disney paris,viaje de arlo,viaje destino sorpresa,viaje dubai,viaje destinos,san juan,viaje club,gaitan,san juan estafa,de viaje destinos san juan,turismo,tour.com,d-viaje vitoria,viaje egipto,viaje en el tiempo,viaje en globo madrid,viaje eurodisney,viaje en ingles,viaje en globo segovia,viaje en tren,viaje express,viajero,viaje de chihiro,viaje mas largo,viaje del heroe,viaje de arlo,operadora sa de cv veracruz,ideas,el tiempo,viaje fin desemana,playa,montaña"]
    eleccion = input("¿Deseas agregar categorías? [S/N] ")
    if eleccion.lower() == "s":
        categorias = input("Ingresa las categorías separadas con comas: ").split(",")
    nueva_entrada.terms_names = {
            'post_tag': etiquetas,
            'category': categorias,
    }
    print("Publicando entrada...")
    id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada))
    limpiar_pantalla()
    print("Correcto! Se guardó la entrada como borrador, y su id es {}".format(id_entrada_publicada))
    eleccion = input("¿Publicar inmediatamente? [S/N] ")
    if eleccion.lower() == "s":
        print("Publicando entrada...")
        nueva_entrada.post_status = 'publish'
        resultado = cliente.call(posts.EditPost(id_entrada_publicada, nueva_entrada))
        if resultado is True:
            input("Entrada publicada")
        else:
            input("Algo salió mal")
    imprimir_menu_opciones()
Exemple #52
0
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))
Exemple #53
0
    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
Exemple #54
0
    def post(self, entry):
        """ Post entry to Wordpress. """

        # get text with readability
        post = WordPressPost()
        post.title = entry.title
        post.content = "Source: <a href='{}'>{}</a><hr\>{}".format(
            entry.link,
            urlparse(entry.link).netloc, self.get_content(entry.link))
        post.terms_names = {
            'post_tag': entry.keywords,
            'category': ["AutomatedPost"]
        }
        post.post_status = 'publish'
        self.client.call(NewPost(post))
Exemple #55
0
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)
Exemple #56
0
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
Exemple #57
0
 def updateBlog(self, begin, end, comic_path):
     # 必须添加header=None,否则默认把第一行数据处理成列名导致缺失
     data = pd.read_csv(self.comic_path, encoding='gbk', header=None)
     csv_reader_lines = data.values.tolist()
     print(csv_reader_lines[0])
     for index in range(begin, end):
         post = WordPressPost()
         blog = csv_reader_lines[index]
         post.title = blog[1]
         post.custom_fields = {'cao_downurl': blog[5]}  # 自定义字段列表
         print(blog[1])
         print(blog[5])
         print(int(blog[0]))
         # post.post_status = 'publish'
         self.wp.call(posts.EditPost(int(blog[0]), 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 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))
Exemple #60
0
def wpsend(content, title):
    try:
        # 链接地址,登录用户名,密码
        wp = Client('http://127.0.0.1/xmlrpc.php', 'bruce', '12345678')
        # print(content)
        post = WordPressPost()
        post.title = str(title)
        post.content = " ''' " + content + " ''' "
        post.post_status = 'publish'
        post.terms_names = {'post_tag': ['福利'], 'category': ['福利', 'magnet']}
        wp.call(NewPost(post))
        localtime = time.localtime(time.time())
        print('文档已上传 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", localtime)))
    except:
        print('没有上传成功')