Example #1
0
async def generate_credentials(gdrive):
    """ - Only generate once for long run - """
    if helper.get_credentials(str(gdrive.from_id)) is not None:
        await gdrive.edit("`You already authorized token...`")
        await asyncio.sleep(1.5)
        return await gdrive.delete()
    """ - Generate credentials - """
    if G_DRIVE_DATA is not None:
        try:
            configs = json.loads(G_DRIVE_DATA)
        except json.JSONDecodeError:
            return await gdrive.edit(
                "`[AUTHENTICATE - ERROR]`\n\n"
                "`Status` : **BAD**\n"
                "`Reason` : **G_DRIVE_DATA** entity is not valid!")
    else:
        """ - Only for old user - """
        if G_DRIVE_CLIENT_ID is None and G_DRIVE_CLIENT_SECRET is None:
            return await gdrive.edit(
                "`[AUTHENTICATE - ERROR]`\n\n"
                "`Status` : **BAD**\n"
                "`Reason` : please get your **G_DRIVE_DATA** "
                "[here](https://telegra.ph/How-To-Setup-Google-Drive-04-03)")
        configs = {
            "installed": {
                "client_id": G_DRIVE_CLIENT_ID,
                "client_secret": G_DRIVE_CLIENT_SECRET,
                "auth_uri": GOOGLE_AUTH_URI,
                "token_uri": GOOGLE_TOKEN_URI,
            }
        }
    await gdrive.edit("`Creating credentials...`")
    flow = InstalledAppFlow.from_client_config(configs,
                                               SCOPES,
                                               redirect_uri=REDIRECT_URI)
    auth_url, _ = flow.authorization_url(access_type='offline',
                                         prompt='consent')
    msg = await gdrive.respond(
        "`Go to your BOTLOG group to authenticate token...`")
    async with gdrive.client.conversation(BOTLOG_CHATID) as conv:
        url_msg = await conv.send_message(
            "Please go to this URL:\n"
            f"{auth_url}\nauthorize then reply the code")
        r = conv.wait_event(
            events.NewMessage(outgoing=True, chats=BOTLOG_CHATID))
        r = await r
        code = r.message.message.strip()
        flow.fetch_token(code=code)
        creds = flow.credentials
        await asyncio.sleep(3.5)
        await gdrive.client.delete_messages(gdrive.chat_id, msg.id)
        await gdrive.client.delete_messages(BOTLOG_CHATID, [url_msg.id, r.id])
        """ - Unpack credential objects into strings - """
        creds = base64.b64encode(pickle.dumps(creds)).decode()
        await gdrive.edit("`Credentials created...`")
    helper.save_credentials(str(gdrive.from_id), creds)
    await gdrive.delete()
    return
Example #2
0
async def create_app(gdrive):
    """- Create google drive service app -"""
    creds = helper.get_credentials(str(gdrive.from_id))
    if creds is not None:
        """- Repack credential objects from strings -"""
        creds = pickle.loads(base64.b64decode(creds.encode()))
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            await gdrive.edit("`Refreshing credentials...`")
            """- Refresh credentials -"""
            creds.refresh(Request())
            helper.save_credentials(
                str(gdrive.from_id),
                base64.b64encode(pickle.dumps(creds)).decode())
        else:
            await gdrive.edit("`Credentials is empty, please generate it...`")
            return False
    return build('drive', 'v3', credentials=creds, cache_discovery=False)