Ejemplo n.º 1
1
def wordPressPost():
	for i in range(38):
		content = """<iframe src="//www.youtube-nocookie.com/embed/""" + urls[i] + """?rel=0" \
height="360" width="640" allowfullscreen="" frameborder="0"></iframe>"""

		post = WordPressPost()
		post.title = titles[i]
		post.content = content
		print titles[i]
		print content
		post.link = 'http://medtwice.com/pregnancy-by-week-week-'+str(i+4)
		post.post_status = 'publish'
		category = wp.call(taxonomies.GetTerm('category', 44))
		post.terms.append(category)
		post.id = wp.call(NewPost(post))
    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
Ejemplo n.º 3
0
	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!"
Ejemplo n.º 4
0
	def post_article(self,wpUrl,wpUserName,wpPassword,articleTitle, articleCategories, articleContent, articleTags,PhotoUrl):
		self.path=os.getcwd()+"/00000001.jpg"
		self.articlePhotoUrl=PhotoUrl
		self.wpUrl=wpUrl
		self.wpUserName=wpUserName
		self.wpPassword=wpPassword
		#Download File
		f = open(self.path,'wb')
		f.write(urllib.urlopen(self.articlePhotoUrl).read())
		f.close()
		#Upload to WordPress
		client = Client(self.wpUrl,self.wpUserName,self.wpPassword)
		filename = self.path
		# prepare metadata
		data = {'name': 'picture.jpg','type': 'image/jpg',}
		
		# read the binary file and let the XMLRPC library encode it into base64
		with open(filename, 'rb') as img:
			data['bits'] = xmlrpc_client.Binary(img.read())
		response = client.call(media.UploadFile(data))
		attachment_id = response['id']
		#Post
		post = WordPressPost()
		post.title = articleTitle
		post.content = articleContent
		post.terms_names = { 'post_tag': articleTags,'category': articleCategories}
		post.post_status = 'publish'
		post.thumbnail = attachment_id
		post.id = client.call(posts.NewPost(post))
		print 'Post Successfully posted. Its Id is: ',post.id
Ejemplo n.º 5
0
def sent_to_wp(title, content):
    #prepare metadata
    # data = {
    #         'name': filename,
    #         'type': 'image/jpeg',  # mimetype
    # }
    #
    # # read the binary file and let the XMLRPC library encode it into base64
    wp = Client('http://abc/xmlrpc.php', 'link', '!@#abc')
    if wp:
        print('wp link ok')
    else:
        print('wp link false')

    # sent_to_wp(title,content)
    # with open(fullname, 'rb') as img:
    #         data['bits'] = xmlrpc_client.Binary(img.read())
    # response = wp.call(media.UploadFile(data))
    # #print('response: %s' % response)
    # attachment_id = response['id']
    #print('attachment_id: %s %s' %(type(attachment_id),attachment_id))

    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'
    #post.thumbnail = attachment_id
    post.id = wp.call(posts.NewPost(post))
    print('title:%s  =>post success' % title)
    print(
        '-----------------------------------------------------------------------------------------------'
    )
Ejemplo n.º 6
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)
Ejemplo n.º 7
0
    def publish(self, title, content):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布

        post.terms_names = {
            'post_tag': ['news'],  # 文章所属标签,没有则自动创建
            'category': ['news'],  # 文章所属分类,没有则自动创建
        }

        post.custom_fields = []
        post.custom_fields.append({
            'key': '_aioseop_keywords',
            'value': self.keywords
        })
        post.custom_fields.append({
            'key': '_aioseop_description',
            'value': self.description
        })
        post.custom_fields.append({
            'key': '_aioseop_title',
            'value': self.title
        })
        post.id = self.wp.call(posts.NewPost(post))
Ejemplo n.º 8
0
def wordpress_background_task(api):
    log("IOT background task")

    data1= "{"
    for key1, value in cbpi.cache.get("sensors").iteritems():
        data1 += ", " if key1 >1 else ""
        data1 += "\"%s\":%s" % (value.name, value.instance.last_value)
    data1 += "}"
    
    data2= "{"
    for key2, value2 in cbpi.cache.get("actors").iteritems():
        data2 += ", " if key2 >1 else ""
        data2 += "\"%s\":%s,%s" % (value2.name, value2.state, value2.power)
    data2 += "}"
    
    log("Wordpress Update")
    
    blog = Client(Wordpress_Domain + "xmlrpc.php", Wordpress_Username, Wordpress_Password)
    post = WordPressPost()
    # Create a title with some simple styling classes
    post.title = time.strftime("%y/%m/%d %H:%M:%S", time.localtime())
    post.content = data1 + "<br />" + data2
    post.terms_names = {
            'post_tag': [Wordpress_Tag],
            'category': [Wordpress_Category],
    }
    post.id = blog.call(posts.NewPost(post))
    # Always publish these posts
    post.post_status = 'publish'
    blog.call(posts.EditPost(post.id, post))
Ejemplo n.º 9
0
def send_to_wordpress(id, title, categories, tags, content, configuration):
    if len(content.strip()) == 0:
        return

    client = get_client(configuration)

    if id:
        post = client.call(posts.GetPost(id))
        pass
    else:
        post = WordPressPost()
    post.content = content
    if title is not None:
        post.title = title
    if post.title is None:
        post.title = 'My post'
    post.terms_names = {
        'post_tag': tags,
        'category': categories,
    }

    if id:
        client.call(posts.EditPost(post.id, post))
    else:
        post.id = client.call(posts.NewPost(post))

    print("Blog post with id " + post.id +
          " was successfully sent to WordPress.")
    return post.id
