def activate(self): if self.config is None: self.log.info("SocialSupport is not configured - plugin not " "activating.") else: # Configure clients auth = OAuthHandler(self.config['TWITTER_CONSUMER_KEY'], self.config['TWITTER_CONSUMER_SECRET']) auth.set_access_token(self.config['TWITTER_OAUTH_TOKEN'], self.config['TWITTER_OAUTH_SECRET']) self.twitter_client = API(auth) self.since_id = None self.zendesk_client = Zendesk(self.config['ZENDESK_INSTANCE_URI'], self.config['ZENDESK_USER'], self.config['ZENDESK_PASSWORD']) self.log.info("Starting SocialSupport.") super(SocialSupport, self).activate() # Set up persistence. self.log.info("Setting up persistence.") self['SUPPORT_TRAINING_CORPUS'] = [] self['SUPPORT_TRAINING_QUEUE'] = [] self['SUPPORT_TRAINER_QUEUE'] = {} self['TRAINER_SCOREBOARD'] = {}
def get_conn(self) -> Zendesk: conn = self.get_connection(self.__zendesk_conn_id) self.__url = "https://" + conn.host return Zendesk(zdesk_url=self.__url, zdesk_email=conn.login, zdesk_password=conn.password, zdesk_token=True)
def zd(request): try: # If a zdtestcfg exists, then prefer it because it has been # manually created just for test running. from zdtestcfg import testconfig config = testconfig except: try: import zdeskcfg # Create an object using the [zdesk] and [sandbox] sections of # ~/.zdeskcfg and the zdeskcfg module config = zdeskcfg.get_ini_config(section='sandbox') # It's possible that zdeskcfg is installed, but if the config # file does not exist or have a valid configuration, we should # not try to use it. if True not in map(bool, config.values()): config = {} except: config = {} if config: return Zendesk(**config) else: assert 0, 'No Zendesk configuration found.\n' \ 'Create tests/zdtestcfg.py or install and configure zdeskcfg.'
def _deploy(article_id, zendesk_url, cloudfront_url, username, password): path = "site/" + article_id + "/index.html" locale = "en-us" # Check if the article_id is valid. if not os.path.exists("posts/" + article_id): print(Fore.RED + "The article_id you entered is invalid." + Fore.RESET) sys.exit(1) title = open("posts/" + article_id + "/title.html").readline() if not title: print(Fore.RED + "Add a title to posts/" + article_id + "/title.html before deploying the article." + Fore.RESET) sys.exit(1) # Prepare files for being pushed to Zendesk. renderer.render_zendesk_deployment(cloudfront_url, article_id) # Push the images to CloudFront. cloudfront_images.push_to_cloudfront(article_id) # Delete extra images on CloudFront. cloudfront_images.delete_from_cloudfront(article_id) # Build connection to Zendesk. zendesk = Zendesk(zendesk_url, username, password) if not compare_repos.compare_article_contents(article_id, zendesk): return # Packages the data in a dictionary matching the expected JSON. update_article = { "translation": { "title": title, "body": open(path, mode='rb').read() } } response = zendesk.help_center_article_translation_update( article_id, locale, update_article) # Check if article is in Draft mode. check_draft = response["translation"]["draft"] if check_draft: print(Fore.YELLOW + "Reminder that article " + article_id + " is still in draft mode." + Fore.RESET) print "Article " + article_id + " has been updated at: " + zendesk_url + "/" + article_id
def _create_shell(section_id): # Get subdomain. try: subdomain = os.environ["ZENDESK_SUBDOMAIN"] url = file_constants.get_url_from_subdomain(subdomain) except KeyError: print(Fore.RED + "Please set the environment variable ZENDESK_SUBDOMAIN" + Fore.RESET) sys.exit(1) # Get username. try: username = os.environ["ZENDESK_USR"] except KeyError: print(Fore.RED + "Please set the environment variable ZENDESK_USR" + Fore.RESET) sys.exit(1) # Get password. try: password = os.environ["ZENDESK_PWD"] except KeyError: print(Fore.RED + "Please set the environment variable ZENDESK_PWD" + Fore.RESET) sys.exit(1) zendesk = Zendesk(url, username, password) # Add a temporary title and leave it in draft mode. new_article = {"article": {"title": "Temporary Title", "draft": True}} response = zendesk.help_center_section_article_create(id=section_id, data=new_article) # Report success. print('Successfully created the article.') # Create the article shell locally. article_id = response['article']['id'] _empty_article(str(article_id))
merch_dir = "C:\\Users\\DmitryDmytrenko\\Documents\\Technology\\DD\\Zendesk\\Py app\\Files From Brad Merch\\*.xlsx" wb = load_workbook(filename=max(glob.glob(merch_dir), key=os.path.getctime)) sheet = wb.worksheets[0] print(max(glob.glob(merch_dir), key=os.path.getctime)) print(sheet) reply = int(input("Please enter 1 to continue with the file and tab above ")) if reply == 1: print("Will process the file above to create ZD tickets!") else: print("Tickets won't be created") exit() zendesk = Zendesk(zdesk_url='https://envusa.zendesk.com', zdesk_email='*****@*****.**', zdesk_password='******', zdesk_token=True) needed_rows = list(sheet.rows)[1:] dictionary = {} for row in needed_rows: fcid = row[5].value order_id = row[0].value order_date = row[1].value name = row[2].value mail_code = row[3].value address = row[6].value.replace("\n", " ") requester_email = row[8].value requester_phone = row[7].value
from zdesk import Zendesk app = Flask(__name__) app.config.from_pyfile('settings.py') celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask redis = StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB']) zendesk = Zendesk(zdesk_url=app.config['ZENDESK_URL'], zdesk_email=app.config['ZENDESK_EMAIL'], zdesk_password=app.config['ZENDESK_TOKEN'], zdesk_token=True) from . import api # NOQA
from zdesk import Zendesk import json from sys import argv import os zendesk = Zendesk('https://sent.zendesk.com', os.environ["EMAIL"], os.environ["PASSWORD"]) def main(jsonfile): precontent = open(jsonfile).read() content = json.loads(precontent) # jsonfile.close() for review in content["Reviews"]: new_ticket = { "ticket": { "requester": { "name": review["Author"].encode('ascii', 'ignore'), "email": "*****@*****.**" }, "subject": review["Title"].encode('ascii', 'ignore'), "comment": { "body": review["Content"].encode('ascii', 'ignore') } } } # Create the ticket and get its URL result = zendesk.ticket_create(data=new_ticket)
{ "position": 2, "locale": "jp", "name": "テスト用", "description": "テスト用カテゴリ" } } zendesk.help_center_category_create(data=testCategoryData) sectionId = 360000342113 testSectionData = { "section": { "position": 2, "locale": "jp", "name": "テスト用セクション", "description": "テスト用セクション" }} zendesk.help_center_category_section_create(sectionId, testSectionData) if __name__ == '__main__': zendesk = Zendesk('https://yourcompany.zendesk.com', '*****@*****.**', 'passwd') articlesData = articlesDataFactory("sampleArticleData.xlsx") # taggerFieldData = taggerFieldDataFactory("sampleFieldData.xlsx") articlesCreateOnInstance(zendesk, articlesData) # taggerFieldCreate(zendesk, taggerFieldData)
# # In either case, you can use your actual password and set `token = 0` or # `zdesk_token = False`, but it is a very good idea to configure an API token # by visiting this URL at your own Zendesk instance: # https://example.zendesk.com/settings/api/ try: import zdeskcfg # Create an object using the [zdesk] section of # ~/.zdeskcfg and the zdeskcfg module #zendesk = Zendesk(**zdeskcfg.get_ini_config()) # Create an object using the [zdesk] and [sandbox] sections of # ~/.zdeskcfg and the zdeskcfg module zendesk = Zendesk(**zdeskcfg.get_ini_config(section='sandbox')) except ImportError: testconfig = { 'zdesk_email': '*****@*****.**', 'zdesk_password': '******', 'zdesk_url': 'https://example-sandbox22012201.zendesk.com', 'zdesk_token': True } if testconfig[ 'zdesk_url'] == 'https://example-sandbox22012201.zendesk.com': print( 'Could not import zdeskcfg and no manual configuration provided.') print( 'Please `pip install zdeskcfg` or edit example with manual configuration.'
def get_conn(self): conn = self.get_connection(self.__zendesk_conn_id) self.__url = "https://" + conn.host return Zendesk(self.__url, conn.login, conn.password, True)
def __init__(self, infopath='~/files/zendeskinfo.yaml'): import yaml from zdesk import Zendesk with open(os.path.expanduser(infopath), 'rt') as f: self.zendeskinfo = yaml.load(f) self.zendesk = Zendesk(**self.zendeskinfo)
def __init__(self, config): self.config = config self.zendesk = Zendesk(self.config['url'], self.config['user'], self.config['password'])
def zdgrab(verbose=False, tickets=None, work_dir=os.path.join(os.path.expanduser('~'), 'zdgrab'), agent='me'): "Download attachments from Zendesk tickets." cfg = zdgrab.getconfig() if cfg['zdesk_url'] and cfg['zdesk_email'] and cfg['zdesk_password']: if verbose: print('Configuring Zendesk with:\n' ' url: {}\n' ' email: {}\n' ' token: {}\n' ' password: (hidden)\n'.format( cfg['zdesk_url'], cfg['zdesk_email'], repr(cfg['zdesk_token']) )) zd = Zendesk(**cfg) else: msg = textwrap.dedent("""\ Error: Need Zendesk config to continue. Config file (~/.zdeskcfg) should be something like: [zdesk] url = https://example.zendesk.com email = [email protected] password = dneib393fwEF3ifbsEXAMPLEdhb93dw343 token = 1 [zdgrab] agent = [email protected] """) print(msg) return 1 # Log the cfg if verbose: print('Running with zdgrab config:\n' ' verbose: {}\n' ' tickets: {}\n' ' work_dir: {}\n' ' agent: {}\n'.format(verbose, tickets, work_dir, agent)) # tickets=None means default to getting all of the attachments for this # user's open tickets. If tickets is given, try to split it into ints if tickets: # User gave a list of tickets try: tickets = [int(i) for i in tickets.split(',')] except ValueError: print('Error: Could not convert to integers: {}'.format(tickets)) return 1 # dict of paths to attachments retrieved to return. format is: # { 'path/to/ticket/1': [ 'path/to/attachment1', 'path/to/attachment2' ], # 'path/to/ticket/2': [ 'path/to/attachment1', 'path/to/attachment2' ] } grabs = {} # Save the current directory so we can go back once done start_dir = os.getcwd() # Normalize all of the given paths to absolute paths work_dir = os.path.abspath(work_dir) # Check for and create working directory if not os.path.isdir(work_dir): os.makedirs(work_dir) # Change to working directory to begin file output os.chdir(work_dir) if verbose: print('Retrieving tickets') if tickets: # tickets given, query for those response = zd.tickets_show_many(ids=','.join([s for s in map(str,tickets)]), get_all_pages=True) result_field = 'tickets' else: # List of tickets not given. Get all of the attachments for all of this # user's open tickets. q = 'status<solved assignee:{}'.format(agent) response = zd.search(query=q, get_all_pages=True) result_field = 'results' if response['count'] == 0: # No tickets from which to get attachments print("No tickets provided for attachment retrieval.") return {} results = response[result_field] # Fix up some headers to use for downloading the attachments. # We're going to borrow the zdesk object's httplib client. headers = {} if zd.zdesk_email is not None and zd.zdesk_password is not None: headers["Authorization"] = "Basic {}".format( base64.b64encode(zd.zdesk_email.encode('ascii') + b':' + zd.zdesk_password.encode('ascii'))) # Get the attachments from the given zendesk tickets for ticket in results: if result_field == 'results' and ticket['result_type'] != 'ticket': # This is not actually a ticket. Weird. Skip it. continue if verbose: print('Ticket {}'.format(ticket['id'])) ticket_dir = os.path.join(work_dir, str(ticket['id'])) ticket_com_dir = os.path.join(ticket_dir, 'comments') comment_num = 0 if verbose: print('Retrieving audits') response = zd.ticket_audits(ticket_id=ticket['id'], get_all_pages=True) audits = response['audits'] for audit in audits: for event in audit['events']: if event['type'] != 'Comment': # This event isn't a comment. Skip it. continue comment_num += 1 comment_dir = os.path.join(ticket_com_dir, str(comment_num)) if verbose and event['attachments']: print('Comment {}'.format(comment_num)) for attachment in event['attachments']: name = attachment['file_name'] if os.path.isfile(os.path.join(comment_dir, name)): if verbose: print('Attachment {} already present'.format(name)) continue # Get this attachment if verbose: print('Attachment {}'.format(name)) # Check for and create the download directory if not os.path.isdir(comment_dir): os.makedirs(comment_dir) os.chdir(comment_dir) response = zd.client.request('GET', attachment['content_url'], headers=headers) if response.status_code != 200: print('Error downloading {}'.format(attachment['content_url'])) continue with open(name, 'wb') as f: f.write(response.content) # Check for and create the grabs entry to return if ticket_dir not in grabs: grabs[ticket_dir] = [] grabs[ticket_dir].append( os.path.join('comments', str(comment_num), name) ) # Let's try to extract this if it's compressed zdsplode(name, verbose=verbose) os.chdir(start_dir) return grabs
def __init__(self, url, email, api, search_string): self.zendesk = Zendesk(url, zdesk_email=email, zdesk_api=api) self.barcode_re = re.compile(r"barcode\s(\d+)") self.username_re = re.compile(r"assigned_to\s(\w+)") self.search = search_string self.me = self.zendesk.users_me()['user']
#Define ZenDesk API Information config = { 'zdesk_email': '<ZENDESK_USER_EMAIL>', 'zdesk_password': '******', 'zdesk_url': '<ZENDESK_URL>', 'zdesk_token': <'TRUE OR FALSE'> } #Define telephone country code (if Active Directory numbers formatted without code) telephone_prefix = "1" #Connect to S3 with Boto3 s3 = boto3.client('s3') #Create ZenDesk Connection zendesk = Zendesk(**config) def lambda_handler(event, context): #List User users = zendesk.users_list().get('users', []) print("Listing Current ZenDesk Users") for user in users: name = user['name'] print(name) #Find Most Recently Modified Active Users File from S3 bucket_list = s3.list_objects(Bucket=bucket).get('Contents', []) print(bucket_list) for file in bucket_list:
type=str, nargs='*', help='New word that will replace old word') parser.add_argument('--ask', help='Ask before applying the change', action='store_true') parser.add_argument('-d', '--dry-run', action='store_true') parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() if len(args.old) != len(args.new): print('OLD must have the same number of argument than NEW') sys.exit(1) zendesk = Zendesk(zdesk_url=args.url, zdesk_email=args.username, zdesk_password=args.token, zdesk_token=True) page = 1 articles = zendesk.help_center_articles_list(per_page=100, page=page) if args.ask and not query_yes_no('Found "' + str(articles['count']) + '". Do you want to keep going?'): sys.exit(1) while True: for article in articles['articles']: translations = zendesk.help_center_article_translations( article_id=article['id'], locales=args.locale) for translation in translations['translations']: for i in range(0, len(args.old)): if translation['body'] is None or args.old[
def zdkb(verbose=False, listing=None, fetch=False, kb_dir=os.path.join(os.path.expanduser('~'), 'zdkb')): "Manage Zendesk knowledgbases" cfg = zdkb.getconfig() # Log the cfg if verbose: print('Running with zdkb config:\n' ' verbose: {}\n' ' listing: {}\n' ' kb_dir: {}\n'.format(verbose, listing, kb_dir)) #if state['categories'] or state['topics'] or state['forums'] or state['list_zdf']: if listing or fetch: if cfg['zdesk_url'] and cfg['zdesk_email'] and cfg['zdesk_password']: if verbose: print('Configuring Zendesk with:\n' ' url: {}\n' ' email: {}\n' ' token: {}\n' ' password: (hidden)\n'.format( cfg['zdesk_url'], cfg['zdesk_email'], repr(cfg['zdesk_token']))) zd = Zendesk(**cfg) else: msg = textwrap.dedent("""\ Config file (e.g. ~/.zdf2pdf.cfg) should be something like: [zdf2pdf] url = https://example.zendesk.com mail = [email protected] password = dneib393fwEF3ifbsEXAMPLEdhb93dw343 is_token = 1 """) print(msg) msg = textwrap.dedent("""\ Error: Need Zendesk config for requested operation. Config file (~/.zdeskcfg) should be something like: [zdesk] url = https://example.zendesk.com email = [email protected] password = dneib393fwEF3ifbsEXAMPLEdhb93dw343 token = 1 [zdkb] kb_dir = /path/to/kb_dir """) print(msg) return 1 # If any listing was requested we will do that and exit, regardless of # any other supplied options. if listing == 'all': # List available zendesk forums with their IDs and titles and exit. # Listing is formatted like for following: # 12345 Category 1 name # 09876 Forum 1 name # 54321 Forum 2 name # 67890 Category 2 name if verbose: print('Listing all forums') response = zd.forums_list(get_all_pages=True) forums = response['forums'] cat_ids = set(f['category_id'] for f in forums) categories = zd.categories_list(get_all_pages=True) for cat_id in cat_ids: if cat_id: try: cat_name = next(c['name'] for c in categories if c['id'] == cat_id) except StopIteration: cat_name = 'None' else: cat_id = 'None' cat_name = 'None' print('{} ({})'.format(cat_name, cat_id)) for forum in forums: if repr(forum['category_id']) == cat_id: print(' {} ({})'.format(forum['name'], forum['id'])) return 0 elif listing: if verbose: print('Listing all entries in forum {}'.format(listing)) # List a zendesk forum's entries with their titles and IDs and exit try: forum_id = int(listing) except ValueError: print('Error: Could not convert to integer: {}'.format(listing)) return 1 entries = zd.forum_topics(id=listing, get_all_pages=True) for entry in entries['topics']: print('{} ({})'.format(entry['title'], entry['id'])) return 0 # Save the current directory so we can go back once done start_dir = os.getcwd() # Normalize all of the given paths to absolute paths kb_dir = os.path.abspath(kb_dir) # Check for and create working directory if not os.path.isdir(kb_dir): print('kb_dir does not exist: {}'.format(kb_dir)) return 1 if fetch: # Change to working directory to begin file output os.chdir(kb_dir) response = zd.forums_list(get_all_pages=True) forums = response['forums'] response = zd.categories_list(get_all_pages=True) categories = response['categories'] response = zd.topics_list(get_all_pages=True) topics = response['topics'] with open('categories', 'w') as cat_file: json.dump(categories, cat_file) for forum in forums: forum_name = forum['name'].replace('/', '-') if not os.path.isdir(forum_name): os.mkdir(forum_name) os.chdir(forum_name) with open(forum_name + '.json', 'w') as forum_json: json.dump(forum, forum_json) os.chdir(kb_dir) for topic in topics: try: forum_name = next(f['name'] for f in forums if f['id'] == topic['forum_id']) except StopIteration: forum_name = 'None' forum_name = forum_name.replace('/', '-') if not os.path.isdir(forum_name): os.mkdir(forum_name) os.chdir(forum_name) topic_filename = topic['title'].replace('/', '-') with open(topic_filename + '.html', 'w') as topic_html: topic_html.write(topic['body']) with open(topic_filename + '.json', 'w') as topic_json: del topic['body'] json.dump(topic, topic_json) os.chdir(kb_dir) return 0 return 0