Ejemplo n.º 1
0
import argparse
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.exceptions import InvalidCredentialsError
import time

parser = argparse.ArgumentParser()
parser.add_argument("userlist",
                    help="A text file containing a list of usernames")
parser.add_argument("passlist",
                    help="A text file containing a list of passwords")
parser.add_argument("url", help="URL pointing to xmlrpc.php")
args = parser.parse_args()

users = [line.rstrip('\n') for line in open(args.userlist)]
passwords = [line.rstrip('\n') for line in open(args.passlist)]

for user in users:
    for password in passwords:
        time.sleep(0.5)
        wp = Client(args.url, user, password)
        try:
            wp.call(GetPosts())
            print("Success? u: " + user + " p: " + password)
        except InvalidCredentialsError:
            print("Fail? u: " + user + " p: " + password)
Ejemplo n.º 2
0
items = mydoc.getElementsByTagName('loc')

for i in range(len(items)):
    items[i] = items[i].firstChild.data
"""post_titles = list()
post_contents = list()

for post in all_posts:
    title = cleanhtml(post.title)
    content = cleanhtml(post.content)
    post_titles.append(title)
    post_contents.append(content)"""

client = Client("https://www.evcilhayvanbakimi.com/xmlrpc.php", 'NorkQ',
                'emsile2158')
all_posts = client.call(GetPosts())
tags = client.call(taxonomies.GetTerms('post_tag'))

for i in range(len(tags)):
    tags[i] = tags[i].name

tags = tags
titles = items
titles.pop(0)

print(tags)
print(titles)


class Post():
    def __init__(self, title, descr, image, category, addres):
from wordpress_xmlrpc import WordPressPost

#You dont need these commented out lines if you use wordpress_xmlrpc
# blogs_list=pd.read_csv("blog_links.csv", header=None)
# blogs_list.rename(columns={0: 'Links'}, inplace=True)

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, GetPost
from wordpress_xmlrpc.methods.users import GetUserInfo

client = Client("https://trustmeyourealive.com/xmlrpc.php", 'username',
                'password')
all_posts = client.call(
    GetPosts({
        'number': 50,
        'post_status': 'publish'
    },
             results_class=WordPressPost))

# print all_posts[0]

titles = []  #all_posts[0] etc
content = []  #one_post.content etc
post_id = 0
for i, post in enumerate(all_posts):
    post_id = all_posts[i].id
    one_post = client.call(GetPost(post_id))
    one_post.content = re.sub(r'<[^<]+?>', '', one_post.content)
    one_post.content = re.sub(r"\[.*?\]", '', one_post.content)

    titles.append(all_posts[i])
Ejemplo n.º 4
0
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost
from wordpress_xmlrpc.methods.users import GetUserInfo

url = 'http://www.py4seo.com/xmlrpc.php'
login = '******'
passw = '1234567'

client = Client(url, login, passw)

posts = client.call(GetPosts({'number': 10000}))

post = WordPressPost()

post.title = 'My post'
post.content = 'This is a wonderful blog post about XML-RPC.'

post.id = client.call(NewPost(post))

# whoops, I forgot to publish it!
post.post_status = 'publish'

client.call(EditPost(post.id, post))
Ejemplo n.º 5
0
 def check_post(self,num):
     posts=self.wp.call(GetPosts({'number':num}))
     for i in posts:
         print(i.id,'-',i.title,'-',i.post_status)