def insert_pipop_wordpress(filename, data):
    kan = ""
    en = "\n\n"
    for x in data["lyric"]:
        kan = kan + x["furigana"] + "\n" + x["roman"] + "\n\n"
        en = en + x["en"] + "\n\n"

    data_image = {
        'name': str(time.time()) + '.jpg',
        'type': 'image/jpeg',
    }
    if "http" in data["thumbnail"]:
        dow(data["thumb_max"], filename)
    else:
        filename = "image_des_wp_pipop/" + image_thum[random.randint(0, 390)]
    # read the binary file and let the XMLRPC library encode it into base64
    with open(filename, 'rb') as img:
        data_image['bits'] = xmlrpc_client.Binary(img.read())

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

    attachment_id = response['id']

    post = WordPressPost()

    cate = []
    cate.append("Jpop Lyrics")
    post.terms_names = {
        'category': cate,
    }
    post.title = "FULL lyric and english translation of " + data[
        "name"] + " - " + data["singer"]
    post.content = form(
        data["name"], data["singer"], kan, en,
        "https://www.youtube.com/embed/" +
        data["link_youtube"].split("v=")[-1], data["name_ro"])
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.id = client.call(posts.NewPost(post))

    now_1 = datetime.now()
    # print((post.id, -1, 1, random.randint(45, 50) / 10, now_1, "X.X.X.X"))
    #
    # print((attachment_id,
    #        "{0} lyric, {0} english translation, {0} {1} lyrics".format(data["name"],
    #                                                                    data["singer"])))
    ctn = connect.connect(user="******",
                          password="******",
                          host="103.253.145.165",
                          database="admin_songlyrics")
    cusor = ctn.cursor()
    insert_rate(
        (post.id, -1, 1, random.randint(45, 50) / 10, now_1, "X.X.X.X"), cusor,
        ctn)
    update_des_image(
        attachment_id,
        "{0} lyric, {0} english translation, {0} {1} lyrics".format(
            data["name"], data["singer"]), cusor, ctn)
    # admin_score(post.id,random.randint(45,50)/10)
    print("ok pipop_wp!")
Ejemplo n.º 11
0
async def normal_handler(event):
    post = WordPressPost()
    msg = event.message.to_dict()
    fwd_channel_name = (await client.get_entity(
        PeerChannel(msg['fwd_from']['channel_id']))).username
    title, content = tit_le(msg)
    post.title = '@' + fwd_channel_name + ': ' + title
    post.content = content
    post.id = wp.call(posts.NewPost(post))
    post.post_status = 'publish'
    # add image
    # set to the path to your file
    try:
        filename = (await event.message.download_media())
        data = {
            'name': 'picture.jpg',
            'type': 'image/jpeg',  # mimetype
        }
        with open(filename, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']
        post.thumbnail = attachment_id
        # delete pictures
        remove(filename)
    except:
        print("with out pictures")

    wp.call(posts.EditPost(post.id, post))
def new_post(dir_str, photo_name):
    # prepare metadata
    category = '未分类'
    if photo_name.startswith('1__'):
        category = '清纯'
    if photo_name.startswith('2__'):
        category = '性感'
    data = {
        'name': photo_name,
        'type': 'image/jpeg',  # mimetype
    }
    # read the binary file and let the XMLRPC library encode it into base64
    with open('{}/{}'.format(dir_str, photo_name), 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp_clt.call(media.UploadFile(data))
    attachment_id = response['id']
    post = WordPressPost()
    post.title = photo_name[3:-4]
    post.content = ''
    post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    post.comment_status = 'open'  # 不开启评论则设置成closed
    post.terms_names = {
        'post_tag': ['haole', category],  # 文章所属标签,没有则自动创建
        'category': ['haole', category]  # 文章所属分类,没有则自动创建
    }
    post.thumbnail = attachment_id  # 缩略图的id
    post.id = wp_clt.call(posts.NewPost(post))
def sent_to_wp(filename,fullname,title,content):
    #prepare metadata
    data = {
            'name': filename,
            'type': 'image/jpeg',  # mimetype
    }
    #
    # # read the binary file and let the XMLRPC library encode it into base64
    wp = Client('http://www.abc.cn/xmlrpc.php', 'www', 'abc16')
    # sent_to_wp(title,content)
    with open(fullname, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp.call(media.UploadFile(data))
    #print('response: %s' % response)
    attachment_id = response['id']
    #print('attachment_id: %s %s' %(type(attachment_id),attachment_id))

    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.id = wp.call(posts.NewPost(post))
    print('title:%s  =>post success' % title)
    print('-----------------------------------------------------------------------------------')
Ejemplo n.º 14
0
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))
Ejemplo n.º 15
0
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))
Ejemplo n.º 16
0
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
Ejemplo n.º 17
0
def make_post(content):
    wp = Client('https://yoursite.com/xmlrpc.php', 'user', 'pass')
    post = WordPressPost()
    post.title = content['title']
    post.content = content['body']
    post.terms_names = {
        'post_tag': ['AutoBlogger', 'BotPosted'],
        'category': ['News', 'Update']
    }
    # Lets Now Check How To Upload Media Files
    filename = '1.jpg'
    data = {
        'name': '1.jpg',
        'type': 'image/jpeg'  # Media Type
    }
    # Now We Have To Read Image From Our Local Directory !
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    attachment_id = response['id']

    # Above Code Just Uploads The Image To Our Gallery
    # For Adding It In Our Main Post We Need To Save Attachment ID
    post.thumbnail = attachment_id
    post.post_status = 'publish'
    post.id = wp.call(posts.NewPost(post))
    # Set Default Status For Post .i.e Publish Default Is Draft

    # We Are Done With This Part :) Lets Try To Run It
    print("Sucessfully Posted To Our Blog !")
Ejemplo n.º 18
0
    def post_article(self, wpUrl, wpUserName, wpPassword, articleCategories,
                     path):
        self.path = path
        self.wpUrl = wpUrl
        self.wpUserName = wpUserName
        self.wpPassword = wpPassword

        client = Client(self.wpUrl, self.wpUserName, self.wpPassword)
        filename = self.path

        try:
            myFile = open(filename, "r")
            rawText = myFile.read()
            rawText = rawText.decode('latin-1')
            myFile.close()
            articleTitle = remove_tags(rawText)
            articleContent = rawText
            post = WordPressPost()
            post.title = articleTitle[:90]
            post.content = articleContent
            post.terms_names = {'category': articleCategories}
            post.post_status = 'publish'
            post.mime_type = "text/html"
            post.id = client.call(posts.NewPost(post))
            print("success : " + os.path.basename(path))
            os.remove(path)
        except (Exception, e):
            print("error : " + os.path.basename(path))
            print(e)
