Esempio n. 1
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))
Esempio n. 2
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!"
Esempio n. 3
0
def create_post(title, text="", url="", image_url=""):

    shortened_url = shorten_link(url) if url else ""

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

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

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

    try:
        redditsync.wordpress.wp.call(NewPost(post))
    except Exception as err:
        logging.error(str(err))
        sys.exit()
def 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
Esempio n. 5
0
	def post(self):    
                from lxml import etree
		try:
                  self.ui.label.setText("Importing necessary modules...")
                  from wordpress_xmlrpc import Client, WordPressPost
                  status = 1  		
                except:
                  status = 0
                if(status==1):
                  from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
		  from wordpress_xmlrpc.methods.users import GetUserInfo
                  self.ui.label.setText("Imported modules...")
		  data = etree.parse("config.xml")
		  user = data.find("user").text	
		  url = data.find("url").text
		  pwd = data.find("pass").text
                  self.ui.label.setText("Imported data...")
                  try:  
                    wp = Client(url+"/xmlrpc.php", user, pwd)
	            	  
                  except:
                    status = 0
                  if (status == 1):  
                    post = WordPressPost()
		    post.content = str(self.ui.BodyEdit.toPlainText())
		    post.title = str(self.ui.TitleEdit.text())
                    post.content = post.content + "<br><small><i>via QuickPress</i></small></br>"
                    post.post_status = 'publish'
		    wp.call(NewPost(post))	
                    self.ui.label.setText("Published") 
                  else:
                    self.ui.label.setText("Check Internet Connection and try again...")
                else:
		  self.ui.label.setText("module(wordpress_xmlrpc) not found, you can install manually from terminal using pip install python-wordpress-xmlrpc")                
Esempio n. 6
0
def build_collection_message(collection):
	post = WordPressPost()
	post.title = collection.title

	games = []
	for game in collection.games.all():
		games.append({
			'name' : game.name,
			'brief_comment' : game.brief_comment,
			'icon' : settings.MEDIA_URL + game.icon.name,
			'category' : game.category.name,
			'size' : game.size,
			'platforms' : _get_game_platforms(game),
			'id' : game.id,
			'android_download_url' : game.android_download_url,
			'iOS_download_url' : game.iOS_download_url,
			'rating' : game.rating,
			'recommended_reason' : _normalize_content(game.recommended_reason)
			})

	post.content = str(render_to_string('collection_web.tpl', {
		'content' : _normalize_content(collection.recommended_reason),
		'cover' : settings.MEDIA_URL + collection.cover.name,
		'games' : games
	}))

	post.terms_names = {
		'category' : [u'游戏合集']
	}

	post.post_status = 'publish'

	return WebMessage(collection.id, post)
Esempio n. 7
0
def create_post_from_file(a_file):
    post = WordPressPost()
    file_content = get_content_for_file(a_file)
    match = yaml_match_from_post_data(file_content)
    yaml_data = extract_yaml_data_using_match(file_content, match)
    add_meta_info_from_yaml_to_post(yaml_data, post, a_file)
    post.content = file_content[match.end():].strip()
    return post
Esempio n. 8
0
def make_post(content, wp):
    start = datetime.datetime.utcnow()
    end = start + datetime.timedelta(7)
    dates = (start.strftime('%b %d'), end.strftime('%b %d'))
    post = WordPressPost()
    post.title = "This week's schedule (%s - %s)" % dates
    post.content = content
    post.post_status = 'draft'
    wp.call(NewPost(post))
Esempio n. 9
0
 def build(self, title, content, categories=[], tags=[]):
     post = WordPressPost()
     post.title = title
     post.content = content
     post.terms_names = {
         'post_tag': tags,
         'category': categories,
     }
     post.post_status = 'publish'
     return NewPost(post)
Esempio n. 10
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))
Esempio n. 11
0
def post_file(wp, f, t, y, m, d):
  p = WordPressPost()
  p.title = t
  p.content = slurp(f)
  # 9am zulu is early Eastern-Pacific
  p.date = p.date_modified = datetime(y,m,d,9)
  p.post_status = 'publish'
  p.comment_status = 'closed'
  if wp:
    wp.call(NewPost(p))
Esempio n. 12
0
    def toWordPressPost(self):
        post = WordPressPost()

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

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

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

        return post
Esempio n. 14
0
    def postDraft(self, title, body):
        '''
        Creates a draft with title and graph
        
        Currently both title and graph are just strings
        '''
        post = WordPressPost()
        post.title = title
        post.content = body