Ejemplo n.º 6
0
def main():
    args = sys.argv[1:]
    if len(args) != 2:
        print(
            'Usage: ./ssp_se_load_roster.py <Wordpress xmlrpc url> <csvfile>')
        sys.exit(1)

    xmlrpc = args[0]
    csvfile_name = args[1]

    if not os.path.isfile(csvfile_name):
        print('I can\'t find the file: ' + csvfile_name)
        sys.exit(1)

    username = raw_input('Enter your WordPress user name: ')
    password = getpass()

    wp = Client(xmlrpc, username, password)

    listofseriesterms = wp.call(GetTerms('series'))

    print('To which series are you going to add all these posts? (id, name)')
    series = {}
    for seriesterm in listofseriesterms:
        print(seriesterm.id + ', ' + seriesterm.name)
        series[seriesterm.id] = seriesterm.name
    main_series_termid = raw_input('Please enter the id: ')

    if not main_series_termid in series:
        print('That series id does not exist')
        sys.exit(1)
    else:
        print(series[main_series_termid] + ' series selected.')

    child_series = {}
    for seriesterm in listofseriesterms:
        if seriesterm.parent == main_series_termid:
            child_series[seriesterm.name.lower()] = seriesterm.id

    print('child_series')
    print(child_series)

    existing_posts = wp.call(GetPosts({
        'post_type': 'podcast',
        'number': 9999
    }))
    existing_series_posts = {}
    child_series_existing_episode_numbers = {}
    for post in existing_posts:
        post_terms = []
        for term in post.terms:
            if term.id in child_series.values(
            ) or term.id == main_series_termid:
                post_terms.append(term.id)
        if post_terms:
            for customfield in post.custom_fields:
                if customfield['key'] == 'date_recorded' and customfield[
                        'value']:
                    date_recorded_string = customfield['value']
                elif customfield['key'] == 'episode_number' and customfield[
                        'value']:
                    for post_term_id in post_terms:
                        if post_term_id in child_series_existing_episode_numbers:
                            child_series_existing_episode_numbers[
                                post_term_id].append(int(customfield['value']))
                        else:
                            child_series_existing_episode_numbers[
                                post_term_id] = [int(customfield['value'])]
            date_recorded = getdatetime(date_recorded_string)
            existing_series_posts[date_recorded] = (post.id, post_terms)

    #open and parse the csv
    replace_all = False
    replace_none = False

    fieldname_translation = {
        'date': 'date_recorded',
        'title': 'title',
        'series': 'series',
        'track': 'episode_number',
        'passage': 'bible_passage',
        'preacher': 'preacher',
        'comments': 'content',
        'time': 'time'
    }

    list_from_csv = {}
    with open(csvfile_name, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        for messyentry in reader:
            entry = {}
            for entrykey, entryval in messyentry.iteritems():
                entry[fieldname_translation[entrykey.lower()]] = entryval
            if not (('date_recorded' in entry) or ('preacher' in entry)):
                continue
            if entry['date_recorded'] == '' or entry['preacher'] == '':
                continue
            csvdate = getdatetime(entry['date_recorded'])
            if csvdate == None:
                continue
            entry['date_recorded'] = csvdate.strftime('%d-%m-%Y')
            try:
                int(entry['episode_number'])
            except (ValueError, KeyError):
                entry['episode_number'] = ''
            for fieldname in fieldname_translation.values():
                if not fieldname in entry:
                    entry[fieldname] = ''
            if not entry['series']:
                entry['series'] = 'one-off'
            if (csvdate in existing_series_posts):
                if not (replace_none or replace_all):
                    confirmation_raw_in = raw_input(
                        'There is already a podcast in this series with date '
                        + csvdate.strftime('%d %b %Y') +
                        ', replace it? \n(Y/N/All/None)\n').lower()
                elif replace_none:
                    continue
                if confirmation_raw_in == 'none':
                    replace_none = True
                if not confirmation_raw_in in ['y', 'all']:
                    continue
                if confirmation_raw_in == 'all':
                    replace_all = True
                if wp.call(DeletePost(existing_series_posts[csvdate][0])):
                    print('Deleted old post for ' +
                          csvdate.strftime('%d %b %Y') + '.')
            entry['bible_passage'] = cleanUpScripture(entry['bible_passage'])
            list_from_csv[csvdate] = entry

    template_settings = {
        'ep_title_template': 'title',
        'service_time': 'time',
        'comments_template': 'content'
    }

    #work out series and episode_numbers:
    for seriestermid in child_series_existing_episode_numbers:
        try:
            child_series_existing_episode_numbers[seriestermid] = sorted(
                child_series_existing_episode_numbers[seriestermid],
                reverse=True)[0]
        except IndexError as e:
            print(e)
            try:
                child_series_existing_episode_numbers[seriestermid] = int(
                    series[seriestermid].count)
            except:
                child_series_existing_episode_numbers[seriestermid] = 0

    prefix = 'ss_podcasting_data_'
    termidlist = ['0', main_series_termid]
    optionslist = []
    templates_per_series = {}
    for child_series_termid in child_series.values():
        termidlist.append(child_series_termid)
    for termid_item in termidlist:
        templates_per_series[termid_item] = {}
        if termid_item == '0':
            suffix = ''
        else:
            suffix = '_' + termid_item
        for eachsetting in template_settings:
            optionslist.append(prefix + eachsetting + suffix)
    list_of_WPOptions = wp.call(GetOptions(optionslist))
    for wp_Option in list_of_WPOptions:
        if wp_Option.name[len(prefix):] in template_settings:
            templates_per_series['0'][
                wp_Option.name[len(prefix):]] = wp_Option.value
        else:
            for termid_item in termidlist:
                suffix = '_' + termid_item
                if wp_Option.name[-len(suffix):] == suffix:
                    templates_per_series[termid_item][wp_Option.name[
                        len(prefix):-len(suffix)]] = wp_Option.value

    timezone = get_localzone()

    for entry, details in sorted(list_from_csv.iteritems()):
        if not details['series'].lower() in child_series:
            wpseries = WordPressTerm()
            wpseries.taxonomy = 'series'
            wpseries.name = details['series']
            wpseries.parent = main_series_termid
            wpseries.id = wp.call(NewTerm(wpseries))
            child_series[details['series']] = wpseries.id
            listofseriesterms.append(wpseries)
            series[wpseries.id] = wpseries.name
            child_series[wpseries.name.lower()] = wpseries.id
            if details['episode_number'] == '':
                details['episode_number'] = '1'
                child_series_existing_episode_numbers[wpseries.id] = 1
            else:
                child_series_existing_episode_numbers[wpseries.id] = int(
                    details['episode_number'])
            details['seriesid'] = wpseries.id
        else:
            try:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]]
            except KeyError:
                for seriesterm in listofseriesterms:
                    if seriesterm.id == child_series[
                            details['series'].lower()]:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = seriesterm.count
                    else:
                        child_series_existing_episode_numbers[child_series[
                            details['series'].lower()]] = 0
            if details['episode_number'] == '':
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] += 1
                details['episode_number'] = str(
                    child_series_existing_episode_numbers[child_series[
                        details['series'].lower()]])
            else:
                child_series_existing_episode_numbers[child_series[
                    details['series'].lower()]] = int(
                        details['episode_number'])
            details['seriesid'] = child_series[details['series'].lower()]
        for template_setting, detail in template_settings.iteritems():
            list = [details['seriesid'], main_series_termid, '0']
            while details[detail] == '':
                try:
                    details[detail] = templates_per_series[list.pop(
                        0)][template_setting]
                except KeyError:
                    continue
        publishtime = gettime(details['time'])
        if publishtime:
            local_datetime = timezone.localize(
                datetime.combine(entry, publishtime.time()))
            details['post_date_gmt'] = local_datetime.astimezone(pytz.utc)
        newpost = WordPressPost()
        newpost.post_type = 'podcast'
        newpost.title = details['title']
        newpost.date = details['post_date_gmt']
        newpost.post_status = 'draft'
        newpost.content = details['content']
        newpost.terms = [wp.call(GetTerm('series', main_series_termid))]
        if details['seriesid']:
            newpost.terms.append(
                wp.call(GetTerm('series', details['seriesid'])))
        newpost.custom_fields = [{
            'key': 'preacher',
            'value': details['preacher']
        }, {
            'key': 'date_recorded',
            'value': details['date_recorded']
        }, {
            'key': 'bible_passage',
            'value': details['bible_passage']
        }, {
            'key': 'episode_number',
            'value': details['episode_number']
        }, {
            'key': 'publish_now',
            'value': 'on'
        }]
        newpost.id = wp.call(NewPost(newpost))
        if newpost.id:
            print('Created Post ID ' + str(newpost.id) + ' for date: ' +
                  details['date_recorded'])