Ejemplo n.º 19
0
    def detail_page(self, response):
        title = response.doc('h1').text(),
        texts = str(response.doc('.loadimg.fadeInUp > p'))  #获取所有的HTML标签和内容
        texts = texts.replace("https://www.ttfhvip.com/d/file", "/downimages")
        texts = texts.replace("下面我们一起来看看她最新的番号作品吧!", "")
        texts = texts.replace("点击查看更多番号作品", "")

        for each in response.doc('.loadimg.fadeInUp > p > img').items():
            img_url = each.attr.src
            if ("ttfhvip" in img_url):  #过滤掉不在ttfhvip站点上的图片连接
                split_url = img_url.split('/')
                dir_name = split_url[-2] + '/'
                dir_path = self.deal.mkDir(dir_name)
                file_name = split_url[-1]
                self.crawl(img_url,
                           callback=self.save_img,
                           save={
                               'dir_path': dir_path,
                               'file_name': file_name
                           })
        title = ''.join(str(title))
        title = title.replace("('", "")
        title = title.replace("',)", "")
        wp = Client('http://192.168.2.98/xmlrpc.php', '东京不热郎', 'qaz78963')
        post = WordPressPost()
        post.title = title
        post.content = texts
        post.post_status = 'draft'  #publish-发布,draft-草稿,private-私密
        post.terms_names = {
            'category': ['素人']  #文章所属分类,没有则自动创建
        }
        post.id = wp.call(posts.NewPost(post))
Ejemplo n.º 20
0
def post(wp_url, wp_user, wp_pw, wp_title, wp_context, wp_thumbnail, wp_tags,
         wp_categorys):
    while True:
        try:
            client = Client(wp_url, wp_user, wp_pw)
            if wp_thumbnail != None:
                filename = wp_thumbnail
                # prepare metadata
                data = {
                    'name': 'picture.jpg',
                    'type': 'image/jpeg',  # mimetype
                }

                # read the binary file and let the XMLRPC library encode it into base64
                with open(filename, 'rb') as img:
                    data['bits'] = xmlrpc_client.Binary(img.read())

                response = client.call(media.UploadFile(data))
                attachment_id = response['id']
            post = WordPressPost()
            post.title = wp_title
            post.content = wp_context
            post.post_status = 'publish'
            if wp_thumbnail != None:
                post.thumbnail = attachment_id
            post.terms_names = {'post_tag': wp_tags, 'category': wp_categorys}
            post.id = client.call(posts.NewPost(post))
            return "https://weporn.tv/?p=" + str(post.id)
        except:
            pass
Ejemplo n.º 21
0
def main():
    (options, args) = parse_options()

    #
    # Check if the file exists
    #
    if not os.path.exists(args[0]):
        print("File:%s does not exists, aborting!" % args[0])
        sys.exit(1)

    new_post_file = open(args[0], 'r')
    new_post_content = new_post_file.read()
    new_post_file.close()

    client = Client('http://192.168.50.50/xmlrpc.php', 'tony',
                    'tony_wordpress_123')

    now = datetime.datetime.now()

    post = WordPressPost()
    post.title = 'My New Post - %s' % now.strftime("%Y-%m-%d_%H_%M_%S")
    post.content = new_post_content
    post.id = client.call(posts.NewPost(post))

    post.post_status = 'publish'
    client.call(posts.EditPost(post.id, post))
Ejemplo n.º 22
0
def postNewPostByXmlRpc(title, content, enterName, techField, techMaturity,
                        contactName, contactTel, contactEmail, completeDate,
                        applyStatus, cowork_type, apply_score, result_type,
                        award_type, award_level, prospect_promotion,
                        patent_name, postal_address, district, images, prov):
    print("postNewPostByXmlRpc")
    wp = Client('http://39.106.104.45/wordpress/xmlrpc.php', 'shikun',
                'ShiKun001')
    post = WordPressPost()
    post.title = title
    post.content = gen_content(content, enterName, applyStatus, apply_score,
                               result_type, award_type, award_level,
                               prospect_promotion, patent_name, postal_address,
                               images)
    post.terms_names = {
        'category': ['成果展示']
    }
    #post.custom_fields = {
    #    'enter-name':enterName,
    #    'tech-field': techField,
    #    'tech-maturity': techMaturity,
    #    'contact-name':contactName,
    #    'contact-tel':contactTel,
    #    'contact-email':contactEmail
    #};
    post.id = wp.call(NewPost(post))
    print("post.id = " + str(post.id))
    postId = post.id
    insertOtherDataIntoDB(postId, enterName, techField, techMaturity,
                          contactName, contactTel, contactEmail, completeDate,
                          cowork_type, district)

    insertProvDataIntoDB(postId, prov, enterName)
    savePostId(postId)
Ejemplo n.º 23
0
def postArticle(art, title, im, category, tags):

    host = ""
    user = ""
    password = ""
    conn = MySQLdb.connect(host=host, user=user, passwd=password, db="")
    cursor = conn.cursor()

    cursor.execute(
        "UPDATE scraped_articles SET paraphrase_flag = 0 WHERE title = %s",
        (title))
    data = cursor.fetchall()
    cursor.close()
    conn.close()

    client = Client("wp url", "admin", "")
    # set to the path to your file
    if len(im) < 2:
        print im
        im = getPic.searchPic(title)
    else:
        print im
        im = getPic.savePic(im)
    filename = "google_images/" + im

    # prepare metadata
    data = {
        'name': filename,
        'type': "image/jpg",  # mimetype
    }

    # read the binary file and let the XMLRPC library encode it into base64
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())

    response = client.call(media.UploadFile(data))
    # response == {
    #       'id': 6,
    #       'file': 'picture.jpg'
    #       'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
    #       'type': 'image/jpg',
    # }
    print response
    attachment_id = response['id']

    post = WordPressPost()
    post.title = str(title)

    post.terms_names = {
        'post_tag': ["premium"],
        'category': ['business'],
    }

    post.content = str(art)
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.id = client.call(posts.NewPost(post))

    print "uploaded!"
