def __init__(self, thread_id, quip_api_base_url): self.quip_client = quip.QuipClient(access_token=ACCESS_TOKEN, base_url=quip_api_base_url) self.thread_id = thread_id super(TwitterBot, self).__init__(TWITTER_API_KEY, TWITTER_API_SECRET, TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_SECRET)
def main(): logging.getLogger().setLevel(logging.DEBUG) # parser = argparse.ArgumentParser(description="Backup of a Quip account") # parser.add_argument("--access_token", required=True, # help="Access token for the user whose account should be backed up") # parser.add_argument("--root_folder_id", default=None, # help="If provided, only the documents in the given folder will be " # "backed up. Otherwise all folder and documents will be backed up.") # parser.add_argument("--quip_api_base_url", default=None, # help="Alternative base URL for the Quip API. If none is provided, " # "https://platform.quip.com will be used") # parser.add_argument("--output_directory", default="./", # help="Directory where to place backup data.") # args = parser.parse_args() # client = quip.QuipClient( # access_token=args.access_token, base_url=args.quip_api_base_url, # request_timeout=120) client = quip.QuipClient( access_token= "ZE5CQU1BcmtwRnQ=|1600850712|2bH//fDrlft1cx03ktiYFA9kfST9arohKRuPd+WmL4k=" ) output_directory = os.path.join(_normalize_path(""), "baqup") _ensure_path_exists(output_directory) shutil.rmtree(output_directory, ignore_errors=True) output_static_diretory = os.path.join(output_directory, _OUTPUT_STATIC_DIRECTORY_NAME) shutil.copytree(_STATIC_DIRECTORY, output_static_diretory) _run_backup(client, output_directory, args.root_folder_id)
def main(): # Get Quip document auth_key = open( '/home/ubuntu/emailGoals/quip_credentials.json').read().rstrip('\n') client = quip.QuipClient(access_token=auth_key, base_url="https://platform.quip.com", retry_rate_limit=True, request_timeout=120) user = client.get_authenticated_user() thread = client.get_thread("hD7jAZ1Rau8Z") # Get credentials for Google credentials = get_credentials() http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) # Create and send message message = MIMEText(thread["html"].encode('utf-8'), 'html') message['to'] = "*****@*****.**" message['from'] = "*****@*****.**" message['subject'] = "Goals" service.users().messages().send(userId="me", body={ 'raw': base64.urlsafe_b64encode( message.as_string()) }).execute()
def receive(self, message): addresses = message.to.split(',') thread_id = "" token = "" for address in addresses: try: (to, domain) = address.split('@') (thread_id, token) = to.split('+', 1) if len(thread_id) == 11 and len(token) > 0: break except: pass text = "" for content_type, body in message.bodies('text/plain'): text = body.decode() # Strip some common signature patterns for pattern in ["\n----", "\nIFTTT"]: if pattern in text: text = text[:text.find(pattern)] if len(text) > 0: break # TODO: Attachments if len(text) > 0 and len(thread_id) == 11 and len(token) > 0: client = quip.QuipClient(access_token=token) client.new_message(thread_id, text, silent="silent" in message.subject)
def export(access_token, thread_token): if not access_token or not thread_token: raise Exception("access_token and thread_token must not empty") client = quip.QuipClient(access_token=access_token) thread = client.get_thread(thread_token) htmlTpl = """<!DOCTYPE html> <html lang="zh-cn"> <head> <title>{{title}}</title> <meta charset="utf-8" /> </head> <body> <div class="document-content"> <section class="section"> {{text}} </section> </div> </body> </html> """ title = thread['thread']['title'] html = str(thread['html']) htmlTpl = htmlTpl.replace('{{title}}', title) htmlTpl = htmlTpl.replace('{{text}}', html) print(htmlTpl) return title, htmlTpl
def create_new_from_template(self, access_token, template_thread_id, title, member_ids): client = quip.QuipClient(access_token) try: template_json = client.get_thread(template_thread_id) logging.debug('template_json: %s', template_json) except quip.QuipError as err: logging.debug('QuipError %s', err) web.ctx.status = err.message return err.message except: raise template_html = template_json.get('html') template_title = template_json.get('thread').get('title') new_html = template_html.replace(template_title, title) try: new_thread_response = client.new_document(new_html, member_ids=member_ids) logging.debug('new_thread_response %s', new_thread_response) return new_thread_response except quip.QuipError as err: logging.debug('QuipError %s', err) web.ctx.status = err.message return err.message except: raise
def main(): logging.getLogger().setLevel(logging.DEBUG) parser = argparse.ArgumentParser(description="Backup of a Quip account") parser.add_argument( "--access_token", required=True, help="Access token for the user whose account should be backed up") parser.add_argument( "--root_folder_id", default=None, help="If provided, only the documents in the given folder will be " "backed up. Otherwise all folder and documents will be backed up.") parser.add_argument( "--quip_api_base_url", default=None, help="Alternative base URL for the Quip API. If none is provided, " "https://platform.quip.com will be used") parser.add_argument("--output_directory", default="./", help="Directory where to place backup data.") args = parser.parse_args() client = quip.QuipClient(access_token=args.access_token, base_url=args.quip_api_base_url) output_directory = _normalize_path(args.output_directory) shutil.rmtree(output_directory, ignore_errors=True) output_static_diretory = os.path.join(output_directory, _OUTPUT_STATIC_DIRECTORY_NAME) shutil.copytree(_STATIC_DIRECTORY, output_static_diretory) _ensure_path_exists(output_directory) _run_backup(client, output_directory, args.root_folder_id)
def translate_to_quip(url, quip_token, quip_folder): ''' Assembles the functions in this module and initiates the quip client. ''' # set url to translate and call translate function translated_html = translate_html(url) # establish quip connection, find folder id and send translated post to quip as new doc. client = quip.QuipClient(quip_token) folder_id = find_quip_folder(quip_folder, client) new_thread = client.new_document(translated_html, member_ids=[folder_id]) #translate_notes(new_thread,client) return new_thread
def main(): parser = argparse.ArgumentParser(description="Create a Quip document") parser.add_argument("--access_token", required=True, help="Quip access token") parser.add_argument("--skip_duplicates", required=False, action="store_true", help="Skip notes with the same title") parser.set_defaults(skip_duplicates=False) args = parser.parse_args() access_token = args.access_token skip_duplicates = args.skip_duplicates client = quip.QuipClient(access_token=access_token) folder = client.new_folder(UPLOAD_FOLDER_NAME) folder_id = folder["folder"]["id"] print "Uploading Apple Notes to Quip..." for logged_line in upload_notes(access_token, folder_id, skip_duplicates): print logged_line.replace("<div>", "").replace("</div>", "").replace("\n", "")[0:60] + "..."
def main(): logging.getLogger().setLevel(logging.DEBUG) parser = argparse.ArgumentParser(description="Backup of a Quip account") parser.add_argument("--access_token", required=True, help="Access token for the user whose account should be backed up") parser.add_argument("--root_folder_id", default=None, help="If provided, only the documents in the given folder will be " "backed up. Otherwise all folder and documents will be backed up.") parser.add_argument("--quip_api_base_url", default=None, help="Alternative base URL for the Quip API. If none is provided, " "https://platform.quip.com will be used") parser.add_argument("--output_directory", default="./", help="Directory where to place backup data.") parser.add_argument("--cache_directory", default=None, help="Directory where to cache downloaded thread data") parser.add_argument("--use_rate_limiting", action='store_true', help="Watch API rate limit and wait when it runs out") args = parser.parse_args() cache_dir = args.cache_directory if cache_dir is not None: cache_dir = _normalize_path(cache_dir) _ensure_path_exists(cache_dir) client = BaqupClient( cache_dir=cache_dir, access_token=args.access_token, base_url=args.quip_api_base_url, request_timeout=120, use_rate_limiting=bool(args.use_rate_limiting)) else: client = quip.QuipClient( access_token=args.access_token, base_url=args.quip_api_base_url, request_timeout=120, thread_cache_dir=thread_cache_dir, use_rate_limiting=bool(args.use_rate_limiting)) output_directory = os.path.join( _normalize_path(args.output_directory), "baqup") _ensure_path_exists(output_directory) shutil.rmtree(output_directory, ignore_errors=True) output_static_diretory = os.path.join( output_directory, _OUTPUT_STATIC_DIRECTORY_NAME) shutil.copytree(_STATIC_DIRECTORY, output_static_diretory) _run_backup(client, output_directory, args.root_folder_id)
def execute(self, config, to_user, from_user, referring_user, **payload): """Updates the quip members document""" admins = models.UserManager.load(config['admins']) from_user = admins[from_user] token = config['services']['quip']['token'] client = quip.QuipClient(access_token=token) document_id = config['services']['quip']['document'] last_row_id = self.fetch_last_row_id(client, document_id) new_row = self.build_new_row( to_user=to_user, from_user=from_user, referring_user=referring_user) client.edit_document(document_id, new_row, operation=quip.QuipClient.AFTER_SECTION, section_id=last_row_id)
def main(): parser = argparse.ArgumentParser(description="Twitter gateway for Quip.") parser.add_argument("--access_token", required=True, help="User's access token") parser.add_argument( "--quip_api_base_url", default=None, help="Alternative base URL for the Quip API. If none is provided, " "https://platform.quip.com will be used") args = parser.parse_args() quip_client = quip.QuipClient(access_token=args.access_token, base_url=args.quip_api_base_url or "https://platform.quip.com") websocket_info = quip_client.new_websocket() open_websocket(websocket_info["url"])
def GET(self): set_cors_headers() web_input = web.input() logging.debug('web_input: %s', web_input) access_token = web_input.get('access_token') thread_id = web_input.get('thread_id') client = quip.QuipClient(access_token) try: thread_json = client.get_thread(thread_id) logging.debug('thread_json: %s', thread_json) web.header('Content-Type', 'application/json') return json.dumps(thread_json) except quip.QuipError as err: logging.debug('QuipError %s', err) web.ctx.status = err.message return err.message except: raise
def post(self): api_token = self.request.get("api_token") if not api_token: self.error(400) return thread_id = self.request.get("thread_id") if not thread_id or len(thread_id) != 11: self.error(400) return client = quip.QuipClient(access_token=api_token) service = self.request.get("service") payload = json.loads(self.request.body) logging.info("Payload: %s", payload) if service == "github": self._handle_github(client, thread_id, payload) elif service == "crashlytics": self._handle_crashlytics(client, thread_id, payload) elif service == "pagerduty": self._handle_pagerduty(client, thread_id, payload) else: self.error(400)
def main(): # logging.getLogger().setLevel(logging.DEBUG) parser = argparse.ArgumentParser(description="Simulate oauth client") parser.add_argument("--client_id", help="Client id to use in oauth call") parser.add_argument("--client_secret", help="Client secret to be used in oauth call") parser.add_argument("--redirect_uri", default='http://localhost:8900', help="Client secret to be used in oauth call") parser.add_argument( "--quip_api_base_url", default="http://platform.docker.qa:10000", help="Alternative base URL for the Quip API. If none is provided, " "http://platform.docker.qa:10000 will be used") args = parser.parse_args() start_server_in_thread() client = quip.QuipClient(client_id=args.client_id, client_secret=args.client_secret, base_url=args.quip_api_base_url, request_timeout=120) authorization_url = client.get_authorization_url(args.redirect_uri) print('Authorize access using the following url: %s' % authorization_url) # Wait for auth code from http server code = q.get() token_info = client.get_access_token(args.redirect_uri, code) print("token_info: %s" % json.dumps(token_info, indent=1)) client.access_token = token_info['access_token'] user = client.get_authenticated_user() print('user: %s(%s)' % (user['name'], user['emails'][0])) httpd.shutdown()
#! /usr/bin/python import click import nbformat import os import quip from bs4 import BeautifulSoup from nbconvert import HTMLExporter QUIP_ACCESS_TOKEN = os.environ.get('QUIP_ACCESS_TOKEN') quip_client = quip.QuipClient(access_token=QUIP_ACCESS_TOKEN) def _html_from_notebook(notebook_path): with open(notebook_path, 'r') as f: notebook_to_convert = f.read() notebook = nbformat.reads(notebook_to_convert, as_version=4) html_exporter = HTMLExporter(anchor_link_text='', exclude_input=True) (body, resources) = html_exporter.from_notebook_node(notebook) return body @click.group() def cli1(): pass
import quip import sys token = None if len(sys.argv) == 2: print("Using Login Token: " + sys.argv[1]) token = sys.argv[1] else: # no default token print("Must provide login token") sys.exit(1) try: client = quip.QuipClient(access_token=token) user = client.get_authenticated_user() except Exception as e: print(e) client = user = None sys.exit(1) def proceed(client, user): print("Logged in user: " + str(user['name'])) folders = {} threads = {} def getData(client, threads, tid): thread = client.get_thread(tid) threads[thread['thread']['title']] = (thread['thread']['id'],
import quip import os client = quip.QuipClient(access_token=os.environ.get("QUIP_API_KEY", "InvalidKey"), base_url="https://platform.quip.com") # Fetches all attributes of client, useful for debugging # print(dir(client)) def get_thread(suffix): # TODO: Make this handle URLs as well by parsing out the junk resp = client.get_thread(suffix) print(resp) return resp["thread"]["id"] def get_document_html(thread_id): resp = client.get_thread(thread_id) return resp["html"] def toggle_checkmark(thread_id, section_id, item): if ('checked' in item['class']): item['class'].remove('checked') else: item['class'].append('checked') replace_document_section(thread_id, section_id, item)
# user = client.get_authenticated_user() # starred = client.get_folder(user["starred_folder_id"]) # print "There are", len(starred["children"]), "items in your starred folder" def Traverse(client,foldid): folder = client.get_folder(foldid) for child in folder["children"]: if "folder_id" in child: Traverse(client,child["folder_id"]) elif "thread_id" in child: threadid = child["thread_id"] DealwithThread(client,threadid) def DealwithThread(client,threadid): thread = client.get_thread(threadid) link = thread["thread"]["link"] title = thread["thread"]["title"] pdfkit.from_url(link,"hah.pdf",configuration=config) # if client.access_token: # request.add_header("Authorization", "Bearer " + client.access_token) # re = urlopen(request, timeout=500) # with open("./%s.txt" % (title),"w") as thedox: # thedox.write(re.read()) import quip client = quip.QuipClient(access_token="ZE5CQU1BcmtwRnQ=|1600850712|2bH//fDrlft1cx03ktiYFA9kfST9arohKRuPd+WmL4k=",request_timeout=500) user = client.get_authenticated_user() # Traverse(client,user["private_folder_id"]) for i in user["group_folder_ids"]: Traverse(client,i)
''' Created on May 17, 2016 @author: ubuntu ''' import postachio_to_quip from bs4 import BeautifulSoup import quip import config url = 'http://aproximatebible.postach.io/post/interfacing-religion' folder = 'testing' client = quip.QuipClient(config.quip_token) user = client.get_authenticated_user() desktop_folder_id = client.get_folder(user['desktop_folder_id']) #print thread['ZeFAAAPFArH']['html'] print desktop_folder_id # html = postachio_to_quip.translate_html(url) # # notes = html.find_all('blockquote') # # for note in notes: # print note
def main(): parser = argparse.ArgumentParser( description="Post Quip threads to WordPress") parser.add_argument("--quip_access_token", required=True, help="Access token for your Quip account") parser.add_argument("--wordpress_xmlrpc_url", required=True, help="XML-RPC endpoint for your WordPress blog") parser.add_argument("--wordpress_username", required=True, help="Username for your WordPress blog") parser.add_argument("--wordpress_password", required=True, help="Password for your WordPress blog") parser.add_argument("--publish", type=bool, default=True, help="Publish the post immediately") parser.add_argument( "thread_ids", metavar="thread_id", nargs="+", help="The thread IDs of the documents you want to publish") args = parser.parse_args() client = quip.QuipClient(access_token=args.quip_access_token) server = xmlrpclib.ServerProxy(args.wordpress_xmlrpc_url) threads = client.get_threads(args.thread_ids) for thread in threads.values(): # Parse the document tree = client.parse_document_html(thread["html"]) # Upload each image to wordpress and replace with the new URL for img in tree.iter("img"): src = img.get("src") if not src.startswith("/blob"): continue _, _, thread_id, blob_id = src.split("/") blob_response = client.get_blob(thread_id, blob_id) mimetype = blob_response.info().get("Content-Type") ext = "." + mimetype.split("/")[-1] filename = blob_response.info().get("Content-Disposition").split( '"')[-2] if not filename.endswith(ext): filename += ext result = server.wp.uploadFile( 0, args.wordpress_username, args.wordpress_password, { "name": filename, "type": mimetype, "bits": xmlrpclib.Binary(blob_response.read()), "overwrite": True, }) img.set("src", result["url"]) # Remove the title element to avoid repeating it for child in tree: if child.text == thread["thread"]["title"]: tree.remove(child) break html = unicode(xml.etree.cElementTree.tostring(tree)) # Strip the <html> tags that were introduced in parse_document_html html = html[6:-7] post_id = server.wp.newPost( 0, args.wordpress_username, args.wordpress_password, { "post_title": thread["thread"]["title"], "post_content": html, }) if args.publish: server.mt.publishPost(post_id, args.wordpress_username, args.wordpress_password)
def receive(self, message): addresses = message.to.split(',') thread_id = "" token = "" client = None for address in addresses: try: (to, domain) = address.split('@') (thread_id, token) = to.split('+', 1) except: pass if len(thread_id) in [11, 12] and len(token) > 0: client = quip.QuipClient(access_token=token, request_timeout=30) try: client.get_thread(thread_id) break except Exception as e: client = None logging.exception(e) client = quip.QuipClient(access_token=to, request_timeout=30) try: client.get_authenticated_user() thread_id = "" break except Exception as e: client = None logging.exception(e) if not client: logging.error("Could not find token in %r", addresses) self.abort(404) text = None for content_type, body in message.bodies("text/plain"): text = body.decode() # Strip some common signature patterns for pattern in ["\n----", "\nIFTTT"]: if pattern in text: text = text[:text.find(pattern)] if len(text) > 0: break html = None for content_type, body in message.bodies("text/html"): html = body.decode() if len(html) > 0: break attachments = [] if hasattr(message, "attachments"): for filename, attachment in message.attachments: try: blob = files.blobstore.create( _blobinfo_uploaded_filename=filename) with files.open(blob, 'a') as f: f.write(attachment.decode()) files.finalize(blob) host = self.request.host_url.replace("http:", "https:") attachments.append( "%s/attach/%s" % (host, files.blobstore.get_blob_key(blob))) except Exception: pass message_id = None if "message-id" in message.original: message_id = message.original["message-id"] if thread_id: # Post a message args = { "silent": "silent" in message.subject, } if attachments: args["attachments"] = ",".join(attachments) if message_id: args["service_id"] = message_id client.new_message(thread_id, text, **args) else: # Create a thread from the message body thread = client.new_document(html or text, format="html" if html else "markdown", title=message.subject) if attachments: client.new_message(thread["thread"]["id"], attachments=",".join(attachments))
#! /usr/bin/python import quip import time import sys from os.path import expanduser if len(sys.argv) <= 1: print "Please input arguments" exit() HOME = expanduser("~") ACCESS_TOKEN = open(HOME + "/.api/quip.apikey", 'r').read().split('\n')[0] THREAD_ID = "AYWAAAC1CSQ" try: client = quip.QuipClient(access_token=ACCESS_TOKEN) user = client.get_authenticated_user() record = " ".join(sys.argv[1:]) date = time.strftime("%Y%m%d %H:%M") thread = client.get_thread(THREAD_ID) line = [line for line in thread["html"].split('\n') if line != ""][1] title_scetion_id = line.split('\'')[1] content = "<p class='line'>" + date + " " + record + "</p>" edit_mode = 3 client.edit_document(THREAD_ID, content, edit_mode, "html", title_scetion_id) print date, record except: print "Failed"