def blacklist_init():
    try:
        global sql
        sql = import_module('sedenecem.sql.blacklist_sql')
    except Exception as e:
        sql = None
        LOGS.warn('Karaliste özelliği çalıştırılamıyor, SQL bağlantısı bulunamadı')
Exemple #2
0
async def blacklist_init():
    try:
        import sedenbot.moduller.sql_helper.blacklist_sql as sql
    except:
        LOGS.warn(
            'Karaliste özelliği çalıştırılamıyor, SQL bağlantısı bulunamadı')
        sql = None
def autopic(client, message):
    args = extract_args(message)
    autopic = KEY_AUTOPP in TEMP_SETTINGS
    if args == 'disable':
        if autopic:
            del TEMP_SETTINGS[KEY_AUTOPP]
            edit(message, f'`{get_translation("autoppDisabled")}`')
            return
        else:
            edit(message, f'`{get_translation("autoppDisabledAlready")}`')
            return
    elif autopic:
        edit(message, f'`{get_translation("autoppEnabledAlready")}`')
        return

    TEMP_SETTINGS[KEY_AUTOPP] = True

    edit(message, f'`{get_translation("autoppProcess")}`')

    FONT_FILE = 'sedenecem/fonts/GoogleSans.ttf'

    downloaded_file_name = 'oldpp.png'
    photo = 'newpp.png'

    if path.exists(downloaded_file_name):
        LOGS.info(get_translation('autoppLog'))
    else:
        if AUTO_PP and len(AUTO_PP) > 0:
            with open(downloaded_file_name, 'wb') as load:
                load.write(get(AUTO_PP).content)
        else:
            try:
                profile_photo = client.get_profile_photos('me', limit=1)
                downloaded_file_name = download_media_wc(
                    profile_photo[0], downloaded_file_name)
            except BaseException:
                edit(message, f'`{get_translation("autoppConfig")}`')
                return

    edit(message, f'`{get_translation("autoppResult")}`')

    while KEY_AUTOPP in TEMP_SETTINGS:
        try:
            current_time = datetime.now().strftime('%H:%M')
            img = Image.open(downloaded_file_name)
            drawn_text = ImageDraw.Draw(img)
            fnt = ImageFont.truetype(FONT_FILE, 70)
            size = drawn_text.multiline_textsize(current_time, font=fnt)
            drawn_text.text(
                ((img.width - size[0]) / 2, (img.height - size[1])),
                current_time,
                font=fnt,
                fill=(255, 255, 255),
            )
            img.save(photo)
            client.set_profile_photo(photo=photo)
            remove(photo)
            sleep(60)
        except BaseException:
            return
async def blacklist_init():
    try:
        global sql
        sql = import_module("sedenbot.moduller.sql_helper.blacklist_sql")
    except:
        sql = None
        LOGS.warn(
            'Karaliste özelliği çalıştırılamıyor, SQL bağlantısı bulunamadı')
Exemple #5
0
def pmpermit_init():
    try:
        global sql
        from importlib import import_module
        sql = import_module('sedenecem.sql.pm_permit_sql')
    except Exception as e:
        sql = None
        LOGS.warn(f'{get_translation("pmpermitSqlLog")}')
        raise e
Exemple #6
0
def snips_init():
    try:
        global sql
        from importlib import import_module
        sql = import_module('sedenecem.sql.snips_sql')
    except Exception as e:
        sql = None
        LOGS.warn(f'{get_translation("snipsSqlLog")}')
        raise e
Exemple #7
0
def blacklist_init():
    try:
        global sql
        from importlib import import_module
        sql = import_module('sedenecem.sql.blacklist_sql')
    except Exception as e:
        sql = None
        LOGS.warn(get_translation('blacklistSqlLog'))
        raise e
def chat_init():
    try:
        global sql
        from importlib import import_module
        sql = import_module('sedenecem.sql.keep_read_sql')
    except Exception as e:
        sql = None
        LOGS.warn(get_translation('chatSqlLog'))
        raise e
def notes_init():
    try:
        global sql
        from importlib import import_module
        sql = import_module('sedenecem.sql.notes_sql')
    except Exception as e:
        sql = None
        LOGS.warn(get_translation('notesSqlLog'))
        raise e