Ejemplo n.º 24
0
def make_post(content, categorys='0', tags='0', date=None):
    '''
    :param content: dict() formatado corretamente
    :param categorys: lista com as categorias do post
    :param tags: lista com as tags do post
    :param date: data para o post ser publicado ( formato datetime.datetime())
    :return:
    '''
    #URL DO SITE, USUARIO , SENHA !!!
    wp = Client(authData['url'] + '/xmlrpc.php', authData['adminUsername'],
                authData['adminPassword'])
    post = WordPressPost()
    post.title = content['title']
    post.content = content['body']

    if tags[0] != '0':

        post.terms_names = {'post_tag': tags}
    try:
        categorys[0] == 0
    except IndexError:
        pass
    else:
        if categorys[0] != '0':
            post.terms_names = {'category': categorys}

    # Lets Now Check How To Upload Media Files
    filename = content['image']
    data = {
        'name': content['title'] + '.jpeg',
        'type': 'image/jpeg'  # Media Type
    }
    # Now We Have To Read Image From Our Local Directory !
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    attachment_id = response['id']

    # Above Code Just Uploads The Image To Our Gallery
    # For Adding It In Our Main Post We Need To Save Attachment ID
    post.thumbnail = attachment_id

    #deletando do pc a imagem
    remove(filename)

    #setando para o post ser publicado (nao ficar de rascunho)
    post.post_status = 'publish'

    # marcando p/ o post ser postado na data desejada
    if date != None:
        post.date = date
    post.id = wp.call(posts.NewPost(post))
    # Set Default Status For Post .i.e Publish Default Is Draft

    # We Are Done With This Part :) Lets Try To Run It
    if not date:
        print(post.title, " Postado com sucesso !")
    if date:
        print(post.title, " Vai ser postado em ", date, '!')
Ejemplo n.º 25
0
 def new_post(self, title, content, tags, attachment_id):
     post = WordPressPost()
     post.title = title
     post.content = content
     post.terms = tags
     post.thumbnail = attachment_id
     post.post_status = 'publish'
     post.id = self.client.call(posts.NewPost(post))
Ejemplo n.º 26
0
 def new_post(self, title, content, image_id):
     post = WordPressPost()
     post.title = title
     post.content = content
     post.thumbnail = image_id
     post.post_status = 'publish'
     post.id = self._wp.call(NewPost(post))
     return post.id
Ejemplo n.º 27
0
    def post2wp(title, content):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.post_status = 'draft'

        post.id = self.wp.call(posts.NewPost(post))
        print post.id
Ejemplo n.º 28
0
def create_wordpress_post(config, video_url, audio_url, metadata):
    """ creates a wordpress post with the embedded video and Audio """
    import datetime
    from wordpress_xmlrpc import Client, WordPressPost
    from wordpress_xmlrpc.methods import posts

    wordpress_handle = Client(config["wordpress"]["url"] + "/xmlrpc.php",
                              config["wordpress"]["user"],
                              config["wordpress"]["password"])

    if video_url is not None:
        video_html = "<div>[iframe src=\"https://player.vimeo.com" + \
            video_url + "\" width=\"" + config["wordpress"]["video_width"] + \
            "\" height=\"" + config["wordpress"]["video_height"] + "\" \
            frameborder=\"0\" allowfullscreen=\"allowfullscreen\"]</div>"

    else:
        video_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider kein Video</div>"

    if audio_url is not None:
        download_html = "<a style=\"text-decoration:none; background-color:" +\
            config["wordpress"]["download_button_color"] +\
            "; border-radius:3px; padding:5px; color:#ffffff; \
            border-color:black; border:1px;\" href=\""                                                       + audio_url +\
            "\" title=\"" + config["Wordpress"]["download_button_text"] + \
            "\" target=\"_blank\">" +\
            config["wordpress"]["download_button_text"] + "</a>"
        audio_html = "<div><h3>Audiopredigt:</h3><audio controls src=\"" + \
            audio_url + "\"></audio></div>"
    else:
        audio_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider keine Tonaufnahme</div>"

        download_html = ""

    if (video_url is None) and (audio_url is None):
        video_html = "<div> Es tut uns Leid, aus technischen Gr&uuml;nden gibt \
            es zu diesem Gottesdienst leider kein Video und keine Tonaufnahme\
            </div>"

        download_html = ""
        audio_html = ""

    date_time = datetime.datetime(metadata["date"].year,
                                  metadata["date"].month, metadata["date"].day,
                                  config["sermon_start_utc"])

    post = WordPressPost()
    post.title = metadata["title"] + " // " + metadata["preacher"]
    post.content = video_html + audio_html + download_html
    post.date = date_time
    post.terms_names = {
        'post_tag': [metadata["title"], metadata["preacher"]],
        'category': [config["wordpress"]["category"]],
    }
    post.post_status = 'publish'
    post.id = wordpress_handle.call(posts.NewPost(post))
