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!")
コード例 #2
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
コード例 #3
0
def imageUpload(img_url, file_name=None, i=None):
    cleanImgUrl = img_url.split('?')[0]
    imageName = img_url.split('/')[-1]
    cleanImgName = imageName.split('?')[0]
    fileImg = urllib.request.urlretrieve(cleanImgUrl, cleanImgName)
    imageType = fileImg[1]['Content-Type']
    if file_name:
        fname = file_name.split('-')
        fname.pop()
        fname = '-'.join(fname)
        if i: fname += '_%s' % i
        data = {
            'name': fname + '.' + imageType.split('/')[-1],
            'type': imageType
        }
    else:
        data = {
            'name': cleanImgName + '.' + imageType.split('/')[-1],
            'type': imageType
        }
    with open(cleanImgName, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    print(data)
    response = client.call(media.UploadFile(data))
    return response
コード例 #4
0
ファイル: online.py プロジェクト: Anko59/Act-Care
def uploadImageFromUrl(url, name):
    fileName = name + url.split('.')[-1]
    urllib.urlretrieve(url, fileName)
    data = {'name': fileName, 'type': 'image/' + url.split('.')[-1]}
    with open(fileName, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = client.call(media.UploadFile(data))
コード例 #5
0
ファイル: mks.py プロジェクト: fccn/nau-wp-sync
    def _upload_image_thumbnail(self, image_url):
        log.info(
            "Uploading new page image thumbnail. {url}".format(url=image_url))
        attachment_id = None

        image_response = requests.get(image_url)
        image_response_len = len(image_response.content)
        if image_response_len == 0:
            log.warning("No image downloaded from {url}".format(url=image_url))
        else:
            image_content = image_response.content
            mimetypes.init()
            imageMimetype = mimetypes.guess_type(image_url)[0]
            imageName = image_url[image_url.rindex('/') + 1:]
            bits = xmlrpc.client.Binary(image_content)

            try:
                uploadImageResponse = self.getClient().call(
                    media.UploadFile({
                        'name': imageName,
                        'type': imageMimetype,
                        'bits': bits,
                        'overwrite': True
                    }))
                attachment_id = uploadImageResponse['id']
                log.debug(
                    "Added course image thumbnail with id={image_id}".format(
                        image_id=attachment_id))
            except:
                log.error(
                    "Error uploading course image with URL: {url}".format(
                        url=image_url))

        return attachment_id
コード例 #6
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
コード例 #7
0
def upload_file_to_wp(client, filepath):
    # prepare metadata
    name = os.path.basename(filepath)
    img_type = imghdr.what(filepath)
    if img_type is None:
        img_type = 'jpeg'
    data = {
        'name': name,
        'type': 'image/%s' % img_type,  # mimetype
    }

    # read the binary file and let the XMLRPC library encode it into base64
    with open(filepath, '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',
    # }
    if response and response.has_key('id'):
        attachment_id = response['id']
        return attachment_id
    else:
        return None
コード例 #8
0
    def upload_pic(self, img_url):
        try:
            img_data = requests.get(img_url).content
            img_name = './uploads/' + str(uuid.uuid4()) + '.jpg'
            with open(img_name, 'wb') as handler:
                handler.write(img_data)

            filename = img_name

            # prepare metadata
            data = {
                'name': img_name,
                '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 = self.client.call(media.UploadFile(data))
            attachment_id = response['id']
        except Exception as e:
            print('Some errors trying to save the image from remote host: ' +
                  str(img_url))
            attachment_id = ""

        return attachment_id
コード例 #9
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()
コード例 #10
0
    def load_file(self):
        fname = askopenfilename(filetypes=(("PNG Image", "*.png"),
                                           ("JPG Image", "*.jpg;*.jpeg"),
                                           ("GIF Image", "*.gif"),
                                           ("Bitmap Image",
                                            "*.bmp"), ("All Files", "*")))
        print(mimetypes.guess_type(fname)[0])
        try:
            wp = Client('https://your.wordpress.installation/xmlrpc.php',
                        'Username', 'password')
        except TimeoutError:
            self.status.delete(0, END)
            self.status.insert(0, 'Unable to connect to WP')
        except gaierror:
            self.status.config(state=NORMAL)
            self.status.delete(1.0, END)
            self.status.insert(1.0, 'DNS lookup failed')
            self.status.config(state=DISABLED)
            raise

        print(MyFrame.path_leaf(fname))
        data = {
            'name': MyFrame.path_leaf(fname),
            'type': mimetypes.guess_type(fname)[0]
        }
        with open(fname, 'rb') as img:
            data['bits'] = xmlrpc_client.Binary(img.read())
        response = wp.call(media.UploadFile(data))
        print(response['url'])
        self.status.config(state=NORMAL)
        self.status.delete(1.0, END)
        self.status.insert(1.0, 'Link: ' + response['url'])
        self.status.config(state=DISABLED)
コード例 #11
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 !")
コード例 #12
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))
コード例 #13
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))
コード例 #14
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))
コード例 #15
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))
コード例 #16
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('-----------------------------------------------------------------------------------')
コード例 #17
0
 def upload_picture(self, filepath, name=None, mimetype=None):
     if name is None:
         name = filepath.split('/')[-1]
     if mimetype is None:
         _ = name.split('.')[-1]
         mimetype = 'image/{}'.format(_)
     filename = filepath
     if filepath.startswith('http'):
         headers = {
             'Referer':
             'http://www.mm131.com/',
             'User-Agent':
             'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
         }
         r = requests.get(filepath, headers=headers)
         img_cont = r.content
         filename = base64.b64encode(filepath) + '.' + filepath.split(
             '/')[-1].split('.')[-1]
         with open(filename, 'wb') as f:
             f.write(img_cont)
     data = {
         'name': name,
         'type': mimetype,  # mimetype
     }
     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']
     except Exception as e:
         attachment_id = None
     os.remove(filename)
     return attachment_id
