# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#

# Asena UserBot - Yusuf Usta


""" Di�른r kategorilere uymayan fazlal캼k komutlar캼n yer ald캼��캼 mod칲l. """

import twitter_scraper
import os
import time
import asyncio
import shutil
from bs4 import BeautifulSoup
import re
from time import sleep
from html import unescape
from re import findall
from selenium import webdriver
from urllib.parse import quote_plus
from urllib.error import HTTPError
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from wikipedia import summary
from wikipedia.exceptions import DisambiguationError, PageError
from urbandict import define
from requests import get
from search_engine_parser import GoogleSearch
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googletrans import LANGUAGES, Translator
translator = Translator(service_urls=[
      'translate.google.cn',
])
from gtts import gTTS
from gtts.lang import tts_langs
from emoji import get_emoji_regexp
from youtube_dl import YoutubeDL
from youtube_dl.utils import (DownloadError, ContentTooShortError,
                              ExtractorError, GeoRestrictedError,
                              MaxDownloadsReached, PostProcessingError,
                              UnavailableVideoError, XAttrMetadataError)
from asyncio import sleep
from userbot import CMD_HELP, BOTLOG, BOTLOG_CHATID, YOUTUBE_API_KEY, CHROME_DRIVER, GOOGLE_CHROME_BIN
from userbot.events import register
from telethon.tl.types import DocumentAttributeAudio
from userbot.modules.upload_download import progress, humanbytes, time_formatter
from ImageDown import ImageDown
import base64, binascii
import random
from userbot.cmdhelp import CmdHelp
import requests
import urllib.parse
import aiohttp

CARBONLANG = "auto"
TTS_LANG = "tr"
TRT_LANG = "tr"


from telethon import events
import subprocess
from telethon.errors import MessageEmptyError, MessageTooLongError, MessageNotModifiedError
import io
import glob
from json import loads
from requests import get

@register(pattern="^.tts2 (.*)", outgoing=True)
async def tts2(query):
    textx = await query.get_reply_message()
    mesj = query.pattern_match.group(1)
    parca = mesj.split(" ")[0]
    if parca == "kad캼n":
        cins = "female"
    else:
        cins = "male"

    message = mesj.replace(parca, "")
    if message:
        pass
    elif textx:
        message = textx.text
    else:
        await query.edit(
            "`Yaz캼dan sese 칞evirmek i칞in bir metin gir. Kullan캼m: .tts2 erkek/kad캼n merhaba`")
        return

    mp3 = get(f"https://texttospeech.responsivevoice.org/v1/text:synthesize?text={message}&lang={TTS_LANG}&engine=g3&name=&pitch=0.5&rate=0.5&volume=1&key=AsenaUserbot&gender={cins}").content
    with open("h.mp3", "wb") as audio:
        audio.write(mp3)
    await query.client.send_file(query.chat_id, "h.mp3", voice_note=True)
    os.remove("h.mp3")
    await query.delete()

@register(pattern="^.reddit ?(.*)", outgoing=True)
async def reddit(event):
    sub = event.pattern_match.group(1)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36 Avast/77.2.2153.120',
    }       

    if len(sub) < 1:
        await event.edit("`L칲tfen bir Subreddit belirtin. 칐rnek: ``.reddit kopyamakarna`")
        return

    kaynak = get(f"https://www.reddit.com/r/{sub}/hot.json?limit=1", headers=headers).json()

    if not "kind" in kaynak:
        if kaynak["error"] == 404:
            await event.edit("`B칬yle bir Subreddit bulunamad캼.`")
        elif kaynak["error"] == 429:
            await event.edit("`Reddit yava�륿aman i칞in uyar캼yor.`")
        else:
            await event.edit("`Bir �른yler oldu ama... Neden oldu bilmiyorum.`")
        return
    else:
        await event.edit("`Veriler getiriliyor...`")

        veri = kaynak["data"]["children"][0]["data"]
        mesaj = f"**{veri['title']}**\n拘�勇끝veri['score']}\n\nBy: __u/{veri['author']}__\n\n[Link](https://reddit.com{veri['permalink']})"
        try:
            resim = veri["url"]
            with open(f"reddit.jpg", 'wb') as load:
                load.write(get(resim).content)

            await event.client.send_file(event.chat_id, "reddit.jpg", caption=mesaj)
            os.remove("reddit.jpg")
        except Exception as e:
            print(e)
            await event.edit(mesaj + "\n\n`" + veri["selftext"] + "`")