#        post,terms_names = {
#            'post_tag': ['test'],
#            'category': ['testCat']}
        self.wp.call(NewPost(post))
Esempio n. 15
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
Esempio n. 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
Esempio n. 17
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
Esempio n. 18
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))
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 !")
Esempio n. 20
0
def _make_post(client, title, content):
    """
    Make a post on the wordpress site for this content item.
    """
    print 'MAKING POST FOR:', title
    post = WordPressPost()
    post.title = title
    post.content = content
    post.terms_names = {
      'post_tag': ['test', 'firstpost'],
      'category': ['Introductions', 'Tests']
    }
    post.publish = True
    client.call(NewPost(post))
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!")
Esempio n. 22
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
Esempio n. 23
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({'key': 'custom_source_url', 'value': url})
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Esempio n. 24
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)
Esempio n. 25
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!"
Esempio n. 26
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))
def main():
    blog_settings = yaml.load(Path('./blog.yml').read_text())
    wp = Client(blog_settings['xmlrpc-url'], blog_settings['username'],
                blog_settings['password'])
    articles = wp.call(GetPosts())

    [article.title for article in articles]

    post = WordPressPost()
    post.title = 'My new title'
    post.content = 'This is the body of my new post.'
    wp.call(NewPost(post))

    post.post_status = 'publish'
    wp.call(EditPost(post.id, post))
Esempio n. 28
0
def wp_post(post_title,post_content,post_tag):
    wp = Client(wprpcurl, username, password)
    print wp.call(GetPosts())
    print wp.call(GetUserInfo())
    post = WordPressPost()
    post.title = post_title
    post.content = post_content
    dict1 = {}
    for x in post_tag:
        dict1.setdefault('post_tag',[]).append(str(x))
    dict1.setdefault('category',[]).append('vps')
    post.terms_names = dict1
    post.post_status = 'publish'
    wp.call(NewPost(post))
    print wp.call(GetPosts())
Esempio n. 29
0
 def updateBlog(self, begin, end, comic_path):
     # 必须添加header=None,否则默认把第一行数据处理成列名导致缺失
     data = pd.read_csv(self.comic_path, encoding='gbk', header=None)
     csv_reader_lines = data.values.tolist()
     print(csv_reader_lines[0])
     for index in range(begin, end):
         post = WordPressPost()
         blog = csv_reader_lines[index]
         post.title = blog[1]
         post.custom_fields = {'cao_downurl': blog[5]}  # 自定义字段列表
         print(blog[1])
         print(blog[5])
         print(int(blog[0]))
         # post.post_status = 'publish'
         self.wp.call(posts.EditPost(int(blog[0]), post))
Esempio n. 30
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))
Esempio n. 31
0
def sourcename(url, cat1=None, cat2=None, cat3=None, d=True):
    html = getPage(url, "page1.html")
    os.remove('pages/page1.html')
    title = html.select('h1')[0].text
    first_para = html.select('.story-content > p:nth-of-type(1)')[0].text
    second_para = html.select('.story-content > p:nth-of-type(2)')[0].text
    try:
        image = html.select('.image > img')[0].get('src')
    except Exception:
        image = None
    wp = Client('http://www.domain.com/xml-rpc.php', 'username', 'password')
    if image:
        filename = 'http://www.livemint.com' + image
        path = os.getcwd() + "\\00000001.jpg"
        f = open(path, 'wb')
        f.write(urllib.urlopen(filename).read())
        f.close()
        # prepare metadata
        data = {
            'name': 'picture.jpeg',
            'type': 'image/jpeg',  # mimetype
        }

        with open(path, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
    post = WordPressPost()
    post.title = title
    post.user = 14
    post.post_type = "post"
    post.content = first_para + '\n' + '\n' + second_para
    if d:
        post.post_status = "draft"
    else:
        post.post_status = "publish"
    if image:
        attachment_id = response['id']
        post.thumbnail = attachment_id
    post.custom_fields = []
    post.custom_fields.append({
        'key': 'custom_source_url',
        'value': url
    })
    if cat1:
        cat1 = wp.call(taxonomies.GetTerm('category', cat1))
        post.terms.append(cat1)
    if cat2:
        cat2 = wp.call(taxonomies.GetTerm('category', cat2))
        post.terms.append(cat2)
    if cat3:
        cat3 = wp.call(taxonomies.GetTerm('category', cat3))
        post.terms.append(cat3)
    addpost = wp.call(posts.NewPost(post))
Esempio n. 32
0
def posting():

    wp = Client('<YOURWORDPRESSSIT>/xmlrpc.php','YOURUSERNAME','YOURPASSWORD')
    #publish_date = (publish, '%a %b %d %H:%M:%S %Y %z')

    post = WordPressPost()
    post.title = title #Commit Title
    post.content = description #Commit message
    post.post_status = 'publish'
    post.terms_names = {
        'category': ['12SDD']
        }
    #post.date = publish_date

    #Creates a new wordpress post and posts it on the site.
    wp.call(NewPost(post))
Esempio n. 33
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))
Esempio n. 34
0
def _create_wp_post(song, content):
    # Create the NewPost object - see docs at
    # http://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/wordpress.html
    # We're missing some fields but ehhhh who knows if they even exist anymore
    post = WordPressPost()
    post.title = str(song)
    post.content = content
    post.comment_status = 'open'
    post.ping_status = 'closed'
    post.post_status = 'publish'
    post.post_type = 'post'
    post.excerpt = song.tagline
    post.date = datetime.now(tz=timezone.utc)
    post.date_modified = datetime.now(tz=timezone.utc)

    return NewPost(post)