Ejemplo n.º 29
0
 def post_article(self, articleTitle, articleCategories, articleContent,
                  articleTags, imageUrl, tempDir, imageName, dirDelimiter,
                  postStatus):
     # ---	Get image extension
     imgExt = imageUrl.split('.')[-1].lower()
     # --------------------------------------------------------------
     self.imgPath = tempDir + dirDelimiter + imageName + "." + imgExt
     self.articleImageUrl = imageUrl
     # ---	Download image file
     f = open(self.imgPath, 'wb')
     try:
         f.write(urllib.request.urlopen(self.articleImageUrl).read())
     except:
         print("Error downloading image")
         return -1
     f.close()
     # --------------------------------------------------------------
     # ---	Upload image to WordPress
     filename = self.imgPath
     # prepare metadata
     data = {
         'name': imageName + '.' + imgExt,
         'type': 'image/' + imgExt,
     }
     # read the binary file and let the XMLRPC library encode it into base64
     try:
         with open(filename, 'rb') as img:
             data['bits'] = xmlrpc_client.Binary(img.read())
     except:
         print("Error while reading downloaded image file")
         return -2
     try:
         response = self.wpClient.call(media.UploadFile(data))
     except:
         print("Error while uploading image file")
         return -3
     attachment_id = response['id']
     # --------------------------------------------------------------
     # ---	Post article
     post = WordPressPost()
     post.title = articleTitle
     post.content = articleContent
     post.terms_names = {
         'post_tag': articleTags,
         'category': articleCategories
     }
     # More about post statuses: https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.posts.GetPostStatusList
     post.post_status = postStatus
     post.thumbnail = attachment_id
     try:
         post.id = self.wpClient.call(posts.NewPost(post))
     except:
         print("Error while posting article")
         return -4
     print('Post Successfully posted. Its Id is: ', post.id)
     # --------------------------------------------------------------
     return post.id
Ejemplo n.º 30
0
def post_new_article(title, content, terms_names):
    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    post.terms_names = terms_names

    post.id = wp.call(posts.NewPost(post))
    return post.id
Ejemplo n.º 31
0
 def postInWordpress(self, title, content, ):
     post = WordPressPost()
     post.title = title
     post.content = content
     post.post_status = 'publish'
     post.terms_names = {'post_tag': ['leak', 'pastebin leak', 'hack leak', 'hack'],'category': ['Leaks']}
     post.id = self.wordpress.call(NewPost(post))
     p = self.wordpress.call(GetPosts())[0]
     return p.link
def new_page(username, password):
    client = Client(admin.url + 'xmlrpc.php', username, password)
    post = WordPressPost()
    post.title = '233'
    post.content = '233'
    post.id = client.call(posts.NewPost(post))
    post.post_status = 'publish'
    client.call(posts.EditPost(post.id, post))
    print "[-----Create new articles------]"
    return post.id, post.title, post.content
Ejemplo n.º 33
0
 def add_post(self, title, text, category):
     post = WordPressPost()
     post.title = title
     post.content = text
     post.terms_names = {
         'category': [category],
     }
     post.id = self._client.call(posts.NewPost(post))
     post.post_status = 'publish'
     self._client.call(posts.EditPost(post.id, post))
def build_draft_post(title, content):
    post = WordPressPost()
    post.title = title
    post.content = content
    post.terms_names = {
        'post_tag': config_keys['wordpress_tags'],
        'category': config_keys['wordpress_categories']
    }

    # Don't duplicate same year / week no; reuse
    current_posts = wp.call(posts.GetPosts())
    dup_posts = filter(lambda p: p.title.split(':') == post.title.split(':'), current_posts)
    if dup_posts:
        # lets assume this returns in a sensible order
        dup_id = dup_posts[0].id
        wp.call(posts.EditPost(dup_id, post))
        post.id = dup_id
    else:
        post.id = wp.call(posts.NewPost(post))
    return post
Ejemplo n.º 35
0
    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
Ejemplo n.º 36
0
 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 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
Ejemplo n.º 38
0
def post_to_wp(title, content, field):
    post = WordPressPost()
    post.post_status = 'publish'
    post.terms_names = {'category': ['西藏旅游问答']}

    post.title = title
    post.content = content
    post.custom_fields = field

    post.id = wp.call(posts.NewPost(post))
    print(str(title) + '\n' + str(wp_url) + '?p=' + str(post.id) + '\n')
Ejemplo n.º 39
0
def wp_post(title,content,tags,category):
    post = WordPressPost()
    post.title = title
    post.content = content
    post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
    post.terms_names = {
        'post_tag': [tags],  # 文章所属标签,没有则自动创建
        'category': [category]  # 文章所属分类,没有则自动创建
    }
    # post.thumbnail = attachment_id #缩略图的id
    post.id = wp.call(posts.NewPost(post))
    return post.id
Ejemplo n.º 40
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
Ejemplo n.º 41
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))
Ejemplo n.º 42
0
 def process_item(self, item, spider):
     post = WordPressPost()
     post.title = item['title']
     post.content = item['content'] + settings.get('GOTO_SOURCE', "[%s]") % item['link']
     post.date = datetime.datetime.strptime(item['publish_date'],
                                         "%Y-%m-%d %H:%M")
     post.terms_names = {
         'post_tag': item['tag'],
         'category': item['category'] if len(item['category']) > 0 else ['gist'],
     }
     post.post_status = 'publish'
     post.thumbnail = self.create_thumbnail(item)
     post.id = self.client.call(posts.NewPost(post))
     return item
Ejemplo n.º 43
0
    def addItem(self, item):
        # 跳转链作为唯一标识去重
#        exist_posts = self.rpcClient.call(posts.GetPosts({'custom_fields':{'key':'link_value', 'value' : item.link}}))
        if self.itemExist(item.link):
            return
        print 'item.link = '+item.link
        res = urlparse.urlparse(item.thumb)
        if len(res.query) > 0:
            qs = urlparse.parse_qs(res.query)
#    huihui图片ID
            des = qs['id'][0]
            filename = des+'.png'
            destfile = 'temp/'+filename
        else:
            filename = item.thumb[item.thumb.rfind('/'):]
            destfile = 'temp'+filename
        downloadimage(item.thumb,destfile)
        
        # prepare metadata
        data = {
                'name': filename,
                'type': 'image/png',  # mimetype
        }
        
        # read the binary file and let the XMLRPC library encode it into base64
        with open(destfile, 'rb') as img:
                data['bits'] = xmlrpc_client.Binary(img.read())
        
        response = self.rpcClient.call(media.UploadFile(data))
        attachment_id = response['id']

        post = WordPressPost()
        post.title = item.title
        post.content = item.content
        post.thumbnail = attachment_id
        post.custom_fields = [{'key':'link_value', 'value' : item.link}]
        post.id = self.rpcClient.call(posts.NewPost(post))
    #    # attachment_id.parentid = post.id
    #    # whoops, I forgot to publish it!
        post.post_status = 'publish'
        