Exemple #10
0
def globals_init():
    try:
        global sql, sql2
        from importlib import import_module

        sql = import_module('sedenecem.sql.gban_sql')
        sql2 = import_module('sedenecem.sql.gmute_sql')
    except Exception as e:
        sql = None
        sql2 = None
        LOGS.warn(get_translation('globalsSqlLog'))
        raise e
Exemple #11
0
async def upload_file(http, file_path, file_name, mime_type, event, parent_id):
    # Google Drive servis örneği oluşturur.
    drive_service = build("drive", "v2", http=http, cache_discovery=False)
    # Dosya tipi açıklaması
    media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=True)
    body = {
        "title": file_name,
        "description": "Seden UserBot kullanılarak yüklendi.",
        "mimeType": mime_type,
    }
    if parent_id:
        body["parents"] = [{"id": parent_id}]
    # İzinlerin açıklaması: Linke sahip olan herkes görebilir.
    # Diğer izinler şurada bulunabilir: https://developers.google.com/drive/v2/reference/permissions
    permissions = {
        "role": "reader",
        "type": "anyone",
        "value": None,
        "withLink": True
    }
    # Dosyayı ekler
    file = drive_service.files().insert(body=body, media_body=media_body)
    response = None
    display_message = ""
    while response is None:
        status, response = file.next_chunk()
        await asyncio.sleep(1)
        if status:
            percentage = int(status.progress() * 100)
            progress_str = "[{0}{1}] {2}%".format(
                "".join(["▰" for i in range(math.floor(percentage / 10))]),
                "".join(["▱"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2))
            current_message = f"Google Drive'a uploadlanıyor.\nDosya Adı: {file_name}\n{progress_str}"
            if display_message != current_message:
                try:
                    await event.edit(current_message)
                    display_message = current_message
                except Exception as e:
                    LOGS.info(str(e))
                    pass
    file_id = response.get("id")
    # Yeni izinleri ekler.
    drive_service.permissions().insert(fileId=file_id,
                                       body=permissions).execute()
    # Dosya örneğini tanımlar ve indirmek için bağlantıyı edinir.
    file = drive_service.files().get(fileId=file_id).execute()
    download_url = file.get("webContentLink")
    return download_url
Exemple #12
0
async def magnet_download(event):
    magnet_uri = event.pattern_match.group(1)
    # Magnet URI'ı kuyruğa ekler.
    try:
        download = aria2.add_magnet(magnet_uri)
    except Exception as e:
        LOGS.info(str(e))
        await event.edit("Hata:\n`" + str(e) + "`")
        return
    gid = download.gid
    await check_progress_for_dl(gid=gid, event=event, previous=None)
    await sleep(5)
    new_gid = await check_metadata(gid)
    await check_progress_for_dl(gid=new_gid, event=event, previous=None)
Exemple #13
0
async def amagnet_download(event):
    uri = [event.pattern_match.group(1)]
    try:  # URL'yi kuyruğa ekler.
        download = aria2.add_uris(uri, options=None, position=None)
    except Exception as e:
        LOGS.info(str(e))
        await event.edit("Hata :\n`{}`".format(str(e)))
        return
    gid = download.gid
    await check_progress_for_dl(gid=gid, event=event, previous=None)
    file = aria2.get_download(gid)
    if file.followed_by_ids:
        new_gid = await check_metadata(gid)
        await progress_status(gid=new_gid, event=event, previous=None)
Exemple #14
0
async def create_directory(http, directory_name, parent_id):
    drive_service = build("drive", "v2", http=http, cache_discovery=False)
    permissions = {
        "role": "reader",
        "type": "anyone",
        "value": None,
        "withLink": True
    }
    file_metadata = {
        "title": directory_name,
        "mimeType": G_DRIVE_DIR_MIME_TYPE
    }
    if parent_id:
        file_metadata["parents"] = [{"id": parent_id}]
    file = drive_service.files().insert(body=file_metadata).execute()
    file_id = file.get("id")
    drive_service.permissions().insert(fileId=file_id,
                                       body=permissions).execute()
    LOGS.info("Created Gdrive Folder:\nName: {}\nID: {} ".format(
        file.get("title"), file_id))
    return file_id
Exemple #15
0
async def check_progress_for_dl(gid, event, previous):
    complete = None
    while not complete:
        file = aria2.get_download(gid)
        complete = file.is_complete
        try:
            if not complete and not file.error_message:
                msg = f"\nİndirilen dosya: `{file.name}`"
                msg += f"\nHız: {file.download_speed_string()}"
                msg += f"\nİşlem: {file.progress_string()}"
                msg += f"\nToplam Boyut: {file.total_length_string()}"
                msg += f"\nDurum: {file.status}"
                msg += f"\nTahmini bitiş: {file.eta_string()}"
                if msg != previous:
                    await event.edit(msg)
                    msg = previous
            else:
                LOGS.info(str(file.error_message))
                await event.edit(f"`{msg}`")
            await sleep(5)
            await check_progress_for_dl(gid, event, previous)
            file = aria2.get_download(gid)
            complete = file.is_complete
            if complete:
                await event.edit(f"Dosya başarıyla indirdi: `{file.name}`"
                                 )
                return False
        except Exception as e:
            if " not found" in str(e) or "'file'" in str(e):
                await event.edit("İndirme iptal edildi :\n`{}`".format(file.name))
                await sleep(2.5)
                await event.delete()
                return
            elif " depth exceeded" in str(e):
                file.remove(force=True)
                await event.edit(
                    "İndirme otomatik olarak iptal edildi:\n`{}`\nTorrent ya da link ölü."
                    .format(file.name))
Exemple #16
0
def extract_w_h(file):
    """ Bir medyanın yüksekliğini-genişliğini gösterir. """
    command_to_run = [
        "ffprobe",
        "-v",
        "quiet",
        "-print_format",
        "json",
        "-show_format",
        "-show_streams",
        file,
    ]
    # https://stackoverflow.com/a/11236144/4723940
    try:
        t_response = subprocess.check_output(command_to_run,
                                             stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exc:
        LOGS.warning(exc)
    else:
        x_reponse = t_response.decode("UTF-8")
        response_json = json.loads(x_reponse)
        width = int(response_json["streams"][0]["width"])
        height = int(response_json["streams"][0]["height"])
        return width, height
Exemple #17
0
# (at your option) any later version.
#
# SedenUserBot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
""" Tüm modülleri yükleyen init dosyası """

from sedenbot import LOGS


def __list_all_modules():
    from os.path import dirname, basename, isfile
    import glob

    mod_paths = glob.glob(dirname(__file__) + "/*.py")
    all_modules = [
        basename(f)[:-3] for f in mod_paths
        if isfile(f) and f.endswith(".py") and not f.endswith("__init__.py")
    ]
    return all_modules


ALL_MODULES = sorted(__list_all_modules())
LOGS.info("Yüklenecek modüller: %s", str(ALL_MODULES))
__all__ = ALL_MODULES + ["ALL_MODULES"]
Exemple #18
0
async def uploadir(udir_event):
    """ .uploadir komutu bir klasördeki tüm dosyaları uploadlamanıza yarar """
    input_str = extract_args(udir_event)
    if os.path.exists(input_str):
        await udir_event.edit("İşleniyor...")
        lst_of_files = []
        for r, d, f in os.walk(input_str):
            for file in f:
                lst_of_files.append(os.path.join(r, file))
            for file in d:
                lst_of_files.append(os.path.join(r, file))
        LOGS.info(lst_of_files)
        uploaded = 0
        await udir_event.edit(
            " {} dosya bulundu. Upload birazdan başlayacak. Lütfen bekleyin :)"
            .format(len(lst_of_files)))
        for single_file in lst_of_files:
            if os.path.exists(single_file):
                # https://stackoverflow.com/a/678242/4723940
                caption_rts = os.path.basename(single_file)
                c_time = time.time()
                if not caption_rts.lower().endswith(".mp4"):
                    await udir_event.client.send_file(
                        udir_event.chat_id,
                        single_file,
                        caption=caption_rts,
                        force_document=False,
                        allow_cache=False,
                        reply_to=udir_event.message.id,
                        progress_callback=lambda d, t: asyncio.get_event_loop(
                        ).create_task(
                            progress(d, t, udir_event, c_time,
                                     "Uploadlanıyor...", single_file)))
                else:
                    thumb_image = os.path.join(input_str, "thumb.jpg")
                    c_time = time.time()
                    metadata = extractMetadata(createParser(single_file))
                    duration = 0
                    width = 0
                    height = 0
                    if metadata.has("duration"):
                        duration = metadata.get("duration").seconds
                    if metadata.has("width"):
                        width = metadata.get("width")
                    if metadata.has("height"):
                        height = metadata.get("height")
                    await udir_event.client.send_file(
                        udir_event.chat_id,
                        single_file,
                        caption=caption_rts,
                        thumb=thumb_image,
                        force_document=False,
                        allow_cache=False,
                        reply_to=udir_event.message.id,
                        attributes=[
                            DocumentAttributeVideo(
                                duration=duration,
                                w=width,
                                h=height,
                                round_message=False,
                                supports_streaming=True,
                            )
                        ],
                        progress_callback=lambda d, t: asyncio.get_event_loop(
                        ).create_task(
                            progress(d, t, udir_event, c_time,
                                     "Uploadlanıyor...", single_file)))
                os.remove(single_file)
                uploaded = uploaded + 1
        await udir_event.edit(
            "{} dosya başarıyla uploadlandı.".format(uploaded))
    else:
        await udir_event.edit("404: Directory Not Found")
Exemple #19
0
async def check_metadata(gid):
    file = aria2.get_download(gid)
    new_gid = file.followed_by_ids[0]
    LOGS.info("GID " + gid + " şu değerden şu değere değiştiriliyor:" + new_gid)
    return new_gid
Exemple #20
0
async def permitpm(event):
    UNAPPROVED_MSG = DEF_UNAPPROVED_MSG
    if 'PM_USER_MSG' in globals() and PM_USER_MSG:
        UNAPPROVED_MSG = PM_USER_MSG
    """ İzniniz olmadan size PM gönderenleri yasaklamak içindir. \
        Yazmaya devam eden kullanıcıları engeller. """
    if PM_AUTO_BAN:
        self_user = await event.client.get_me()
        if event.is_private and event.chat_id != 777000 and event.chat_id != self_user.id and not (
                await event.get_sender()).bot:
            try:
                from sedenbot.moduller.sql_helper.pm_permit_sql import is_approved
                from sedenbot.moduller.sql_helper.globals import gvarstatus
            except:
                return
            apprv = is_approved(event.chat_id)
            notifsoff = gvarstatus("NOTIF_OFF")

            # Bu bölüm basitçe akıl sağlığı kontrolüdür.
            # Eğer mesaj daha önceden onaylanmamış olarak gönderildiyse
            # flood yapmayı önlemek için unapprove mesajı göndermeyi durdurur.
            if not apprv and event.text != UNAPPROVED_MSG:
                if event.chat_id in LASTMSG:
                    prevmsg = LASTMSG[event.chat_id]
                    # Eğer önceden gönderilmiş mesaj farklıysa unapprove mesajı tekrardan gönderilir.
                    if event.text != prevmsg:
                        async for message in event.client.iter_messages(
                                event.chat_id,
                                from_user='******',
                                search=UNAPPROVED_MSG):
                            await message.delete()
                        await event.reply(UNAPPROVED_MSG)
                    LASTMSG.update({event.chat_id: event.text})
                else:
                    await event.reply(UNAPPROVED_MSG)
                    LASTMSG.update({event.chat_id: event.text})

                if notifsoff:
                    await event.client.send_read_acknowledge(event.chat_id)
                if event.chat_id not in COUNT_PM:
                    COUNT_PM.update({event.chat_id: 1})
                else:
                    COUNT_PM[event.chat_id] = COUNT_PM[event.chat_id] + 1

                if COUNT_PM[event.chat_id] > 4:
                    await event.respond(
                        "`Sen benim sahibimin PM'ini spamlıyorsun, bu benim hoşuma gitmiyor.`\n"
                        "`Şu an ENGELLENDIN ve SPAM olarak bildirildin, ileride değişiklik olmadığı sürece..`"
                    )

                    try:
                        del COUNT_PM[event.chat_id]
                        del LASTMSG[event.chat_id]
                    except KeyError:
                        if BOTLOG:
                            await event.client.send_message(
                                BOTLOG_CHATID,
                                "PM sayacı kafayı yemiş gibi, botu lütfen yeniden başlatın.",
                            )
                        LOGS.info(
                            "PM sayacı kafayı yemiş gibi, botu lütfen yeniden başlatın."
                        )
                        return

                    await event.client(BlockRequest(event.chat_id))
                    await event.client(ReportSpamRequest(peer=event.chat_id))

                    if BOTLOG:
                        name = await event.client.get_entity(event.chat_id)
                        name0 = str(name.first_name)
                        await event.client.send_message(
                            BOTLOG_CHATID,
                            "[" + name0 + "](tg://user?id=" +
                            str(event.chat_id) + ")" +
                            " kişisi sadece bir hayal kırıklığı idi. PM'ni meşgul ettiği için engellendi.",
                        )
Exemple #21
0
async def download(target_file):
    """ .download komutu userbot sunucusuna dosya indirmenizi sağlar. """
    await target_file.edit("İşleniyor...")
    input_str = extract_args(target_file)
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        # https://stackoverflow.com/a/761825/4723940
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            progress_str = "[{0}{1}] {2}%".format(
                ''.join(["▰" for i in range(math.floor(percentage / 10))]),
                ''.join(["▱"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2))
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"{status}..\
                \nBağlantı: {url}\
                \nDosya adı: {file_name}\
                \n{progress_str}\
                \n{humanbytes(downloaded)} of {humanbytes(total_length)}\
                \nTahmini bitiş: {estimated_total_time}"

                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await target_file.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
        if downloader.isSuccessful():
            await target_file.edit(
                "`{}` konumuna indirme başarılı.".format(downloaded_file_name))
        else:
            await target_file.edit("Geçersiz bağlantı\n{}".format(url))
    elif target_file.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await target_file.client.download_media(
                await target_file.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, target_file, c_time, "İndiriliyor...")))
        except Exception as e:  # pylint:disable=C0103,W0703
            await target_file.edit(str(e))
        else:
            await target_file.edit(
                "`{}` konumuna indirme başarılı.".format(downloaded_file_name))
    else:
        await target_file.edit("Sunucuma indirmek için bir mesajı yanıtlayın.")
Exemple #22
0
async def welcome_to_chat(event):
    try:
        from sedenbot.moduller.sql_helper.welcome_sql import get_current_welcome_settings
        from sedenbot.moduller.sql_helper.welcome_sql import update_previous_welcome
    except:
        return
    cws = get_current_welcome_settings(event.chat_id)
    if cws:
        """user_added=True,
        user_joined=True,
        user_left=False,
        user_kicked=False"""
        if (event.user_joined
                or event.user_added) and not (await event.get_user()).bot:
            if CLEAN_WELCOME:
                try:
                    await event.client.delete_messages(event.chat_id,
                                                       cws.previous_welcome)
                except Exception as e:
                    LOGS.warn(str(e))
            a_user = await event.get_user()
            chat = await event.get_chat()
            me = await event.client.get_me()

            title = chat.title if chat.title else "this chat"
            participants = await event.client.get_participants(chat)
            count = len(participants)
            mention = "[{}](tg://user?id={})".format(a_user.first_name,
                                                     a_user.id)
            my_mention = "[{}](tg://user?id={})".format(me.first_name, me.id)
            first = a_user.first_name
            last = a_user.last_name
            if last:
                fullname = f"{first} {last}"
            else:
                fullname = first
            username = f"@{a_user.username}" if a_user.username else mention
            userid = a_user.id
            my_first = me.first_name
            my_last = me.last_name
            if my_last:
                my_fullname = f"{my_first} {my_last}"
            else:
                my_fullname = my_first
            my_username = f"@{me.username}" if me.username else my_mention
            file_media = None
            current_saved_welcome_message = None
            if cws and cws.f_mesg_id:
                msg_o = await event.client.get_messages(entity=BOTLOG_CHATID,
                                                        ids=int(cws.f_mesg_id))
                file_media = msg_o.media
                current_saved_welcome_message = msg_o.message
            elif cws and cws.reply:
                current_saved_welcome_message = cws.reply
            current_message = await event.reply(
                current_saved_welcome_message.format(mention=mention,
                                                     title=title,
                                                     count=count,
                                                     first=first,
                                                     last=last,
                                                     fullname=fullname,
                                                     username=username,
                                                     userid=userid,
                                                     my_first=my_first,
                                                     my_last=my_last,
                                                     my_fullname=my_fullname,
                                                     my_username=my_username,
                                                     my_mention=my_mention),
                file=file_media)
            update_previous_welcome(event.chat_id, current_message.id)
Exemple #23
0
async def autopic(event):
    args = extract_args(event)
    if len(args) > 0 and args != 'disable':
        await event.edit('`Kullanım: .autopp / .autopp disable`')
        return

    if KEY_AUTOPP in ASYNC_POOL and len(args) < 1:
        await event.edit(
            "`Görünüşe göre profil fotoğrafınız zaten otomatik olarak değişiyor.`"
        )
        return

    if args == 'disable':
        if KEY_AUTOPP in ASYNC_POOL:
            ASYNC_POOL.remove(KEY_AUTOPP)
            await event.edit(
                '`Profil fotoğrafınız artık otomatik olarak değişmeyecek.`')
            return
        else:
            await event.edit(
                "`Görünüşe göre profil fotoğrafınız zaten otomatik olarak değişmiyor.`"
            )
            return

    await event.edit("`Profil fotoğrafınız ayarlanıyor ...`")

    FONT_FILE_TO_USE = await get_font_file(event.client, "@FontDunyasi")

    downloaded_file_name = "eskipp.png"
    photo = "yenipp.png"
    if os.path.exists(downloaded_file_name):
        LOGS.info('[AUTOPP] Dosya zaten mevcut, indirme atlanıyor ...')
    else:
        if AUTO_PP and len(AUTO_PP) > 0:
            with open(downloaded_file_name, 'wb') as load:
                load.write(get(AUTO_PP).content)
        else:
            try:
                await event.client.download_profile_photo(me.id,
                                                          downloaded_file_name,
                                                          download_big=True)
            except:
                await event.edit(
                    '`Lütfen AUTO_PP değişkeninizi ayarlayın veya bir profil fotoğrafı koyun.`'
                )
                return

    await event.edit("`Profil fotoğrafınız ayarlandı :)`")

    ASYNC_POOL.append(KEY_AUTOPP)

    while KEY_AUTOPP in ASYNC_POOL:
        current_time = datetime.now().strftime("%H:%M")
        img = Image.open(downloaded_file_name)
        drawn_text = ImageDraw.Draw(img)
        fnt = ImageFont.truetype(FONT_FILE_TO_USE, 70)
        size = drawn_text.multiline_textsize(current_time, font=fnt)
        drawn_text.text(((img.width - size[0]) / 2, (img.height - size[1])),
                        current_time,
                        font=fnt,
                        fill=(255, 255, 255))
        img.save(photo)
        file = await event.client.upload_file(photo)  # pylint:disable=E0602
        try:
            await event.client(
                functions.photos.UploadProfilePhotoRequest(  # pylint:disable=E0602
                    file))
            os.remove(photo)
            await asyncio.sleep(60)
        except:
            return
Exemple #24
0
async def gdrive_upload_function(dryb):
    """ .gdrive komutu dosyalarınızı Google Drive'a uploadlar. """
    await dryb.edit("İşleniyor ...")
    input_str = dryb.pattern_match.group(1)
    if CLIENT_ID is None or CLIENT_SECRET is None:
        return
    if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
        required_file_name = None
    if "|" in input_str:
        url, file_name = input_str.split("|")
        url = url.strip()
        # https://stackoverflow.com/a/761825/4723940
        file_name = file_name.strip()
        head, tail = os.path.split(file_name)
        if head:
            if not os.path.isdir(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head)):
                os.makedirs(os.path.join(TEMP_DOWNLOAD_DIRECTORY, head))
                file_name = os.path.join(head, tail)
        downloaded_file_name = TEMP_DOWNLOAD_DIRECTORY + "" + file_name
        downloader = SmartDL(url, downloaded_file_name, progress_bar=False)
        downloader.start(blocking=False)
        c_time = time.time()
        display_message = None
        while not downloader.isFinished():
            status = downloader.get_status().capitalize()
            total_length = downloader.filesize if downloader.filesize else None
            downloaded = downloader.get_dl_size()
            now = time.time()
            diff = now - c_time
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed()
            elapsed_time = round(diff) * 1000
            progress_str = "[{0}{1}] {2}%".format(
                ''.join(["▰" for i in range(math.floor(percentage / 10))]),
                ''.join(["▱"
                         for i in range(10 - math.floor(percentage / 10))]),
                round(percentage, 2))
            estimated_total_time = downloader.get_eta(human=True)
            try:
                current_message = f"{status}...\
                \nURL: {url}\
                \nDosya adı: {file_name}\
                \n{progress_str}\
                \n{humanbytes(downloaded)} of {humanbytes(total_length)}\
                \nBitiş: {estimated_total_time}"

                if round(diff %
                         10.00) == 0 and current_message != display_message:
                    await dryb.edit(current_message)
                    display_message = current_message
            except Exception as e:
                LOGS.info(str(e))
                pass
        if downloader.isSuccessful():
            await dryb.edit(
                "`{}` dizinine indirme başarılı. \nGoogle Drive'a yükleme başlatılıyor.."
                .format(downloaded_file_name))
            required_file_name = downloaded_file_name
        else:
            await dryb.edit("Geçersiz URL\n{}".format(url))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            required_file_name = input_str
            await dryb.edit(
                "`{}` dosyası sunucuda bulundu. Google Drive'a yükleme başlatılıyor.."
                .format(input_str))
        else:
            await dryb.edit(
                "Sunucuda dosya bulunamadı. Lütfen doğru dosya konumunu belirtin."
            )
            return False
    elif dryb.reply_to_msg_id:
        try:
            c_time = time.time()
            downloaded_file_name = await dryb.client.download_media(
                await dryb.get_reply_message(),
                TEMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(progress(d, t, dryb, c_time, "İndiriliyor...")))
        except Exception as e:
            await dryb.edit(str(e))
        else:
            required_file_name = downloaded_file_name
            await dryb.edit(
                "`{}` dizinine indirme başarrılı. \nGoogle Drive'a yükleme başlatılıyor.."
                .format(downloaded_file_name))
    if required_file_name:
        if G_DRIVE_AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(G_DRIVE_AUTH_TOKEN_DATA)
        # Token dosyasının olup olmadığını kontrol eder, eğer yoksa yetkilendirme kodu ile oluşturur.
        if not os.path.isfile(G_DRIVE_TOKEN_FILE):
            storage = await create_token_file(G_DRIVE_TOKEN_FILE, dryb)
            http = authorize(G_DRIVE_TOKEN_FILE, storage)
        # Yetkilendirir, dosya parametrelerini edinir, dosyayı uploadlar ve URL'yi indirme için paylaşır.
        http = authorize(G_DRIVE_TOKEN_FILE, None)
        file_name, mime_type = file_ops(required_file_name)
        # required_file_name tam dosya yoluna sahiptir.
        # Bazen API başlangıç URI'sini geri alırken hatayla karşılaşır.
        try:
            g_drive_link = await upload_file(http, required_file_name,
                                             file_name, mime_type, dryb,
                                             parent_id)
            await dryb.edit(
                f"Dosya :`{required_file_name}`\nUpload başarılı! \nİndirme linki: [Google Drive]({g_drive_link})!"
            )
        except Exception as e:
            await dryb.edit(
                f"Google Drive'a yükleme başarısız.\nHata kodu:\n`{e}`")
Exemple #25
0
async def lydia_init():
    try:
        from sedenbot.moduller.sql_helper.lydia_sql import get_s, get_all_s, add_s, remove_s
    except:
        LOGS.warn("Lydia veritabanı bağlantısı başarısız oldu")