Esempio n. 35
0
    def _take_action(self, parsed_args):
        with open(parsed_args.filename, 'r',
                  encoding=parsed_args.encoding) as f:
            raw_body = f.read()
        formatted_body = markdown.markdown(raw_body)

        if parsed_args.dry_run:
            print('New %s post "%s":\n' %
                  (parsed_args.status, parsed_args.title))
            print(formatted_body)
        else:
            post = WordPressPost()
            post.title = parsed_args.title
            post.content = formatted_body
            post.post_status = parsed_args.status
            self.wp.call(NewPost(post))
Esempio n. 36
0
def blog_content(title,content,tage,category):
  passwd=""
  wp = Client('http://123.206.66.55/xmlrpc.php', 'admin', passwd)
  """
  发表博文
  """
  post = WordPressPost()
  post.title = title
  post.content = content
  post.post_status = 'publish'
  print tage
  post.terms_names = {
    'post_tag': tage,
    'category': category
  }
  wp.call(NewPost(post))
Esempio n. 37
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
Esempio n. 38
0
 def process_item(self, item, spider):
     wp = Client('https://www.along.party/xmlrpc.php', '', '')
     post = WordPressPost()
     post.title = item['title']
     post.user = item['author']
     post.link = item['url']
     # post.date = item['publish_time']
     post.content = item['body']
     post.content = u"%s \n 本文转载自 <a href='%s'> %s</a> " % (
         item['body'], item['url'], item['title'])
     post.post_status = 'publish'
     post.terms_names = {'post_tag': 'Python', 'category': 'Python'}
     wp.call(NewPost(post))
Esempio n. 39
0
def sends(data):
    # print targeturl
    #u=content1[i][0]

    #链接WordPress,输入xmlrpc链接,后台账号密码
    wp = Client('http://www.stock-t.com/wordpress/xmlrpc.php', 'jiehunt',
                'yxpbl1982')
    post = WordPressPost()
    post.title = 'MyStockRecommend'
    # post.post_type='test'
    post.content = data
    post.post_status = 'publish'
    #发送到WordPress
    #print 'here3'
    wp.call(NewPost(post))
    time.sleep(3)
    print('posts updates')
Esempio n. 40
0
 def edit_posts(self, post_id, title, feature_img, staff, content, img_list,
                tag_list, categrory):
     post = WordPressPost()
     post.title = title
     if staff:
         content = staff + '<br>' + content
     post.content = content
     post.categrory = []
     post.categrory.append(categrory)
     if tag_list:
         post.terms_names = {
             'post_tag': tag_list,
             'category': post.categrory
         }
     else:
         post.terms_names = {'post_tag': '', 'category': post.categrory}
     #img_list设置为空,避免图片重复上传
     img_list = []
     if img_list:
         img_name = img_list[-1].split('/')[-1]
         filename = img_list[-1].replace('http://', '/www/wwwroot/')
         data = {'name': img_name, 'type': 'image/jpeg'}
         try:
             with open(filename, 'rb') as img:
                 data['bits'] = xmlrpc_client.Binary(img.read())
             response = self.wp.call(media.UploadFile(data))
             attachment_id = response['id']
             post.thumbnail = attachment_id
         except:
             print('最后一张图片不存在:', img_list[-1])
     #    for i in range(len(img_list)):
     #        img_name=img_list[i].split('/')[-1]
     #        filename = './'+img_name
     #上传的图片本地文件路径
     # prepare metadata
     #        data = {'name': 'picture.jpg','type': 'image/jpeg',}
     #        data['name']=img_name
     # read the binary file and let the XMLRPC library encode it into base64
     #        with open(filename,'rb') as img:
     #            data['bits'] = xmlrpc_client.Binary(img.read())
     #        response=self.wp.call(media.UploadFile(data))
     #        if i ==len(img_list)-1:
     #            attachment_id = response['id']
     #            post.thumbnail=attachment_id
     post.post_status = 'publish'
     self.wp.call(EditPost(post_id, post))
     print('正在修正[ID]:%s,[标题]:%s' % (post_id, post.title))
     if os.path.isfile(self.wp_log):
         with open(self.wp_log, 'a+') as f:
             f.writelines(str(post_id) + '\n')
     return post_id, len(post.content)