#        cats = self.rpcClient.call(taxonomies.GetTerms('category'))
        for cat in self.categorys:
            if cat.name == item.category:
                post.terms = [cat]
                break
                
        self.rpcClient.call(posts.EditPost(post.id, post))
Ejemplo n.º 44
0
def post_picture(image_url):
    fileImg = urlopen(image_url)
    imageName = fileImg.url.split('/')[-1]+'.jpg'
    data = {
        'name': imageName,
        'type': 'image/jpeg',
    }
    data['bits'] = xmlrpc_client.Binary(fileImg.read())

    response = client.call(media.UploadFile(data))
    attachment_id = response['id']
    post = WordPressPost()
    post.title = 'Picture of the Day'
    post.post_status = 'publish'
    post.thumbnail = attachment_id
    post.id = client.call(posts.NewPost(post))
Ejemplo n.º 45
0
def upload(name, title):
    client = Client("http://domain.com/xmlrpc.php", "username", "password")
    imgfile = os.path.join(DATA_DIR, name)
    # imgfile = 'op/%s'%name
    data = {"name": name, "type": "image/jpg"}
    with open(imgfile, "rb+") as imag:
        data["bits"] = xmlrpc_client.Binary(imag.read())
    response = client.call(media.UploadFile(data))
    attachment_id = response["id"]
    _title = lxml.html.fromstring(title).text
    post = WordPressPost()
    post.title = _title
    post.post_status = "publish"
    post.thumbnail = attachment_id
    post.comment_status = "open"
    post.id = client.call(posts.NewPost(post))
Ejemplo n.º 46
0
def publish(pic, title, content):
    '''
    '''
    attachment = upload(pic)
    wp_client = Client(rpc_service_url, user, password)
    post = WordPressPost()
    post.title = title
    post.content = '%s\n\n<a href="%s"><img class="alignnone size-full wp-image-%s" alt="%s" src="%s" /></a>' % (content, attachment["url"], attachment["id"], attachment["file"], attachment["url"])
    #post.tags='test, test2'
    #post.categories=['pet','picture']
    post.thumbnail = attachment["id"]
    #change status to publish
    post.id = wp_client.call(posts.NewPost(post))
    post.post_status = 'publish'
    wp_client.call(posts.EditPost(post.id, post))
    return post.id
    def upload_article(self, article, img_url, tags, categories):
        """
        Create a post object, initialize its properties and upload it.
        :param article: HTML string
        :param img_url: the url to img
        :param tags: list with tags
        :param categories: list with categories
        """
        post = WordPressPost()
        post.title = self.title
        post.content = article
        post.thumbnail = self._upload_image(img_url)
        post.terms_names = {'post_tag': tags,
                            'category': categories}

        # post.post_status = 'publish'
        post.id = self.client.call(NewPost(post))
Ejemplo n.º 48
0
 def process_item(self, item, spider):
     wp_filename = item.filename('wp')
     if os.path.exists(wp_filename):
         with open(wp_filename) as fh:
             post = pickle.load(fh)
             fh.close()
             # #
             # Here one might update or fix things
             if False:
                 post.terms_names = {
                     'category': [item['source_name'].title()],
                     'post_tag': get_place_post_tag_names(item['place'])
                 }
                 self.client.call(posts.EditPost(post.id, post))
                 pass
             pass
         pass
     else:
         post = WordPressPost()
         post.title = item['headline']
         try:
             post.content = item['body']
         except KeyError:
             return None
         try:
             item['place']
         except KeyError:
             item['place'] = ""
         post.terms_names = {
             'category': [item['source_name'].title()],
             'post_tag': get_place_post_tag_names(item['place'])
         }
         post.link = item['source_url']
         post.date = item['time']
         post.post_status = 'publish'
         post.id = self.client.call(posts.NewPost(post))
         with open(wp_filename, 'wb') as fh:
             pickle.dump(post, fh)
             fh.close()
         pass
     return item
     pass
Ejemplo n.º 49
0
def post_data_to_site(titles, filenames):
	post_ids = []
	client = Client('http://domain.com/xmlrpc.php','username','password')
	for i in range(0,len(titles)):
		post_title, filename = titles[i], filenames[i]
		imgfile = os.path.join(DATA_DIR, filename)
		data = {'name':filename, 'type':'image/jpg'}
		with open(imgfile, 'rb+') as img:
			data['bits'] = xmlrpc_client.Binary(img.read())
		response = client.call(media.UploadFile(data))
		attachment_id = response['id']
		post = WordPressPost()
		post.title = post_title
		post.post_status = 'publish'
		post.thumbnail = attachment_id
		post.comment_status = 'open'
		post.id = client.call(posts.NewPost(post))
		post_ids.append(post.id)
		print post.id
	return post_ids	
Ejemplo n.º 50
0
def publish(pic, title, content):
    '''
    publish a post and set to open to comment and ping(trackback)
    '''
    attachment = upload(pic)
    wp_client = Client(rpc_service_url, user, password)
    post = WordPressPost()
    post.title = title
    post.content = "%s\n\n<a href='%s'><img class='alignnone size-full wp-image-%s' alt='%s' src='%s' /></a>" % (content, attachment['url'], attachment['id'], attachment['file'], attachment['url'])
    #post.tags='test, test2'
    #post.categories=['pet','picture']
    post.thumbnail = attachment['id']
    #change status to publish
    post.id = wp_client.call(posts.NewPost(post))
    post.post_status = 'publish'
    post.comment_status = 'open'
    post.ping_status = 'open'
    post.user = account_ids[r.randint(0, len(account_ids)-1)]
    wp_client.call(posts.EditPost(post.id, post))
    return post.id
