Skip to content

Instantly share code, notes, and snippets.

@chucknado

chucknado/post_articles.py

Last active Mar 11, 2020
Embed
What would you like to do?
Uploads a collection of HTML files to Help Center
from pathlib import Path
from bs4 import BeautifulSoup
import requests
"""
1. Place the HTML files in a folder named 'html_files' in the same folder as this file.
2. Change the settings starting on line 14 to values that are valid for your account.
3. In your command line interface, navigate to the folder containing this file and run `python3 post_articles.py`.
4. In Guide, set the correct sections, authors, and access permissions for the articles.
"""
# settings
author_id = '12345' # initial author of the articles
section_id = '12345' # initial section of the articles
user_segment_id = '12345' # initial user segment who can view the articles
permission_group_id = '12345' # initial group who can edit and publish the articles
locale = 'en-us' # initial locale of the articles
subdomain = 'your_subdomain'
your_user_name = 'jdoe@example.com'
your_api_token = 'y0urap1t0ken'
auth = f'{your_user_name}/token', your_api_token
# build endpoint to create articles
url = f'https://{subdomain}.zendesk.com/api/v2/help_center/sections/{section_id}/articles.json'
# get list of files to upload
html_files_path = Path('html_files')
files = list(html_files_path.glob(f'**/*.html'))
for file in files:
# open and parse the file
with file.open(mode='r', encoding='utf-8') as f:
html_source = f.read()
tree = BeautifulSoup(html_source, 'lxml')
title = tree.h1.string.strip()
tree.h1.decompose()
body = str(tree.body)
if title is None or body is None:
print('ERROR: title or body problem in \"{}\" (extra inner tags, etc)'.format(file.name))
exit()
# prepare article payload
article = {
'title': title,
'body': body,
'author_id': author_id,
'locale': locale,
'user_segment_id': user_segment_id,
'permission_group_id': permission_group_id
}
data = {'article': article}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, json=data, auth=auth, headers=headers)
if response.status_code != 201:
print('- Failed to create article with error {}: {}'.format(response.status_code, response.text))
else:
print(f"- Successfully created article: {article['title']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment