', 'Belirtilen web sitesinden bir ekran görüntüsü alır ve gönderir.', 'ss https://fusuf.codes'
79 | ).add()
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | [No more support.](https://t.me/fusufs/826)
3 |
4 | ----
5 |
6 |
7 |

8 |
Asena UserBot
9 |
10 |
11 | Asena UserBot, Telegram kullanmanızı kolaylaştıran bir bottur. Tamamen açık kaynaklı ve ücretsizdir.
12 |
13 | Kurulum |
14 | Güncelleme |
15 | Telegram Kanalı
16 |
17 |
18 |
19 | ----
20 |  
21 | ## Kurulum
22 | ### Çok Basit Yöntem
23 | [Youtube Videosu](https://www.youtube.com/watch?v=mUUQ53TYqI0) 
24 |
25 | **Android:** Termuxu açın ve bu kodu yapıştırın: `bash <(curl -L https://kutt.it/88I5KA)`
26 |
27 | **iOS:** iSH açın ve bu kodu yapıştırın: `apk update && apk add bash && apk add curl && curl -L -o asena_installer.sh https://t.ly/vATX && chmod +x asena_installer.sh && bash asena_installer.sh`
28 |
29 | **Windows 10:** [Python](https://www.microsoft.com/en-us/p/python-38/9mssztt1n39l#activetab=pivot:overviewtab) indirin ardından PowerShell bu kodu yapıştırın: `Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://kutt.it/aYTzCx')`
30 |
31 | ### Basit Yöntem
32 | Eğer botu kurma hakkında fikriniz yoksa burayı okuyunuz: [Kurulum Rehberi](https://github.com/Quiec/AsenaUserBot/wiki/Kurulum/)
33 |
34 | [](https://heroku.com/deploy?template=https://github.com/Quiec/AsenaUserBot)
35 | ### Zor Yöntem
36 | ```python
37 | git clone https://github.com/Quiec/AsenaUserBot.git
38 | cd AsenaUserBot
39 | pip install -r requirements.txt
40 | # Config.env oluşturun ve düzenleyin. #
41 | python3 main.py
42 | ```
43 |
44 | ## Örnek Plugin
45 | ```python
46 | from userbot.events import register
47 | from userbot.cmdhelp import CmdHelp # <-- Bunu ekleyin.
48 |
49 | @register(outgoing=True, pattern="^.deneme")
50 | async def deneme(event):
51 | await event.edit('Gerçekten deneme!')
52 |
53 | Help = CmdHelp('deneme') # Bilgi ekleyeceğiz diyoruz.
54 | Help.add_command('deneme', # Komut
55 | None, # Komut parametresi varsa yazın yoksa None yazın
56 | 'Gerçekten deneme yapıyor!', # Komut açıklaması
57 | 'deneme' # Örnek kullanım.
58 | )
59 | Help.add_info('@Fusuf tarafından yapılmıştır.') # Bilgi ekleyebilirsiniz.
60 | # Ya da uyarı --> Help.add_warning('KULLANMA!')
61 | Help.add() # Ve Ekleyelim.
62 | ```
63 |
64 | ## Bilgilendirme
65 | Herhangi bir istek & şikâyet & öneri varsa [destek grubuna](https://t.me/AsenaSupport) ulaşabilirsiniz.
66 |
67 | ```
68 | Userbottan dolayı; Telegram hesabınız yasaklanabilir.
69 | Bu bir açık kaynaklı projedir, yaptığınız her işlemden kendiniz sorumlusunuz. Kesinlikle Asena yöneticileri sorumluluk kabul etmemektedir.
70 | Asenayı kurarak bu sorumlulukları kabul etmiş sayılırsınız.
71 | ```
72 |
73 | ## Credit
74 | Thanks for;
75 |
76 | [Seden UserBot](https://github.com/TeamDerUntergang/Telegram-UserBot)
77 |
78 | [Userge](https://github.com/UsergeTeam/Userge)
79 |
80 | [Spechide](https://github.com/Spechide)
81 |
--------------------------------------------------------------------------------
/userbot/modules/dil.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | from userbot.cmdhelp import CmdHelp
10 | from userbot import PLUGIN_CHANNEL_ID, CMD_HELP
11 | from userbot.events import register
12 | from re import search
13 | from json import loads, JSONDecodeError
14 | from userbot.language import LANGUAGE_JSON
15 | from os import remove
16 |
17 | @register(outgoing=True, pattern="^.dil ?(.*)")
18 | @register(outgoing=True, pattern="^.lang ?(.*)")
19 | async def dil(event):
20 | global LANGUAGE_JSON
21 |
22 | komut = event.pattern_match.group(1)
23 | if search(r"y[uü]kle|install", komut):
24 | await event.edit("`Dil dosyası yükleniyor... Lütfen bekleyiniz.`")
25 | if event.is_reply:
26 | reply = await event.get_reply_message()
27 | dosya = await reply.download_media()
28 |
29 | if ((len(reply.file.name.split(".")) >= 2) and (not reply.file.name.split(".")[1] == "asenajson")):
30 | return await event.edit("`Lütfen geçerli bir` **AsenaJSON** `dosyası verin!`")
31 |
32 | try:
33 | dosya = loads(open(dosya, "r").read())
34 | except JSONDecodeError:
35 | return await event.edit("`Lütfen geçerli bir` **AsenaJSON** `dosyası verin!`")
36 |
37 | await event.edit(f"`{dosya['LANGUAGE']}` `dili yükleniyor...`")
38 | pchannel = await event.client.get_entity(PLUGIN_CHANNEL_ID)
39 |
40 | dosya = await reply.download_media(file="./userbot/language/")
41 | dosya = loads(open(dosya, "r").read())
42 | await reply.forward_to(pchannel)
43 |
44 | LANGUAGE_JSON = dosya
45 | await event.edit(f"✅ `{dosya['LANGUAGE']}` `dili başarıyla yüklendi!`\n\n**İşlemlerin geçerli olması için botu yeniden başlatın!**")
46 | else:
47 | await event.edit("**Lütfen bir dil dosyasına yanıt verin!**")
48 | elif search(r"bilgi|info", komut):
49 | await event.edit("`Dil dosyası bilgileri getiriliyor... Lütfen bekleyiniz.`")
50 | if event.is_reply:
51 | reply = await event.get_reply_message()
52 | if ((len(reply.file.name.split(".")) >= 1) and (not reply.file.name.split(".")[1] == "asenajson")):
53 | return await event.edit("`Lütfen geçerli bir` **AsenaJSON** `dosyası verin!`")
54 |
55 | dosya = await reply.download_media()
56 |
57 | try:
58 | dosya = loads(open(dosya, "r").read())
59 | except JSONDecodeError:
60 | return await event.edit("`Lütfen geçerli bir` **AsenaJSON** `dosyası verin!`")
61 |
62 | await event.edit(
63 | f"**Dil: **`{dosya['LANGUAGE']}`\n"
64 | f"**Dil Kodu: **`{dosya['LANGCODE']}`\n"
65 | f"**Çevirmen: **`{dosya['AUTHOR']}`\n"
66 |
67 | f"\n\n`Dil dosyasını yüklemek için` `.dil yükle` `komutunu kullanınız.`"
68 | )
69 | else:
70 | await event.edit("**Lütfen bir dil dosyasına yanıt verin!**")
71 | else:
72 | await event.edit(
73 | f"**Dil: **`{LANGUAGE_JSON['LANGUAGE']}`\n"
74 | f"**Dil Kodu: **`{LANGUAGE_JSON['LANGCODE']}`\n"
75 | f"**Çevirmen: **`{LANGUAGE_JSON ['AUTHOR']}`\n"
76 |
77 | f"\n\nDiğer diller için @AsenaDil kanalına bakabilirsiniz."
78 | )
79 |
80 | CmdHelp('dil').add_command(
81 | 'dil', None, 'Yüklediğiniz dil hakkında bilgi verir.'
82 | ).add_command(
83 | 'dil bilgi', None, 'Yanıt verdiğiniz dil dosyası hakkında bilgi verir.'
84 | ).add_command(
85 | 'dil yükle', None, 'Yanıt verdiğiniz dil dosyasını yükler.'
86 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/rgb.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # @NaytSeyd tarafından portlanmıştır.
10 | #
11 |
12 | import io
13 | import os
14 | import random
15 | import textwrap
16 |
17 | from PIL import Image, ImageChops, ImageDraw, ImageFont
18 | from telethon.tl.types import InputMessagesFilterDocument
19 | from userbot.events import register
20 | from userbot import CMD_HELP, bot
21 | from userbot.cmdhelp import CmdHelp
22 |
23 | # ██████ LANGUAGE CONSTANTS ██████ #
24 |
25 | from userbot.language import get_value
26 | LANG = get_value("rgb")
27 |
28 | # ████████████████████████████████
29 |
30 | @register(outgoing=True, pattern="^.rgb(?: |$)(.*)")
31 | async def sticklet(event):
32 | R = random.randint(0,256)
33 | G = random.randint(0,256)
34 | B = random.randint(0,256)
35 |
36 | # Giriş metnini al
37 | sticktext = event.pattern_match.group(1).strip()
38 |
39 | if len(sticktext) < 1:
40 | await event.edit(LANG['NEED_TEXT'])
41 | return
42 |
43 | # Komutu düzenle
44 | await event.edit(LANG['CONVERTING'])
45 |
46 | # https://docs.python.org/3/library/textwrap.html#textwrap.wrap
47 | sticktext = textwrap.wrap(sticktext, width=10)
48 | # Listeyi bir dizeye dönüştür
49 | sticktext = '\n'.join(sticktext)
50 |
51 | image = Image.new("RGBA", (512, 512), (255, 255, 255, 0))
52 | draw = ImageDraw.Draw(image)
53 | fontsize = 230
54 |
55 | FONT_FILE = await get_font_file(event.client, "@FontArsiv")
56 |
57 | font = ImageFont.truetype(FONT_FILE, size=fontsize)
58 |
59 | while draw.multiline_textsize(sticktext, font=font) > (512, 512):
60 | fontsize -= 10
61 | font = ImageFont.truetype(FONT_FILE, size=fontsize)
62 |
63 | width, height = draw.multiline_textsize(sticktext, font=font)
64 | draw.multiline_text(((512-width)/2,(512-height)/2), sticktext, font=font, fill=(R, G, B))
65 |
66 | image_stream = io.BytesIO()
67 | image_stream.name = "@resim.webp"
68 |
69 | def trim(im):
70 | bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
71 | diff = ImageChops.difference(im, bg)
72 | diff = ImageChops.add(diff, diff, 2.0, -100)
73 | bbox = diff.getbbox()
74 | return im.crop(bbox) if bbox else im
75 |
76 | image = trim(image)
77 | image.save(image_stream, "WebP")
78 | image_stream.seek(0)
79 |
80 | # mesajı sil
81 | await event.delete()
82 | try:
83 | await event.client.send_file(event.chat_id, image_stream, reply_to=event.message.reply_to_msg_id)
84 | except:
85 | await event.edit("__Bu grupta sticker gönderimine izin verilmiyor.__")
86 |
87 | # Temizlik
88 | try:
89 | os.remove(FONT_FILE)
90 | except:
91 | pass
92 |
93 |
94 | async def get_font_file(client, channel_id):
95 | # Önce yazı tipi mesajlarını al
96 | font_file_message_s = await client.get_messages(
97 | entity=channel_id,
98 | filter=InputMessagesFilterDocument,
99 | # Bu işlem çok fazla kullanıldığında
100 | # "FLOOD_WAIT" yapmaya neden olabilir
101 | limit=None
102 | )
103 | # Yazı tipi listesinden rastgele yazı tipi al
104 | # https://docs.python.org/3/library/random.html#random.choice
105 | font_file_message = random.choice(font_file_message_s)
106 | # Dosya yolunu indir ve geri dön
107 | return await client.download_media(font_file_message)
108 |
109 | CmdHelp('rgb').add_command(
110 | 'rbg', '', 'Metninizi RGB çıkartmaya dönüştürün.'
111 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/open_apis_textpro.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 | import asyncio
3 | import json
4 | import os
5 | import requests
6 | from userbot import CMD_HELP, bot
7 | from userbot.events import register
8 | from userbot.cmdhelp import CmdHelp
9 | # from userbot.language import get_value
10 |
11 | def download(url):
12 | response = requests.get(url)
13 | file = open("./tp.png", "wb")
14 | file.write(response.content)
15 | file.close()
16 | return True
17 |
18 | @register(outgoing=True, pattern="^.textpro ?(.*)")
19 | async def apis(event):
20 | degerler = event.pattern_match.group(1)
21 |
22 | try:
23 | txt = degerler.split()
24 | model = txt[0]
25 | text = degerler.replace(model, "")
26 |
27 | except IndexError:
28 | return await event.edit("**Eksik Paramatreler!**\n\n**Örnek:** `textpro neon Asena`\n\n__Stiller:__ `neon`, `neon2`, `devil`, `batman`, `led`, `yıldırım`, `bp`, `yaprak`, `ask`, `ask2`, `afis`, `glitch`")
29 |
30 | url = ""
31 |
32 | if model == "neon":
33 | url = "https://textpro.me/create-glowing-neon-light-text-effect-online-free-1061.html"
34 | elif model == "neon2":
35 | url = "https://textpro.me/neon-text-effect-online-963.html"
36 | elif model == "devil":
37 | url = "https://textpro.me/create-neon-devil-wings-text-effect-online-free-1014.html"
38 | elif model == "batman":
39 | url = "https://textpro.me/make-a-batman-logo-online-free-1066.html"
40 | elif model == "led":
41 | url = "https://textpro.me/color-led-display-screen-text-effect-1059.html"
42 | elif model == "yıldırım":
43 | url = "https://textpro.me/online-thunder-text-effect-generator-1031.html"
44 | elif model == "bp":
45 | url = "https://textpro.me/create-blackpink-logo-style-online-1001.html"
46 | elif model == "yaprak":
47 | url = "https://textpro.me/natural-leaves-text-effect-931.html"
48 | elif model == "ask":
49 | url = "https://textpro.me/free-advanced-glow-text-effect-873.html"
50 | elif model == "ask2":
51 | url = "https://textpro.me/create-neon-light-on-brick-wall-online-1062.html"
52 | elif model == "afis":
53 | url = "https://textpro.me/create-light-glow-sliced-text-effect-online-1068.html"
54 | elif model == "glitch":
55 | url = "https://textpro.me/create-impressive-glitch-text-effects-online-1027.html"
56 |
57 | else:
58 | return await event.edit("**Yanlış Paramatre!**\n\n**Örnek:** `textpro neon Asena`\n\n__Stiller:__ `neon`, `neon2`, `devil`, `batman`, `led`, `yıldırım`, `bp`, `yaprak`, `ask`, `ask2`, `afis`, `glitch`")
59 |
60 | await event.edit("__Fotoğraf Oluşturuluyor..__")
61 | async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
62 | async with session.get('https://open-apis-rest.up.railway.app/api/textpro?url=' + url + '&text1=' + text) as response:
63 |
64 | html = await response.text()
65 | html2 = json.loads(html)
66 | if html2["status"] == "OK":
67 | img = html2["data"]
68 | download(img)
69 | await event.client.send_file(event.chat_id, './tp.png', caption="@AsenaUserBot ile Yüklendi.")
70 | os.remove("./tp.png")
71 | await event.delete()
72 | return True
73 | else:
74 | return await event.edit("Sunucu ile ilgili bir sorun var. Lütfen bunu destek ekibine bildirin.")
75 |
76 | Help = CmdHelp('textpro')
77 | Help.add_command('textpro',
78 | ' ',
79 | 'Farklı Stillerde Görseller Üretir. (Tüm stilleri görmek için boş bırakın)',
80 | 'textpro devil phaticusthiccy'
81 | )
82 | Help.add_info("@phaticusthiccy tarafından yapılmıştır.")
83 | Help.add()
84 |
--------------------------------------------------------------------------------
/userbot/modules/degistir.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | import re
10 | import userbot.modules.sql_helper.mesaj_sql as sql
11 | from userbot import CMD_HELP
12 | from userbot.events import register
13 | from userbot.main import PLUGIN_MESAJLAR, ORJ_PLUGIN_MESAJLAR, PLUGIN_CHANNEL_ID
14 | from userbot.cmdhelp import CmdHelp
15 |
16 | # ██████ LANGUAGE CONSTANTS ██████ #
17 |
18 | from userbot.language import get_value
19 | LANG = get_value("degistir")
20 |
21 | # ████████████████████████████████ #
22 |
23 | @register(outgoing=True, pattern="^.change ?(.*)")
24 | @register(outgoing=True, pattern="^.de[gğ]i[sş]tir ?(.*)")
25 | async def degistir(event):
26 | plugin = event.pattern_match.group(1)
27 | mesaj = re.search(r"\"(.*)\"", plugin)
28 |
29 | if mesaj:
30 | rege = re.findall(r"(?:|$)(.*)\"(.*)\"", plugin)
31 | plugin = rege[0][0]
32 | mesaj = rege[0][1]
33 | else:
34 | mesaj = []
35 |
36 | plugin = plugin.strip()
37 | TURLER = ["afk", "alive", "pm", "kickme", "dızcı", "ban", "mute", "approve", "disapprove", "block"]
38 | if type(mesaj) == list:
39 | if plugin in TURLER:
40 | if event.is_reply:
41 | reply = await event.get_reply_message()
42 | if reply.media:
43 | mesaj = await reply.forward_to(PLUGIN_CHANNEL_ID)
44 | PLUGIN_MESAJLAR[plugin] = reply
45 | sql.ekle_mesaj(plugin, f"MEDYA_{mesaj.id}")
46 | return await event.edit(f"Plugin(`{plugin}`) {LANG['SETTED_MEDIA']}")
47 | PLUGIN_MESAJLAR[plugin] = reply.text
48 | sql.ekle_mesaj(plugin, reply.text)
49 | return await event.edit(f"Plugin(`{plugin}`) {LANG['SETTED_REPLY']}")
50 |
51 | silme = sql.sil_mesaj(plugin)
52 | if silme == True:
53 | PLUGIN_MESAJLAR[plugin] = ORJ_PLUGIN_MESAJLAR[plugin]
54 | await event.edit(LANG['SUCCESS_DELETED'])
55 | else:
56 | await event.edit(f"{LANG['ERROR_DELETED']}: `{silme}`")
57 | else:
58 | await event.edit(LANG['NOT_FOUND'] + ":`afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block`")
59 | elif len(plugin) < 1:
60 | await event.edit(LANG['USAGE'])
61 | elif type(mesaj) == str:
62 | if plugin in TURLER:
63 | if mesaj.isspace():
64 | await event.edit(LANG['CANNOT_EMPTY'])
65 | return
66 | else:
67 | PLUGIN_MESAJLAR[plugin] = mesaj
68 | sql.ekle_mesaj(plugin, mesaj)
69 | await event.edit(LANG['SETTED'].format(plu=plugin, msj=mesaj))
70 | else:
71 | await event.edit(LANG['NOT_FOUND'] + ":`afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block`")
72 |
73 | CmdHelp('degistir').add_command(
74 | 'değiştir', ' ', 'Değiştir, bottaki plugin-mesajlarını değiştirmenize yarar. Eğer mesaj yazmazsanız Plugin mesajını orijinal haline döndürür.', '.değiştir afk \"Şu an burda değilim... Belki hiç gelmem\"'
75 | ).add_info(
76 | '**Desteklenen Pluginler:** `afk/alive/pm/kickme/dızcı/ban/mute/approve/disapprove/block`\n**Alive Değişkenleri:** `{plugin}, {telethon}, {asena}, {python}, {username}, {fullname}, {lastname}, {id}, {mention}`\n\
77 | **Ban/Mute Değişkenleri:** `{id}, {username}, {first_name}, {last_name}, {mention}, {date}, {count}`\n\
78 | **AFK Değişkenleri:** `{username}, {mention}, {first_name}, {last_name}, {last_seen_seconds}, {last_seen}, {last_seen_long}`\n\
79 | **PMpermit Değişkenler(pm, block, approve, disapprove):** `{id}, {username}, {mention}, {first_name}, {last_name}`\
80 | **Kickme Değişkenleri:** `{title}`'
81 | ).add()
--------------------------------------------------------------------------------
/userbot/cmdhelp.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 | from userbot import PATTERNS, CMD_HELP, CMD_HELP_BOT
9 |
10 | class CmdHelp:
11 | """
12 | Komut yardımlarını daha iyi üretmek için yazdığım sınıf.
13 | """
14 |
15 | FILE = ""
16 | ORIGINAL_FILE = ""
17 | FILE_AUTHOR = ""
18 | IS_OFFICIAL = True
19 | COMMANDS = {}
20 | PREFIX = PATTERNS[:1]
21 | WARNING = ""
22 | INFO = ""
23 |
24 | def __init__(self, file: str, official : bool = True, file_name : str = None):
25 | self.FILE = file
26 | self.ORIGINAL_FILE = file
27 | self.IS_OFFICIAL = official
28 | self.FILE_NAME = file_name if not file_name == None else file + '.py'
29 | self.COMMANDS = {}
30 | self.FILE_AUTHOR = ""
31 | self.WARNING = ""
32 | self.INFO = ""
33 |
34 | def set_file_info(self, name : str, value : str):
35 | if name == 'name':
36 | self.FILE = value
37 | elif name == 'author':
38 | self.FILE_AUTHOR = value
39 | return self
40 |
41 | def add_command(self, command : str, params = None, usage: str = '', example = None):
42 | """
43 | Komut ekler.
44 | """
45 |
46 | self.COMMANDS[command] = {'command': command, 'params': params, 'usage': usage, 'example': example}
47 | return self
48 |
49 | def add_warning(self, warning):
50 | self.WARNING = warning
51 | return self
52 |
53 | def add_info(self, info):
54 | self.INFO = info
55 | return self
56 |
57 | def get_result(self):
58 | """
59 | Sonuç getirir.
60 | """
61 |
62 | result = f"**📗 Dosya:** `{self.FILE}`\n"
63 | if self.WARNING == '' and self.INFO == '':
64 | result += f"**⬇️ Official:** {'✅' if self.IS_OFFICIAL else '❌'}\n\n"
65 | else:
66 | result += f"**⬇️ Official:** {'✅' if self.IS_OFFICIAL else '❌'}\n"
67 |
68 | if self.INFO == '':
69 | if not self.WARNING == '':
70 | result += f"**⚠️ Uyarı:** {self.WARNING}\n\n"
71 | else:
72 | if not self.WARNING == '':
73 | result += f"**⚠️ Uyarı:** {self.WARNING}\n"
74 | result += f"**ℹ️ Info:** {self.INFO}\n\n"
75 |
76 | for command in self.COMMANDS:
77 | command = self.COMMANDS[command]
78 | if command['params'] == None:
79 | result += f"**🛠 Komut:** `{PATTERNS[:1]}{command['command']}`\n"
80 | else:
81 | result += f"**🛠 Komut:** `{PATTERNS[:1]}{command['command']} {command['params']}`\n"
82 |
83 | if command['example'] == None:
84 | result += f"**💬 Açıklama:** `{command['usage']}`\n\n"
85 | else:
86 | result += f"**💬 Açıklama:** `{command['usage']}`\n"
87 | result += f"**⌨️ Örnek:** `{PATTERNS[:1]}{command['example']}`\n\n"
88 | return result
89 |
90 | def add(self):
91 | """
92 | Direkt olarak CMD_HELP ekler.
93 | """
94 | CMD_HELP_BOT[self.FILE] = {'info': {'official': self.IS_OFFICIAL, 'warning': self.WARNING, 'info': self.INFO}, 'commands': self.COMMANDS}
95 | CMD_HELP[self.FILE] = self.get_result()
96 | return True
97 |
98 | def getText(self, text : str):
99 | if text == 'REPLY_OR_USERNAME':
100 | return ' '
101 | elif text == 'OR':
102 | return 'veya'
103 | elif text == 'USERNAMES':
104 | return ''
105 |
--------------------------------------------------------------------------------
/userbot/modules/shazam_helper/communication.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 | #-*- encoding: Utf-8 -*-
3 | from uuid import uuid5, getnode, NAMESPACE_DNS, NAMESPACE_URL
4 | from random import seed, random, choice
5 | from pytz import all_timezones
6 | from requests import get, post
7 | from base64 import b64encode
8 | from locale import getlocale
9 | from json import dumps
10 | from time import time
11 |
12 | from .signature_format import DecodedMessage
13 | from .user_agent import USER_AGENTS
14 |
15 | locale = (getlocale()[0] or 'tr_TR').split('.')[0]
16 |
17 | first_uuid = str(uuid5(NAMESPACE_DNS, str(getnode()))).upper()
18 | second_uuid = str(uuid5(NAMESPACE_URL, str(getnode())))
19 |
20 | def recognize_song_from_signature(signature : DecodedMessage) -> dict:
21 |
22 | # Même si Macron ne veut pas, nous on est là
23 |
24 | fuzz = random() * 15.3 - 7.65
25 |
26 | seed(getnode())
27 |
28 | return post('https://amp.shazam.com/discovery/v5/fr/FR/android/-/tag/' + first_uuid + '/' + second_uuid, params = {
29 | 'sync': 'true',
30 | 'webv3': 'true',
31 | 'sampling': 'true',
32 | 'connected': '',
33 | 'shazamapiversion': 'v3',
34 | 'sharehub': 'true',
35 | 'video': 'v3'
36 | }, headers = {
37 | 'Content-Type': 'application/json',
38 | 'User-Agent': choice(USER_AGENTS),
39 | 'Content-Language': 'tr_TR'
40 | }, json = {
41 | "geolocation": {
42 | "altitude": random() * 400 + 100 + fuzz,
43 | "latitude": random() * 180 - 90 + fuzz,
44 | "longitude": random() * 360 - 180 + fuzz
45 | },
46 | "signature": {
47 | "samplems": int(signature.number_samples / signature.sample_rate_hz * 1000),
48 | "timestamp": int(time() * 1000),
49 | "uri": signature.encode_to_uri()
50 | },
51 | "timestamp": int(time() * 1000),
52 | "timezone": choice([timezone for timezone in all_timezones if 'Europe/' in timezone])
53 | }).json()
54 |
55 |
56 | if __name__ == '__main__':
57 |
58 | print(dumps(recognize_song_from_signature(DecodedMessage.decode_from_uri('data:audio/vnd.shazam.sig;base64,gCX+ynzKnegoBQAAAJwRlAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAAACGAQAAAHwAAAAAQCgFAABAAANgeAAAACdVdK4MAT15RAgN3XWPCjsqeFUPHjR5JQ4VQXh5CR6/dF0OS3h2zg0MvHaHD1FneFgMEtdmRQ4PZ2z4DhF2dZIMNHZwTQ834XZIDAOkaYwQBqpqLA8wVHKtDCWfczEPNGF90AwZXnmqCRPEejgJBY18xA8nGnDzDEEAA2ByAQAAGVlxRRkJinLDGgazd8QQAbN0aCsBOm5iJQoXbXwWBQRsBRMDyHY6Hh9fc88QBt1qaSgIdXeLIQUGdgcmBRxwsRYBRnU8Hgo7anIsBBJxpSQCNXT5FR9ja1MdAkt2iBIK+3QwJgZTdWwZDNFq0xUMG3OqIQNOeDMtJzhv6R4AaG4wKwVDd84XAb50UScDi24/HgllbRgZDz5tliwFWXIDFQB+cQkjITltLRQDpHYcGAEIc8QnAQluqB8SIHMFGRE3bmocBiVxuCoIw3HOFgCZdD4tIoB0ER4VSWzWJQ/CbYQcAYhyvCoKKnv/GAksbc4eJ/d9PSUBg3nrGAFxcSstLeJwkSYKF3QrHgAyb/olDzRvOCAAB3k2LRPhcYIsASlz/RIA0G9MJBgWcB0cAc5wjyUGCnNhGQSVd/EmA9B0uhoIl3IYLQE4cFImFZJ1RR4GonRPKAHBeIgUFWlsEB8II4AKEQiSdpAhFAtpLB4BZmSFKQAAQgADYIsBAAAMA3IWPAWTcoo2DiRwiE0BwnDpMgZecVNLAfpxkUMAVnQJSALmb88zCqd03jcABHLvTgZDb7w/ANJw+08T+3ISPhKGcH9DD6VzyzIA9XKaRTV3bnIvATRysjwC5XG7OAmNcT8yBEBwhD8PL3R/MwDNcBttEMRy7DImfHvBMwb2dL87Dl91Jm5O/XTIZADKcwVrAQJzEl4Oa3RdVgEIeck9ATR6+UkGrnbvVAMPdRpQAQV0ZTgB+3bHMRSEeMU6Ez5+ckoAM324VgUFfYg8BZ90r0Qf7H8zMgPWdXE2Aeh7kU8BfHgAQwHxe6dLAHl4SlgIEX9rPg6denRGE+l5+0oCr4KWMQWxebRLDax/cDwB93mESRN5e0BMAq6Cbj8JMoR7PgBbenNXA858zkoI5H36SA43et5FE/h50TERoHcbTwH4eNg0AdZ3TToL1HeaOACEeNQ8APqBNEEBqXc/TgZ8ebBNATeDvUBbKWuJPAHhYTBiBbdtDUsBkmW0XgICdL44AB1r/FQSeWu7OgBDAANghgEAAAv0aDh4ACtneoYBcGbUjwA0Zy6dALtoQqca4mfRcgHUZhSGAepqEKQKZmp6cADXZwabAeRlqpEFLmq3cVYWbv5wFHZof3cAimZphwANZjOeAU9rQKcIv2WscSX0aMCcABRq0J8APWZVrQFzaoCFAKNsh5gB6myJdgzCaQJ7DwJwWosAJWqQjwCnb5KSAPptCZwB4G56fwZ9bhmVDp9rU3cWBW3DrgcgazCbBkFt3ZIT+Wm5qA2zaXJ+ALVpF5YA8mnBmQFKaz+KAGZs65ESWmxvhACIafeqAbZqQHEAA20ffADaao+kAc5q+XQAHGpGkMLkYkylDMlrBHIWUmRUdgMxZWWPA8tr2a4J8mY2eQD4ai2bBAdq0ZITDGhLhgBUZl2eAFhng6gCfGLIgQtKZ4xwGc1j5ZsBK2QBeQFQanV0AfRjsaEBeGItiQEDZeF8DS9kDHoSe2UsdwFtZU5+CmFpLngOZGQ4hw0rXOeOAJ1gmagB4F4DmwEJYQKACANd6J4VuFJtrAAA')), indent = 4, ensure_ascii = False))
--------------------------------------------------------------------------------
/userbot/modules/remove_bg.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # Prakasaka tarafından portlanmıştır.
10 | #
11 |
12 | import io
13 | import os
14 | import requests
15 | from userbot.events import register
16 | from telethon.tl.types import MessageMediaPhoto
17 | from userbot import CMD_HELP, REM_BG_API_KEY, TEMP_DOWNLOAD_DIRECTORY
18 | from userbot.cmdhelp import CmdHelp
19 |
20 | # ██████ LANGUAGE CONSTANTS ██████ #
21 |
22 | from userbot.language import get_value
23 | LANG = get_value("remove_bg")
24 |
25 | # ████████████████████████████████ #
26 |
27 | @register(outgoing=True, pattern="^.rbg(?: |$)(.*)")
28 | async def kbg(remob):
29 | """ .rbg komutu ile görüntünün arka planını kaldırın """
30 | if REM_BG_API_KEY is None:
31 | await remob.edit(
32 | LANG['NEED_API_KEY']
33 | )
34 | return
35 | input_str = remob.pattern_match.group(1)
36 | message_id = remob.message.id
37 | if remob.reply_to_msg_id:
38 | message_id = remob.reply_to_msg_id
39 | reply_message = await remob.get_reply_message()
40 | await remob.edit(LANG['TRYING'])
41 | try:
42 | if isinstance(
43 | reply_message.media, MessageMediaPhoto
44 | ) or "image" in reply_message.media.document.mime_type.split('/'):
45 | downloaded_file_name = await remob.client.download_media(
46 | reply_message, TEMP_DOWNLOAD_DIRECTORY)
47 | await remob.edit(LANG['RBG'])
48 | output_file_name = await ReTrieveFile(downloaded_file_name)
49 | os.remove(downloaded_file_name)
50 | else:
51 | await remob.edit(LANG['CANT_RBG'])
52 | except Exception as e:
53 | await remob.edit(str(e))
54 | return
55 | elif input_str:
56 | await remob.edit(
57 | f"`{LANG['ONLINE_RBG']}`\n{input_str}")
58 | output_file_name = await ReTrieveURL(input_str)
59 | else:
60 | await remob.edit(LANG['NEED'])
61 | return
62 | contentType = output_file_name.headers.get("content-type")
63 | if "image" in contentType:
64 | with io.BytesIO(output_file_name.content) as remove_bg_image:
65 | remove_bg_image.name = "removed_bg.png"
66 | await remob.client.send_file(
67 | remob.chat_id,
68 | remove_bg_image,
69 | caption=LANG['CAPTION'],
70 | force_document=True,
71 | reply_to=message_id)
72 | await remob.delete()
73 | else:
74 | await remob.edit("**Hata {}**\n`{}`".format(LANG['ERROR'],
75 | output_file_name.content.decode("UTF-8")))
76 |
77 |
78 | async def ReTrieveFile(input_file_name):
79 | headers = {
80 | "X-API-Key": REM_BG_API_KEY,
81 | }
82 | files = {
83 | "image_file": (input_file_name, open(input_file_name, "rb")),
84 | }
85 | r = requests.post("https://api.remove.bg/v1.0/removebg",
86 | headers=headers,
87 | files=files,
88 | allow_redirects=True,
89 | stream=True)
90 | return r
91 |
92 |
93 | async def ReTrieveURL(input_url):
94 | headers = {
95 | "X-API-Key": REM_BG_API_KEY,
96 | }
97 | data = {"image_url": input_url}
98 | r = requests.post("https://api.remove.bg/v1.0/removebg",
99 | headers=headers,
100 | data=data,
101 | allow_redirects=True,
102 | stream=True)
103 | return r
104 |
105 | CmdHelp('rgb').add_command(
106 | 'rbg', '', 'remove.bg API kullanarak görüntülerin arka planını kaldırır.'
107 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/galeri.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | import re
10 | import asyncio
11 |
12 | from userbot import CMD_HELP, ASYNC_POOL, GALERI_SURE
13 | from userbot.events import register
14 | from userbot.main import FotoDegistir
15 | from userbot.cmdhelp import CmdHelp
16 |
17 | # ██████ LANGUAGE CONSTANTS ██████ #
18 |
19 | from userbot.language import get_value
20 | LANG = get_value("galeri")
21 |
22 | # ████████████████████████████████ #
23 |
24 | URL_REGEX = re.compile(
25 | # https://github.com/django/django/blob/stable/1.3.x/django/core/validators.py#L45
26 | r'^(?:http|ftp)s?://' # http:// or https://
27 | r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
28 | r'localhost|' #localhost...
29 | r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
30 | r'(?::\d+)?' # optional port
31 | r'(?:/?|[/?]\S+)$', re.IGNORECASE)
32 |
33 | @register(outgoing=True, pattern="^.galeri ?(.*)")
34 | async def galeri(event):
35 | try:
36 | import userbot.modules.sql_helper.galeri_sql as sql
37 | except:
38 | await event.edit("`SQL dışı mod'ta galeri çalışmaz!`")
39 | secenek = event.pattern_match.group(1)
40 | secen = secenek.split(" ")
41 | if secen[0] == "ekle":
42 | if len(secen) > 1:
43 | URL = re.search(URL_REGEX, secen[1])
44 | if URL != None:
45 | sql.ekle_foto(secen[1])
46 | sql.getir_foto()
47 | await event.edit(LANG['ADDED_LIST'])
48 | else:
49 | await event.edit(LANG['INVALID_URL'])
50 | else:
51 | await event.edit(LANG['EXAMPLE'])
52 | elif secen[0] == "liste":
53 | yfoto = ""
54 | sql.getir_foto()
55 | fotolar = sql.TUM_GALERI
56 | for foto in fotolar:
57 | yfoto += f"\n▶️ ({foto.g_id}) [Fotoğraf]({foto.foto})"
58 | await event.edit(f"**{LANG['LIST']}**\n" + yfoto)
59 | elif secen[0] == "sil":
60 | if secen[1].isdigit():
61 | silme = sql.sil_foto(secen[1])
62 | if silme == True:
63 | await event.edit(LANG['REMOVED'])
64 | else:
65 | await event.edit(f"{LANG['REMOVED_ERROR']}: {silme}")
66 | else:
67 | await event.edit(f"**{LANG['NEED_NUMBER']}** `.galeri sil 2`")
68 | elif secen[0] == "başla":
69 | if "galeri" in ASYNC_POOL:
70 | await event.edit(LANG['WORKING'])
71 | return
72 | ASYNC_POOL.append("galeri")
73 | sql.getir_foto()
74 | await event.edit(LANG['STARTED'])
75 | if len(sql.TUM_GALERI) >= 1:
76 | while "galeri" in ASYNC_POOL:
77 | fotolar = sql.TUM_GALERI
78 | i = 0
79 | while i < len(fotolar):
80 | if not "galeri" in ASYNC_POOL:
81 | break
82 | if i == len(fotolar):
83 | i = 0
84 | await FotoDegistir(i)
85 | await asyncio.sleep(GALERI_SURE)
86 | i += 1
87 | else:
88 | await event.edit(LANG['NEED_PHOTO'])
89 | return
90 | elif secen[0] == "kapa":
91 | if "galeri" in ASYNC_POOL:
92 | ASYNC_POOL.remove("galeri")
93 | await event.edit(LANG['STOPPED'])
94 | else:
95 | event.edit(LANG['ALREADY_STOP'])
96 | return
97 | else:
98 | await event.edit(LANG['INVALID'])
99 |
100 | CmdHelp('galeri').add_command(
101 | 'galeri ekle', '', 'Galeri sırasına fotoğraf ekler', 'galeri ekle https://i.hizliresim.com/wFSVKd.jpg'
102 | ).add_command(
103 | 'galeri liste', None, 'Galeri sırasını gösterir.'
104 | ).add_command(
105 | 'galeri sil', '', 'Galeri sırasından bir resmi siler.', 'galeri sil 4'
106 | ).add()
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | All participants of RaphielGang are expected to abide by our Code of Conduct,
4 | both online and during in-person events that are hosted and/or associated with RaphielGang.
5 |
6 |
7 | ### The Pledge
8 |
9 | In the interest of fostering an open and welcoming environment, we pledge to make participation
10 | in our project and our community a harassment-free experience for everyone, regardless of age,
11 | body size, disability, ethnicity, gender identity and expression, level of experience,
12 | nationality, personal appearance, race, religion, or sexual identity and orientation.
13 |
14 |
15 | ### The Standards
16 |
17 | Examples of behaviour that contributes to creating a positive environment include:
18 |
19 | * **Be welcoming**: We strive to be a community that welcomes and supports people of all backgrounds and identities. This includes, but is not limited to members of any race, ethnicity, culture, national origin, colour, immigration status, social and economic class, educational level, sex, sexual orientation, gender identity and expression, age, size, family status, political belief, religion, and mental and physical ability.
20 | * **Be considerate**: Your work will be used by other people, and you in turn will depend on the work of others. Any decision you take will affect users and colleagues, and you should take those consequences into account when making decisions. Remember that we're a world-wide community, so you might not be communicating in someone else's primary language.
21 | * **Be respectful**: Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners. We might all experience some frustration now and then, but we cannot allow that frustration to turn into a personal attack. It’s important to remember that a community where people feel uncomfortable or threatened is not a productive one.
22 | * **Gracefully accepting constructive criticism**: Not everyone are perfect, you can get some critism of your works from us, but it's not means that we don't accepting your contribution, we just want you to fixing it and making it better.
23 | * **Referring to people by their preferred pronouns/words**, but we do not have standardized gender-neutral pronouns/words, so your milleage may vary.
24 | * **Do not attack somebody because you have a different opinion** All opinions are accepted as long as they are reasonable, and everyone have right to shouting their opinion.
25 | * **Just chill :D**
26 | * **Don't forget, nobody is perfect, mistakes can be made**
27 | * **Equality is not a privilege, it's a rule!**
28 |
29 | ### Examples of unacceptable behaviour by participants include:
30 |
31 | * **Trolling, insulting/derogatory comments, public or private harassment**
32 | * **Publishing others' private information (Doxing)** such as a physical or electronic address, without explicit permission
33 | * **Not being respectful to reasonable communication boundaries** such as 'leave me alone,' 'go away,' or 'Fuck off.'
34 | * **The usage of sexualised language or imagery and unwelcome sexual attention or advances**
35 | * **Demonstrating the graphics or any other content you know may be considered disturbing**
36 | * **Assuming or promoting any kind of inequality** including but not limited to: age, body size, disability, ethnicity, gender identity and expression, nationality and race, personal appearance, religion, or sexual identity and orientation
37 | * **Drug promotion of any kind**
38 | * **Attacking personal tastes**
39 | * **Other conduct which you know could reasonably be considered inappropriate in a professional setting**
40 |
41 |
42 | ### Enforcement
43 |
44 | Violations of the Code of Conduct may be reported by sending an email to [raphielscape@outlook.com](mailto:raphielscape@outlook.com).
45 | All reports will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances.
46 | Further details of specific enforcement policies may be posted separately.
47 |
48 | We hold the right and responsibility to remove comments or other contributions that
49 | are not aligned to this Code of Conduct, or to ban temporarily or permanently any members
50 | for other behaviours that they deem inappropriate, threatening, offensive, or harmful.
--------------------------------------------------------------------------------
/userbot/modules/nekobin.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """ Nekobin ile etkileşim için komutlar içeren UserBot modülü (https://nekobin.com/) """
11 |
12 | import os
13 | from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP, TEMP_DOWNLOAD_DIRECTORY
14 | from userbot.events import register
15 | from userbot.cmdhelp import CmdHelp
16 | import aiohttp
17 | import asyncio
18 | import json
19 |
20 | URL = "https://nekobin.com/"
21 |
22 | # ██████ LANGUAGE CONSTANTS ██████ #
23 |
24 | from userbot.language import get_value
25 | LANG = get_value("dogbin")
26 |
27 | # ████████████████████████████████ #
28 |
29 | @register(outgoing=True, pattern=r"^.paste(?: |$)([\s\S]*)")
30 | async def paste(pstl):
31 | """ .paste komutu metni doğrudan nekobine yapıştırır """
32 |
33 | match = pstl.pattern_match.group(1).strip()
34 | reply_id = pstl.reply_to_msg_id
35 |
36 | if not match and not reply_id:
37 | await pstl.edit(LANG['ELON_SAYS'])
38 | return
39 |
40 | if match:
41 | message = match
42 | elif reply_id:
43 | message = (await pstl.get_reply_message())
44 | if message.media:
45 | downloaded_file_name = await pstl.client.download_media(
46 | message,
47 | TEMP_DOWNLOAD_DIRECTORY,
48 | )
49 | m_list = None
50 | with open(downloaded_file_name, "rb") as fd:
51 | m_list = fd.readlines()
52 | message = ""
53 | for m in m_list:
54 | message += m.decode("UTF-8") + "\r"
55 | os.remove(downloaded_file_name)
56 | else:
57 | message = message.message
58 |
59 | # Throwbin
60 | await pstl.edit(LANG['PASTING'])
61 | async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
62 | async with session.get("https://open-apis-rest.up.railway.app/api/nekobin?text=" + message) as response:
63 |
64 | html = await response.text()
65 | html2 = json.loads(html)
66 | if html2["status"] == "OK":
67 | reply_text = LANG['PASTED'] + "\n\n" + LANG['URL'] + " " + html2["data"]["url"]
68 | await pstl.edit(reply_text)
69 | if BOTLOG:
70 | await pstl.client.send_message(
71 | BOTLOG_CHATID,
72 | f"Nekobine metin yapıştırma başarıyla yürütüldü",
73 | )
74 | else:
75 | return await pstl.edit("__Sunucu ile ilgili bir sorun var. Daha sonra tekrar deneyin.__")
76 |
77 |
78 | @register(outgoing=True, pattern="^.getpaste ?(.*)")
79 | async def get_dogbin_content(event):
80 | """ .getpaste komutu Nekobin url içeriğini aktarır """
81 | url = event.pattern_match.group(1)
82 |
83 | if "nekobin" not in url:
84 | return await event.edit(LANG["UNSUPPORTED_URL"])
85 |
86 | await event.edit(LANG['DATA_CHECKING'])
87 | async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
88 | async with session.get("https://open-apis-rest.up.railway.app/api/nekobinget?url=" + url) as response:
89 |
90 | html = await response.text()
91 | html2 = json.loads(html)
92 | if html2["status"] == "OK":
93 | await event.edit(LANG["DOGBIN_DATA"] + "\n\n" + html2["data"])
94 | if BOTLOG:
95 | await event.client.send_message(
96 | BOTLOG_CHATID,
97 | LANG['DOGBIN_ENDED'],
98 | )
99 | else:
100 | return await event.edit(LANG["DOGBIN_NOT_RESPOND"])
101 |
102 | CmdHelp('paste').add_command(
103 | 'paste', '', 'Nekobin kullanarak yapıştırılmış veya kısaltılmış url oluşturma (https://nekobin.com)'
104 | ).add_command(
105 | 'getpaste', "nekobin url", 'Nekobin url içeriğini metne aktarır (https://nekobin.com)'
106 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/lydia.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # credit goes to @snapdragon and @devpatel_73 for making it work on this userbot.
10 | #
11 |
12 | from userbot.events import register
13 | from userbot import CMD_HELP
14 | from userbot import LYDIA_API_KEY
15 | import coffeehouse as cf
16 | from coffeehouse.lydia import LydiaAI
17 | from coffeehouse.api import API
18 | import asyncio
19 | import logging
20 | from userbot.cmdhelp import CmdHelp
21 |
22 | logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s',
23 | level=logging.WARNING)
24 |
25 | # ██████ LANGUAGE CONSTANTS ██████ #
26 |
27 | from userbot.language import get_value
28 | LANG = get_value("lydia")
29 |
30 | # ████████████████████████████████ #
31 |
32 | try:
33 | from userbot.modules.sql_helper.lydia_sql import get_s, get_all_s, add_s, remove_s
34 | except:
35 | logging.log(level=logging.WARNING,
36 | msg="Lydia veritabanı bağlantısı başarısız oldu")
37 |
38 | # SQL dışı mod
39 | ACC_LYDIA = {}
40 |
41 | if LYDIA_API_KEY:
42 | api_key = LYDIA_API_KEY
43 | api_client = API(api_key)
44 | lydia = LydiaAI(api_client)
45 |
46 |
47 | @register(outgoing=True, pattern="^.repcf$")
48 | async def repcf(event):
49 | if event.fwd_from:
50 | return
51 | await event.edit(LANG['WORKING'])
52 | try:
53 | session = lydia.create_session()
54 | reply = await event.get_reply_message()
55 | msg = reply.text
56 | text_rep = session.think_thought(msg)
57 | await event.edit(LANG['LYDIA_SAYS'].format(text_rep))
58 | except Exception as e:
59 | await event.edit(str(e))
60 |
61 | @register(outgoing=True, pattern="^.addcf$")
62 | async def addcf(event):
63 | if event.fwd_from:
64 | return
65 | await event.edit(LANG['SQL_OFF'])
66 | await asyncio.sleep(3)
67 | await event.edit(LANG['WORKING'])
68 | reply_msg = await event.get_reply_message()
69 | if reply_msg:
70 | session = lydia.create_session()
71 | session_id = session.id
72 | if reply_msg.from_id is None:
73 | return await event.edit(LANG['REPLY_USER_ERR'])
74 | ACC_LYDIA.update({(event.chat_id & reply_msg.from_id): session})
75 | await event.edit(LANG['LYDIA_ACTIVATED'].format(str(reply_msg.from_id), str(event.chat_id)))
76 | else:
77 | await event.edit(LANG['REPLY_FOR_ACTIVATE'])
78 |
79 | @register(outgoing=True, pattern="^.remcf$")
80 | async def remcf(event):
81 | if event.fwd_from:
82 | return
83 | await event.edit(LANG['SQL_OFF'])
84 | await asyncio.sleep(3)
85 | await event.edit("İşleniyor...")
86 | reply_msg = await event.get_reply_message()
87 | try:
88 | del ACC_LYDIA[event.chat_id & reply_msg.from_id]
89 | await event.edit(LANG['LYDIA_DEACTIVATED'].format(str(reply_msg.from_id), str(event.chat_id)))
90 | except Exception:
91 | await event.edit(LANG['LYDIA_OFF_FOR_USER'])
92 |
93 |
94 | @register(incoming=True, disable_edited=True)
95 | async def user(event):
96 | user_text = event.text
97 | try:
98 | session = ACC_LYDIA[event.chat_id & event.from_id]
99 | msg = event.text
100 | async with event.client.action(event.chat_id, "typing"):
101 | text_rep = session.think_thought(msg)
102 | wait_time = 0
103 | for i in range(len(text_rep)):
104 | wait_time = wait_time + 0.1
105 | await asyncio.sleep(wait_time)
106 | await event.reply(text_rep)
107 | except (KeyError, TypeError):
108 | return
109 |
110 | CmdHelp('lydia').add_command(
111 | 'addcf', '', 'Lydia\'nın otomatik sohbetini etkinleştirir.'
112 | ).add_command(
113 | 'remcf', '', 'Lydia\'nın otomatik sohbetini devre dışı bırakır.'
114 | ).add_command(
115 | 'repcf', '', 'Lydia\'nın otomatik sohbetiini belli bir kişi için etkinleştirir.'
116 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/deepfry.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | # Deepfry modülü kaynak kodu: https://github.com/Ovyerus/deeppyer
11 | # @NaytSeyd tarafından portlanmıştır.
12 |
13 | import io
14 | from random import randint, uniform
15 | from userbot import CMD_HELP
16 | from userbot.events import register
17 |
18 | from PIL import Image, ImageEnhance, ImageOps
19 | from telethon.tl.types import DocumentAttributeFilename
20 | from userbot.cmdhelp import CmdHelp
21 |
22 | # ██████ LANGUAGE CONSTANTS ██████ #
23 |
24 | from userbot.language import get_value
25 | LANG = get_value("deepfry")
26 |
27 | # ████████████████████████████████ #
28 |
29 | @register(pattern="^.deepfry(?: |$)(.*)", outgoing=True)
30 | async def deepfryer(event):
31 | try:
32 | frycount = int(event.pattern_match.group(1))
33 | if frycount < 1:
34 | raise ValueError
35 | except ValueError:
36 | frycount = 1
37 |
38 | if event.is_reply:
39 | reply_message = await event.get_reply_message()
40 | data = await check_media(reply_message)
41 |
42 | if isinstance(data, bool):
43 | await event.edit(LANG['CANT_DEEPFRY'])
44 | return
45 | else:
46 | await event.edit(LANG['REPLY_PHOTO'])
47 | return
48 |
49 | # Fotoğrafı (yüksek çözünürlük) bayt dizisi olarak indir
50 | await event.edit(LANG['MEDIA_DOWNLOADING'])
51 | image = io.BytesIO()
52 | await event.client.download_media(data, image)
53 | image = Image.open(image)
54 |
55 | # Resime uygula
56 | await event.edit(LANG['APPLYING_DEEPFRY'])
57 | for _ in range(frycount):
58 | image = await deepfry(image)
59 |
60 | fried_io = io.BytesIO()
61 | fried_io.name = "image.jpeg"
62 | image.save(fried_io, "JPEG")
63 | fried_io.seek(0)
64 |
65 | await event.reply(file=fried_io)
66 |
67 |
68 | async def deepfry(img: Image) -> Image:
69 | colours = (
70 | (randint(50, 200), randint(40, 170), randint(40, 190)),
71 | (randint(190, 255), randint(170, 240), randint(180, 250))
72 | )
73 |
74 | img = img.copy().convert("RGB")
75 |
76 | # Resim formatı ayarla
77 | img = img.convert("RGB")
78 | width, height = img.width, img.height
79 | img = img.resize((int(width ** uniform(0.8, 0.9)), int(height ** uniform(0.8, 0.9))), resample=Image.LANCZOS)
80 | img = img.resize((int(width ** uniform(0.85, 0.95)), int(height ** uniform(0.85, 0.95))), resample=Image.BILINEAR)
81 | img = img.resize((int(width ** uniform(0.89, 0.98)), int(height ** uniform(0.89, 0.98))), resample=Image.BICUBIC)
82 | img = img.resize((width, height), resample=Image.BICUBIC)
83 | img = ImageOps.posterize(img, randint(3, 7))
84 |
85 | # Renk yerleşimi oluştur
86 | overlay = img.split()[0]
87 | overlay = ImageEnhance.Contrast(overlay).enhance(uniform(1.0, 2.0))
88 | overlay = ImageEnhance.Brightness(overlay).enhance(uniform(1.0, 2.0))
89 |
90 | overlay = ImageOps.colorize(overlay, colours[0], colours[1])
91 |
92 | # Kırmızı ve sarıyı ana görüntüye yerleştir ve keskinleştir
93 | img = Image.blend(img, overlay, uniform(0.1, 0.4))
94 | img = ImageEnhance.Sharpness(img).enhance(randint(5, 300))
95 |
96 | return img
97 |
98 |
99 | async def check_media(reply_message):
100 | if reply_message and reply_message.media:
101 | if reply_message.photo:
102 | data = reply_message.photo
103 | elif reply_message.document:
104 | if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
105 | return False
106 | if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
107 | return False
108 | data = reply_message.media.document
109 | else:
110 | return False
111 | else:
112 | return False
113 |
114 | if not data or data is None:
115 | return False
116 | else:
117 | return data
118 |
119 | CmdHelp('deepfry').add_command(
120 | 'deepfry', '', 'Belirlenen görüntüye deepfry efekti uygular.', 'deepfry 5'
121 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/lyrics.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | import os
11 | import lyricsgenius
12 | import asyncio
13 |
14 | from userbot.events import register
15 | from userbot import CMD_HELP, GENIUS
16 | from userbot.cmdhelp import CmdHelp
17 |
18 | # ██████ LANGUAGE CONSTANTS ██████ #
19 |
20 | from userbot.language import get_value
21 | LANG = get_value("lyrics")
22 |
23 | # ████████████████████████████████ #
24 |
25 | @register(outgoing=True, pattern="^.lyrics(?: |$)(.*)")
26 | async def lyrics(lyric):
27 | if r"-" in lyric.text:
28 | pass
29 | else:
30 | await lyric.edit(LANG['WRONG_TYPE'])
31 | return
32 |
33 | if GENIUS is None:
34 | await lyric.edit(
35 | LANG['GENIUS_NOT_FOUND'])
36 | return
37 | else:
38 | genius = lyricsgenius.Genius(GENIUS)
39 | try:
40 | args = lyric.text.split('.lyrics')[1].split('-')
41 | artist = args[0].strip(' ')
42 | song = args[1].strip(' ')
43 | except:
44 | await lyric.edit(LANG['GIVE_INFO'])
45 | return
46 |
47 | if len(args) < 1:
48 | await lyric.edit(LANG['GIVE_INFO'])
49 | return
50 |
51 | await lyric.edit(LANG['SEARCHING'].format(artist, song))
52 |
53 | try:
54 | songs = genius.search_song(song, artist)
55 | except TypeError:
56 | songs = None
57 |
58 | if songs is None:
59 | await lyric.edit(LANG['NOT_FOUND'].format(artist, song))
60 | return
61 | if len(songs.lyrics) > 4096:
62 | await lyric.edit(LANG['TOO_LONG'])
63 | with open("lyrics.txt", "w+") as f:
64 | f.write(f"{LANG['LYRICS']} \n{artist} - {song}\n\n{songs.lyrics}")
65 | await lyric.client.send_file(
66 | lyric.chat_id,
67 | "lyrics.txt",
68 | reply_to=lyric.id,
69 | )
70 | os.remove("lyrics.txt")
71 | else:
72 | await lyric.edit(f"{LANG['LYRICS']} \n`{artist} - {song}`\n\n```{songs.lyrics}```")
73 | return
74 |
75 | @register(outgoing=True, pattern="^.singer(?: |$)(.*)")
76 | async def singer(lyric):
77 | if r"-" in lyric.text:
78 | pass
79 | else:
80 | await lyric.edit(LANG['WRONG_TYPE'])
81 | return
82 |
83 | if GENIUS is None:
84 | await lyric.edit(
85 | LANG['GENIUS_NOT_FOUND'])
86 | return
87 | else:
88 | genius = lyricsgenius.Genius(GENIUS)
89 | try:
90 | args = lyric.text.split('.singer')[1].split('-')
91 | artist = args[0].strip(' ')
92 | song = args[1].strip(' ')
93 | except:
94 | await lyric.edit(LANG['GIVE_INFO'])
95 | return
96 |
97 | if len(args) < 1:
98 | await lyric.edit(LANG['GIVE_INFO'])
99 | return
100 |
101 | await lyric.edit(LANG['SEARCHING'].format(artist, song))
102 |
103 | try:
104 | songs = genius.search_song(song, artist)
105 | except TypeError:
106 | songs = None
107 |
108 | if songs is None:
109 | await lyric.edit(LANG['NOT_FOUND'].format(artist, song))
110 | return
111 | await lyric.edit(LANG['SINGER_LYRICS'].format(artist, song))
112 | await asyncio.sleep(1)
113 |
114 | split = songs.lyrics.splitlines()
115 | i = 0
116 | while i < len(split):
117 | try:
118 | if split[i] != None:
119 | await lyric.edit(split[i])
120 | await asyncio.sleep(2)
121 | i += 1
122 | except:
123 | i += 1
124 | await lyric.edit(LANG['SINGER_ENDED'])
125 |
126 | return
127 |
128 |
129 |
130 | CMD_HELP.update({
131 | "lyrics":
132 | "Kullanım: .`lyrics - <şarkı ismi>`\n"
133 | "NOT: ""-"" ayracı önemli!",
134 | "singer":
135 | "Şarkı söyler, Kullanım: .`singer - <şarkı ismi>`\n"
136 | "NOT: ""-"" ayracı önemli!"
137 |
138 | })
139 |
140 | CmdHelp('lyrics').add_command(
141 | 'lyrics', ' - <şarkı ismi>', 'Şarkı sözlerini getirir.', 'lyrics System Of a Down - Scince'
142 | ).add_command(
143 | 'singer', ' - <şarkı ismi>', 'Şarkı söyler.', 'singer System Of a Down - Scince'
144 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/spammer.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | import asyncio
11 | import threading
12 |
13 | from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
14 | from userbot.events import register
15 | from userbot.cmdhelp import CmdHelp
16 |
17 | @register(outgoing=True, pattern="^.tspam")
18 | async def tmeme(e):
19 | message = e.text
20 | messageSplit = message.split(" ", 1)
21 | tspam = str(messageSplit[1])
22 | message = tspam.replace(" ", "")
23 | for letter in message:
24 | await e.respond(letter)
25 | await e.delete()
26 | if BOTLOG:
27 | await e.client.send_message(
28 | BOTLOG_CHATID,
29 | "#TSPAM \n\n"
30 | "TSpam başarıyla gerçekleştirildi"
31 | )
32 |
33 | @register(outgoing=True, pattern="^.spam")
34 | async def spammer(e):
35 | if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
36 | message = e.text
37 | messageSplit = message.split(" ", 2)
38 | counter = int(messageSplit[1])
39 | spam_message = str(messageSplit[2])
40 | await asyncio.wait([e.respond(spam_message) for i in range(counter)])
41 | await e.delete()
42 | if BOTLOG:
43 | await e.client.send_message(
44 | BOTLOG_CHATID,
45 | "#SPAM \n\n"
46 | "Spam başarıyla gerçekleştirildi"
47 | )
48 |
49 | @register(outgoing=True, pattern="^.bigspam")
50 | async def bigspam(e):
51 | if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
52 | message = e.text
53 | messageSplit = message.split(" ", 2)
54 | counter = int(messageSplit[1])
55 | spam_message = str(messageSplit[2])
56 | for i in range(1, counter):
57 | await e.respond(spam_message)
58 | await e.delete()
59 | if BOTLOG:
60 | await e.client.send_message(
61 | BOTLOG_CHATID,
62 | "#BIGSPAM \n\n"
63 | "Bigspam başarıyla gerçekleştirildi"
64 | )
65 |
66 |
67 | @register(outgoing=True, pattern="^.picspam")
68 | async def tiny_pic_spam(e):
69 | if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
70 | message = e.text
71 | text = message.split()
72 | counter = int(text[1])
73 | link = str(text[2])
74 | for i in range(1, counter):
75 | await e.client.send_file(e.chat_id, link)
76 | await e.delete()
77 | if BOTLOG:
78 | await e.client.send_message(
79 | BOTLOG_CHATID,
80 | "#PICSPAM \n\n"
81 | "PicSpam başarıyla gerçekleştirildi"
82 | )
83 |
84 |
85 | @register(outgoing=True, pattern="^.delayspam")
86 | async def delayspammer(e):
87 | # Teşekkürler @ReversedPosix
88 | if not e.text[0].isalpha() and e.text[0] not in ("/", "#", "@", "!"):
89 | message = e.text
90 | messageSplit= message.split(" ", 3)
91 | spam_delay = float(messageSplit[1])
92 | counter = int(messageSplit[2])
93 | spam_message = str(messageSplit[3])
94 | from userbot.events import register
95 | await e.delete()
96 | delaySpamEvent = threading.Event()
97 | for i in range(1, counter):
98 | await e.respond(spam_message)
99 | delaySpamEvent.wait(spam_delay)
100 | if BOTLOG:
101 | await e.client.send_message(
102 | BOTLOG_CHATID,
103 | "#DelaySPAM \n\n"
104 | "DelaySpam başarıyla gerçekleştirildi"
105 | )
106 |
107 | CmdHelp('spammer').add_command(
108 | 'tspam', '', 'Verilen mesajı tek tek göndererek spam yapar.'
109 | ).add_command(
110 | 'spam', ' ', 'Verilen miktarda spam gönderir.'
111 | ).add_command(
112 | 'bigspam', ' ', 'Verilen miktarda spam gönderir.'
113 | ).add_command(
114 | 'picspam', ' ', 'Verilen miktarda resimli spam gönderir.'
115 | ).add_command(
116 | 'delayspam', ' ', 'Verilen miktar ve verilen gecikme ile gecikmeli spam yapar.'
117 | ).add_warning(
118 | 'Sorumluluk size aittir!!'
119 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/snips.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """ Küresel notlar tutmak için yapılmış olan UserBot modülü. """
11 |
12 | from userbot.events import register
13 | from userbot import CMD_HELP, BOTLOG_CHATID
14 | from userbot.cmdhelp import CmdHelp
15 |
16 | # ██████ LANGUAGE CONSTANTS ██████ #
17 |
18 | from userbot.language import get_value
19 | LANG = get_value("snips")
20 |
21 | # ████████████████████████████████
22 |
23 | @register(outgoing=True,
24 | pattern=r"\$\w*",
25 | ignore_unsafe=True,
26 | disable_errors=True)
27 | async def on_snip(event):
28 | """ Snip mantığı. """
29 | try:
30 | from userbot.modules.sql_helper.snips_sql import get_snip
31 | except AttributeError:
32 | return
33 | name = event.text[1:]
34 | snip = get_snip(name)
35 | message_id_to_reply = event.message.reply_to_msg_id
36 | if not message_id_to_reply:
37 | message_id_to_reply = None
38 | if snip and snip.f_mesg_id:
39 | await event.delete()
40 | msg_o = await event.client.get_messages(entity=BOTLOG_CHATID,
41 | ids=int(snip.f_mesg_id))
42 | await event.client.send_message(event.chat_id,
43 | msg_o.message,
44 | reply_to=message_id_to_reply,
45 | file=msg_o.media)
46 | elif snip and snip.reply:
47 | await event.client.send_message(event.chat_id,
48 | snip.reply,
49 | reply_to=message_id_to_reply)
50 |
51 |
52 | @register(outgoing=True, pattern="^.snip (\w*)")
53 | async def on_snip_save(event):
54 | """ .snip komutu gelecekte kullanılmak üzere snips kaydeder. """
55 | try:
56 | from userbot.modules.sql_helper.snips_sql import add_snip
57 | except AtrributeError:
58 | await event.edit(LANG['NO_SQL'])
59 | return
60 | keyword = event.pattern_match.group(1)
61 | string = event.text.partition(keyword)[2]
62 | msg = await event.get_reply_message()
63 | msg_id = None
64 | if msg and msg.media and not string:
65 | if BOTLOG_CHATID:
66 | await event.client.send_message(
67 | BOTLOG_CHATID, f"#SNIP\
68 | \nKELIME: {keyword}\
69 | \n\nAşağıdaki mesaj snip için veri olarak kaydedilir, lütfen silmeyin !!"
70 | )
71 | msg_o = await event.client.forward_messages(
72 | entity=BOTLOG_CHATID,
73 | messages=msg,
74 | from_peer=event.chat_id,
75 | silent=True)
76 | msg_id = msg_o.id
77 | else:
78 | await event.edit(
79 | LANG['NEED_BOTLOG']
80 | )
81 | return
82 | elif event.reply_to_msg_id and not string:
83 | rep_msg = await event.get_reply_message()
84 | string = rep_msg.text
85 | success = "`Snip {}. {}:` **${}** `"
86 | if add_snip(keyword, string, msg_id) is False:
87 | await event.edit(success.format(LANG['UPDATED'], LANG['USAGE'], keyword))
88 | else:
89 | await event.edit(success.format(LANG['SAVED'], LANG['USAGE'], keyword))
90 |
91 |
92 | @register(outgoing=True, pattern="^.snips$")
93 | async def on_snip_list(event):
94 | """ .snips komutu sizin tarafınızdan kaydedilen snip'leri listeler. """
95 | try:
96 | from userbot.modules.sql_helper.snips_sql import get_snips
97 | except AttributeError:
98 | await event.edit("`SQL dışı modda çalışıyor!`")
99 | return
100 |
101 | message = LANG['NO_SNIP']
102 | all_snips = get_snips()
103 | for a_snip in all_snips:
104 | if message == LANG['NO_SNIP']:
105 | message = f"{LANG['SNIPS']}:\n"
106 | message += f"`${a_snip.snip}`\n"
107 | else:
108 | message += f"`${a_snip.snip}`\n"
109 |
110 | await event.edit(message)
111 |
112 |
113 | @register(outgoing=True, pattern="^.remsnip (\w*)")
114 | async def on_snip_delete(event):
115 | """ .remsnip komutu belirlenini snipi siler. """
116 | try:
117 | from userbot.modules.sql_helper.snips_sql import remove_snip
118 | except AttributeError:
119 | await event.edit("`SQL dışı modda çalışıyor!`")
120 | return
121 | name = event.pattern_match.group(1)
122 | if remove_snip(name) is True:
123 | await event.edit(f"`Snip:` **{name}** `{LANG['DELETED']}`")
124 | else:
125 | await event.edit(f"`Snip:` **{name}** `{LANG['NOT_FOUND']}` ")
126 |
127 | CmdHelp('snips').add_command(
128 | '$', None, 'Snipi çağırır.'
129 | ).add_command(
130 | 'snip', ' ', 'Bir snip (küresel not) olarak kaydeder. (Resimler, dokümanlar ve çıkartmalar ile çalışır !)'
131 | ).add_command(
132 | 'snips', None, 'Kaydedilen tüm snip\'leri listeler.'
133 | ).add_command(
134 | 'remsnip', '', 'Belirtilen snip\'i siler.'
135 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/weather.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """Bir bölgenin hava durumunu gösterir."""
11 |
12 | import json
13 | from requests import get
14 | from datetime import datetime
15 | from pytz import country_timezones as c_tz
16 | from pytz import timezone as tz
17 | from pytz import country_names as c_n
18 |
19 | from userbot import CMD_HELP, WEATHER_DEFCITY
20 | from userbot import OPEN_WEATHER_MAP_APPID as OWM_API
21 | from userbot.events import register
22 | from userbot.cmdhelp import CmdHelp
23 |
24 | # ===== CONSTANT =====
25 | # ██████ LANGUAGE CONSTANTS ██████ #
26 |
27 | from userbot.language import (get_value, LANGUAGE_JSON)
28 | LANG = get_value("weather")
29 |
30 | # ████████████████████████████████ #
31 |
32 | if WEATHER_DEFCITY:
33 | DEFCITY = WEATHER_DEFCITY
34 | else:
35 | DEFCITY = None
36 | # ====================
37 |
38 |
39 | async def get_tz(con):
40 | """ Verilen ülkenin zaman dilimini alır. """
41 | """ @aragon12 ve @zakaryan2004'e teşekkürler. """
42 | for c_code in c_n:
43 | if con == c_n[c_code]:
44 | return tz(c_tz[c_code][0])
45 | try:
46 | if c_n[con]:
47 | return tz(c_tz[con][0])
48 | except KeyError:
49 | return
50 |
51 |
52 | @register(outgoing=True, pattern="^.weather(?: |$)(.*)")
53 | async def get_weather(weather):
54 | """ .weather komutu bir bölgenin hava durumunu OpenWeatherMap üzerinden alır. """
55 |
56 | if not OWM_API:
57 | await weather.edit(
58 | LANG['NEED_API_KEY'])
59 | return
60 |
61 | APPID = OWM_API
62 |
63 | if not weather.pattern_match.group(1):
64 | CITY = DEFCITY
65 | if not CITY:
66 | await weather.edit(
67 | LANG['NO_CITY']
68 | )
69 | return
70 | else:
71 | CITY = weather.pattern_match.group(1)
72 |
73 | timezone_countries = {
74 | timezone: country
75 | for country, timezones in c_tz.items() for timezone in timezones
76 | }
77 |
78 | if "," in CITY:
79 | newcity = CITY.split(",")
80 | if len(newcity[1]) == 2:
81 | CITY = newcity[0].strip() + "," + newcity[1].strip()
82 | else:
83 | country = await get_tz((newcity[1].strip()).title())
84 | try:
85 | countrycode = timezone_countries[f'{country}']
86 | except KeyError:
87 | await weather.edit(LANG['INVALID_COUNTRY'])
88 | return
89 | CITY = newcity[0].strip() + "," + countrycode.strip()
90 |
91 | url = f'https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={APPID}&lang={LANGUAGE_JSON["LANGCODE"]}'
92 | request = get(url)
93 | result = json.loads(request.text)
94 |
95 | if request.status_code != 200:
96 | await weather.edit(LANG['INVALID_COUNTRY'])
97 | return
98 |
99 | cityname = result['name']
100 | curtemp = result['main']['temp']
101 | humidity = result['main']['humidity']
102 | min_temp = result['main']['temp_min']
103 | max_temp = result['main']['temp_max']
104 | desc = result['weather'][0]
105 | if "description" in desc and len(desc['description']) > 0:
106 | desc = desc['description']
107 | else:
108 | desc = desc['main']
109 | country = result['sys']['country']
110 | sunrise = result['sys']['sunrise']
111 | sunset = result['sys']['sunset']
112 | wind = result['wind']['speed']
113 | winddir = result['wind']['deg']
114 |
115 | ctimezone = tz(c_tz[country][0])
116 | time = datetime.now(ctimezone).strftime("%A, %I:%M %p")
117 | fullc_n = c_n[f"{country}"]
118 |
119 | dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
120 |
121 | div = (360 / len(dirs))
122 | funmath = int((winddir + (div / 2)) / div)
123 | findir = dirs[funmath % len(dirs)]
124 | kmph = str(wind * 3.6).split(".")
125 | mph = str(wind * 2.237).split(".")
126 |
127 | def fahrenheit(f):
128 | temp = str(((f - 273.15) * 9 / 5 + 32)).split(".")
129 | return temp[0]
130 |
131 | def celsius(c):
132 | temp = str((c - 273.15)).split(".")
133 | return temp[0]
134 |
135 | def sun(unix):
136 | xx = datetime.fromtimestamp(unix, tz=ctimezone).strftime("%I:%M %p")
137 | return xx
138 |
139 | await weather.edit(
140 | f"**{LANG['TEMP']}:** `{celsius(curtemp)}°C | {fahrenheit(curtemp)}°F`\n"
141 | +
142 | f"**{LANG['MIN_TEMP']}:** `{celsius(min_temp)}°C | {fahrenheit(min_temp)}°F`\n"
143 | +
144 | f"**{LANG['MAX_TEMP']}:** `{celsius(max_temp)}°C | {fahrenheit(max_temp)}°F`\n"
145 | + f"**{LANG['HUMIDITY']}:** `{humidity}%`\n" +
146 | f"**{LANG['WIND_SPEED']}:** `{kmph[0]} kmh | {mph[0]} mph, {findir}`\n" +
147 | f"**{LANG['SUNRISE']}:** `{sun(sunrise)}`\n" +
148 | f"**{LANG['SUNSET']}:** `{sun(sunset)}`\n\n" + f"**{desc}**\n" +
149 | f"`{cityname}, {fullc_n}`\n" + f"`{time}`")
150 |
151 | CmdHelp('weather').add_command(
152 | 'weather', '<şehir>', 'Bir bölgenin hava durumunu verir.'
153 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/purge.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """ Gereksiz mesajları temizlemek için UserBot modülü (genellikle spam veya ot). """
11 |
12 | from asyncio import sleep
13 |
14 | from telethon.errors import rpcbaseerrors
15 |
16 | from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
17 | from userbot.events import register
18 | from userbot.cmdhelp import CmdHelp
19 |
20 | # ██████ LANGUAGE CONSTANTS ██████ #
21 |
22 | from userbot.language import get_value
23 | LANG = get_value("purge")
24 |
25 | # ████████████████████████████████ #
26 |
27 | @register(outgoing=True, pattern="^.purge$")
28 | async def fastpurger(purg):
29 | """ .purge komutu hedeflenen yanıttan başlayarak tüm mesajları temizler. """
30 | chat = await purg.get_input_chat()
31 | msgs = []
32 | itermsg = purg.client.iter_messages(chat, min_id=purg.reply_to_msg_id)
33 | count = 0
34 |
35 | if purg.reply_to_msg_id is not None:
36 | async for msg in itermsg:
37 | msgs.append(msg)
38 | count = count + 1
39 | msgs.append(purg.reply_to_msg_id)
40 | if len(msgs) == 100:
41 | await purg.client.delete_messages(chat, msgs)
42 | msgs = []
43 | else:
44 | await purg.edit(LANG['NEED_MSG'])
45 | return
46 |
47 | if msgs:
48 | await purg.client.delete_messages(chat, msgs)
49 | done = await purg.client.send_message(
50 | purg.chat_id, LANG['PURGED'].format(str(count)))
51 |
52 | if BOTLOG:
53 | await purg.client.send_message(
54 | BOTLOG_CHATID,
55 | "Hedeflenen " + str(count) + " mesaj başarıyla silindi.")
56 | await sleep(2)
57 | await done.delete()
58 |
59 |
60 | @register(outgoing=True, pattern="^.purgeme")
61 | async def purgeme(delme):
62 | """ .purgeme komutu belirtilen miktarda kullanıcın mesajlarını siler. """
63 | message = delme.text
64 | count = int(message[9:])
65 | i = 1
66 |
67 | async for message in delme.client.iter_messages(delme.chat_id,
68 | from_user='me'):
69 | if i > count + 1:
70 | break
71 | i = i + 1
72 | await message.delete()
73 |
74 | smsg = await delme.client.send_message(
75 | delme.chat_id,
76 | LANG['PURGED_ME'].format(str(count))
77 | )
78 | if BOTLOG:
79 | await delme.client.send_message(
80 | BOTLOG_CHATID,
81 | "Hedeflenen " + str(count) + " mesaj başarıyla silindi.")
82 | await sleep(2)
83 | i = 1
84 | await smsg.delete()
85 |
86 |
87 | @register(outgoing=True, pattern="^.del$")
88 | async def delete_it(delme):
89 | """ .del komutu yanıtlanan mesajı siler. """
90 | msg_src = await delme.get_reply_message()
91 | if delme.reply_to_msg_id:
92 | try:
93 | await msg_src.delete()
94 | await delme.delete()
95 | if BOTLOG:
96 | await delme.client.send_message(
97 | BOTLOG_CHATID, "Hedeflenen mesajın silinmesi başarılıyla tamamlandı")
98 | except rpcbaseerrors.BadRequestError:
99 | if BOTLOG:
100 | await delme.client.send_message(
101 | BOTLOG_CHATID, "Bu mesajı silemiyorum.")
102 |
103 |
104 | @register(outgoing=True, pattern="^.edit")
105 | async def editer(edit):
106 | """ .editme komutu son mesajınızı düzenler. """
107 | message = edit.text
108 | chat = await edit.get_input_chat()
109 | self_id = await edit.client.get_peer_id('me')
110 | string = str(message[6:])
111 | i = 1
112 | async for message in edit.client.iter_messages(chat, self_id):
113 | if i == 2:
114 | await message.edit(string)
115 | await edit.delete()
116 | break
117 | i = i + 1
118 | if BOTLOG:
119 | await edit.client.send_message(BOTLOG_CHATID,
120 | "Mesaj düzenleme sorgusu başarıyla yürütüldü")
121 |
122 |
123 | @register(outgoing=True, pattern="^.sd")
124 | async def selfdestruct(destroy):
125 | """ .sd komutu kendi kendine yok edilebilir mesajlar yapar. """
126 | message = destroy.text
127 | counter = int(message[4:6])
128 | text = str(destroy.text[6:])
129 | await destroy.delete()
130 | smsg = await destroy.client.send_message(destroy.chat_id, text)
131 | await sleep(counter)
132 | await smsg.delete()
133 | if BOTLOG:
134 | await destroy.client.send_message(BOTLOG_CHATID,
135 | "sd sorgusu başarıyla tamamlandı")
136 |
137 | CmdHelp('purge').add_command(
138 | 'purge', None, 'Hedeflenen yanıttan başlayarak tüm mesajları temizler.'
139 | ).add_command(
140 | 'purgeme', '', 'Hedeflenen yanıttan başlayarak kendi mesajlarınızı temizler.'
141 | ).add_command(
142 | 'del', '', 'Yanıt verilen mesajı siler.'
143 | ).add_command(
144 | 'edit', '', 'Yanıt verdiğiniz mesajı yeni mesaj ile değiştirir.'
145 | ).add_command(
146 | 'sd', ' ', 'x saniye içinde kendini yok eden bir mesaj oluşturur.'
147 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/shazam.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 | # Telegram @Fusuf
9 |
10 | # Coded by @Fusuf
11 |
12 | from pydub import AudioSegment
13 | from json import dumps
14 | from userbot.events import register
15 | from .shazam_helper.communication import recognize_song_from_signature
16 | from .shazam_helper.algorithm import SignatureGenerator
17 | from requests import get
18 | from os import remove
19 | import urllib.parse
20 | from userbot.cmdhelp import CmdHelp
21 |
22 | @register(outgoing=True, pattern="^.shazam")
23 | async def shazam(event):
24 | if not event.is_reply:
25 | return await event.edit('`Lütfen bir ses dosyasına yanıt verin!`')
26 | else:
27 | await event.edit('`⬇️ Ses dosyası indiriliyor...`')
28 | reply_message = await event.get_reply_message()
29 | dosya = await reply_message.download_media()
30 |
31 | await event.edit('`🛠 Ses dosyası fingerprint formatına çeviriliyor...`')
32 | audio = AudioSegment.from_file(dosya)
33 | audio = audio.set_sample_width(2)
34 | audio = audio.set_frame_rate(16000)
35 | audio = audio.set_channels(1)
36 |
37 | signature_generator = SignatureGenerator()
38 | signature_generator.feed_input(audio.get_array_of_samples())
39 |
40 | signature_generator.MAX_TIME_SECONDS = 12
41 | if audio.duration_seconds > 12 * 3:
42 | signature_generator.samples_processed += 16000 * (int(audio.duration_seconds / 2) - 6)
43 |
44 | results = '{"error": "Not found"}'
45 | sarki = None
46 | await event.edit('`🎧 🎤 Shazamlanıyor...`')
47 | while True:
48 | signature = signature_generator.get_next_signature()
49 | if not signature:
50 | sarki = results
51 | break
52 | results = recognize_song_from_signature(signature)
53 | if results['matches']:
54 | sarki = results
55 | break
56 | else:
57 | await event.edit(f'`İlk {(signature_generator.samples_processed / 16000)} saniyede hiçbir şey bulunamadı... Biraz daha deniyorum.`')
58 |
59 | if not 'track' in sarki:
60 | return await event.edit('`Üzgünüm Shazam verdiniğiniz sesi anlamadı 😔. Biraz daha açık ses iletir misiniz?`')
61 | await event.edit('`✅ Şarkıyı buldum... Bilgiler getiriliyor...`')
62 | Caption = f'**Şarkı:** [{sarki["track"]["title"]}]({sarki["track"]["url"]})\n'
63 | if 'artists' in sarki['track']:
64 | Caption += f'**Sanatçı(lar):** [{sarki["track"]["subtitle"]}](https://www.shazam.com/artist/{sarki["track"]["artists"][0]["id"]})\n'
65 | else:
66 | Caption += f'**Sanatçı(lar):** `{sarki["track"]["subtitle"]}`\n'
67 |
68 | if 'genres'in sarki['track']:
69 | Caption += f'**Tür:** `{sarki["track"]["genres"]["primary"]}`\n'
70 |
71 | if sarki["track"]["sections"][0]["type"] == "SONG":
72 | for metadata in sarki["track"]["sections"][0]["metadata"]:
73 | Caption += f'**{"Yıl" if metadata["title"] == "Sorti" else metadata["title"]}:** `{metadata["text"]}`\n'
74 |
75 | Caption += '\n**Müzik Platformları:** '
76 | for provider in sarki['track']['hub']['providers']:
77 | if provider['actions'][0]['uri'].startswith('spotify:track'):
78 | Url = provider['actions'][0]['uri'].replace(
79 | 'spotify:track:', 'http://open.spotify.com/track/'
80 | )
81 | elif provider['actions'][0]['uri'].startswith('intent:#Intent;action=android.media.action.MEDIA_PLAY_FROM_SEARCH'):
82 | Url = f'https://open.spotify.com/search/' + urllib.parse.quote(sarki["track"]["subtitle"] + ' - ' + sarki["track"]["title"])
83 | elif provider['actions'][0]['uri'].startswith('deezer'):
84 | Url = provider['actions'][0]['uri'].replace(
85 | 'deezer-query://', 'https://'
86 | )
87 | else:
88 | Url = provider['actions'][0]['uri']
89 | Caption += f'[{provider["type"].capitalize()}]({Url}) '
90 | for section in sarki['track']['sections']:
91 | if section['type'] == 'VIDEO':
92 | if 'youtubeurl' in section:
93 | Youtube = get(section['youtubeurl']).json()
94 | else:
95 | return
96 |
97 | Caption += f'\n**Klip Videosu:** [Youtube]({Youtube["actions"][0]["uri"]})'
98 |
99 | if 'images' in sarki["track"] and len(sarki["track"]["images"]) >= 1:
100 | await event.delete()
101 | await event.client.send_file(
102 | event.chat_id,
103 | sarki["track"]["images"]["coverarthq"] if 'coverarthq' in sarki["track"]["images"] else sarki["track"]["images"]["background"],
104 | caption=Caption,
105 | reply_to=reply_message
106 | )
107 | else:
108 | await event.edit(Caption)
109 | remove(dosya)
110 |
111 | CmdHelp('shazam').add_command(
112 | 'shazam', '', 'Yanıt verdiğiniz ses dosyasını Shazamda arar.'
113 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/open_apis_game.py:
--------------------------------------------------------------------------------
1 | import aiohttp
2 | import asyncio
3 | import json
4 | import os
5 | import requests
6 | from userbot import CMD_HELP, bot
7 | from userbot.events import register
8 | from userbot.cmdhelp import CmdHelp
9 | # from userbot.language import get_value
10 |
11 |
12 | def download(url):
13 | response = requests.get(url)
14 | file = open("./avatar.jpg", "wb")
15 | file.write(response.content)
16 | file.close()
17 | return True
18 |
19 | @register(outgoing=True, pattern="^.game ?(.*)")
20 | async def apis(event):
21 | degerler = event.pattern_match.group(1)
22 |
23 | try:
24 | txt = degerler.split()
25 | game_old = txt[0]
26 | game = degerler
27 | except IndexError:
28 | return await event.edit("**Eksik Paramatreler!**\n\n**Örnek:** `game genshin`")
29 |
30 | await event.edit("__" + game + " Adlı oyunun sistem gereksinimleri toplanıyor..__")
31 | async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
32 | async with session.get('https://open-apis-rest.up.railway.app/api/game_specs?game=' + game) as response:
33 |
34 | html = await response.text()
35 | html2 = json.loads(html)
36 | if html2["status"] == "OK":
37 |
38 | name = html2["data"]["game"]["name"]
39 | release_date = html2["data"]["game"]["release_date"]
40 | genre = html2["data"]["game"]["genre"]
41 | dev = html2["data"]["game"]["developer"]
42 | owner = html2["data"]["game"]["publisher"]
43 | avatar = html2["data"]["game"]["avatar"]
44 |
45 | sy_min_cpu = html2["data"]["system_requirements"]["minimum"]["cpu"]
46 | sy_min_gpu = html2["data"]["system_requirements"]["minimum"]["gpu"]
47 | sy_min_ram = html2["data"]["system_requirements"]["minimum"]["ram"]
48 | sy_min_hdd = html2["data"]["system_requirements"]["minimum"]["hdd"]
49 | sy_min_drx = html2["data"]["system_requirements"]["minimum"]["directx"]
50 | sy_min_os = html2["data"]["system_requirements"]["minimum"]["os"]
51 |
52 | sy_rc_cpu = html2["data"]["system_requirements"]["recommended"]["cpu"]
53 | sy_rc_gpu = html2["data"]["system_requirements"]["recommended"]["gpu"]
54 | sy_rc_ram = html2["data"]["system_requirements"]["recommended"]["ram"]
55 | sy_rc_hdd = html2["data"]["system_requirements"]["recommended"]["hdd"]
56 | sy_rc_drx = html2["data"]["system_requirements"]["recommended"]["directx"]
57 | sy_rc_os = html2["data"]["system_requirements"]["recommended"]["os"]
58 |
59 | popularity = html2["data"]["reviews"]["popularity"]
60 | graphics = html2["data"]["reviews"]["graphics"]
61 | design = html2["data"]["reviews"]["design"]
62 | gameplay = html2["data"]["reviews"]["gameplay"]
63 | sound = html2["data"]["reviews"]["sound"]
64 | music = html2["data"]["reviews"]["music"]
65 | innovations = html2["data"]["reviews"]["innovations"]
66 | overall = html2["data"]["reviews"]["overall"]
67 |
68 | download(avatar)
69 | await event.client.send_file(
70 | event.chat_id, './avatar.png',
71 | caption="__Oyun:__ " + name +
72 | "\n__Yayın Tarihi:__ " + release_date +
73 | "\n__Tür:__ " + genre +
74 | "\n__Geliştirici:__ " + dev +
75 | "\n__Sahip Firma:__ " + owner +
76 | "\n\n**Minimum Sistem Gereksinimleri:**" +
77 | "\n__CPU:__ " + sy_min_cpu +
78 | "\n__GPU:__ " + sy_min_gpu +
79 | "\n__RAM:__ " + sy_min_ram +
80 | "\n__HDD:__ " + sy_min_hdd +
81 | "\n__DirectX:__ " + sy_min_drx +
82 | "\n__OS:__ " + sy_min_os +
83 | "\n\n**Önerilen Sistem Gereksinimleri:**" +
84 | "\n__CPU:__ " + sy_rc_cpu +
85 | "\n__GPU:__ " + sy_rc_gpu +
86 | "\n__RAM:__ " + sy_rc_ram +
87 | "\n__HDD:__ " + sy_rc_hdd +
88 | "\n__DirectX:__ " + sy_rc_drx +
89 | "\n__OS:__ " + sy_rc_os +
90 | "\n\n**İncelemeler:**" +
91 | "\n__Popülerite:__ " + popularity +
92 | "\n__Grafik:__ " + graphics +
93 | "\n__Dizayn:__ " + design +
94 | "\n__Oynanış:__ " + gameplay +
95 | "\n__Ses:__ " + sound +
96 | "\n__Müzik:__ " + music +
97 | "\n__Yenilik:__ " + innovations +
98 | "\n__Genel:__ " + overall
99 | )
100 | os.remove("./avatar.png")
101 | await event.delete()
102 | else:
103 | return await event.edit("__" + game + " Adında bir oyun bulunamadı.__")
104 |
105 | Help = CmdHelp('game')
106 | Help.add_command('game',
107 | '',
108 | 'Oyunun Sistem Gereksinimlerini Gösterir.',
109 | 'game genshin'
110 | )
111 | Help.add_info("@phaticusthiccy tarafından yapılmıştır.")
112 | Help.add()
113 |
--------------------------------------------------------------------------------
/userbot/modules/reverse.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # Teşekkürler @kandnub
10 | #
11 |
12 | """ Google'da görsel aramak için kullanılabilen UserBot modülü """
13 |
14 | import io
15 | import os
16 | import urllib
17 | import requests
18 | from bs4 import BeautifulSoup
19 | import re
20 | from PIL import Image
21 |
22 | from userbot import bot, CMD_HELP
23 | from userbot.events import register
24 | from userbot.cmdhelp import CmdHelp
25 |
26 | # ██████ LANGUAGE CONSTANTS ██████ #
27 |
28 | from userbot.language import get_value
29 | LANG = get_value("reverse")
30 |
31 | # ████████████████████████████████ #
32 |
33 | opener = urllib.request.build_opener()
34 | useragent = 'Mozilla/5.0 (Linux; Android 9; SM-G960F Build/PPR1.180610.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.70 Mobile Safari/537.36'
35 | opener.addheaders = [('User-agent', useragent)]
36 |
37 |
38 | @register(outgoing=True, pattern=r"^.reverse(?: |$)(\d*)")
39 | async def okgoogle(img):
40 | """ .reverse komutu Google'da görsel araması yapar """
41 | if os.path.isfile("okgoogle.png"):
42 | os.remove("okgoogle.png")
43 |
44 | message = await img.get_reply_message()
45 | if message and message.media:
46 | photo = io.BytesIO()
47 | await bot.download_media(message, photo)
48 | else:
49 | await img.edit(LANG['NEED_REPLY'])
50 | return
51 |
52 | if photo:
53 | await img.edit(LANG['TRYING'])
54 | try:
55 | image = Image.open(photo)
56 | except OSError:
57 | await img.edit(LANG['INVALID_TYPE'])
58 | return
59 | name = "okgoogle.png"
60 | image.save(name, "PNG")
61 | image.close()
62 | # https://stackoverflow.com/questions/23270175/google-reverse-image-search-using-post-request#28792943
63 | searchUrl = 'https://www.google.com/searchbyimage/upload'
64 | multipart = {
65 | 'encoded_image': (name, open(name, 'rb')),
66 | 'image_content': ''
67 | }
68 | response = requests.post(searchUrl,
69 | files=multipart,
70 | allow_redirects=False)
71 | fetchUrl = response.headers['Location']
72 |
73 | if response != 400:
74 | await img.edit(LANG['UPLOADED_TO_GOOGLE'])
75 | else:
76 | await img.edit(LANG['FUCKOFF'])
77 | return
78 |
79 | os.remove(name)
80 | match = await ParseSauce(fetchUrl +
81 | "&preferences?hl=en&fg=1#languages")
82 | guess = match['best_guess']
83 | imgspage = match['similar_images']
84 |
85 | if guess and imgspage:
86 | await img.edit(f"[{guess}]({fetchUrl})\n\n`{LANG['SEARCHING_PHOTO']}...`")
87 | else:
88 | await img.edit(LANG['NOT_FOUND'])
89 | return
90 |
91 | if img.pattern_match.group(1):
92 | lim = img.pattern_match.group(1)
93 | else:
94 | lim = 3
95 | images = await scam(match, lim)
96 | yeet = []
97 | for i in images:
98 | k = requests.get(i)
99 | yeet.append(k.content)
100 | try:
101 | await img.client.send_file(entity=await
102 | img.client.get_input_entity(img.chat_id
103 | ),
104 | file=yeet,
105 | reply_to=img)
106 | except TypeError:
107 | pass
108 | await img.edit(
109 | f"[{guess}]({fetchUrl})\n\n[{LANG['NOT_FOUND']}]({imgspage})")
110 |
111 |
112 | async def ParseSauce(googleurl):
113 | """ İstediğiniz bilgi için HTML kodunu ayrıştırın / kazıyın. """
114 |
115 | source = opener.open(googleurl).read()
116 | soup = BeautifulSoup(source, 'html.parser')
117 |
118 | results = {'similar_images': '', 'best_guess': ''}
119 |
120 | try:
121 | for similar_image in soup.findAll('input', {'class': 'gLFyf'}):
122 | url = 'https://www.google.com/search?tbm=isch&q=' + \
123 | urllib.parse.quote_plus(similar_image.get('value'))
124 | results['similar_images'] = url
125 | except BaseException:
126 | pass
127 |
128 | for best_guess in soup.findAll('div', attrs={'class': 'r5a77d'}):
129 | results['best_guess'] = best_guess.get_text()
130 |
131 | return results
132 |
133 |
134 | async def scam(results, lim):
135 |
136 | single = opener.open(results['similar_images']).read()
137 | decoded = single.decode('utf-8')
138 |
139 | imglinks = []
140 | counter = 0
141 |
142 | pattern = r'^,\[\"(.*[.png|.jpg|.jpeg])\",[0-9]+,[0-9]+\]$'
143 | oboi = re.findall(pattern, decoded, re.I | re.M)
144 |
145 | for imglink in oboi:
146 | counter += 1
147 | if not counter >= int(lim):
148 | imglinks.append(imglink)
149 | else:
150 | break
151 |
152 | return imglinks
153 |
154 | CmdHelp('reverse').add_command(
155 | 'reverse', '', 'Fotoğraf veya çıkartmaya yanıt vererek görüntüyü Google üzerniden arayabilirsiniz.'
156 | ).add()
--------------------------------------------------------------------------------
/init/init_script.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env dash
2 |
3 | set -e
4 |
5 | scr_dir=$(realpath $(dirname $0))
6 | prog_f=$scr_dir/.progress
7 |
8 | reset_prog() {
9 | if [ -f "$prog_f" ]; then
10 | echo "Cleaning: $prog_f"
11 | rm $prog_f
12 | fi
13 | echo "Al progress has been reset.. now u can re-run the script from start"
14 | exit
15 | }
16 |
17 | save_prog() {
18 | echo "$1=y" >> $prog_f
19 | }
20 |
21 | #reset progress.. if user prompted
22 | [ "$1" = "--reset" ] && reset_prog
23 |
24 | #load progress... if any
25 | [ -f "$prog_f" ] && source $prog_f
26 |
27 | # Welcome Message
28 | welcome() {
29 | echo "*****Welcome to Quiec's userbot setup*****
30 | This Guided Setup shall help you get your own userbot up and running.
31 | You might be asked for sudo password several number of times."
32 | }
33 |
34 | # Package requirements install
35 | packageinstall() {
36 | # add-apt-repository only exists in Ubuntu
37 | [ "$(lsb_release -is)" = "Ubuntu" ] && sudo add-apt-repository ppa:deadsnakes/ppa
38 |
39 | sudo apt --yes --force-yes upgrade
40 | sudo apt --yes --force-yes install build-essential checkinstall git \
41 | libreadline-gplv2-dev libncursesw5-dev libssl-dev wget \
42 | libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
43 | sudo apt --yes --force-yes install python3.7 docker
44 | }
45 |
46 | # Clone the required repo
47 | botclone() {
48 | cd ~
49 | echo "Cloning bot sources..."
50 | if [ -z "$bot_clone" ]; then
51 | git clone https://github.com/Quuiec/AsenaUserBot -b master
52 | save_prog "bot_clone"
53 | fi
54 | echo "DONE!!"
55 | cd Telegram-UserBot
56 | }
57 |
58 | # Requirement install function
59 | reqinstall() {
60 | echo "***Installing Requirements***"
61 | if [ -z "$req" ]; then
62 | sudo python3.7 -m pip install -r requirements.txt
63 | clear
64 | save_prog "req"
65 | fi
66 | echo "DONE!!"
67 | }
68 |
69 | DB="n"
70 |
71 | # Questionaire
72 | questions() {
73 | echo "***Please enter your details***"
74 | read -r -p "What's your API_ID? " API_KEY
75 | read -r -p "What's your API_HASH? " API_HASH
76 | read -r -p "What's your Screenshot Layer API Key? " SCREENSHOT_LAYER_ACCESS_KEY
77 |
78 | read -r -p "Do you need PMPermit Enabled? (y/n) " PMPERMIT
79 | if [ "$PMPERMIT" = "y" ]; then
80 | PM_AUTO_BAN=True
81 | else
82 | PM_AUTO_BAN=False
83 | fi
84 |
85 | read -r -p "Do you need Logging Enabled? (y/n) " LOG
86 | if [ "$LOG" = "y" ]; then
87 | read -r -p "Enter the Log Group ID: " LOGGER_GROUP
88 | LOGGER=True
89 | else
90 | LOGGER=False
91 | LOGGER_GROUP=0
92 | fi
93 | read -r -p "What's your OpenWeatherMap API Key? " OPEN_WEATHER_MAP_APPID
94 |
95 | read -r -p "Do you need a Database Mode? (y/n) " DB
96 | if [ "$DB" = "y" ]; then
97 | read -r -p "Enter your DB URL: " DB_URI
98 | else
99 | DB_URI=None
100 | fi
101 | }
102 |
103 | #Fixup the postgresql server
104 | postgresconfig() {
105 | echo "PostgreSQL config..."
106 | if [ -z "$psql" ]; then
107 | TRACK = echo `ls /etc/postgresql`
108 | sudo mv init/pg_hba.conf /etc/postgresql/$TRACK/main/pg_hba.conf
109 | sudo echo "listen_address = '*'" >> postgresql.conf
110 | save_prog "psql"
111 | fi
112 | echo "DONE!!"
113 | }
114 |
115 | # Config write function
116 | writeconfig() {
117 | echo "Configuring..."
118 | if [ -z "$gen_conf" ]; then
119 | questions
120 | echo "API_KEY=$API_KEY
121 | API_HASH=$API_HASH
122 | SCREENSHOT_LAYER_ACCESS_KEY=$SCREENSHOT_LAYER_ACCESS_KEY
123 | PM_AUTO_BAN=$PM_AUTO_BAN
124 | LOGGER=$LOGGER
125 | LOGGER_GROUP=$LOGGER_GROUP
126 | OPEN_WEATHER_MAP_APPID=$OPEN_WEATHER_MAP_APPID
127 | DATABASE_URL=$DB_URI" >> config.env
128 | sudo mv config.env ~/Telegram-UserBot
129 | save_prog "gen_conf"
130 | fi
131 | echo "DONE!!"
132 | }
133 |
134 | #Generate the userbot.session
135 | session() {
136 | echo "Generating session..."
137 | if [ -z "$sess" ]; then
138 | python3 windows_startup_script.py
139 | python3.7 -m userbot test
140 | save_prog "sess"
141 | fi
142 | echo "DONE!!"
143 | }
144 |
145 | #Spinup Docker installation
146 | dockerspin() {
147 | echo "Docker installation..."
148 | if [ -z "$dock" ]; then
149 | sudo systemctl start docker
150 | sudo systemctl enable docker
151 | sudo chmod 777 /var/run/docker.sock
152 | cd ~/Telegram-UserBot
153 | docker build -t userbot .
154 | save_prog "dock"
155 | fi
156 | echo "DONE!!"
157 | }
158 |
159 | # Systemd service bringup
160 | systemd() {
161 | echo "Sys service..."
162 | if [ -z "$sysserv" ]; then
163 | sudo mv userbot /etc/systemd/system/userbot.service
164 | save_prog "sysserv"
165 | fi
166 | sudo systemctl start userbot.service
167 | sudo systemctl enable userbot.service
168 | echo "DONE!!"
169 | }
170 |
171 | # Close down
172 | close() {
173 | echo "
174 |
175 | Pushed to systemd service. Bot runs on docker, and it will run across reboots too.
176 |
177 | Hope you love using my bot."
178 | exit
179 | }
180 |
181 | #
182 | # Here's where the mejik happens
183 | #
184 | clear
185 | welcome
186 |
187 | createuser
188 | cd /tmp || exit
189 | botclone
190 |
191 | reqinstall
192 |
193 | writeconfig
194 |
195 | if [ "$DB" = "y" ]
196 | then
197 | postgresconfig
198 | fi
199 |
200 | session
201 | dockerspin
202 |
203 | systemd
204 | close
205 |
--------------------------------------------------------------------------------
/userbot/modules/sozluk.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # Turkish word meaning. Only Turkish. Coded @By_Azade, Asena uyarlaması @qulec
10 | #
11 |
12 | import requests
13 |
14 | import aiohttp
15 | import asyncio
16 | import json
17 |
18 | from userbot import CMD_HELP
19 | from userbot.events import register
20 | from bs4 import BeautifulSoup
21 | import os
22 | from json import loads
23 | from userbot.cmdhelp import CmdHelp
24 |
25 | def searchTureng_tr(word):
26 | url="https://tureng.com/tr/turkce-ingilizce/"+word
27 | try:
28 | answer = requests.get(url)
29 | except:
30 | return "No connection"
31 | soup = BeautifulSoup(answer.content, 'html.parser')
32 | trlated='{} Kelimesinin Anlamı/Anlamları:\n\n'.format(word)
33 | try:
34 | table = soup.find('table')
35 | td = table.find_all('td', attrs={'lang':'en'})
36 | # print(td)
37 | for val in td[0:5]:
38 | trlated = '{}👉 {}\n'.format(trlated , val.text )
39 | return trlated
40 | except:
41 | return "Sonuç bulunamadı"
42 |
43 | @register(outgoing=True, pattern="^.tureng ?(.*)")
44 | async def tureng(event):
45 | input_str = event.pattern_match.group(1)
46 | result = searchTureng_tr(input_str)
47 | await event.edit(result)
48 |
49 | def getSimilarWords(kelime, limit = 5):
50 | benzerler = []
51 | if not os.path.exists('autocomplete.json'):
52 | words = requests.get(f'https://sozluk.gov.tr/autocomplete.json')
53 | open('autocomplete.json', 'a+').write(words.text)
54 | words = words.json()
55 | else:
56 | words = loads(open('autocomplete.json', 'r').read())
57 |
58 | for word in words:
59 | if word['madde'].startswith(kelime) and not word['madde'] == kelime:
60 | if len(benzerler) > limit:
61 | break
62 | benzerler.append(word['madde'])
63 | benzerlerStr = ""
64 | for benzer in benzerler:
65 | if not benzerlerStr == "":
66 | benzerlerStr += ", "
67 | benzerlerStr += f"`{benzer}`"
68 | return benzerlerStr
69 |
70 | @register(outgoing=True, pattern="^.tdk ?(.*)")
71 | async def tdk(event):
72 | inp = event.pattern_match.group(1)
73 | await event.edit('**Bekle!**\n__Sözlükte arıyorum...__')
74 | async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
75 | async with session.get('https://open-apis-rest.up.railway.app/api/tdk?word=' + str(inp)) as response:
76 |
77 | html = await response.text()
78 | html2 = json.loads(html)
79 | if html2["status"] == "OK":
80 | SAVE = "./soz.mp3"
81 | resp = requests.get(html2["data"]["ses"])
82 | with open(SAVE, "wb") as f:
83 | f.write(resp.content)
84 |
85 | song = await event.client.send_file(event.chat_id, "./soz.mp3", voice_note=True)
86 | await event.client.send_message(event.chat_id, "**Kelime:** " + "__" + inp + "__" + "\n**Anlamı:** " + "__" + html2["data"]["anlam"] + "__" + "\n**Atasözü:** " + "__" + html2["data"]["atasozu"] + "__", reply_to=song, link_preview=False)
87 | await event.delete()
88 | else:
89 | return await event.edit(f'__Kelimeniz({inp}) Büyük Türkçe Sözlük\'te Bulunamadı!__')
90 |
91 | @register(outgoing=True, pattern="^.tdk2 ?(.*)")
92 | async def tdk(event):
93 | inp = event.pattern_match.group(1)
94 | await event.edit('**Bekle!**\n__Sözlükte arıyorum...__')
95 | response = requests.get(f'https://sozluk.gov.tr/gts?ara={inp}').json()
96 | if 'error' in response:
97 | await event.edit(f'**Kelimeniz({inp}) Büyük Türkçe Sözlük\'te Bulunamadı!**')
98 | words = getSimilarWords(inp)
99 | if not words == '':
100 | return await event.edit(f'__Kelimeniz({inp}) Büyük Türkçe Sözlük\'te Bulunamadı!__\n\n**Benzer Kelimeler:** {words}')
101 | else:
102 | anlamlarStr = ""
103 | for anlam in response[0]["anlamlarListe"]:
104 | anlamlarStr += f"\n**{anlam['anlam_sira']}.**"
105 | if ('ozelliklerListe' in anlam) and ((not anlam["ozelliklerListe"][0]["tam_adi"] == None) or (not anlam["ozelliklerListe"][0]["tam_adi"] == '')):
106 | anlamlarStr += f"__({anlam['ozelliklerListe'][0]['tam_adi']})__"
107 | anlamlarStr += f' ```{anlam["anlam"]}```'
108 |
109 | if response[0]["cogul_mu"] == '0':
110 | cogul = '❌'
111 | else:
112 | cogul = '✅'
113 |
114 | if response[0]["ozel_mi"] == '0':
115 | ozel = '❌'
116 | else:
117 | ozel = '✅'
118 |
119 |
120 | await event.edit(f'**Kelime:** `{inp}`\n\n**Çoğul Mu:** {cogul}\n**Özel Mi:** {ozel}\n\n**Anlamlar:**{anlamlarStr}')
121 | words = getSimilarWords(inp)
122 | if not words == '':
123 | return await event.edit(f'**Kelime:** `{inp}`\n\n**Çoğul Mu:** `{cogul}`\n**Özel Mi:** {ozel}\n\n**Anlamlar:**{anlamlarStr}' + f'\n\n**Benzer Kelimeler:** {words}')
124 |
125 |
126 | CmdHelp('sozluk').add_command(
127 | 'tdk', '', 'Verdiğiniz kelimeyi TDK Sözlükte arar.'
128 | ).add_command(
129 | 'tdk2', '', 'Kelimeyi TDK Sözlükte arar. (Daha Kapsamlı)'
130 | ).add_command(
131 | 'tureng', '', 'Verdiğiniz kelimeyi Tureng Sözlükte arar.'
132 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/song.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | import datetime
10 | import asyncio
11 | from telethon import events
12 | from telethon.errors.rpcerrorlist import YouBlockedUserError
13 | from telethon.tl.functions.account import UpdateNotifySettingsRequest
14 | from userbot import bot, CMD_HELP
15 | from userbot.events import register
16 | import os
17 | import subprocess
18 | import glob
19 | from random import randint
20 | from userbot.cmdhelp import CmdHelp
21 |
22 | # ██████ LANGUAGE CONSTANTS ██████ #
23 |
24 | from userbot.language import get_value
25 | LANG = get_value("song")
26 |
27 | # ████████████████████████████████ #
28 |
29 | @register(outgoing=True, pattern="^.deez(\d*|)(?: |$)(.*)")
30 | async def deezl(event):
31 | if event.fwd_from:
32 | return
33 | sira = event.pattern_match.group(1)
34 | if sira == '':
35 | sira = 0
36 | else:
37 | sira = int(sira)
38 |
39 | sarki = event.pattern_match.group(2)
40 | if len(sarki) < 1:
41 | if event.is_reply:
42 | sarki = await event.get_reply_message().text
43 | else:
44 | await event.edit(LANG['GIVE_ME_SONG'])
45 |
46 | await event.edit(LANG['SEARCHING'])
47 | chat = "@DeezerMusicBot"
48 | async with bot.conversation(chat) as conv:
49 | try:
50 | mesaj = await conv.send_message(str(randint(31,62)))
51 | sarkilar = await conv.get_response()
52 | await mesaj.edit(sarki)
53 | sarkilar = await conv.get_response()
54 | except YouBlockedUserError:
55 | await event.reply(LANG['BLOCKED_DEEZER'])
56 | return
57 | await event.client.send_read_acknowledge(conv.chat_id)
58 | if sarkilar.audio:
59 | await event.client.send_read_acknowledge(conv.chat_id)
60 | await event.client.send_message(event.chat_id, LANG['UPLOADED_WITH'], file=sarkilar.message)
61 | await event.delete()
62 | elif sarkilar.buttons[0][0].text == "No results":
63 | await event.edit(LANG['NOT_FOUND'])
64 | else:
65 | await sarkilar.click(sira)
66 | sarki = await conv.wait_event(events.NewMessage(incoming=True,from_users=595898211))
67 | await event.client.send_read_acknowledge(conv.chat_id)
68 | await event.client.send_message(event.chat_id, f"`{sarkilar.buttons[sira][0].text}` | " + LANG['UPLOADED_WITH'], file=sarki.message)
69 | await event.delete()
70 |
71 | @register(outgoing=True, pattern="^.song(?: |$)(.*)")
72 | async def port_song(event):
73 | if event.fwd_from:
74 | return
75 |
76 | cmd = event.pattern_match.group(1)
77 | if len(cmd) < 1:
78 | await event.edit(LANG['UPLOADED_WITH'])
79 |
80 | reply_to_id = event.message.id
81 | if event.reply_to_msg_id:
82 | reply_to_id = event.reply_to_msg_id
83 |
84 | await event.edit(LANG['SEARCHING_SPOT'])
85 | dosya = os.getcwd()
86 | os.system(f"spotdl --song {cmd} -f {dosya}")
87 | await event.edit(LANG['DOWNLOADED'])
88 |
89 | l = glob.glob("*.mp3")
90 | if len(l) >= 1:
91 | await event.edit(LANG['UPLOADING'])
92 | await event.client.send_file(
93 | event.chat_id,
94 | l[0],
95 | force_document=True,
96 | allow_cache=False,
97 | reply_to=reply_to_id
98 | )
99 | await event.delete()
100 | else:
101 | await event.edit(LANG['NOT_FOUND'])
102 | return
103 | os.system("rm -rf *.mp3")
104 | subprocess.check_output("rm -rf *.mp3",shell=True)
105 |
106 | @register(outgoing=True, pattern="^.songpl ?(.*)")
107 | async def songpl(event):
108 | if event.fwd_from:
109 | return
110 | DELAY_BETWEEN_EDITS = 0.3
111 | PROCESS_RUN_TIME = 100
112 | cmd = event.pattern_match.group(1)
113 |
114 | if len(cmd) < 1:
115 | await event.edit(LANG['USAGE_PL'])
116 |
117 | reply_to_id = event.message.id
118 | if event.reply_to_msg_id:
119 | reply_to_id = event.reply_to_msg_id
120 | await event.edit(LANG['SEARCHING_PL'])
121 | dosya = os.getcwd() + "/playlist/" + "pl.pl"
122 | klasor = os.getcwd() + "/playlist/"
123 | sonuc = os.system(f"spotdl --playlist {cmd} --write-to=\"{dosya}\"")
124 | sonuc2 = os.system(f"spotdl --list {dosya} -f {klasor}")
125 | await event.edit(LANG['DOWNLOADED'])
126 | l = glob.glob(f"{klasor}/*.mp3")
127 | i = 0
128 | if len(l) >= 1:
129 | while i < len(l):
130 | await event.reply(LANG['SENDING_SONGS'] + l[i])
131 | await event.client.send_file(
132 | event.chat_id,
133 | l[i],
134 | force_document=True,
135 | allow_cache=False,
136 | caption=cmd,
137 | reply_to=reply_to_id
138 | )
139 | else:
140 | await event.edit(LANG['NOT_FOUND_PL'])
141 | return
142 | os.system(f"rm -rf {klasor}/*.mp3")
143 | subprocess.check_output(f"rm -rf {klasor}/*.mp3",shell=True)
144 | os.system(f"rm -rf {klasor}/*.pl")
145 | subprocess.check_output(f"rm -rf {klasor}/*.pl",shell=True)
146 |
147 | CmdHelp('song').add_command(
148 | 'deez', '<şarkı ismi/youtube/spotify/soundcloud>', 'Birçok siteden şarkıyı arayıp, şarkıyı indirir.'
149 | ).add_command(
150 | 'song', '<şarkı ismi/youtube/spotify>', 'Şarkı indirir.'
151 | ).add_command(
152 | 'songpl', '', 'Spotify Playlist\'inden şarkı indirir'
153 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/qrcode.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """ QR kodları ile ilgili komutları içeren UserBot modülü. """
11 |
12 | import os
13 | import qrcode
14 | import barcode
15 | from barcode.writer import ImageWriter
16 | from urllib3 import PoolManager
17 | from bs4 import BeautifulSoup
18 | from userbot import CMD_HELP
19 | from userbot.events import register
20 | from userbot.cmdhelp import CmdHelp
21 |
22 | # ██████ LANGUAGE CONSTANTS ██████ #
23 |
24 | from userbot.language import get_value
25 | LANG = get_value("qrcode")
26 |
27 | # ████████████████████████████████ #
28 |
29 | @register(pattern=r"^.decode$", outgoing=True)
30 | async def parseqr(qr_e):
31 | """ .decode komutu cevap verilen fotoğraftan QR kodu / Barkod içeriğini alır """
32 | downloaded_file_name = await qr_e.client.download_media(
33 | await qr_e.get_reply_message())
34 |
35 | # QR kodunu çözmek için resmi ZXing web sayfasını ayrıştır
36 | files = {'f': open(downloaded_file_name, 'rb').read()}
37 | t_response = None
38 |
39 | try:
40 | http = PoolManager()
41 | t_response = http.request(
42 | 'POST', "https://zxing.org/w/decode", fields=files)
43 | t_response = t_response.data
44 | http.clear()
45 | except:
46 | pass
47 |
48 | os.remove(downloaded_file_name)
49 | if not t_response:
50 | await qr_e.edit(LANG['ERROR'])
51 | return
52 | soup = BeautifulSoup(t_response, "html.parser")
53 | qr_contents = soup.find_all("pre")[0].text
54 | await qr_e.edit(qr_contents)
55 |
56 |
57 | @register(pattern=r".barcode(?: |$)([\s\S]*)", outgoing=True)
58 | async def barcode_read(event):
59 | """ .barcode komutu verilen içeriği içeren bir barkod oluşturur. """
60 | await event.edit(LANG['TRYING'])
61 | input_str = event.pattern_match.group(1)
62 | message = f"{LANG['USAGE']} `.barcode <{LANG['TEXT']}>`"
63 | reply_msg_id = event.message.id
64 | if input_str:
65 | message = input_str
66 | elif event.reply_to_msg_id:
67 | previous_message = await event.get_reply_message()
68 | reply_msg_id = previous_message.id
69 | if previous_message.media:
70 | downloaded_file_name = await event.client.download_media(
71 | previous_message)
72 | m_list = None
73 | with open(downloaded_file_name, "rb") as fd:
74 | m_list = fd.readlines()
75 | message = ""
76 | for m in m_list:
77 | message += m.decode("UTF-8") + "\r\n"
78 | os.remove(downloaded_file_name)
79 | else:
80 | message = previous_message.message
81 | else:
82 | event.edit("SÖZDİZİMİ: `.barcode `")
83 | return
84 |
85 | bar_code_type = "code128"
86 | try:
87 | bar_code_mode_f = barcode.get(bar_code_type,
88 | message,
89 | writer=ImageWriter())
90 | filename = bar_code_mode_f.save(bar_code_type)
91 | await event.client.send_file(event.chat_id,
92 | filename,
93 | reply_to=reply_msg_id)
94 | os.remove(filename)
95 | except Exception as e:
96 | await event.edit("Lütfen `.barcode www.google.com` şeklinde(internet sitesi) kullanın. Herhangi bir mesajı barkod yapmak için `.makeqr` komutunu kullanabilirsiniz.")
97 | print(str(e))
98 | return
99 | await event.delete()
100 |
101 |
102 | @register(pattern=r".makeqr(?: |$)([\s\S]*)", outgoing=True)
103 | async def make_qr(makeqr):
104 | """ .makeqr komutu verilen içeriği içeren bir QR kodu yapar. """
105 | input_str = makeqr.pattern_match.group(1)
106 | message = f"{LANG['USAGE']}: `.makeqr <{LANG['TEXT']}>`"
107 | reply_msg_id = None
108 | if input_str:
109 | message = input_str
110 | elif makeqr.reply_to_msg_id:
111 | previous_message = await makeqr.get_reply_message()
112 | reply_msg_id = previous_message.id
113 | if previous_message.media:
114 | downloaded_file_name = await makeqr.client.download_media(
115 | previous_message)
116 | m_list = None
117 | with open(downloaded_file_name, "rb") as file:
118 | m_list = file.readlines()
119 | message = ""
120 | for media in m_list:
121 | message += media.decode("UTF-8") + "\r\n"
122 | os.remove(downloaded_file_name)
123 | else:
124 | message = previous_message.message
125 |
126 | qr = qrcode.QRCode(
127 | version=1,
128 | error_correction=qrcode.constants.ERROR_CORRECT_L,
129 | box_size=10,
130 | border=4,
131 | )
132 | qr.add_data(message)
133 | qr.make(fit=True)
134 | img = qr.make_image(fill_color="black", back_color="white")
135 | img.save("img_file.webp", "PNG")
136 | await makeqr.client.send_file(makeqr.chat_id,
137 | "img_file.webp",
138 | reply_to=reply_msg_id)
139 | os.remove("img_file.webp")
140 | await makeqr.delete()
141 |
142 | CmdHelp('qrcode').add_command(
143 | 'barcode', '', 'Verilen içerikten bir barkod yapın.', 'barcode www.google.com'
144 | ).add_command(
145 | 'decode', '', 'Barkod veya QRCode çözmek için.'
146 | ).add_command(
147 | 'makeqr', '', 'Verilen içerikten bir QR kodu yapın.', 'makeqr www.google.com'
148 | ).add()
--------------------------------------------------------------------------------
/userbot/events.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | """ Olayları yönetmek için UserBot modülü.
10 | UserBot'un ana bileşenlerinden biri. """
11 |
12 | import sys
13 | from asyncio import create_subprocess_shell as asyncsubshell
14 | from asyncio import subprocess as asyncsub
15 | from os import remove
16 | from time import gmtime, strftime
17 | from traceback import format_exc
18 |
19 | from telethon import events
20 |
21 | from userbot import bot, BOTLOG_CHATID, LOGSPAMMER, PATTERNS
22 |
23 |
24 | def register(**args):
25 | """ Yeni bir etkinlik kaydedin. """
26 | pattern = args.get('pattern', None)
27 | disable_edited = args.get('disable_edited', False)
28 | groups_only = args.get('groups_only', False)
29 | trigger_on_fwd = args.get('trigger_on_fwd', False)
30 | trigger_on_inline = args.get('trigger_on_inline', False)
31 | disable_errors = args.get('disable_errors', False)
32 |
33 | if pattern:
34 | args["pattern"] = pattern.replace("^.", "^["+ PATTERNS + "]")
35 | if "disable_edited" in args:
36 | del args['disable_edited']
37 |
38 | if "ignore_unsafe" in args:
39 | del args['ignore_unsafe']
40 |
41 | if "groups_only" in args:
42 | del args['groups_only']
43 |
44 | if "disable_errors" in args:
45 | del args['disable_errors']
46 |
47 | if "trigger_on_fwd" in args:
48 | del args['trigger_on_fwd']
49 |
50 | if "trigger_on_inline" in args:
51 | del args['trigger_on_inline']
52 |
53 | def decorator(func):
54 | async def wrapper(check):
55 | if not LOGSPAMMER:
56 | send_to = check.chat_id
57 | else:
58 | send_to = BOTLOG_CHATID
59 |
60 | if not trigger_on_fwd and check.fwd_from:
61 | return
62 |
63 | if check.via_bot_id and not trigger_on_inline:
64 | return
65 |
66 | if groups_only and not check.is_group:
67 | await check.respond("`Bunun bir grup olduğunu sanmıyorum.`")
68 | return
69 |
70 | try:
71 | await func(check)
72 |
73 |
74 | except events.StopPropagation:
75 | raise events.StopPropagation
76 | except KeyboardInterrupt:
77 | pass
78 | except BaseException:
79 | if not disable_errors:
80 | date = strftime("%Y-%m-%d %H:%M:%S", gmtime())
81 |
82 | text = "**USERBOT HATA RAPORU**\n"
83 | link = "[Asena Destek Grubu](https://t.me/AsenaSupport)"
84 | text += "İsterseniz, bunu rapor edebilirsiniz"
85 | text += f"- sadece bu mesajı buraya iletin {link}.\n"
86 | text += "Hata ve Tarih dışında hiçbir şey kaydedilmez\n"
87 |
88 | ftext = "========== UYARI =========="
89 | ftext += "\nBu dosya sadece burada yüklendi,"
90 | ftext += "\nsadece hata ve tarih kısmını kaydettik,"
91 | ftext += "\ngizliliğinize saygı duyuyoruz,"
92 | ftext += "\nburada herhangi bir gizli veri varsa"
93 | ftext += "\nbu hata raporu olmayabilir, kimse verilerinize ulaşamaz.\n"
94 | ftext += "================================\n\n"
95 | ftext += "--------USERBOT HATA GUNLUGU--------\n"
96 | ftext += "\nTarih: " + date
97 | ftext += "\nGrup ID: " + str(check.chat_id)
98 | ftext += "\nGönderen kişinin ID: " + str(check.sender_id)
99 | ftext += "\n\nOlay Tetikleyici:\n"
100 | ftext += str(check.text)
101 | ftext += "\n\nGeri izleme bilgisi:\n"
102 | ftext += str(format_exc())
103 | ftext += "\n\nHata metni:\n"
104 | ftext += str(sys.exc_info()[1])
105 | ftext += "\n\n--------USERBOT HATA GUNLUGU BITIS--------"
106 |
107 | command = "git log --pretty=format:\"%an: %s\" -10"
108 | ftext += "\n\n\nUserbot ID: QXNlbmEgVGVsZWdyYW0*"
109 | ftext += "\nSon 10 commit:\n"
110 |
111 | process = await asyncsubshell(command,
112 | stdout=asyncsub.PIPE,
113 | stderr=asyncsub.PIPE)
114 | stdout, stderr = await process.communicate()
115 | result = str(stdout.decode().strip()) \
116 | + str(stderr.decode().strip())
117 |
118 | ftext += result
119 |
120 | file = open("error.log", "w+")
121 | file.write(ftext)
122 | file.close()
123 |
124 | if LOGSPAMMER:
125 | await check.client.respond("`Üzgünüm, UserBot'um çöktü.\
126 | \nHata günlükleri UserBot günlük grubunda saklanır.`")
127 |
128 | await check.client.send_file(send_to,
129 | "error.log",
130 | caption=text)
131 | remove("error.log")
132 | else:
133 | pass
134 | if not disable_edited:
135 | bot.add_event_handler(wrapper, events.MessageEdited(**args))
136 | bot.add_event_handler(wrapper, events.NewMessage(**args))
137 |
138 | return wrapper
139 |
140 | return decorator
141 |
--------------------------------------------------------------------------------
/userbot/modules/autopp.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2020 Yusuf Usta.
2 | #
3 | # Licensed under the GPL-3.0 License;
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 | # @NaytSeyd tarafından portlanmıştır.
10 | # @frknkrc44 tarafından düzenlenmiştir.
11 | # @Fusuf tarafından AutoVideo yazılmıştır.
12 |
13 | import os
14 | from datetime import datetime
15 | from PIL import Image, ImageDraw, ImageFont
16 | from telethon.tl import functions
17 | from telethon.tl.types import InputMessagesFilterDocument
18 | from userbot import CMD_HELP, AUTO_PP, ASYNC_POOL
19 | from userbot.events import register
20 | import asyncio
21 | import random
22 | import shutil
23 | import requests
24 | import time
25 | from telethon.errors import VideoFileInvalidError
26 | from userbot.cmdhelp import CmdHelp
27 |
28 | # ██████ LANGUAGE CONSTANTS ██████ #
29 |
30 | from userbot.language import get_value
31 | LANG = get_value("autopp")
32 |
33 | # ████████████████████████████████ #
34 |
35 | # Before kang; please ask to @fusuf :) #
36 | @register(outgoing=True, pattern="^.autovideo ?(.*)$")
37 | async def autovideo(event):
38 | if 'autovideo' in ASYNC_POOL:
39 | await event.edit(LANG['VIDEO_ALREADY_CHANGING'])
40 | return
41 |
42 | if not event.reply_to_msg_id:
43 | return await event.edit(LANG['NEED_VIDEO'])
44 | else:
45 | await event.edit(LANG['SETTING_VIDEO'])
46 |
47 | # Telethon doesn't support download profile-video so ... #
48 | reply = await event.get_reply_message()
49 | video = await reply.download_media()
50 | yazi = event.pattern_match.group(1)
51 |
52 | try:
53 | os.remove("./pp.mp4")
54 | except:
55 | pass
56 |
57 | try:
58 | await event.client(functions.photos.UploadProfilePhotoRequest(
59 | video=await event.client.upload_file(video)
60 | ))
61 | except VideoFileInvalidError:
62 | return await event.edit(LANG['INVALID_VIDEO'])
63 |
64 | ASYNC_POOL.append('autovideo')
65 |
66 | await event.edit(LANG['STARTED_VIDEO'])
67 | while "autovideo" in ASYNC_POOL:
68 | saat = time.strftime("%H\.%M")
69 | tarih = time.strftime("%d\/%m\/%Y")
70 |
71 | if yazi:
72 | yazi = yazi.replace("$saat", saat).replace("$tarih", tarih)
73 | KOMUT = f"text=\'{yazi}\' :expansion=normal: y=h-line_h-10:x=(mod(5*n\,w+tw)-tw): fontcolor=white: fontsize=30: box=1: boxcolor=black@0.5: boxborderw=5: shadowx=2: shadowy=2"
74 | else:
75 | KOMUT = f"text=\'Saat\: {saat} Tarih\: {tarih} {yazi}\' :expansion=normal: y=h-line_h-10:x=(mod(5*n\,w+tw)-tw): fontcolor=white: fontsize=30: box=1: boxcolor=black@0.5: boxborderw=5: shadowx=2: shadowy=2"
76 |
77 | ses = await asyncio.create_subprocess_shell(f"ffmpeg -y -i '{video}' -vf drawtext=\"{KOMUT}\" pp.mp4")
78 | await ses.communicate()
79 |
80 | await event.client(functions.photos.UploadProfilePhotoRequest(
81 | video=await event.client.upload_file("pp.mp4")
82 | ))
83 | os.remove("./pp.mp4")
84 | await asyncio.sleep(60)
85 |
86 | os.remove(video)
87 |
88 | @register(outgoing=True, pattern="^.autopp (.*)")
89 | async def autopic(event):
90 | if 'autopic' in ASYNC_POOL:
91 | await event.edit(LANG['PHOTO_ALREADY_CHANGING'])
92 | return
93 |
94 | await event.edit(LANG['SETTING'])
95 |
96 | FONT_FILE_TO_USE = await get_font_file(event.client, "@FontDunyasi")
97 |
98 | downloaded_file_name = "./userbot/eskipp.png"
99 | r = requests.get(AUTO_PP)
100 |
101 | with open(downloaded_file_name, 'wb') as f:
102 | f.write(r.content)
103 | photo = "yenipp.png"
104 | await event.edit(LANG['SETTED'])
105 |
106 | ASYNC_POOL.append('autopic')
107 |
108 | while 'autopic' in ASYNC_POOL:
109 | shutil.copy(downloaded_file_name, photo)
110 | current_time = datetime.now().strftime("%H:%M")
111 | img = Image.open(photo)
112 | drawn_text = ImageDraw.Draw(img)
113 | fnt = ImageFont.truetype(FONT_FILE_TO_USE, 70)
114 | size = drawn_text.multiline_textsize(current_time, font=fnt)
115 | drawn_text.text(((img.width - size[0]) / 2, (img.height - size[1])),
116 | current_time, font=fnt, fill=(255, 255, 255))
117 | img.save(photo)
118 | file = await event.client.upload_file(photo) # pylint:disable=E0602
119 | try:
120 | await event.client(functions.photos.UploadProfilePhotoRequest( # pylint:disable=E0602
121 | file
122 | ))
123 | os.remove(photo)
124 | await asyncio.sleep(60)
125 | except:
126 | return
127 |
128 | async def get_font_file(client, channel_id):
129 | # Önce yazı tipi mesajlarını al
130 | font_file_message_s = await client.get_messages(
131 | entity=channel_id,
132 | filter=InputMessagesFilterDocument,
133 | # Bu işlem çok fazla kullanıldığında
134 | # "FLOOD_WAIT" yapmaya neden olabilir
135 | limit=None
136 | )
137 | # Yazı tipi listesinden rastgele yazı tipi al
138 | # https://docs.python.org/3/library/random.html#random.choice
139 | font_file_message = random.choice(font_file_message_s)
140 | # Dosya yolunu indir ve geri dön
141 | return await client.download_media(font_file_message)
142 |
143 | CmdHelp('autopp').add_command(
144 | 'autopp', None, 'Bu komut belirlediğiniz fotoğrafı profil resmi yapar ve bir saat ekler. Bu saat her dakika değişir.', '.autopp'
145 | ).add()
146 |
147 | CmdHelp('autovideo').add_command(
148 | 'autopp', None,
149 | 'Bu komut yanıt verdiğiniz videoyu profil video yapar ve bir saat veya tarih veya istediğiniz bir yazı ekler. Bu saat her dakika değişir. nEğer botun kendi yazısını kullanmak istiyorsanız ekstradan bir şey yazmayın. Kendi yazınızı eklemek istiyorsanız .autovideo yazı şeklinde kullanın. ',
150 | '.autovideo ahan saat $saat bu da tarih $tarih'
151 | ).add()
--------------------------------------------------------------------------------
/userbot/modules/notes.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2019 The Raphielscape Company LLC.
2 | #
3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License");
4 | # you may not use this file except in compliance with the License.
5 | #
6 |
7 | # Asena UserBot - Yusuf Usta
8 |
9 |
10 | """ Not tutma komutlarını içeren UserBot modülüdür. """
11 |
12 | from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP
13 | from userbot.events import register
14 | from asyncio import sleep
15 | from userbot.cmdhelp import CmdHelp
16 |
17 | # ██████ LANGUAGE CONSTANTS ██████ #
18 |
19 | from userbot.language import get_value
20 | LANG = get_value("notes")
21 |
22 | # ████████████████████████████████ #
23 |
24 | @register(outgoing=True, pattern="^.notes$")
25 | async def notes_active(svd):
26 | """ .notes komutu sohbette kaydedilmiş tüm notları listeler. """
27 | try:
28 | from userbot.modules.sql_helper.notes_sql import get_notes
29 | except AttributeError:
30 | await svd.edit("`Bot Non-SQL modunda çalışıyor!!`")
31 | return
32 | message = LANG['NOT_FOUND']
33 | notes = get_notes(svd.chat_id)
34 | for note in notes:
35 | if message == LANG['NOT_FOUND']:
36 | message = f"{LANG['NOTES']}:\n"
37 | message += "`#{}`\n".format(note.keyword)
38 | else:
39 | message += "`#{}`\n".format(note.keyword)
40 | await svd.edit(message)
41 |
42 |
43 | @register(outgoing=True, pattern=r"^.clear (\w*)")
44 | async def remove_notes(clr):
45 | """ .clear komutu istenilen notu siler. """
46 | try:
47 | from userbot.modules.sql_helper.notes_sql import rm_note
48 | except AttributeError:
49 | await clr.edit("`Bot Non-SQL modunda çalışıyor!!`")
50 | return
51 | notename = clr.pattern_match.group(1)
52 | if rm_note(clr.chat_id, notename) is False:
53 | return await clr.edit(" **{}** `{}`".format(notename, LANG['CLEAR_NOT_FOUND']))
54 | else:
55 | return await clr.edit(
56 | "**{}** `{}`".format(notename, LANG['CLEAR']))
57 |
58 |
59 | @register(outgoing=True, pattern=r"^.save (\w*)")
60 | async def add_note(fltr):
61 | """ .save komutu bir sohbette not kaydeder. """
62 | try:
63 | from userbot.modules.sql_helper.notes_sql import add_note
64 | except AttributeError:
65 | await fltr.edit("`Bot Non-SQL modunda çalışıyor!!`")
66 | return
67 | keyword = fltr.pattern_match.group(1)
68 | string = fltr.text.partition(keyword)[2]
69 | msg = await fltr.get_reply_message()
70 | msg_id = None
71 | if msg and msg.media and not string:
72 | if BOTLOG_CHATID:
73 | await fltr.client.send_message(
74 | BOTLOG_CHATID, f"#NOTE\
75 | \nGrup ID: {fltr.chat_id}\
76 | \nAnahtar kelime: {keyword}\
77 | \n\nBu mesaj sohbette notu cevaplamak için kaydedildi, lütfen bu mesajı silmeyin!"
78 | )
79 | msg_o = await fltr.client.forward_messages(entity=BOTLOG_CHATID,
80 | messages=msg,
81 | from_peer=fltr.chat_id,
82 | silent=True)
83 | msg_id = msg_o.id
84 | else:
85 | await fltr.edit(
86 | "`Bir medyayı not olarak kaydetmek için BOTLOG_CHATID değerinin ayarlanmış olması gereklidir.`"
87 | )
88 | return
89 | elif fltr.reply_to_msg_id and not string:
90 | rep_msg = await fltr.get_reply_message()
91 | string = rep_msg.text
92 | success = "`{} {}. ` #{} `{}`"
93 | if add_note(str(fltr.chat_id), keyword, string, msg_id) is False:
94 | return await fltr.edit(success.format(LANG['SUCCESS'], 'güncellendi', keyword, LANG['CALL']))
95 | else:
96 | return await fltr.edit(success.format(LANG['SUCCESS'], 'eklendi', keyword, LANG['CALL']))
97 |
98 |
99 | @register(pattern=r"#\w*",
100 | disable_edited=True,
101 | disable_errors=True,
102 | ignore_unsafe=True)
103 | async def incom_note(getnt):
104 | """ Notların mantığı. """
105 | try:
106 | if not (await getnt.get_sender()).bot:
107 | try:
108 | from userbot.modules.sql_helper.notes_sql import get_note
109 | except AttributeError:
110 | return
111 | notename = getnt.text[1:]
112 | note = get_note(getnt.chat_id, notename)
113 | message_id_to_reply = getnt.message.reply_to_msg_id
114 | if not message_id_to_reply:
115 | message_id_to_reply = None
116 | if note and note.f_mesg_id:
117 | msg_o = await getnt.client.get_messages(entity=BOTLOG_CHATID,
118 | ids=int(
119 | note.f_mesg_id))
120 | await getnt.client.send_message(getnt.chat_id,
121 | msg_o.mesage,
122 | reply_to=message_id_to_reply,
123 | file=msg_o.media)
124 | elif note and note.reply:
125 | await getnt.client.send_message(getnt.chat_id,
126 | note.reply,
127 | reply_to=message_id_to_reply)
128 | except AttributeError:
129 | pass
130 |
131 | CmdHelp('notes').add_command(
132 | '#', None, 'Belirtilen notu çağırır.'
133 | ).add_command(
134 | 'save', ' ya da bir mesajı .save şeklinde yanıtlayarak kullanılır', 'Yanıtlanan mesajı ismiyle birlikte bir not olarak kaydeder. (Resimler, belgeler ve çıkartmalarda da çalışır.)'
135 | ).add_command(
136 | 'notes', None, 'Bir sohbetteki tüm notları çağırır.'
137 | ).add_command(
138 | 'clear', '', 'Belirtilen notu siler.'
139 | ).add()
--------------------------------------------------------------------------------