Ejemplo n.º 51
0
def post_to_blog():
    from wordpress_xmlrpc import Client
    from wordpress_xmlrpc.methods.posts import NewPost

    wp_client = Client('http://pioupioutweet.ovh/xmlrpc.php', 'piou', 'Toto1piou')

    post = WordPressPost()
    post_text = time.strftime("%A %d %B %Y %H:%M:%S")
    post_text += ' Bird left the feeder !'
    post.title = post_text
    post.content = 'Here attached is the latest video recorded by the feeder.'

    post.terms_names = {
        'post_tag': ['Bird', 'BirdFeeding', 'BirdVideo'],
        'category': ['BirdFeeder', 'Video']
    }
    post.post_status = 'publish'
    post.id = wp_client.call(NewPost(post))
    LOGGER.debug(post)
    return post
Ejemplo n.º 52
0
    def newPostToWordpress(self, postName):
        printDebug("STEP", "You are going to create a new post!")
        post = WordPressPost()
        post.id = self.wp.call(NewPost(post))
        ## get the text of new post
        fileName = postName
        fmt, txt = formatter.readInputFile(fileName)
        self.format = fmt
        try:
            self.updatePost(post, txt)
        except Exception as e:
            printDebug("WARN", "Failed to send post to wordpress")
            printDebug("DEBUG", "Error was {0}".format(e))
            return 

        printDebug("INFO", "Post sent successfully")
        # Now download the sent post and save it.
        postNew = self.wp.call(GetPost(post.id))
        self.writePosts([postNew])
        printDebug("ADVICE", "You should now delete : {0}.".format(postName))
        return 0
Ejemplo n.º 53
0
def post_to_wp_sonymusic(post_content, cred):
	# Set up wordpress to accept posts from script
	wp = Client(cred[0], cred[1], cred[2])
	
	for entry in post_content:
		new_post = WordPressPost()
		new_post.title = unicode(entry[0].find_all("p")[0].contents[0])
		
		new_post.content = u"***Begin Original Content Here***\u000D"
		new_post.content += u"Posted on: " + entry[0].find("p", {"class": "infoDate"}).contents[0] + u"\u000D"
		new_post.content += u"<a href=\u0022" + entry[1] + u"\u0022>See original post</a>\u000D"
		
		for p in entry[0].find("div", {"id": "infoArticle"}):
			temp = unicode(p)
			new_post.content += temp
	
		new_post.id = wp.call(posts.NewPost(new_post))

		# Publish the post
		new_post.post_status = 'publish'
		wp.call(posts.EditPost(new_post.id, new_post))
Ejemplo n.º 54
0
def post(params):
  require_params(params,["xmlrpc_url","username","password","title","content","categories"])

  wp = Client(params["xmlrpc_url"], params["username"], params["password"])
  if not wp:
    return None

  post = WordPressPost()
  post.title = params["title"]
  post.content = params["content"]
  post.post_status = "publish"
  for cate in params["categories"].split(","):
    wpterms = wp.call(taxonomies.GetTerms('category', {"search":cate}))
    for wpterm in wpterms:
      if wpterm.name == cate:
        post.terms.append(wpterm)
  try:
    post.id = wp.call(posts.NewPost(post))
  except xml.parsers.expat.ExpatError:
    pass
  return True