Ejemplo n.º 7
0
# 连接服务器
client = Client('http://wordpress.localhost/xmlrpc.php', 'admin',
                'my_password')

# 获取发贴对象
post = WordPressPost()

# 设置文章标题
post.title = "My post from python"

# 添加文章内容
post.content = "This is a wonderful blog post about XML-RPC."
#post.id = client.call(NewPost(post))

# 设置文章分类和标签
post.terms_names = {'post_tag': ['test', 'python post'], 'category': ['Tests']}

# 把状态设置为“发布“
post.post_status = 'publish'

# 发布文章
client.call(NewPost(post))

# 获取所有文章
articles = client.call(GetPosts())
# 返回的articles是个列表对象
for article in articles:
    # 调用每个文章对象的struct属性可以得到这个文章的结构,是一个字典
    print(article.struct['post_title'])
Ejemplo n.º 8
0
                            {'key': 'meetupLastUpdated', 'value': int(event['updated']/1000)}]
    #pdb.set_trace()
    post.post_status = 'publish'
    #pprint(post)
    post.id = wp.call(NewPost(post))
    time.sleep(0.5)
    return

#Query configuration file
configuration = json.loads(open('config.json').read())

#Pull events on WordPress and delete the ones that don't exist
meetupGroupNames = configuration['meetupGroups']
meetupClient = meetup.api.Client(configuration['meetupKey'])
wp = Client('https://greateraustinsecularhub.org/xmlrpc2.php', configuration['wpUser'], configuration['wpKey'])
currentWPEvents = wp.call(GetPosts({'post_type': 'events', 'number': 10000}))
for event in currentWPEvents:
    meetupIDDictionary = next((item for item in event.custom_fields if item["key"] == "meetupID"), None)
    if meetupIDDictionary is not None:
        try:
           tempEvent = meetupClient.GetEvent({'id': meetupIDDictionary['value']})
        except:
           #print("Delete " + meetupIDDictionary['value'])
           deleteWPEvent(event.id)
           #print("Deleted")

