Example #1
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))
 def add_post(self, post, ul_resources=False):
     rec = wordpress_xmlrpc.WordPressPost()
     rec.title = extract_title(post._message)
     rec.content = format_message(post._message)
     if post._pictures:
         if ul_resources:
             post._pictures = [self.upload(f) for f in post._pictures]
         images = ''.join('<img src="{}" />\n'.format(url)
                          for url in post._pictures)
         rec.content = images + '<br />\n' + rec.content
     if post._attachments:
         if ul_resources:
             post._attachments = [(name, self.upload(f))
                                  for name, f in post._attachments]
         attachments = ''.join(
             '<div><a href="{}">{}</a></div>\n'.format(url, name)
             for name, url in post._attachments)
         rec.content += '<br />\n<div>קבצים מצורפים:</div>\n' + attachments
     rec.date = facebook_timestamp_to_datetime(post._created_time)
     if post._updated_time != post._created_time:
         rec.date_modified = facebook_timestamp_to_datetime(
             post._updated_time)
     rec.terms_names = {'post_tag': [post._from['name']]}
     rec.post_status = 'publish'
     rec.comment_status = 'open'
     if self._debug:
         print('posting')
     post_id = self._client.call(posts.NewPost(rec))
     self.add_comments(post_id, post_id, post._comments, ul_resources)
Example #3
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
Example #4
0
def pedir_datos_nueva_entrada():
    limpiar_pantalla()
    nueva_entrada = WordPressPost()
    nueva_entrada.title = input("Ingresa el título de la entrada: ")
    nueva_entrada.content = input("Ingresa todo el contenido de la entrada: ")
    etiquetas = []
    categorias = []
    eleccion = input("¿Deseas agregar etiquetas? [S/N] ")
    if eleccion.lower() == "s":
        etiquetas = input("Ingresa las etiquetas separadas con comas: ").split(",")
    eleccion = input("¿Deseas agregar categorías? [S/N] ")
    if eleccion.lower() == "s":
        categorias = input("Ingresa las categorías separadas con comas: ").split(",")
    nueva_entrada.terms_names = {
            'post_tag': etiquetas,
            'category': categorias,
    }
    print("Publicando entrada...")
    id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada))
    limpiar_pantalla()
    print("Correcto! Se guardó la entrada como borrador, y su id es {}".format(id_entrada_publicada))
    eleccion = input("¿Publicar inmediatamente? [S/N] ")
    if eleccion.lower() == "s":
        print("Publicando entrada...")
        nueva_entrada.post_status = 'publish'
        resultado = cliente.call(posts.EditPost(id_entrada_publicada, nueva_entrada))
        if resultado is True:
            input("Entrada publicada")
        else:
            input("Algo salió mal")
    imprimir_menu_opciones()
Example #5
0
    def create_post(self,
                    title,
                    content,
                    post_format='image',
                    tag=None,
                    category=None,
                    thumnnail_path=None):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.comment_status = 'open'
        post.post_format = post_format  # image,video,0
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
        post.terms_names = {
            'post_tag': tag  #['test', 'beauty'],  文章所属标签,没有则自动创建
            ,
            'category': category  #['校园美女']  文章所属分类,没有则自动创建
        }
        if thumnnail_path is None:
            post.thumbnail = None
        elif thumnnail_path.startswith('http'):
            post.thumbnail = self.add_external_image(thumnnail_path)
        else:
            post.thumbnail = self._find_media(thumnnail_path)  # 缩略图的id

        try:
            self.wp.call(posts.NewPost(post))
        except Exception as e:
            print(e)