Ejemplo n.º 55
0
def add_or_edit_wp_post(title, content, slug, more_info_url, local_img_file):

    # first upload the image
    if local_img_file:
        data = {
            'name': local_img_file.split('/')[-1],
            'type': 'image/jpg',  # mimetype
        }

        # read the binary file and let the XMLRPC library encode it into base64
        with open(local_img_file, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']

    # now post the post and the image
    post = WordPressPost()
    post.post_type = 'post'  # stupid effing theme
    post.title = title
    post.content = content
    post.post_status = 'publish'
    post.slug = slug

    if local_img_file:
        post.thumbnail = attachment_id

    if not get_wp_post_id(slug):
        # this is a new post
        wp.call(NewPost(post))
        msg = "posted"

    else:
        # this post exists, update it
        post.id = get_wp_post_id(slug)
        wp.call(EditPost(post.id, post))
        msg = "edited"

    print "%s %s as %s" % (msg, title, post.slug)
Ejemplo n.º 56
0
def wordpress_post(config):
    print("Connecting to: " + config.wordpress['xmlrpc'])
    wp = Client(config.wordpress['xmlrpc'],
                config.wordpress['username'],
                config.wordpress['password'])

    if config.attach_header:
        print("Uploading header image...")
        # Upload header image
        data = {
            'name': os.path.basename(config.png_header_file),
            'type': 'image/png',
        }

        # Read the image and let the XMLRPC library encode it to base64
        with open(config.png_header_file, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

        response = wp.call(media.UploadFile(data))
        attachment_id = response['id']

    print("Posting blog...")
    post = WordPressPost()
    post.title = config.wordpress['title']
    post.content = config.wordpress['content']
    post.post_format = config.wordpress['post_format']
    post.post_status = config.wordpress['post_status']
    post.comment_status = config.wordpress['comment_status']
    if config.attach_header:
        post.thumbnail = attachment_id
    post.terms_names = {
        'post_tag': [config.wordpress['tags']],
        'category': [config.wordpress['category']]
    }
    post.id = wp.call(NewPost(post))

    if config.wordpress['podcast_plugin'] == 'Powerpress':
        get_audio_size_and_duration(config)
Ejemplo n.º 57
0
def upload_post(auth, **args):
    wp = Client(auth['site'], auth['user'], auth['pass'])

    post = WordPressPost()

    post.post_type = args.get('type', None)
    post.title = args.get('title', None)
    post.content = args.get('content', None)
    post.date = gen_datetime(args['date'], args.get('date-format', None),
                             args.get('zone', 0))

    terms = {key: [value] for key, value in args.get('terms', {}).items()}
    post.terms_names = terms

    if args.get('path', None) is not None:
        post.custom_fields = [{'key': 'enclosure',
                               'value': upload_media(args['path'], wp)
                               }]

    if args.get('publish', False):
        post.post_status = 'publish'

    post.id = wp.call(posts.NewPost(post))
Ejemplo n.º 58
0
def post_to_wp_ameblo(post_content, cred):
	# Set up wordpress to accept posts from script
	wp = Client(cred[0], cred[1], cred[2])
	
	# Dump each thing into a wordpress post
	for entry in post_content:
		new_post = WordPressPost()
		new_post.title = unicode(entry[0].find("h3").find("a").contents[0])
		
		new_post.content = u"***Begin Original Content Here***\u000D"
		new_post.content += u"Posted on: " + unicode(entry[0].find("span", {"class": "date"}).contents[0]) + u"\u000D"
		new_post.content += u"<a href=\u0022" + entry[1] + u"\u0022>See original post</a>\u000D"

		for p in entry[0].find("div", {"class": "contents"}).find("div", {"class": "subContents"}).find("div", {"class": "subContentsInner"}):
			temp = unicode(p)
			if temp != "entryBottom" and not "google_ad_section" in temp:
				new_post.content += temp
		
		new_post.id = wp.call(posts.NewPost(new_post))
		
		# Publish the post
		new_post.post_status = 'publish'
		wp.call(posts.EditPost(new_post.id, new_post))
Ejemplo n.º 59
0
    def create_match_post(self, media_post, title, tags, extra):
        post = WordPressPost()
        post.title = title
        if extra == None:
            extra = ""
        post.content = media_post.get_embed() + extra
        post.terms_names = {
                'post_tag': tags
        }

        post.terms = self.find_terms()
        post.post_status = 'publish'
        post.custom_fields = [
            {
                'key': 'thumbnail',
                'value': media_post.get_thumb()
            },
            {
                'key': 'event_date',
                'value': self.date
            }           
        ]
        post.id = self.client.call(posts.NewPost(post))
        return post
	def post():
		#get id
		post_id = re.search(':wp_id:((.*)|\n)', asc_file_read_str).group(1).strip()

		#get status
		post_status = re.search(':wp_status:((.*)|\n)', asc_file_read_str)

		#get title
		post_title = re.search(':wp_title:((.*)|\n)', asc_file_read_str)

		#get slug
		post_slug = re.search(':wp_slug:((.*)|\n)', asc_file_read_str)

		#get category
		post_category = re.search(':wp_category:((.*)|\n)', asc_file_read_str)
		post_category_str = post_category.group(1).strip().split(", ")

		if len(post_category_str) == 0:
			post_category_str = []
		elif post_category.group(1).strip() == '':
			post_category_str = []
		elif len(post_category_str) == 1:
			post_category_str = post_category.group(1).strip(),

		#get tag
		post_tag = re.search(':wp_tag:((.*)|\n)', asc_file_read_str) 
		post_tag_str = post_tag.group(1).strip().split(", ")

		if len(post_tag_str) == 0:
			post_tag_str = []
		elif post_tag.group(1).strip() == '':
			post_tag_str = []
		elif len(post_tag_str) == 1:
			post_tag_str = post_tag.group(1).strip(),

		#get excerpt
		post_excerpt = re.search(':wp_excerpt:((.*)|\n)', asc_file_read_str)

		#get thumbnail
		post_thumbnail = re.search(':wp_thumbnail:((.*)|\n)', asc_file_read_str)

		#post to wordpress
		from wordpress_xmlrpc import Client, WordPressPost
		from wordpress_xmlrpc.methods import posts
		client = Client(xmlrpc_url, username, password)
		post = WordPressPost()


		date_ = datetime.now()
		#id New or Edit
		if not post_id:
			post.date = date_.strftime("%s")
			post.id = client.call(posts.NewPost(post))
			mode = "New"
			asc_file_re = re.sub(r':wp_id:((.*)|\n)', ':wp_id: ' + post.id , asc_file_read_str)
			asc_file_write = open(filepath, 'w')
			try:
				asc_file_write.write( asc_file_re )
			finally:
				asc_file_write.close()
		else:
			post.date_modified = date_.strftime("%s")
			post.id = post_id
			mode = "Edit"

		post.post_status = post_status.group(1).strip()

		try:
			post.title = post_title.group(1).strip()
		except:
			print 'Title is not exist'

		try:
			post.slug =  post_slug.group(1).strip()
		except:
			print 'Slug is not exist'

		post.content =  html

		try:
			post.excerpt = post_excerpt.group(1).strip()
		except:
			post.excerpt =  ''

		post.terms_names = {
		        'category': post_category_str,
		        'post_tag': post_tag_str,
		}

		try:
			post.thumbnail = post_thumbnail.group(1).strip()
		except:
			post.thumbnail =  ''

		client.call(posts.EditPost(post.id, post))

		post_info = client.call(posts.GetPost(post.id, post))


		#get post info from wordpress
		asc_file_read_slug = open(filepath, 'r')
		asc_file_read_slug_str = asc_file_read_slug.read()

		if post_info:
			asc_file_read_slug_str = re.sub(r':wp_slug:((.*)|\n)', ':wp_slug: ' + post_info.slug, asc_file_read_slug_str)
			if mode == "New":
				new_date = int(post_info.date.strftime("%s"))+(timezone___*60*60)
				new_date = datetime.fromtimestamp(new_date).strftime("%Y-%m-%d %H:%M:%S")
				asc_file_read_slug_str = re.sub(r':wp_date:((.*)|\n)', ':wp_date: ' + new_date, asc_file_read_slug_str)
			elif mode == "Edit":
				edit_date = int(post_info.date_modified.strftime("%s"))+(timezone___*60*60)
				edit_date = datetime.fromtimestamp(edit_date).strftime("%Y-%m-%d %H:%M:%S")
				asc_file_read_slug_str = re.sub(r':wp_modified:((.*)|\n)', ':wp_modified: ' + edit_date, asc_file_read_slug_str)
			asc_file_re_slug_write = open(filepath, 'w')
			try:
				asc_file_re_slug_write.write( asc_file_read_slug_str )
			finally:
				asc_file_re_slug_write.close()

		print '==========================\n' + mode + ' Post ID: ' + post.id + ' \nStatus: ' + post.post_status + '\nTitle: ' + post.title + '\nSlug: ' + post_info.slug + '\nCategory: ' + post_category.group(1).strip() + '\nTag: ' + post_tag.group(1).strip() + '\n'