#Loop through meetup groups
for meetupGroupName in meetupGroupNames:
 
    #Query the meet up information
    print('Searching ' + meetupGroupName)
Ejemplo n.º 9
0
from xmlrpc.client import Transport, ServerProxy

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost


class SpecialTransport(Transport):
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0'


if __name__ == '__main__':
    #authenticate
    wp_url = "http://ryanbradley.com/xmlrpc.php"
    wp_username = "******"
    wp_password = "******"
    # wp_url = "https://colorlib.com/wp/xmlrpc.php"
    # wp_username = "******"
    # wp_password = "******"

    #wp = Client('http://blog.blog.com/xmlrpc.php', 'normal_username', 'normal_password', transport=SpecialTransport())

    wp = Client(wp_url, wp_username, wp_password, transport=SpecialTransport())
    #wp = ServerProxy(wp_url, transport=SpecialTransport(), verbose=True, allow_none=True)

    print(wp.call(GetPosts()))

Ejemplo n.º 10
0
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost, EditPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media

XML_RPC_API = 'http://wp.py4seo.com/xmlrpc.php'
USER = '******'
PASS = '******'

wp_client = Client(XML_RPC_API, USER, PASS)

all_posts = wp_client.call(GetPosts())

file = 'Neil-Armstrong.jpg'

data = {
    'name': file,
    'type': 'image/jpeg',
}

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

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

print(response)

my_post = all_posts[0]
my_post.thumbnail = response['id']
Ejemplo n.º 11
0
'''
Create the Wordpress Client which will retrieve and post posts
'''
wp = Client(settings['WORDPRESS_URL']+'/xmlrpc.php', settings['WORDPRESS_USERNAME'], settings['WORDPRESS_PASSWORD'])

print('Getting Wordpress Posts')
'''
Get all Wordpress posts (in batches of 20) from the specified category.
And add all the titles to the wordpressPosts list.
If no category is specified, then gets all posts, and does not categorize posts.
'''
wpOffset = 0
wpIncrement = 20
while True:
    posts = wp.call(GetPosts({'number': wpIncrement, 'offset': wpOffset}))
    if len(posts) == 0:
        print ('Imported ' + str(len(wordpressPosts)) + ' Wordpress posts.')
        break  # no more posts returned
    for post in posts:
        #if it's in the specified category, add it to the list
        if settings['WORDPRESS_CATEGORY'] in str(post.terms):
            wordpressPosts.append(post)
            print ('id : ' + post.id)
            print ('title : ' + post.title)
            fields = GetCustomFields(post.custom_fields)
            print ('gistid : ' + fields['gistid'])
            print ('---')
    wpOffset = wpOffset + wpIncrement