コード例 #1
0
    def createPost(self, title, description, size, tags, links, category):
        wp = Client(self.wp_url,
                    self.wp_username,
                    self.wp_password,
                    transport=SpecialTransport())
        post = WordPressPost()
        post.post_status = 'publish'
        title = title.replace('.', ' ')
        title = title.replace('_', ' ')
        post.title = title
        post.content = 'Size:<b> ' + size + '</b> <br /><br /><br />'
        post.content = post.content + description
        post.content = post.content + '<br /><div class=' "downLinks" '>Download Links:</div>'

        addLinks = '<textarea readonly>'
        for link in links:
            addLinks = addLinks + link + '&#13;&#10;'
        addLinks = addLinks + '</textarea>'

        post.content = post.content + addLinks

        post.terms_names = {'post_tag': tags, 'category': [category]}

        id = wp.call(NewPost(post))
        postLink = WordPressPost()
        postLink = wp.call(GetPost(id))
        return postLink.link
コード例 #2
0
def publish_to_wordpress(ep_id,
                         sermon_title,
                         sermon_description,
                         wp_client=None):
    if wp_client is None:
        wordpress_params = {
            'url': CONF['wordpress']['url'],
            'username': CONF['wordpress']['user'],
            'password': CONF['wordpress']['password'],
        }
        wp_client = Client(**wordpress_params)
    ep_id = ep_id.lower()
    ep_emb_id = '-'.join([ep_id[0:5], ep_id[5:]])
    pb_url = 'https://www.podbean.com/media/player/{}?from=yiiadmin'.format(
        ep_emb_id)
    full_content = '''<h2>{0}</h2>
    <iframe src="{1}" width="100%" height="100" frameborder="0" scrolling="no" data-link="{1}" data-name="pb-iframe-player"></iframe>
    {2}'''.format(sermon_title.encode('utf8'), pb_url, sermon_description)
    post = WordPressPost()
    # post and activate new post
    post = WordPressPost()
    post.title = sermon_title
    post.content = full_content
    post.post_status = CONF['wordpress']['publish_mode']
    post.terms_names = {'category': ['Podcast']}
    return wp_client.call(NewPost(post)), sermon_title
コード例 #3
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))
コード例 #4
0
    def insert_post(self, joomla_post, category_id):

        client = self.get_client()
        post = WordPressPost()
        post.title = joomla_post.get_title()

        text_to_replace = joomla_post.get_introtext()

        text_to_replace = str(text_to_replace).replace("href=\"images/",
                                                       "href=\"/images/")

        post.content = str(text_to_replace).replace("src=\"images/",
                                                    "src=\"/images/")

        post.date = joomla_post.get_created()

        post.thumbnail = self.post_thumbnail(joomla_post.get_id())['id']

        post.post_status = "publish"

        category = client.call(taxonomies.GetTerm('category', category_id))

        post.terms.append(category)

        client.call(NewPost(post))

        return post
コード例 #5
0
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('-----------------------------------------------------------------------------------')
コード例 #6
0
def wpsend(content, title, vido_info_kind):
    try:
        # 链接地址,登录用户名,密码
        wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce', '12345678')
        # print(content)
        post = WordPressPost()
        # 设置标题内容
        post.title = str(title)
        # 文章正文内容
        post.content = " ''' " + content + " ''' "
        # 可见性,publish:全部可见;
        post.post_status = 'publish'
        # 设置标签,分类
        post.terms_names = {
            'post_tag': ['影视'],
            'category': ['影视', '链接资源', vido_info_kind]
        }
        # 验证是否有相同标题
        old_post = wp.call(GetPost(post.title))
        # old_post = GetPost(post.title)
        print(old_post)
        if post.title == old_post:
            wp.call(DeletePost(post.title))
            print('已经删除{}'.format(post.title))
        else:
            # 新建文章
            wp.call(NewPost(post))
            localtime = time.localtime(time.time())
            print('文档已上传 {}'.format(
                time.strftime("%Y-%m-%d %H:%M:%S", localtime)))
    except:
        print('没有上传成功')