Example #6
0
def callback(ch, method, properties, body):
    print(body)
    if str(body).startswith("[wordpress]") and len(str(body)) < 300:
        query = str(body)[11:]
        q = query.split('-')
        nueva_entrada = WordPressPost()
        nueva_entrada.title = q[0]
        nueva_entrada.content = q[1]
        id_entrada_publicada = cliente.call(posts.NewPost(nueva_entrada))
        print("Correcto! Se guardó la entrada como borrador, y su id es {}".
              format(id_entrada_publicada))
        print("Publicando entrada...")
        nueva_entrada.post_status = 'publish'
        resultado = cliente.call(
            posts.EditPost(id_entrada_publicada, nueva_entrada))
        print(resultado)
        if resultado is True:
            print("Entrada publicada")
        else:
            print("Algo salió mal")

        ########## PUBLICA EL RESULTADO COMO EVENTO EN RABBITMQ ##########
        channel.basic_publish(exchange='donbot',
                              routing_key="publicar_slack",
                              body="publicado!")
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!")
Example #8
0
    def test_post_lifecycle(self):
        # create a post object
        post = WordPressPost()
        post.title = 'Test post'
        post.slug = 'test-post'
        post.content = 'This is test post using the XML-RPC API.'
        post.comment_status = 'open'
        post.user = self.userid

        # create the post as a draft
        post_id = self.client.call(posts.NewPost(post))
        self.assertTrue(post_id)

        # fetch the newly-created post
        post2 = self.client.call(posts.GetPost(post_id))
        self.assertTrue(isinstance(post2, WordPressPost))
        self.assertEqual(str(post2.id), post_id)

        # update the post
        post2.content += '<br><b>Updated:</b> This post has been updated.'
        post2.post_status = 'publish'
        response = self.client.call(posts.EditPost(post_id, post2))
        self.assertTrue(response)

        # delete the post
        response = self.client.call(posts.DeletePost(post_id))
        self.assertTrue(response)
Example #9
0
    def test_revisions(self):
        original_title = 'Revisions test'
        post = WordPressPost()
        post.title = original_title
        post.slug = 'revisions-test'
        post.content = 'This is a test post using the XML-RPC API.'
        post_id = self.client.call(posts.NewPost(post))
        self.assertTrue(post_id)

        post.title = 'Revisions test updated'
        post.content += ' This is a second revision.'
        response = self.client.call(posts.EditPost(post_id, post))
        self.assertTrue(response)

        # test wp.getRevisions
        revision_list = self.client.call(posts.GetRevisions(post_id, ['post']))
        self.assert_list_of_classes(revision_list, WordPressPost)

        # workaround for WP bug #22686/22687
        # an auto-draft revision will survive wp.newPost, so pick the 2nd revision
        self.assertEqual(2, len(revision_list))
        real_rev = revision_list[1]
        self.assertTrue(real_rev)
        self.assertNotEquals(post_id, real_rev.id)

        # test wp.restoreRevision
        response2 = self.client.call(posts.RestoreRevision(real_rev.id))
        self.assertTrue(response2)
        post2 = self.client.call(posts.GetPost(post_id))
        self.assertEquals(original_title, post2.title)

        # cleanup
        self.client.call(posts.DeletePost(post_id))