コード例 #18
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))
コード例 #19
0
ファイル: runner.py プロジェクト: razor-dev/Adult-Bot
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
コード例 #20
0
 def readfromclipboard(self):
     temporarybuffer = io.BytesIO()
     ImageGrab.grabclipboard().save(temporarybuffer, format='png')
     ##        temporarybuffer.seek(0,2)
     ##        print(temporarybuffer.tell())
     try:
         wp = Client('https://your.wordpress.installation/xmlrpc.php',
                     'Username', 'password')
     except TimeoutError:
         self.status.delete(0, END)
         self.status.insert(0, 'Unable to connect to WP')
     except gaierror:
         self.status.config(state=NORMAL)
         self.status.delete(1.0, END)
         self.status.insert(1.0, 'DNS lookup failed')
         self.status.config(state=DISABLED)
         raise
     data = {
         'name':
         ''.join(
             random.choice(
                 '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
             ) for i in range(16)) + '.png',
         'type':
         'image/png'
     }
     data['bits'] = xmlrpc_client.Binary(temporarybuffer.getvalue())
     response = wp.call(media.UploadFile(data))
     print(response['url'])
     self.status.config(state=NORMAL)
     self.status.delete(1.0, END)
     self.status.insert(1.0, 'Link: ' + response['url'])
     self.status.config(state=DISABLED)
コード例 #21
0
def upload_audio_to_wordpress(config, audio_path):
    """uploads the audio to wordpress using the credentials stored in config"""
    import mimetypes
    from wordpress_xmlrpc import Client
    from wordpress_xmlrpc.compat import xmlrpc_client
    from wordpress_xmlrpc.methods import media

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

    audio_name = audio_path.split("/")[-1]

    audio_mime_type = mimetypes.guess_type(audio_path)
    # prepare metadata
    data = {
        'name': audio_name,
        'type': audio_mime_type,
    }

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

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

    return response['url']