Esempio n. 41
0
 def buildPost(self, item):
     post = WordPressPost()
     post.title = self.spin.spin(item['title'])
     post.content = self.spin.spin(item['content'])
     post.excerpt = self.spin.spin(item['excerpt'])
     terms = []
     for x in item['tag'].split(','):
         x = x.strip()
         if len(x) != 0:
             terms.append(x)
     if len(terms) == 0:
         terms.append(item['category'])
     post.terms_names = {
         'post_tag': terms,
         'category': item['category'],
     }
     return post
Esempio n. 42
0
    def push_posts(self, title, content, categrory, tag, img_list):
        post = WordPressPost()
        post.title = title
        post.content = content
        post.categrory = []
        post.categrory.append(categrory)

        if tag:
            post.tag = []
            post.tag.append(tag)
            post.terms_names = {
                'post_tag': post.tag,
                'category': post.categrory
            }
        else:
            post.terms_names = {'post_tag': '', 'category': post.categrory}
        post.post_status = 'publish'
        if img_list:
            for i in range(len(img_list)):
                img_name = img_list[i].split('/')[-1]
                filename = './' + img_name
                #上传的图片本地文件路径
                # prepare metadata
                data = {
                    'name': 'picture.jpg',
                    'type': 'image/jpeg',
                }
                data['name'] = img_name
                # read the binary file and let the XMLRPC library encode it into base64
                with open(filename, 'rb') as img:
                    data['bits'] = xmlrpc_client.Binary(img.read())
                response = self.wp.call(media.UploadFile(data))
                if i == len(img_list) - 1:
                    attachment_id = response['id']
                    post.thumbnail = attachment_id
            '''
            response == {
              'id': 6,
              'file': 'picture.jpg'
              'url': 'http://www.example.com/wp-content/uploads/2012/04/16/picture.jpg',
              'type': 'image/jpeg',
            }
            '''
        postid = self.wp.call(NewPost(post))
        print('正在发布[ID]:%s,[标题]:%s' % (postid, post.title))
        return postid, len(post.content)
Esempio n. 43
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
Esempio n. 44
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))
Esempio n. 45
0
def post_file(wp, f, t, y, m, d):
    p = WordPressPost()
    p.title = t
    p.content = slurp(f)
    # All 3 sites are configured to UTC
    if re.search('deutsche', f):
        p.date = datetime(y, m, d, 4)  #  4am UTC is 5am in UTC+1=Berlin
    else:
        p.date = datetime(y, m, d, 10)  # 10am UTC is 5am eastern, 2am pacific
    p.date_modified = p.date
    p.post_status = 'publish'
    p.comment_status = 'closed'
    if wp:
        wp.call(NewPost(p))
Esempio n. 46
0
def requests_digest():

    c = conn.cursor()
    
    c.execute('select id, name, obit_headline, obit_url, requested_at from requests where request_blogged_at is null')
    unblogged = c.fetchall()

    post = WordPressPost()
    today = datetime.strftime(datetime.today(),'%B %-d, %Y')
    post.title = 'New requests for FBI files, ' + today    

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

    post.content = """We've recently requested the FBI files of the following individuals:

    <ul>"""
    

    for entry in unblogged:        
        name = entry[1]
        obit_headline = entry[2]
        obit_url = entry[3]
        
        post.content += "\n<li>{name} (<a href=\"{obit_url}\">New York Times obit</a>)</li>".format(**locals())
        post.terms_names['post_tag'].append(name.lower())

    post.post_status = 'publish'
    
    post_id = wp.call(NewPost(post))
    
    post_url = wp.call(GetPost(post_id)).link.replace('http','https')
    post_date = str(wp.call(GetPost(post_id)).date)
    post_title = wp.call(GetPost(post_id)).title

    for entry in unblogged:
        entry_id = entry[0]
        c.execute('update requests set request_blogged_at = ?, request_blog_url = ? where id = ?',(post_date,post_url,entry_id))

    conn.commit()
    conn.close()

    ftd_tweets.tweet_digest_post(post_title,post_url)