Example #10
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
Example #11
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))
def process_button(site, camera):
    # check github directories and make sure they match whats stored locally
    # if directories match:
    newFaceRecognizer._smile321()
    camera.capture('test_image.jpg')
    print("Picture taken!")
    filepath = 'test_image.jpg'
    data = {'name': 'test_image.jpg', 'type': 'image/jpeg'}
    with open(filepath, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = site.call(media.UploadFile(data))
    attachment_id = response['id']

    yay = WordPressPost()
    yay.title = 'Picture Time!'
    yay.content = 'Lookin\' snazzy'
    d = date.today().strftime("%b-%d-%Y")
    yay.terms_names = {'post_tag': [d], 'category': ['Successful Login']}
    yay.post_status = 'publish'
    yay.thumbnail = attachment_id
    site.call(posts.NewPost(yay))
    camera.close()

    # call cv2 script for unlocking the box
    id, conf = newFaceRecognizer.checkUser()
    if conf >= 45 and id not in newFaceRecognizer.getBannedUsers():
        # call servo unlock fxn
        unlock_servo()
Example #13
0
def wordpress_artice(wppost_status, wp_title, wp_slug_title, wp_content,
                     wp_category, wp_post_tag, wp_host, wp_user, wp_password):
    # 如果遇到错误就出试5次
    success_num = 0
    while success_num < 5:
        try:
            client = Client(wp_host, wp_user, wp_password)

            newpost = WordPressPost()  # 创建一个类实例,注意,它不是一个函数。只要在一个类名后面加上括号就是一个实例
            # newpost.post_status = 'draft'
            newpost.post_status = wppost_status
            newpost.slug = wp_slug_title  # 文章别名,固定链接形式为文章标题时需要
            # 设置发布目录(一篇文章可以属于多个分类目录)
            newpost.terms_names = {
                'category': wp_category,  # 目录
                'post_tag': wp_post_tag  # 标签
            }
            newpost.title = wp_title
            newpost.content = wp_content
            client.call(posts.NewPost(newpost))  #发布新建的文章,返回的是文章id
            print("Wordpress发布成功:", wp_title)

        except Exception as e:
            print("正在重试:", e)
            success_num = success_num + 1
            continue
Example #14
0
    def test_category_post(self):
        # create a test post
        post = WordPressPost()
        post.title = 'Test Post'
        post.slug = 'test-post'
        post.user = self.userid
        post.id = self.client.call(posts.NewPost(post))

        # create a test category
        cat = WordPressTerm()
        cat.name = 'Test Category'
        cat.taxonomy = 'category'
        cat.id = self.client.call(taxonomies.NewTerm(cat))

        # set category on post
        try:
            post.terms = [cat]
            response = self.client.call(posts.EditPost(post.id, post))
            self.assertTrue(response)

            # fetch categories for the post to verify
            post2 = self.client.call(posts.GetPost(post.id, ['terms']))
            post_cats = post2.terms
            self.assert_list_of_classes(post_cats, WordPressTerm)
            self.assertEqual(post_cats[0].id, cat.id)
        finally:
            # cleanup
            self.client.call(taxonomies.DeleteTerm(cat.taxonomy, cat.id))
            self.client.call(posts.DeletePost(post.id))
    def createMP3Post(self, presenter, title, reference, date_str, media_url, verbose=False):
        if verbose:
            print 'createMP3Post starting'


        post = WordPressPost()
        titleTemplate = u"""Podcast : {0} : {1} - {2}"""
        title = title.encode('ascii','ignore')
        post.title = titleTemplate.format(date_str, presenter, title)

        template = u"""[audio  "{4}" ]<p>{0} : {1} - {2} - {3}</p>"""
        post.content = template.format(date_str, presenter, title, reference, media_url)
        post.post_status = 'publish'
        # set the category so this Post is inserted into our 'podcast' feed
        post.terms_names = {'category': [self.feed_category,]}
        post.post_format = 'Link'

        retval = None
        try:
            print ' post = ', post
            print 'post.content =', post.content
            retVal = self.client.call(posts.NewPost(post))
        except Exception as inst:
            print 'createMP3Post: posts.NewPost() failed', inst
        else:
            if verbose:
                print 'createMP3Post complete'
            return retVal
Example #16
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
Example #17
0
def create_template_files(file_name):

	#1. create scss file
	#assets/scss/templates/_[name].scss
	try:
	    fh = open(sass_directory + '_'+ file_name + '.scss','r')
	except:
	# if file does not exist, create it
	    fh = open(sass_directory + '_'+ file_name + '.scss','w')

	#2. Import newly created Sass file to global one
	#assets/scss/templates/app.scss
	with open('assets/scss/foundation.scss', 'a') as f:
	    f.write('\n@import "templates/' + file_name + '";')
		    #f.writelines(lines)

	#3. create image folder
	#assets/images/[name]
	if not(os.path.exists(image_directory + file_name)):
		os.makedirs(image_directory + file_name)

	#4a. Create page template
	if not(os.path.exists(page_template_directory + file_name) ):
		with open(page_template_directory + file_name + '.php', 'a') as f:
			f.writelines(['<?php \n', '/* Template Name: '+ file_name.capitalize() +' */\n', '  get_header();\n', '?>', '\n\n', '<?php get_footer();'])
		#4b. Create page in wordpress and connect to the template page
		client = Client(site_host + 'xmlrpc.php', username, password)
		page = WordPressPage()
		page.title = file_name.capitalize()
		page.content = ''
		page.post_status = 'publish'
		page.template = 'page-templates/about.php'
		page.id = client.call(posts.NewPost(page))
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 !")
Example #19
0
def fabu(single_link):
    print(single_link)
    post.custom_fields = []
    post.custom_fields.append({
        'key':'via',
        'value':single_link,
    })
    html = htmldown(single_link)
    title = html.find('span.ask-title',first=True).text
    title = chs_to_cht(title)
    post.title = title
    print(title)

    try:
        html.find('.best-text', first=True).text
    except:
        try:
            html.find('.long-question',first=True).text
        except:
            content = ''
        else:
            content = html.find('.long-question', first=True).text
    else:
        content = html.find('.best-text', first=True).text

    try:
        html.find('.con-all',first=True).text
    except:
        try:
            html.find('.con',first=True).text
        except:
            content = chs_to_cht(content)
            all_content = content
        else:
            ask_content = html.find('.con', first=True).text
            all_content = str(ask_content) + '\n\n' + str(content)
            all_content = chs_to_cht(all_content)
    else:
        ask_content = html.find('.con-all', first=True).text
        all_content = str(ask_content) + '\n\n' + str(content)
        all_content = chs_to_cht(all_content)

    post.content = all_content
    post.content = all_content.replace("展開全部","")
    print(post.content)

    try:
        html.find('.wgt-ask .q-img-wp img.q-img-item', first=True).attrs['src']
    except AttributeError:
        post.thumbnail = None
    else:
        img = html.find('img.q-img-item', first=True).attrs['src']
        img = HTMLSession().get(img).content
        data = {'name': 'picture.jpg','type': 'image/jpeg'}
        data['bits'] = xmlrpc_client.Binary(img)
        response = wp.call(media.UploadFile(data))
        post.thumbnail = response['id']

    post.id = wp.call(posts.NewPost(post))  # 返回文章ID
    print(str(base_url)+'?p='+str(post.id))
Example #20
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(
        '-----------------------------------------------------------------------------------------------'
    )
Example #21
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))
Example #22
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)
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('-----------------------------------------------------------------------------------')
Example #25
0
def _removedUserPost(user):
    post = WordPressPost()
    post.title = 'User removed'
    post.content = 'New User {}'.format(user)
    post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Remove User']}
    post.post_status = 'publish'
    site.call(posts.NewPost(post))