コード例 #7
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)
コード例 #8
0
def postWordpress(item):

    post = WordPressPost()
    post.title = item.title
    post.content = item.movieUrl
    if item.category == "":
        post.terms_names = {'post_tag': item.tags}
    else:
        category = []
        category.append(item.category)
        post.terms_names = {'post_tag': item.tags, 'category': category}
    post.slug = '[input your prameter]'

    # 投稿時間
    # 現在時間で投稿
    post.date = datetime.now()
    # 予約投稿の場合(例:2017年2月2日0時0分0秒0マイクロ秒)
    #month = random.randint(1,10)
    #day = random.randint(1,22)
    #post.date = datetime(2018, month, day, 0, 0, 0, 0)

    # 投稿する。
    # ステータスを公開済にする。
    post.post_status = 'publish'
    # これなら下書き指定
    # post.post_status = 'draft'

    post.thumbnail = getMediaId(item)
    wp.call(NewPost(post))
コード例 #9
0
ファイル: 爬csdn博文.py プロジェクト: gordy2015/project01
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(
        '-----------------------------------------------------------------------------------------------'
    )
コード例 #10
0
def make_wp_content(hotitem):
    format_cont = Template(post_template)
    # format_cont.substitute(shop = u"天猫", img=hotitem["goods_pic"])
    post = WordPressPost()
    post.title = hotitem["goods_title"]
    post.content = hotitem["goods_introduce"]
    # post.post_type = "tbkitem"
    iteminfo = json.dumps(hotitem)
    post.custom_fields = [{"key": "iteminfo", "value": iteminfo}]
    # post.thumbnail = hotitem["goods_pic"]

    post.content = format_cont.substitute(
        shop=hotitem["platform"].decode("utf8"),
        introduce=hotitem["goods_introduce"],
        origin_price=hotitem["origin_price"],
        quan_price=hotitem["zhekou_price"],
        now_price=float(hotitem["origin_price"]) -
        float(hotitem["zhekou_price"]),
        tbk_link_quan=hotitem["tbk_link_quan"],
        img=hotitem["goods_pic"])
    post.terms_names = {
        'post_tag': hotitem["tag"],
        'category': hotitem["category"],
    }
    post.post_status = "publish"
    return post
コード例 #11
0
def sends():
    print len(targeturl)
    for i in range(len(targeturl)):
        #u=content1[i][0]
        url = "http://whuhan2013.github.io" + targeturl[i]
        print url
        a = Article(url, language='zh')
        a.download()
        a.parse()
        title = a.title
        dst = a.text

        #链接WordPress,输入xmlrpc链接,后台账号密码
        wp = Client('http://127.0.0.1:22222/xmlrpc.php', 'www', '!abc6')
        #示例:wp = Client('http://www.python-cn.com/xmlrpc.php','username','password')
        post = WordPressPost()
        post.title = title
        #post.post_type='test'
        #post.content = dst
        post.description = dst
        post.post_status = 'publish'
        #发送到WordPress
        wp.call(NewPost(post, True))
        time.sleep(3)
        print 'posts updates'
コード例 #12
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()
コード例 #13
0
    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
コード例 #14
0
def wpsend(content, title, vido_info_kind):
    try:
        # 链接地址,登录用户名,密码
        wp = Client('http://magnetkey.xyz/xmlrpc.php', 'bruce',
                    'flzx3qc@ysyhl9t')
        # wp = Client('http://192.168.190.145/xmlrpc.php', 'bruce', '12345678')
        # print(content)
        post = WordPressPost()
        # 设置标题内容
        post.title = str(title)
        # 文章正文内容
        post.content = " ''' " + content + " ''' "
        # 可见性,publish:全部可见;'private':私有
        post.post_status = 'publish'
        # 设置标签,分类
        post.terms_names = {
            'post_tag': ['影视'],
            'category': ['影视', '在线播放资源', vido_info_kind]
        }
        # # 新建文章
        wp.call(NewPost(post))
        localtime = time.localtime(time.time())
        print('文档已上传 {}'.format(time.strftime("%Y-%m-%d %H:%M:%S", localtime)))
    except:
        print('没有上传成功')
コード例 #15
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!")
コード例 #16
0
def newPost(title, content, tags, cats):
    post = WordPressPost()
    post.title = title
    post.content = content
    #post.post_status = 'publish'
    post.terms_names = {'post_tag': tags, 'category': cats}
    wp.call(NewPost(post))
