functions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. """
  2. MIT License
  3. Copyright (c) 2021 TheHamkerCat
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. SOFTWARE.
  19. """
  20. from asyncio import gather, get_running_loop
  21. from datetime import datetime, timedelta
  22. from io import BytesIO
  23. from math import atan2, cos, radians, sin, sqrt
  24. from os import execvp
  25. from random import randint
  26. from re import findall
  27. from sys import executable
  28. from time import time
  29. import aiofiles
  30. import aiohttp
  31. import speedtest
  32. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  33. from pyrogram.types import Message
  34. from wget import download
  35. from wbb import aiohttpsession as aiosession
  36. from wbb import arq
  37. from wbb.utils import aiodownloader
  38. from wbb.utils.dbfunctions import start_restart_stage
  39. from wbb.utils.http import get
  40. """
  41. Just import 'downloader' anywhere and do downloader.download() to
  42. download file from a given url
  43. """
  44. downloader = aiodownloader.Handler()
  45. # Another downloader, but with wget
  46. async def download_url(url: str):
  47. loop = get_running_loop()
  48. file = await loop.run_in_executor(None, download, url)
  49. return file
  50. async def restart(m: Message):
  51. if m:
  52. await start_restart_stage(m.chat.id, m.message_id)
  53. execvp(executable, [executable, "-m", "wbb"])
  54. def generate_captcha():
  55. # Generate one letter
  56. def gen_letter():
  57. return chr(randint(65, 90))
  58. def rndColor():
  59. return (randint(64, 255), randint(64, 255), randint(64, 255))
  60. def rndColor2():
  61. return (randint(32, 127), randint(32, 127), randint(32, 127))
  62. # Generate a 4 letter word
  63. def gen_wrong_answer():
  64. word = ""
  65. for _ in range(4):
  66. word += gen_letter()
  67. return word
  68. # Generate 8 wrong captcha answers
  69. wrong_answers = []
  70. for _ in range(8):
  71. wrong_answers.append(gen_wrong_answer())
  72. width = 80 * 4
  73. height = 100
  74. correct_answer = ""
  75. font = ImageFont.truetype("assets/arial.ttf", 55)
  76. file = f"assets/{randint(1000, 9999)}.jpg"
  77. image = Image.new("RGB", (width, height), (255, 255, 255))
  78. draw = ImageDraw.Draw(image)
  79. # Draw random points on image
  80. for x in range(width):
  81. for y in range(height):
  82. draw.point((x, y), fill=rndColor())
  83. for t in range(4):
  84. letter = gen_letter()
  85. correct_answer += letter
  86. draw.text(
  87. (60 * t + 50, 15), letter, font=font, fill=rndColor2()
  88. )
  89. image = image.filter(ImageFilter.BLUR)
  90. image.save(file, "jpeg")
  91. return [file, correct_answer, wrong_answers]
  92. def test_speedtest():
  93. def speed_convert(size):
  94. power = 2 ** 10
  95. zero = 0
  96. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  97. while size > power:
  98. size /= power
  99. zero += 1
  100. return f"{round(size, 2)} {units[zero]}"
  101. speed = speedtest.Speedtest()
  102. info = speed.get_best_server()
  103. download = speed.download()
  104. upload = speed.upload()
  105. return [speed_convert(download), speed_convert(upload), info]
  106. async def file_size_from_url(url: str) -> int:
  107. async with aiosession.head(url) as resp:
  108. size = int(resp.headers["content-length"])
  109. return size
  110. async def get_http_status_code(url: str) -> int:
  111. async with aiosession.head(url) as resp:
  112. return resp.status
  113. async def make_carbon(code):
  114. url = "https://carbonara.vercel.app/api/cook"
  115. async with aiosession.post(url, json={"code": code}) as resp:
  116. image = BytesIO(await resp.read())
  117. image.name = "carbon.png"
  118. return image
  119. async def transfer_sh(file_or_message):
  120. if isinstance(file_or_message, Message):
  121. file_or_message = await file_or_message.download()
  122. file = file_or_message
  123. async with aiofiles.open(file, "rb") as f:
  124. params = {file: await f.read()}
  125. async with aiohttp.ClientSession() as session:
  126. async with session.post(
  127. "https://transfer.sh/", data=params
  128. ) as resp:
  129. download_link = str(await resp.text()).strip()
  130. return download_link
  131. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  132. Radius_Earth = 6371.0088
  133. data1, data2 = await gather(
  134. get(f"http://ipinfo.io/{ip1}"),
  135. get(f"http://ipinfo.io/{ip2}"),
  136. )
  137. lat1, lon1 = data1["loc"].split(",")
  138. lat2, lon2 = data2["loc"].split(",")
  139. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  140. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  141. dlon = lon2 - lon1
  142. dlat = lat2 - lat1
  143. a = (
  144. sin(dlat / 2) ** 2
  145. + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  146. )
  147. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  148. distance = Radius_Earth * c
  149. return distance
  150. def get_urls_from_text(text: str) -> bool:
  151. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  152. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  153. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  154. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  155. return [x[0] for x in findall(regex, text)]
  156. async def time_converter(message: Message, time_value: str) -> int:
  157. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  158. check_unit = "".join(
  159. list(filter(time_value[-1].lower().endswith, unit))
  160. )
  161. currunt_time = datetime.now()
  162. time_digit = time_value[:-1]
  163. if not time_digit.isdigit():
  164. return await message.reply_text("Incorrect time specified")
  165. if check_unit == "m":
  166. temp_time = currunt_time + timedelta(minutes=int(time_digit))
  167. elif check_unit == "h":
  168. temp_time = currunt_time + timedelta(hours=int(time_digit))
  169. elif check_unit == "d":
  170. temp_time = currunt_time + timedelta(days=int(time_digit))
  171. else:
  172. return await message.reply_text("Incorrect time specified.")
  173. return int(datetime.timestamp(temp_time))
  174. async def extract_userid(message, text: str):
  175. """
  176. NOT TO BE USED OUTSIDE THIS FILE
  177. """
  178. def is_int(text: str):
  179. try:
  180. int(text)
  181. except ValueError:
  182. return False
  183. return True
  184. text = text.strip()
  185. if is_int(text):
  186. return int(text)
  187. entities = message.entities
  188. app = message._client
  189. if len(entities) < 2:
  190. return (await app.get_users(text)).id
  191. entity = entities[1]
  192. if entity.type == "mention":
  193. return (await app.get_users(text)).id
  194. if entity.type == "text_mention":
  195. return entity.user.id
  196. return None
  197. async def extract_user_and_reason(message):
  198. args = message.text.strip().split()
  199. text = message.text
  200. user = None
  201. reason = None
  202. if message.reply_to_message:
  203. reply = message.reply_to_message
  204. # if reply to a message and no reason is given
  205. if not reply.from_user:
  206. return None, None
  207. if len(args) < 2:
  208. reason = None
  209. else:
  210. reason = text.split(None, 1)[1]
  211. return reply.from_user.id, reason
  212. # if not reply to a message and no reason is given
  213. if len(args) == 2:
  214. user = text.split(None, 1)[1]
  215. return await extract_userid(message, user), None
  216. # if reason is given
  217. elif len(args) > 2:
  218. user, reason = text.split(None, 2)[1:]
  219. return await extract_userid(message, user), reason
  220. return user, reason
  221. async def extract_user(message):
  222. return (await extract_user_and_reason(message))[0]
  223. async def test_ARQ(message):
  224. results = ""
  225. funcs = {
  226. "image": arq.image("something"),
  227. "luna": arq.luna("hello"),
  228. "lyrics": arq.lyrics("attention"),
  229. "nlp": arq.nlp("bitcoin"),
  230. "nsfw_scan": arq.nsfw_scan(
  231. url="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
  232. ),
  233. "pornhub": arq.pornhub("something"),
  234. "proxy": arq.proxy(),
  235. "pypi": arq.pypi("python-arq"),
  236. "reddit": arq.reddit("badcode"),
  237. "quotly": arq.quotly(message),
  238. "saavn": arq.saavn("attention"),
  239. "stats": arq.stats(),
  240. "tmdb": arq.tmdb("flash"),
  241. "torrent": arq.torrent("porn"),
  242. "translate": arq.translate("hello"),
  243. "urbandict": arq.urbandict("wtf"),
  244. "wall": arq.wall("anime"),
  245. "wiki": arq.wiki("cat"),
  246. "youtube": arq.youtube("never gonna give you up"),
  247. }
  248. for key, value in funcs.items():
  249. try:
  250. t1 = time()
  251. result = await value
  252. t2 = time()
  253. if result.ok:
  254. results += f"**{key.capitalize()}:** `{t2-t1}`\n"
  255. else:
  256. results += f"**{key.capitalize()}:** `Failed`\n"
  257. except Exception:
  258. results += f"**{key.capitalize()}:** `Failed`\n"
  259. return results
  260. async def get_file_id_from_message(message):
  261. file_id = None
  262. if message.document:
  263. if int(message.document.file_size) > 3145728:
  264. return
  265. mime_type = message.document.mime_type
  266. if mime_type != "image/png" and mime_type != "image/jpeg":
  267. return
  268. file_id = message.document.file_id
  269. if message.sticker:
  270. if message.sticker.is_animated:
  271. if not message.sticker.thumbs:
  272. return
  273. file_id = message.sticker.thumbs[0].file_id
  274. else:
  275. file_id = message.sticker.file_id
  276. if message.photo:
  277. file_id = message.photo.file_id
  278. if message.animation:
  279. if not message.animation.thumbs:
  280. return
  281. file_id = message.animation.thumbs[0].file_id
  282. if message.video:
  283. if not message.video.thumbs:
  284. return
  285. file_id = message.video.thumbs[0].file_id
  286. return file_id