コード例 #22
0
    def UploadFile(self):
        url = self.targetUrl + '/xmlrpc.php'
        client = Client(url, self.atLeastAuthorAccount['log'],
                        self.atLeastAuthorAccount['pwd'])
        # set to the path to your file
        filepath = self.fileToUpload['filepath']

        # prepare metadata
        data = {
            'name': self.fileToUpload['filename'],
            'type': 'image/jpeg',  # mimetype
        }

        # read the binary file and let the XMLRPC library encode it into base64
        with open(filepath, '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/jpeg',
        # }
        print("Uplaod ảnh nhiễm độc thành công!")
        return response
コード例 #23
0
def make_post(content, categorys='0', tags='0', date=None):
    '''
    :param content: dict() formatado corretamente
    :param categorys: lista com as categorias do post
    :param tags: lista com as tags do post
    :param date: data para o post ser publicado ( formato datetime.datetime())
    :return:
    '''
    #URL DO SITE, USUARIO , SENHA !!!
    wp = Client(authData['url'] + '/xmlrpc.php', authData['adminUsername'],
                authData['adminPassword'])
    post = WordPressPost()
    post.title = content['title']
    post.content = content['body']

    if tags[0] != '0':

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

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

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

    #deletando do pc a imagem
    remove(filename)

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

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

    # We Are Done With This Part :) Lets Try To Run It
    if not date:
        print(post.title, " Postado com sucesso !")
    if date:
        print(post.title, " Vai ser postado em ", date, '!')
コード例 #24
0
ファイル: uploadimage.py プロジェクト: superlyb/adbnews
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!"
コード例 #25
0
def upload_image(image_name, client):
    data = {'name': image_name, 'type': 'image/jpeg'}
    with open('images/' + image_name, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    response = client.call(media.UploadFile(data))
    #print('上传了--->'+image_name)
    attachment_id = response['id']
    return attachment_id
コード例 #26
0
 def upload(self, file_name):
     data = {
         'name': file_name,
         'type': mimetypes.guess_type(file_name)[0],
         'bits': xmlrpc_client.Binary(open(file_name, 'rb').read())
     }
     result = self._client.call(media.UploadFile(data))
     return result['url']
コード例 #27
0
ファイル: md2wp.py プロジェクト: whnarthur/markdown2wordpress
def uploadFile(client, filename):
    data = {}
    data['type'] = mimetypes.guess_type(filename)[0]
    data['name'] = filename
    with open(filename, 'rb') as img:
        data['bits'] = xmlrpc_client.Binary(img.read())
    resp = client.call(media.UploadFile(data))
    return resp
コード例 #28
0
def get_urls(url):
    
    try:
        user_agent = {'User-agent': 'Mozilla/5.0'}
        r = requests.get(url,headers = user_agent)
        data = r.text
        soup = BeautifulSoup(data)
        div = soup.find('div', class_="panel-content")
        links = div.findAll('a')
        for a in links:
            try:
                if 'deccanchronicle.com' in a['href']:
                    r = requests.get(a['href'],headers = user_agent)
                    data = r.text
                    soup = BeautifulSoup(data)
                    title = soup.find('h1', class_="title")
                    imgurl = soup.find('div',class_="field-item even")
                    orgimgurl = imgurl['resource']
                    data = data[data.index('<div class="field field-name-field-image'):]
                    data = data[:data.index('<div class="field field-name-field-tags')]
                    soup = BeautifulSoup(data)
                    texts = soup.find_all('p')
                    content = ""
                    for text in texts:
                        content = content+"<p>"+text.getText()
                    wai = WordAi('*****@*****.**','passhere')
                    print(content)
                    print(wai.unique_variation(content))
                    input("Press Enter to continue...")
                    content = content + "<p>" + "Credits : deccanchronicle.com"
                    post = WordPressPost()
                    post.title = title.get_text() #Setting Post Title
                    urllib.request.urlretrieve(orgimgurl, os.path.basename(orgimgurl))
                    filename = os.path.basename(orgimgurl)
                    data = {
                        'name': os.path.basename(orgimgurl),
                        'type': mimetypes.guess_type(filename)[0],  # mimetype
                        }
                    with open(filename, 'rb') as img:
                        data['bits'] = xmlrpc_client.Binary(img.read())
                    response = wp.call(media.UploadFile(data))
                    attachment_id = response['id']
                    post.thumbnail = attachment_id #Setting Feautured Image
                    post.content = content #Setting Content Up
                    post.terms_names = {
                        'post_tag': ['tech', 'techonology'], #Change Tags here
                        'category': ['Techie Stuff'] #Change Category Here
                        }
                    post.post_status = 'publish'
                    wp.call(NewPost(post))
                    #print ("Post Id is %s" %(wp.call(NewPost(post))))
                    print("%s is Posted!" %(title.get_text()))
                    #input("Press Enter to continue...")
            except:
                print('Some Error On This Post %s ' %(title.get_text()))
                raise
    except:
        raise
コード例 #29
0
 def post_article(self, articleTitle, articleCategories, articleContent,
                  articleTags, imageUrl, tempDir, imageName, dirDelimiter,
                  postStatus):
     # ---	Get image extension
     imgExt = imageUrl.split('.')[-1].lower()
     # --------------------------------------------------------------
     self.imgPath = tempDir + dirDelimiter + imageName + "." + imgExt
     self.articleImageUrl = imageUrl
     # ---	Download image file
     f = open(self.imgPath, 'wb')
     try:
         f.write(urllib.request.urlopen(self.articleImageUrl).read())
     except:
         print("Error downloading image")
         return -1
     f.close()
     # --------------------------------------------------------------
     # ---	Upload image to WordPress
     filename = self.imgPath
     # prepare metadata
     data = {
         'name': imageName + '.' + imgExt,
         'type': 'image/' + imgExt,
     }
     # read the binary file and let the XMLRPC library encode it into base64
     try:
         with open(filename, 'rb') as img:
             data['bits'] = xmlrpc_client.Binary(img.read())
     except:
         print("Error while reading downloaded image file")
         return -2
     try:
         response = self.wpClient.call(media.UploadFile(data))
     except:
         print("Error while uploading image file")
         return -3
     attachment_id = response['id']
     # --------------------------------------------------------------
     # ---	Post article
     post = WordPressPost()
     post.title = articleTitle
     post.content = articleContent
     post.terms_names = {
         'post_tag': articleTags,
         'category': articleCategories
     }
     # More about post statuses: https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.posts.GetPostStatusList
     post.post_status = postStatus
     post.thumbnail = attachment_id
     try:
         post.id = self.wpClient.call(posts.NewPost(post))
     except:
         print("Error while posting article")
         return -4
     print('Post Successfully posted. Its Id is: ', post.id)
     # --------------------------------------------------------------
     return post.id
コード例 #30
0
def send_img (imageName): 
    with open(imageName, "rb") as img:
        data = {
            'name': os.path.basename(imageName),
            'bits': xmlrpc_client.Binary(img.read()),
            'type': mimetypes.guess_type(imageName)[0],
        }
        # получаем id загруженной картинки чтобы привязать к посту
        response = wp.call(media.UploadFile(data))
        return response['id']