async def blacklist_init(): try: global sql sql = import_module("darkbot.moduller.sql_helper.blacklist_sql") except: sql = None LOGS.warn( 'Karaliste özelliği çalıştırılamıyor, SQL bağlantısı bulunamadı')
async def amagnet_download(event): uri = [extract_args(event)] 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)
async def magnet_download(event): magnet_uri = extract_args(event) # 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)
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))
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
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
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
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.")
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")
async def lydia_init(): try: from darkbot.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")
async def welcome_to_chat(event): try: from darkbot.moduller.sql_helper.welcome_sql import get_current_welcome_settings from darkbot.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)
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 darkbot.moduller.sql_helper.pm_permit_sql import is_approved from darkbot.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.", )
# (at your option) any later version. # # DarKUserBot 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 darkbot 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"]