Esempio n. 47
0
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()
    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
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')
Esempio n. 50
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))
Esempio n. 51
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 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
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('-----------------------------------------------------------------------------------')
Esempio n. 54
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
Esempio n. 55
0
def insertPostFromDB():
    conn = sqlite3.connect('qtfy.db')
    c = conn.cursor()
    idx = 0
    db = qtfy_db('qtfy.db')
    for row in c.execute("select mid, name, url, desc, info, img from movie"):
        if idx>2:
            break
        post = WordPressPost()
        print row[0]
        post.title =  row[1]
        lk = db.get_movielnks(row[0])
        post.content = gen_webpage(row[3], row[4], row[5], lk) # row[3] + row[4]
        post.terms_names={'post_tag':['liu', 'jing']}
        post.post_status = "publish"
        idx += 1
        print wp.call(NewPost(post))
        
    conn.commit()
    conn.close()
Esempio n. 56
0
def push():

    recent = readjson(os.path.join(archivedir, taskarchivejson_name))
    if recent is not None:

        content = u'<dl>\n'
        wp = Client(WPxmlrpc, WPuser, WPpass)

        recent = sorted(recent, key=lambda r: r['timestamp'])
        for element in recent:
            if element['data']['image'] is not None:
                filename = os.path.join(archivedir, element['data']['image'])
                data = {
                    'name': element['data']['image'],
                    'type': guess_type(filename)[0]
                }

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

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

                content += pskel.format(user=element['data']['user'], image=iskel.format(imageurl=response['url'], imagealt=element['data']['description']), description=element['data']['description'])
            else:
                content += pskel.format(user=element['data']['user'], image='', description=element['data']['description'])

        content += u'</dl>\n'

        post = WordPressPost()
        post.title = '%s %s' %(report_headline, week_timestamp())
        post.content = content
        post.terms_names = {
            'post_tag': post_tag,
            'category': category,
        }

        wp.call(NewPost(post))


    else:
        logger.info('nothing to push')
def post(wp, old_post, title, content, rtcprof, img_info):
    from wordpress_xmlrpc import WordPressPost
    from wordpress_xmlrpc.methods.posts import NewPost, EditPost
    if old_post:
        post = old_post
    else:
        post = WordPressPost()

    post.title = title
    post.content = content
    post.terms_names = {
        'post_tag': [rtcprof.name, 'RTC'],
        'category': ['RTComponents', rtcprof.basicInfo.category]
        }

    post.slug = rtcprof.name
    n = datetime.datetime.now()
    year = n.year
    month = n.month
    day = n.day
    hour = n.hour
    if n.hour < 9:
        day = day - 1
        hour = hour + 24
        if day == 0:
            month = month - 1
            if month == 0:
                month = 12
                year = year -1
            if month in [4, 6, 9, 11]:
                day = 30
            elif month == 2:
                day = 28
            else:
                day = 31
    hour = hour - 9
    post.date = datetime.datetime(year, month, day, hour, n.minute, n.second)
    post.post_status = 'publish'
    if img_info:
        post.thumbnail = img_info['id']
    else:
        post.thumbnail = old_post.thumbnail
    if old_post: # Edit Mode
        wp.call(EditPost(post.id, post))
    else:
        wp.call(NewPost(post))
Esempio n. 58
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))
Esempio n. 59
0
def entry_to_wppost(entry, client):
    post             = WordPressPost()
    # Convert entry values to Post value
    post.user        = get_author_by_display_name(entry.author, client)
    post.date        = entry.published_parsed
    post.post_status = "draft"
    post.title       = entry.title
    post.content     = entry.content[0].value
    post.excerpt     = entry.summary
    post.link        = entry.link
    # There is some given tags
    if len(entry.tags):
        entry.tags = [t.term for t in entry.tags]
        # Add category (with the first tag)
        post.terms_names = {
            'category': entry.tags[0:1],
            'post_tag': [],
        }
        # Add tags
        if len(entry.tags) > 1: post.terms_names['post_tag'] = entry.tags[1:]
    return post