@register(pattern="^.twit ?(.*)", outgoing=True)
async def twit(event):
    hesap = event.pattern_match.group(1)
    if len(hesap) < 1:
        await event.edit("`L칲tfen bir Twitter hesab캼 belirtin. 칐rnek: ``.twit st4r_m0rn1ng`")
        return
    try:
        twits = list(twitter_scraper.get_tweets(hesap, pages=1))
    except Exception as e:
        await event.edit(f"`Muhtemelen b칬yle bir hesap yok. 칂칲nk칲 hata olu�릆u. Hata: {e}`")
        return

    if len(twits) > 2:
        if twits[0]["tweetId"] < twits[1]["tweetId"]:
            twit = twits[1]
            fotolar = twit['entries']['photos']
            sonuc = []
            if len(fotolar) >= 1:
                i = 0
                while i < len(fotolar):
                    with open(f"{hesap}-{i}.jpg", 'wb') as load:
                        load.write(get(fotolar[i]).content)
                    sonuc.append(f"{hesap}-{i}.jpg")
                    i += 1
                await event.client.send_file(event.chat_id, sonuc, caption=f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
                await event.delete()
                return
            await event.edit(f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
        else:
            twit = twits[1]
            fotolar = twit['entries']['photos']
            sonuc = []
            if len(fotolar) >= 1:
                i = 0
                while i < len(fotolar):
                    with open(f"{hesap}-{i}.jpg", 'wb') as load:
                        load.write(get(fotolar[i]).content)
                    sonuc.append(f"{hesap}-{i}.jpg")
                    i += 1
                print(sonuc)
                await event.client.send_file(event.chat_id, sonuc, caption=f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
                await event.delete()
                return
            await event.edit(f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
        return
    else:
        twit = twits[0]
        fotolar = twit['entries']['photos']
        sonuc = []
        if len(fotolar) >= 1:
            i = 0
            while i < len(fotolar):
                with open(f"{hesap}-{i}.jpg", 'wb') as load:
                    load.write(get(fotolar[i]).content)
                sonuc.append(f"{hesap}-{i}.jpg")
                i += 1
            await event.client.send_file(event.chat_id, sonuc, caption=f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
            await event.delete()
            return
        await event.edit(f"**{hesap}**\n{twit['time']}\n\n`{twit['text']}`\n\n游눫{twit['replies']} 游대{twit['retweets']} 仇벒잺{twit['likes']}")
        return
        
@register(outgoing=True, pattern="^.haber(?: |$)(.*)")
async def haber(event):
    TURLER = ["guncel", "magazin", "spor", "ekonomi", "politika", "dunya"]
    cmd = event.pattern_match.group(1)
    if len(cmd) < 1:
            HABERURL = 'https://sondakika.haberler.com/'
    else:
        if cmd in TURLER:
            HABERURL = f'https://sondakika.haberler.com/{cmd}'
        else:
            await event.edit("`Yanl캼�� haber kategorisi! Bulunan kategoriler: .haber guncel/magazin/spor/ekonomi/politika/dunya`")
            return
    await event.edit("`Haberler Getiriliyor...`")

    haber = get(HABERURL).text
    kaynak = BeautifulSoup(haber, "lxml")
    haberdiv = kaynak.find_all("div", attrs={"class":"hblnContent"})
    i = 0
    HABERLER = ""
    while i < 3:
        HABERLER += "\n\n仇�勇�**" + haberdiv[i].find("a").text + "**\n"
        HABERLER += haberdiv[i].find("p").text
        i += 1

    await event.edit(f"**Son Dakika Haberler {cmd.title()}**" + HABERLER)

@register(outgoing=True, pattern="^.karbon ?(.*)")
async def karbon(e):
    cmd = e.pattern_match.group(1)
    if os.path.exists("@AsenaUserBot-Karbon.jpg"):
        os.remove("@AsenaUserBot-Karbon.jpg")

    if len(cmd) < 1:
        await e.edit("Kullan캼m: .karbon mesaj")    
    yanit = await e.get_reply_message()
    if yanit:
        cmd = yanit.message
    await e.edit("`L칲tfen bekleyiniz...`")    

    r = get(f"https://carbonnowsh.herokuapp.com/?code={cmd}")

    with open("@AsenaUserBot-Karbon.jpg", 'wb') as f:
        f.write(r.content)    

    await e.client.send_file(e.chat_id, file="@AsenaUserBot-Karbon.jpg", force_document=True, caption="[AsenaUserBot](https://t.me/asenauserbot) ile olu�릆uruldu.")
    await e.delete()

@register(outgoing=True, pattern="^.crblang (.*)")
async def setlang(prog):
    global CARBONLANG
    CARBONLANG = prog.pattern_match.group(1)
    await prog.edit(f"Karbon mod칲l칲 i칞in varsay캼lan dil {CARBONLANG} olarak ayarland캼.")


@register(outgoing=True, pattern="^.carbon")
async def carbon_api(e):
    """ carbon.now.sh i칞in bir 칞e�를t wrapper """
    await e.edit("`캻�륿eniyor...`")
    CARBON = 'https://carbon.now.sh/?l={lang}&code={code}'
    global CARBONLANG
    textx = await e.get_reply_message()
    pcode = e.text
    if pcode[8:]:
        pcode = str(pcode[8:])
    elif textx:
        pcode = str(textx.message)  # Girilen metin, mod칲le aktar캼l캼yor.
    code = quote_plus(pcode)  # 칂칬z칲lm칲�� url'ye d칬n칲�릆칲r칲l칲yor.
    await e.edit("`캻�륿eniyor...\nTamamlanma Oran캼: 25%`")
    if os.path.isfile("./carbon.png"):
        os.remove("./carbon.png")
    url = CARBON.format(code=code, lang=CARBONLANG)
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=1920x1080")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-gpu")
    prefs = {'download.default_directory': './'}
    chrome_options.add_experimental_option('prefs', prefs)
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    await e.edit("`캻�륿eniyor...\nTamamlanma Oran캼: 50%`")
    download_path = './'
    driver.command_executor._commands["send_command"] = (
        "POST", '/session/$sessionId/chromium/send_command')
    params = {
        'cmd': 'Page.setDownloadBehavior',
        'params': {
            'behavior': 'allow',
            'downloadPath': download_path
        }
    }
    command_result = driver.execute("send_command", params)
    driver.find_element_by_xpath("//button[contains(text(),'Export')]").click()
    # driver.find_element_by_xpath("//button[contains(text(),'4x')]").click()
    # driver.find_element_by_xpath("//button[contains(text(),'PNG')]").click()
    await e.edit("`캻�륿eniyor...\nTamamlanma Oran캼: 75%`")
    # 캻ndirme i칞in bekleniyor
    while not os.path.isfile("./carbon.png"):
        await sleep(0.5)
    await e.edit("`캻�륿eniyor...\nTamamlanma Oran캼: 100%`")
    file = './carbon.png'
    await e.edit("`Resim kar��캼ya y칲kleniyor...`")
    await e.client.send_file(
        e.chat_id,
        file,
        caption="Bu resim [Carbon](https://carbon.now.sh/about/) kullan캼larak yap캼ld캼,\
        \nbir [Dawn Labs](https://dawnlabs.io/) projesi.",
        force_document=True,
        reply_to=e.message.reply_to_msg_id,
    )

    os.remove('./carbon.png')
    driver.quit()
    # Kar��캼ya y칲klemenin ard캼ndan carbon.png kald캼r캼l캼yor
    await e.delete()  # Mesaj siliniyor

@register(outgoing=True, pattern="^.ceviri")
async def ceviri(e):
    # http://www.tamga.org/2016/01/web-tabanl-gokturkce-cevirici-e.html #
    await e.edit("`칂eviriliyor...`")
    textx = await e.get_reply_message()
    pcode = e.text
    if pcode[8:]:
        pcode = str(pcode[8:])
    elif textx:
        pcode = str(textx.message)  # Girilen metin, mod칲le aktar캼l캼yor.
    url = "http://www.tamga.org/2016/01/web-tabanl-gokturkce-cevirici-e.html"
    chrome_options = Options()
    chrome_options.add_argument("--headless")
    chrome_options.add_argument("--window-size=1920x1080")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-gpu")
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    driver.find_element_by_name("Latin_Metin").send_keys(pcode)
    Turk = driver.find_element_by_name("G칬kt칲rk_Metin").get_attribute("value")
    await e.edit(f"**칂eviri: T칲rk칞e -> K칬kT칲rk칞e**\n\n**Verilen Metin:** `{pcode}`\n**칂캼kt캼:** `{Turk}`")


@register(outgoing=True, pattern="^.img((\d*)| ) ?(.*)")
async def img_sampler(event):
    """ .img komutu Google'da resim aramas캼 yapar. """
    await event.edit("`캻�륿eniyor...`")
    query = event.pattern_match.group(3)
    if event.pattern_match.group(2):
        try:
            limit = int(event.pattern_match.group(2))
        except:
            return await event.edit('**L칲tfen d칲zg칲n bir bi칞imde kelimenizi yaz캼n캼z!**\n칐rnek: `.img system of a down`')
    else:
        limit = 5
    await event.edit(f"`{limit} adet {query} resimi indiriliyor...`")
    ig = ImageDown().Yandex(query, limit)
    ig.get_urls()
    paths = ig.download()
    await event.edit('`Telegram\'a Y칲kleniyor...`')
    await event.client.send_file(event.chat_id, paths, caption=f'**캻�릆e** `{limit}` **adet** `{query}` **resimi**')
    await event.delete()

    for path in paths:
        os.remove(path)

@register(outgoing=True, pattern="^.currency ?(.*)")
async def moni(event):
    input_str = event.pattern_match.group(1)
    input_sgra = input_str.split(" ")
    if len(input_sgra) == 3:
        try:
            number = float(input_sgra[0])
            currency_from = input_sgra[1].upper()
            currency_to = input_sgra[2].upper()
            request_url = "https://api.exchangeratesapi.io/latest?base={}".format(
                currency_from)
            current_response = get(request_url).json()
            if currency_to in current_response["rates"]:
                current_rate = float(current_response["rates"][currency_to])
                rebmun = round(number * current_rate, 2)
                await event.edit("{} {} = {} {}".format(
                    number, currency_from, rebmun, currency_to))
            else:
                await event.edit(
                    "`Yazd캼��캼n �른y uzayl캼lar캼n kulland캼��캼 bir para birimine benziyor, bu y칲zden d칬n칲�릆칲remiyorum.`"
                )
        except Exception as e:
            await event.edit(str(e))
    else:
        await event.edit("`S칬zdizimi hatas캼.`")
        return


@register(outgoing=True, pattern=r"^.google ?(.*)")
async def gsearch(q_event):
    """ .google komutu ile basit Google aramalar캼 ger칞ekle�릆irilebilir """
    match = q_event.pattern_match.group(1)
    page = findall(r"page=\d+", match)
    try:
        page = page[0]
        page = page.replace("page=", "")
        match = match.replace("page=" + page[0], "")
    except IndexError:
        page = 1
    search_args = (str(match), int(page))
    gsearch = GoogleSearch()
    gresults = await gsearch.async_search(*search_args)
    msg = ""
    for i in range(10):
        try:
            title = gresults["titles"][i]
            link = gresults["links"][i]
            desc = gresults["descriptions"][i]
            msg += f"[{title}]({link})\n`{desc}`\n\n"
        except IndexError:
            break
    await q_event.edit("**Arama Sorgusu:**\n`" + match + "`\n\n**Sonu칞lar:**\n" +
                       msg,
                       link_preview=False)

    if BOTLOG:
        await q_event.client.send_message(
            BOTLOG_CHATID,
            match + "`s칬zc칲��칲 ba�르r캼yla Google'da arat캼ld캼!`",
        )


@register(outgoing=True, pattern=r"^.wiki (.*)")
async def wiki(wiki_q):
    """ .wiki komutu Vikipedi 칲zerinden bilgi 칞eker. """
    match = wiki_q.pattern_match.group(1)
    try:
        summary(match)
    except DisambiguationError as error:
        await wiki_q.edit(f"Belirsiz bir sayfa bulundu.\n\n{error}")
        return
    except PageError as pageerror:
        await wiki_q.edit(f"Arad캼��캼n캼z sayfa bulunamad캼.\n\n{pageerror}")
        return
    result = summary(match)
    if len(result) >= 4096:
        file = open("wiki.txt", "w+")
        file.write(result)
        file.close()
        await wiki_q.client.send_file(
            wiki_q.chat_id,
            "wiki.txt",
            reply_to=wiki_q.id,
            caption="`Sonu칞 칞ok uzun, dosya yoluyla g칬nderiliyor...`",
        )
        if os.path.exists("wiki.txt"):
            os.remove("wiki.txt")
        return
    await wiki_q.edit("**Arama:**\n`" + match + "`\n\n**Sonu칞:**\n" + result)
    if BOTLOG:
        await wiki_q.client.send_message(
            BOTLOG_CHATID, f"{match}` teriminin Wikipedia sorgusu ba�르r캼yla ger칞ekle�릆irildi!`")


@register(outgoing=True, pattern="^.ud (.*)")
async def urban_dict(ud_e):
    """ .ud komutu Urban Dictionary'den bilgi 칞eker. """
    await ud_e.edit("캻�륿eniyor...")
    query = ud_e.pattern_match.group(1)
    try:
        define(query)
    except HTTPError:
        await ud_e.edit(f"칖zg칲n칲m, {query} i칞in hi칞bir sonu칞 bulunamad캼.")
        return
    mean = define(query)
    deflen = sum(len(i) for i in mean[0]["def"])
    exalen = sum(len(i) for i in mean[0]["example"])
    meanlen = deflen + exalen
    if int(meanlen) >= 0:
        if int(meanlen) >= 4096:
            await ud_e.edit("`Sonu칞 칞ok uzun, dosya yoluyla g칬nderiliyor...`")
            file = open("urbandictionary.txt", "w+")
            file.write("Sorgu: " + query + "\n\nAnlam캼: " + mean[0]["def"] +
                       "\n\n" + "칐rnek: \n" + mean[0]["example"])
            file.close()
            await ud_e.client.send_file(
                ud_e.chat_id,
                "urbandictionary.txt",
                caption="`Sonu칞 칞ok uzun, dosya yoluyla g칬nderiliyor...`")
            if os.path.exists("urbandictionary.txt"):
                os.remove("urbandictionary.txt")
            await ud_e.delete()
            return
        await ud_e.edit("Sorgu: **" + query + "**\n\nAnlam캼: **" +
                        mean[0]["def"] + "**\n\n" + "칐rnek: \n__" +
                        mean[0]["example"] + "__")
        if BOTLOG:
            await ud_e.client.send_message(
                BOTLOG_CHATID,
                query + "`s칬zc칲��칲n칲n UrbanDictionary sorgusu ba�르r캼yla ger칞ekle�릆irildi!`")
    else:
        await ud_e.edit(query + "**i칞in hi칞bir sonu칞 bulunamad캼**")


@register(outgoing=True, pattern=r"^.tts(?: |$)([\s\S]*)")
async def text_to_speech(query):
    textx = await query.get_reply_message()
    message = query.pattern_match.group(1)
    if message:
        pass
    elif textx:
        message = textx.text
    else:
        await query.edit(
            "`Yaz캼dan sese 칞evirmek i칞in bir metin gir.`")
        return

    URL = "https://translate.google.com/translate_tts?ie=UTF-8&q=" + deEmojify(message) + "&tl=" + TTS_LANG + "&client=tw-ob"
    SAVE = "./tts.mp3"
    resp = requests.get(URL)
    with open(SAVE, "wb") as f:
        f.write(resp.content)

    await query.client.send_file(query.chat_id, "./tts.mp3", voice_note=True)
    if BOTLOG:
        await query.client.send_message(
            BOTLOG_CHATID, "Metin ba�르r캼yla sese d칬n칲�릆칲r칲ld칲!")
    await query.delete()
    os.remove("./tts.mp3")

@register(outgoing=True, pattern="^.imdb (.*)")
async def imdb(e):
    try:
        movie_name = e.pattern_match.group(1)
        remove_space = movie_name.split(' ')
        final_name = '+'.join(remove_space)
        page = get("https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name +
                   "&s=all")
        lnk = str(page.status_code)
        soup = BeautifulSoup(page.content, 'lxml')
        odds = soup.findAll("tr", "odd")
        mov_title = odds[0].findNext('td').findNext('td').text
        mov_link = "http://www.imdb.com/" + \
            odds[0].findNext('td').findNext('td').a['href']
        page1 = get(mov_link)
        soup = BeautifulSoup(page1.content, 'lxml')
        if soup.find('div', 'poster'):
            poster = soup.find('div', 'poster').img['src']
        else:
            poster = ''
        if soup.find('div', 'title_wrapper'):
            pg = soup.find('div', 'title_wrapper').findNext('div').text
            mov_details = re.sub(r'\s+', ' ', pg)
        else:
            mov_details = ''
        credits = soup.findAll('div', 'credit_summary_item')
        if len(credits) == 1:
            director = credits[0].a.text
            writer = 'Not available'
            stars = 'Not available'
        elif len(credits) > 2:
            director = credits[0].a.text
            writer = credits[1].a.text
            actors = []
            for x in credits[2].findAll('a'):
                actors.append(x.text)
            actors.pop()
            stars = actors[0] + ',' + actors[1] + ',' + actors[2]
        else:
            director = credits[0].a.text
            writer = 'Not available'
            actors = []
            for x in credits[1].findAll('a'):
                actors.append(x.text)
            actors.pop()
            stars = actors[0] + ',' + actors[1] + ',' + actors[2]
        if soup.find('div', "inline canwrap"):
            story_line = soup.find('div',
                                   "inline canwrap").findAll('p')[0].text
        else:
            story_line = 'Not available'
        info = soup.findAll('div', "txt-block")
        if info:
            mov_country = []
            mov_language = []
            for node in info:
                a = node.findAll('a')
                for i in a:
                    if "country_of_origin" in i['href']:
                        mov_country.append(i.text)
                    elif "primary_language" in i['href']:
                        mov_language.append(i.text)
        if soup.findAll('div', "ratingValue"):
            for r in soup.findAll('div', "ratingValue"):
                mov_rating = r.strong['title']
        else:
            mov_rating = 'Not available'
        await e.edit('<a href=' + poster + '>&#8203;</a>'
                     '<b>Ba�륿캼k : </b><code>' + mov_title + '</code>\n<code>' +
                     mov_details + '</code>\n<b>Reyting : </b><code>' +
                     mov_rating + '</code>\n<b>칖lke : </b><code>' +
                     mov_country[0] + '</code>\n<b>Dil : </b><code>' +
                     mov_language[0] + '</code>\n<b>Y칬netmen : </b><code>' +
                     director + '</code>\n<b>Yazar : </b><code>' + writer +
                     '</code>\n<b>Y캼ld캼zlar : </b><code>' + stars +
                     '</code>\n<b>IMDB Url : </b>' + mov_link +
                     '\n<b>Konusu : </b>' + story_line,
                     link_preview=True,
                     parse_mode='HTML')
    except IndexError:
        await e.edit("Ge칞erli bir film ismi gir.")



@register(pattern="^.trt ?(.*)", outgoing=True)
async def translateme(trans):
    """ .trt komutu verilen metni Google 칂eviri kullanarak 칞evirir. """

    message = trans.pattern_match.group(1)
    textx = await trans.get_reply_message()

    if message:
        pass
    elif textx:
        message = textx.text
    else:
        return await trans.edit("`Bana 칞evirilecek bir metin ver!`")

    message = deEmojify(message)
    if len(message) > 2048:
        return await trans.edit("__Bu mesaj fazla uzun. Maxiumum 2048 karakter kullan캼n.__")

    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
        async with session.get(f"https://translate.google.com/m?hl=auto&sl=auto&tl={TRT_LANG}&ie=UTF-8&prev=_m&q={message}") as response:

            html = await response.text()
            fin = html.split('result-container">')[1].split('</div>')[0]
            if fin == message:
                return await trans.edit("__칖zg칲n칲m Bu Metni 칂eviremedim. L칲tfen Daha Anla��캼l캼r Bir �룐kilde Yaz캼n.__")
    

            transl_lan = LANGUAGES[f'{TRT_LANG.lower()}']
            reply_text = f"**�룟 dile 칞evrildi**: __{transl_lan.title()}__\n**Sonu칞:**\n\n{fin}"

            await trans.edit(reply_text)
            if BOTLOG:
                await trans.client.send_message(
                    BOTLOG_CHATID,
                    f"�룟 kelime az 칬nce {transl_lan.title()} diline 칞evirildi.\n\n{message}",
                )



@register(pattern=".lang (trt|tts) (.*)", outgoing=True)
async def lang(value):
    """ .lang komutu birka칞 mod칲l i칞in varsay캼lan dili de�를�릆irir. """
    util = value.pattern_match.group(1).lower()
    if util == "trt":
        scraper = "Translator"
        global TRT_LANG
        arg = value.pattern_match.group(2).lower()
        if arg in LANGUAGES:
            TRT_LANG = arg
            LANG = LANGUAGES[arg]
        else:
            await value.edit(
                f"`Ge칞ersiz dil kodu!`\n`Ge칞erli dil kodlar캼`:\n\n`{LANGUAGES}`"
            )
            return
    elif util == "tts":
        scraper = "Yaz캼dan Sese"
        global TTS_LANG
        arg = value.pattern_match.group(2).lower()
        if arg in tts_langs():
            TTS_LANG = arg
            LANG = tts_langs()[arg]
        else:
            await value.edit(
                f"`Ge칞ersiz dil kodu!`\n`Ge칞erli dil kodlar캼`:\n\n`{LANGUAGES}`"
            )
            return
    await value.edit(f"`{scraper} mod칲l칲 i칞in varsay캼lan dil {LANG.title()} diline 칞evirildi.`")
    if BOTLOG:
        await value.client.send_message(
            BOTLOG_CHATID,
            f"`{scraper} mod칲l칲 i칞in varsay캼lan dil {LANG.title()} diline 칞evirildi.`")


@register(outgoing=True, pattern="^.yt (.*)")
async def yt_search(video_q):
    """ .yt komutu YouTube 칲zerinde arama yapar. """
    query = video_q.pattern_match.group(1)
    result = ''

    if not YOUTUBE_API_KEY:
        await video_q.edit(
            "`Hata: YouTube API anahtar캼 tan캼mlanmam캼��!`"
        )
        return

    await video_q.edit("```캻�륿eniyor...```")

    full_response = await youtube_search(query)
    videos_json = full_response[1]

    for video in videos_json:
        title = f"{unescape(video['snippet']['title'])}"
        link = f"https://youtu.be/{video['id']['videoId']}"
        result += f"{title}\n{link}\n\n"

    reply_text = f"**Arama Sorgusu:**\n`{query}`\n\n**Sonu칞lar:**\n\n{result}"

    await video_q.edit(reply_text)


async def youtube_search(query,
                         order="relevance",
                         token=None,
                         location=None,
                         location_radius=None):
    """ Bir YouTube aramas캼 yap. """
    youtube = build('youtube',
                    'v3',
                    developerKey=YOUTUBE_API_KEY,
                    cache_discovery=False)
    search_response = youtube.search().list(
        q=query,
        type="video",
        pageToken=token,
        order=order,
        part="id,snippet",
        maxResults=10,
        location=location,
        locationRadius=location_radius).execute()

    videos = []

    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            videos.append(search_result)
    try:
        nexttok = search_response["nextPageToken"]
        return (nexttok, videos)
    except HttpError:
        nexttok = "last_page"
        return (nexttok, videos)
    except KeyError:
        nexttok = "API anahtar캼 hatas캼, l칲tfen yeniden dene."
        return (nexttok, videos)


@register(outgoing=True, pattern=r".rip(audio|video) (.*)")
async def download_video(v_url):
    """ .rip komutu ile YouTube ve birka칞 farkl캼 siteden medya 칞ekebilirsin. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`캻ndirmeye haz캼rlan캼yor...`")

    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True

    elif type == "video":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            '%(id)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True

    try:
        await v_url.edit("`Veri 칞ekiliyor, l칲tfen bekleyin...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`캻ndirilecek i칞erik fazla k캼sa.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Maalesef co��rafi k캼s캼tlamalar sebebiyle bu videoyla i�륿em yapamazs캼n.`")
        return
    except MaxDownloadsReached:
        await v_url.edit("`Maksimum indirme limitini a�릆캼n.`")
        return
    except PostProcessingError:
        await v_url.edit("`캻stek i�륿enirken bir hata olu�릆u.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Medya belirtilen dosya format캼nda mevcut de�를l.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`Bilgi 칞캼kar캼l캼rken bir hata ger칞ekle�릆i.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await v_url.edit(f"`�료rk캼 y칲klenmeye haz캼rlan캼yor:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Kar��캼ya y칲kleniyor...",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(f"`�료rk캼 y칲klenmeye haz캼rlan캼yor:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Kar��캼ya y칲kleniyor...",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()


def deEmojify(inputString):
    """ Emojileri ve di�른r g칲venli olmayan karakterleri metinden kald캼r캼r. """
    return get_emoji_regexp().sub(u'', inputString)

CmdHelp('scrapers').add_command(
    'img', '<limit> <kelime>', 'Google 칲zerinde h캼zl캼 bir resim aramas캼 yapar. Limit yazmazsan캼z 5 tane foto��raf getirir.', 'img10 system of a down'
).add_command(
    'currency', '<miktar> <d칬n칲�릆칲r칲lecek birim> <d칬n칲�른cek birim>', 'Yusufun T칲rk Liras캼 Botu gibi, ama bo�� kald캼��캼nda k캼zlara yazm캼yor.'
).add_command(
    'carbon', '<metin>', 'carbon.now.sh sitesini kullanarak yazd캼klar캼n캼n a������������캼r캼 �른kil g칬r칲nmesini sa�륿ar.'
).add_command(
    'crblang', '<dil>', 'Carbon i칞in dil ayarlar.'
).add_command(
    'karbon', '<metin>', 'Carbon ile ayn캼 ama daha h캼zl캼ms캼.'
).add_command(
    'google', '<kelime>', 'H캼zl캼 bir Google aramas캼 yapar.'
).add_command(
    'wiki', '<terim>', 'Bir Vikipedi aramas캼 ger칞ekle�릆irir.'
).add_command(
    'ud', '<terim>', 'Urban Dictionary aramas캼 yapman캼n kolay yolu?'
).add_command(
    'tts', '<metin>', 'Metni sese d칬n칲�릆칲r칲r.'
).add_command(
    'lang', '<dil>', 'tts ve trt i칞in dil ayarlay캼n.'
).add_command(
    'tts2', '<cinsiyet> <metin>', 'Metni sese d칬n칲�릆칲r칲r.', 'tts2 erkek selam'
).add_command(
    'trt', '<metin>', 'Basit bir 칞eviri mod칲l칲.'
).add_command(
    'yt', '<metin>', 'YouTube 칲zerinde bir arama yapar.'
).add_command(
    'haber', '<guncel/magazin/spor/ekonomi/politika/dunya>', 'Son dakika haberler.'
).add_command(
    'imdb', '<film>', 'Film hakk캼nda bilgi verir.'
).add_command(
    'ripaudio', '<ba�륿ant캼>', 'YouTube 칲zerinden (veya di�른r siteler) ses indirir.'
).add_command(
    'ripvideo', '<ba�륿ant캼>', 'YouTube 칲zerinden (veya di�른r siteler) video indirir.'
).add_info(
    '[Rip komutunun destekledi�를 siteler.](https://ytdl-org.github.io/youtube-dl/supportedsites.html)'
).add()