コード例 #17
0
def showText():
    title = title_entry.get()
    description = description_entry.get('1.0', END)

    isYes = messagebox.askyesno("Confirmation to post",
                                "Are you sure you want to post?")
    if isYes:
        print("Title: {titleKey} \nDescrption: {descriptionKey}".format(
            titleKey=title, descriptionKey=description))
        wp = Client('https://vijayatm.wordpress.com/xmlrpc.php',
                    'yourUserName',
                    'yourPassword')  #replace your username and password here
        data = {'name': 'Python file Name.jpg', 'type': 'image/jpg'}
        with open(imgArg, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        attachmentURL = response['url']
        attachmentID = response['attachment_id']
        print(response)

        post = WordPressPost()
        post.title = title
        post.content = "<img src='{att1}'/><br>{description}".format(
            att1=attachmentURL, description=description)
        post.thumbnail = attachmentID
        post.terms_names = {
            'post_tag': ['vijayatm', 'usingPython', 'tkinter', 'wordpress']
        }
        post.post_status = 'publish'
        resp = wp.call(NewPost(post))
        print(resp)
        root.destroy()
    else:
        messagebox.showinfo('Welcome Back',
                            'Update the description if you want to')
コード例 #18
0
ファイル: wpPost.py プロジェクト: wzy1990/comicSpider
 def updateBlog(self):
     with open('已发布的漫画列表.csv', 'r', encoding='UTF-8') as csv_file:
         csv_reader_lines = csv.reader(csv_file)
         for blog in csv_reader_lines:
             post = WordPressPost()
             post.post_status = 'draft'
             self.wp.call(posts.EditPost(blog[1], post))
コード例 #19
0
ファイル: final.py プロジェクト: paul359/practice
	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
コード例 #20
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))
コード例 #21
0
ファイル: chatwithtutor.py プロジェクト: elitem17/Python
    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)
コード例 #22
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))
コード例 #23
0
    def post(self):
        filename = "linuxlogo.jpg"
        data = {
            'name': 'linuxlogo.jpg',
            'type': 'image/jpeg',
        }
        with open(filename, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())

        r = self.wp_client.call(media.UploadFile(data))
        attachment_id = r['id']

        #Create random content in range of 1000 letters
        s = np.random.uniform(0, 1, size=2)
        s1 = int(s[0] * self.conf.post_nchars + 1)
        s2 = int(s[1] * self.conf.post_title_nchars + 1)

        content = "".join([random.choice(string.letters) for i in xrange(s1)])
        random_title = "".join(
            [random.choice(string.letters) for i in xrange(s2)])

        post = WordPressPost()
        post.title = 'Random title: ' + random_title
        post.content = content
        post.post_status = 'publish'
        post.thumbnail = attachment_id
        post.terms_names = {
            'post_tag': ['test', 'firstpost'],
            'category': ['Uncategorized']
        }
        return self.wp_client.call(NewPost(post))
コード例 #24
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))
コード例 #25
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 !")
コード例 #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))
コード例 #27
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))
コード例 #28
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))
コード例 #29
0
def postToWP(title, article, url_bing):
    request = urllib2.Request(url_bing)
    request.add_header('Authorization', credentialBing)
    requestOpener = urllib2.build_opener()
    response = requestOpener.open(request)
    results = json.load(response)
    l = len(results['d']['results'])
    image = results['d']['results'][random.randint(0,l-1)]['Thumbnail']['MediaUrl']
    response = requests.get(image, stream=True)
    with open('image'+h+m+s+'.jpg', 'wb') as out_file:
        shutil.copyfileobj(response.raw, out_file)
    del response
    filename = 'image'+h+m+s+'.jpg'
    url = 'http://www.'+args.profile+'.com/xmlrpc.php'
    wp = Client(url, 'admin', 'wIn$j5vG$#NryzJGGlBMd20J')
    # prepare metadata
    data = {
        'name': 'image'+h+m+s+'.jpg',
        'type': 'image/jpeg',  # mimetype
    }
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = wp.call(media.UploadFile(data))
    
    img = '/wp-content/uploads/'+yr+'/'+mo+'/image'+h+m+s+'.jpg'
    post = WordPressPost()
    post.title = title
    post.content = '<img class="alignleft" src="'+img+'" width="341" height="341"/> \n' + article
    post.terms_names = {
        'category': categories[:2]
    }
    
    post.post_status = 'publish'
    wp.call(NewPost(post))
    return True
コード例 #30
0
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))