Example #26
0
def _unlockPost(user):
    post = WordPressPost()
    post.title = 'Box Unlocked'
    post.content = 'Unlocked by {}'.format(user)
    post.terms_names = {'post_tag' : [date.today().strftime("%b-%d-%Y")], 'category': ['Successful Login']}
    post.post_status = 'publish'
    site.call(posts.NewPost(post))
Example #27
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))
Example #28
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))
Example #29
0
    def postBlog(self, new_blog):
        print('正在发布:', new_blog[1])
        post = WordPressPost()
        kuohao = '【{}】'
        post.title = new_blog[1] + kuohao.format(new_blog[2]) + kuohao.format(
            new_blog[8])
        post.post_status = 'publish'  # 文章状态,不写默认是草稿,private表示私密的,draft表示草稿,publish表示发布
        comic_cover = '<img src="' + new_blog[
            6] + '" alt="" class="aligncenter size-full wp-image-154" />'
        post.content = comic_cover + '<h5>漫画简介:</h5><blockquote style="text-indent: 30px;">' + new_blog[
            7] + '</blockquote>'

        serial_status = '精彩连载,' if '连载' in new_blog[8] else '经典完结,'
        categorys = serial_status + new_blog[3]
        post.terms_names = {
            'post_tag': new_blog[4].split(','),  # 文章所属标签,没有则自动创建
            'category':
            categorys.split(',') + new_blog[5].split('+')  # 文章所属分类,没有则自动创建
        }

        post.custom_fields = []  # 自定义字段列表
        # 资源价格
        price = int(new_blog[11]) * 10 if new_blog[11] else 2 * 10
        post.custom_fields.append({'key': 'cao_price', 'value': price})
        # 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[9]})
        # 资源下载密码
        post.custom_fields.append({'key': 'cao_pwd', 'value': new_blog[10]})
        # 资源下载次数
        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[4]
            }, {
                'title': '是否完结',
                'desc': new_blog[8]
            }]
        })
        try:
            self.wp.call(posts.NewPost(post))
            print('发布成功:', new_blog[1])
        except:
            print('发布失败:', new_blog[1])
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, '!')