Skip to content

Instantly share code, notes, and snippets.

@sinabigo
Created November 28, 2021 04:35
Show Gist options
  • Save sinabigo/5c8ae9cad22c77d1eb234bd1bfdfcb59 to your computer and use it in GitHub Desktop.
Save sinabigo/5c8ae9cad22c77d1eb234bd1bfdfcb59 to your computer and use it in GitHub Desktop.
message with dropbox python api client. Crappy python, my bad ## پیام با دراپ باکس
import asyncio
import aiohttp
from codetiming import Timer
import dropbox
import asyncio
import json
import logging
import os
import pathlib
import subprocess
import tempfile
import dropbox
import sys
import traceback
from dropbox.files import WriteMode
from dropbox.exceptions import ApiError, AuthError
from dropbox import DropboxOAuth2FlowNoRedirect
from typing import Optional
from codetiming import Timer
import discord
from discord.ext import commands
import rich
import uritools
import argparse
import contextlib
import datetime
import os
import six
import sys
import time
import unicodedata
import logging
LOGGER = logging.getLogger("try_dropbox")
# NOTE: /Dropbox/Apps/cerebro_downloads
DROPBOX_CEREBRO_TOKEN = os.environ.get("DROPBOX_CEREBRO_TOKEN")
# DEFAULT_DROPBOX_FOLDER = "/cerebro_downloads"
DEFAULT_DROPBOX_FOLDER = "/test_cerebro_downloads"
# list_files_in_folder()
LOCALFILE = 'data/croc.jpeg'
BACKUPPATH = '/croc.jpeg'
# Establish connection
def get_dropbox_client(token=DROPBOX_CEREBRO_TOKEN):
try:
dbx = dropbox.Dropbox(token)
print('Connected to Dropbox successfully')
except Exception as e:
print(str(e))
# Check that the access token is valid
try:
dbx.users_get_current_account()
except AuthError:
sys.exit("ERROR: Invalid access token; try re-generating an "
"access token from the app console on the web.")
return dbx
# explicit function to list files
def list_files_in_folder():
# here dbx is an object which is obtained
# by connecting to dropbox via token
dbx = get_dropbox_client()
try:
folder_path = DEFAULT_DROPBOX_FOLDER
# dbx object contains all functions that
# are required to perform actions with dropbox
files = dbx.files_list_folder(folder_path, recursive=True).entries
print("------------Listing Files in Folder------------ ")
for file in files:
# listing
print(file.name)
except Exception as ex:
print(str(ex))
exc_type, exc_value, exc_traceback = sys.exc_info()
# [ERROR] MEMES REPOSITORIES: exc_value: table memes already exists
LOGGER.error("Error Class: {}".format(str(ex.__class__)))
output = "[{}] {}: {}".format("UNEXPECTED", type(ex).__name__, ex)
LOGGER.warning(output)
LOGGER.error("exc_type: {}".format(exc_type))
LOGGER.error("exc_value: {}".format(exc_value))
traceback.print_tb(exc_traceback)
# import pdb;pdb.set_trace()
raise
def download_img():
# here dbx is an object which is obtained
# by connecting to dropbox via token
dbx = get_dropbox_client()
try:
# folder_path = DEFAULT_DROPBOX_FOLDER
with open("Prime_Numbers.txt", "wb") as f:
metadata, res = dbx.files_download(path=f"{DEFAULT_DROPBOX_FOLDER}/Ehp39giWsAIY7ES.jpeg")
f.write(res.content)
except Exception as ex:
print(str(ex))
exc_type, exc_value, exc_traceback = sys.exc_info()
# [ERROR] MEMES REPOSITORIES: exc_value: table memes already exists
LOGGER.error("Error Class: {}".format(str(ex.__class__)))
output = "[{}] {}: {}".format("UNEXPECTED", type(ex).__name__, ex)
LOGGER.warning(output)
LOGGER.error("exc_type: {}".format(exc_type))
LOGGER.error("exc_value: {}".format(exc_value))
traceback.print_tb(exc_traceback)
# import pdb;pdb.set_trace()
raise
@contextlib.contextmanager
def stopwatch(message):
"""Context manager to print how long a block of code took."""
t0 = time.time()
try:
yield
finally:
t1 = time.time()
print('Total elapsed time for %s: %.3f' % (message, t1 - t0))
def upload(dbx, fullname, folder, subfolder, name, overwrite=False):
"""Upload a file.
Return the request response, or None in case of error.
"""
path = '/%s/%s/%s' % (folder, subfolder.replace(os.path.sep, '/'), name)
while '//' in path:
path = path.replace('//', '/')
mode = (dropbox.files.WriteMode.overwrite
if overwrite
else dropbox.files.WriteMode.add)
mtime = os.path.getmtime(fullname)
with open(fullname, 'rb') as f:
data = f.read()
with stopwatch('upload %d bytes' % len(data)):
try:
res = dbx.files_upload(
data, path, mode,
client_modified=datetime.datetime(*time.gmtime(mtime)[:6]),
mute=True)
except dropbox.exceptions.ApiError as err:
print('*** API error', err)
return None
print('uploaded as', res.name.encode('utf8'))
return res
def upload_img():
# here dbx is an object which is obtained
# by connecting to dropbox via token
dbx = get_dropbox_client()
try:
# folder_path = DEFAULT_DROPBOX_FOLDER
dbx.files_upload("Potential headline: Game 5 a nail-biter as Warriors inch out Cavs", f"{DEFAULT_DROPBOX_FOLDER}/bossjones.jpeg")
with open("Prime_Numbers.txt", "wb") as f:
metadata, res = dbx.files_download(path=f"{DEFAULT_DROPBOX_FOLDER}/Ehp39giWsAIY7ES.jpeg")
f.write(res.content)
except Exception as ex:
print(str(ex))
exc_type, exc_value, exc_traceback = sys.exc_info()
# [ERROR] MEMES REPOSITORIES: exc_value: table memes already exists
LOGGER.error("Error Class: {}".format(str(ex.__class__)))
output = "[{}] {}: {}".format("UNEXPECTED", type(ex).__name__, ex)
LOGGER.warning(output)
LOGGER.error("exc_type: {}".format(exc_type))
LOGGER.error("exc_value: {}".format(exc_value))
traceback.print_tb(exc_traceback)
# import pdb;pdb.set_trace()
raise
# Uploads contents of LOCALFILE to Dropbox
def backup():
with open(LOCALFILE, 'rb') as f:
# We use WriteMode=overwrite to make sure that the settings in the file
# are changed on upload
print("Uploading " + LOCALFILE + " to Dropbox as " + BACKUPPATH + "...")
try:
dbx.files_upload(f.read(), BACKUPPATH, mode=WriteMode('overwrite'))
except ApiError as err:
# This checks for the specific error where a user doesn't have
# enough Dropbox space quota to upload this file
if (err.error.is_path() and
err.error.get_path().reason.is_insufficient_space()):
sys.exit("ERROR: Cannot back up; insufficient space.")
elif err.user_message_text:
print(err.user_message_text)
sys.exit()
else:
print(err)
sys.exit()
# Change the text string in LOCALFILE to be new_content
# @param new_content is a string
def change_local_file(new_content):
print("Changing contents of " + LOCALFILE + " on local machine...")
with open(LOCALFILE, 'wb') as f:
f.write(new_content)
# Look at all of the available revisions on Dropbox, and return the oldest one
def select_revision():
# Get the revisions for a file (and sort by the datetime object, "server_modified")
print("Finding available revisions on Dropbox...")
entries = dbx.files_list_revisions(BACKUPPATH, limit=30).entries
revisions = sorted(entries, key=lambda entry: entry.server_modified)
for revision in revisions:
print(revision.rev, revision.server_modified)
# Return the oldest revision (first entry, because revisions was sorted oldest:newest)
return revisions[0].rev
def cli_oauth():
'''
This example walks through a basic oauth flow using the existing long-lived token type
Populate your app key and app secret in order to run this locally
'''
auth_flow = DropboxOAuth2FlowNoRedirect(DROPBOX_CEREBRO_APP_KEY, DROPBOX_CEREBRO_APP_SECRET)
authorize_url = auth_flow.start()
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
auth_code = input("Enter the authorization code here: ").strip()
try:
oauth_result = auth_flow.finish(auth_code)
except Exception as e:
print('Error: %s' % (e,))
exit(1)
with dropbox.Dropbox(oauth2_access_token=oauth_result.access_token) as dbx:
dbx.users_get_current_account()
print("Successfully set up client!")
backup()
dbx = get_dropbox_client()
import bpdb
bpdb.set_trace()
print(dbx)
to_rev = select_revision()
list_files_in_folder()
backup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment