functions.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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, floor, radians, sin, sqrt
  24. from os import execvp
  25. from random import randint
  26. from re import findall
  27. from re import sub as re_sub
  28. from sys import executable
  29. from time import time
  30. import aiofiles
  31. import aiohttp
  32. import speedtest
  33. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  34. from pyrogram.types import Message
  35. from wbb import aiohttpsession as aiosession
  36. from wbb.modules.userbot import eor
  37. from wbb.utils.dbfunctions import start_restart_stage
  38. from wbb.utils.http import get
  39. async def progress(
  40. current: int,
  41. total: int,
  42. start: int,
  43. task_id: int,
  44. message: Message,
  45. ):
  46. percentage = current / total * 100
  47. elapsed = time() - start
  48. speed = (current / 1000000) / elapsed # In MB/s
  49. eta = (100 / percentage * elapsed) / 60 # In Minutes
  50. # Only edit at every 5 seconds
  51. if round(elapsed % 5.00) != 0 and current != total:
  52. return
  53. round_pct = floor(percentage / 10)
  54. bar = ("▰" * round_pct) + ("▱" * (10 - round_pct))
  55. text = f"""
  56. {bar}
  57. **Progress:** {int(percentage)}%
  58. **Speed:** {round(speed, 2)}MB/s
  59. **ETA:** {round(eta, 2)}m
  60. **Task ID:** {task_id}
  61. """
  62. await eor(message, text=text)
  63. async def restart(m: Message):
  64. if m:
  65. await start_restart_stage(m.chat.id, m.message_id)
  66. execvp(executable, [executable, "-m", "wbb"])
  67. def generate_captcha():
  68. # Generate one letter
  69. def gen_letter():
  70. return chr(randint(65, 90))
  71. def rndColor():
  72. return (randint(64, 255), randint(64, 255), randint(64, 255))
  73. def rndColor2():
  74. return (randint(32, 127), randint(32, 127), randint(32, 127))
  75. # Generate a 4 letter word
  76. def gen_wrong_answer():
  77. word = ""
  78. for _ in range(4):
  79. word += gen_letter()
  80. return word
  81. # Generate 8 wrong captcha answers
  82. wrong_answers = []
  83. for _ in range(8):
  84. wrong_answers.append(gen_wrong_answer())
  85. width = 80 * 4
  86. height = 100
  87. correct_answer = ""
  88. font = ImageFont.truetype("assets/arial.ttf", 55)
  89. file = f"assets/{randint(1000, 9999)}.jpg"
  90. image = Image.new("RGB", (width, height), (255, 255, 255))
  91. draw = ImageDraw.Draw(image)
  92. # Draw random points on image
  93. for x in range(width):
  94. for y in range(height):
  95. draw.point((x, y), fill=rndColor())
  96. for t in range(4):
  97. letter = gen_letter()
  98. correct_answer += letter
  99. draw.text(
  100. (60 * t + 50, 15), letter, font=font, fill=rndColor2()
  101. )
  102. image = image.filter(ImageFilter.BLUR)
  103. image.save(file, "jpeg")
  104. return [file, correct_answer, wrong_answers]
  105. def test_speedtest():
  106. def speed_convert(size):
  107. power = 2 ** 10
  108. zero = 0
  109. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  110. while size > power:
  111. size /= power
  112. zero += 1
  113. return f"{round(size, 2)} {units[zero]}"
  114. speed = speedtest.Speedtest()
  115. info = speed.get_best_server()
  116. download = speed.download()
  117. upload = speed.upload()
  118. return [speed_convert(download), speed_convert(upload), info]
  119. async def get_http_status_code(url: str) -> int:
  120. async with aiosession.head(url) as resp:
  121. return resp.status
  122. async def make_carbon(code):
  123. url = "https://carbonara.vercel.app/api/cook"
  124. async with aiosession.post(url, json={"code": code}) as resp:
  125. image = BytesIO(await resp.read())
  126. image.name = "carbon.png"
  127. return image
  128. async def transfer_sh(file_or_message):
  129. if isinstance(file_or_message, Message):
  130. file_or_message = await file_or_message.download()
  131. file = file_or_message
  132. async with aiofiles.open(file, "rb") as f:
  133. params = {file: await f.read()}
  134. async with aiohttp.ClientSession() as session:
  135. async with session.post(
  136. "https://transfer.sh/", data=params
  137. ) as resp:
  138. download_link = str(await resp.text()).strip()
  139. return download_link
  140. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  141. Radius_Earth = 6371.0088
  142. data1, data2 = await gather(
  143. get(f"http://ipinfo.io/{ip1}"),
  144. get(f"http://ipinfo.io/{ip2}"),
  145. )
  146. lat1, lon1 = data1["loc"].split(",")
  147. lat2, lon2 = data2["loc"].split(",")
  148. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  149. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  150. dlon = lon2 - lon1
  151. dlat = lat2 - lat1
  152. a = (
  153. sin(dlat / 2) ** 2
  154. + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  155. )
  156. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  157. distance = Radius_Earth * c
  158. return distance
  159. def get_urls_from_text(text: str) -> bool:
  160. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  161. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  162. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  163. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  164. return [x[0] for x in findall(regex, text)]
  165. async def time_converter(message: Message, time_value: str) -> int:
  166. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  167. check_unit = "".join(
  168. list(filter(time_value[-1].lower().endswith, unit))
  169. )
  170. currunt_time = datetime.now()
  171. time_digit = time_value[:-1]
  172. if not time_digit.isdigit():
  173. return await message.reply_text("Incorrect time specified")
  174. if check_unit == "m":
  175. temp_time = currunt_time + timedelta(minutes=int(time_digit))
  176. elif check_unit == "h":
  177. temp_time = currunt_time + timedelta(hours=int(time_digit))
  178. elif check_unit == "d":
  179. temp_time = currunt_time + timedelta(days=int(time_digit))
  180. else:
  181. return await message.reply_text("Incorrect time specified.")
  182. return int(datetime.timestamp(temp_time))
  183. async def extract_userid(message, text: str):
  184. """
  185. NOT TO BE USED OUTSIDE THIS FILE
  186. """
  187. def is_int(text: str):
  188. try:
  189. int(text)
  190. except ValueError:
  191. return False
  192. return True
  193. text = text.strip()
  194. if is_int(text):
  195. return int(text)
  196. entities = message.entities
  197. app = message._client
  198. if len(entities) < 2:
  199. return (await app.get_users(text)).id
  200. entity = entities[1]
  201. if entity.type == "mention":
  202. return (await app.get_users(text)).id
  203. if entity.type == "text_mention":
  204. return entity.user.id
  205. return None
  206. async def extract_user_and_reason(message):
  207. args = message.text.strip().split()
  208. text = message.text
  209. user = None
  210. reason = None
  211. if message.reply_to_message:
  212. reply = message.reply_to_message
  213. # if reply to a message and no reason is given
  214. if not reply.from_user:
  215. return None, None
  216. if len(args) < 2:
  217. reason = None
  218. else:
  219. reason = text.split(None, 1)[1]
  220. return reply.from_user.id, reason
  221. # if not reply to a message and no reason is given
  222. if len(args) == 2:
  223. user = text.split(None, 1)[1]
  224. return await extract_userid(message, user), None
  225. # if reason is given
  226. elif len(args) > 2:
  227. user, reason = text.split(None, 2)[1:]
  228. return await extract_userid(message, user), reason
  229. return user, reason
  230. async def extract_user(message):
  231. return (await extract_user_and_reason(message))[0]
  232. def get_file_id_from_message(
  233. message,
  234. max_file_size=3145728,
  235. mime_types=["image/png", "image/jpeg"],
  236. ):
  237. file_id = None
  238. if message.document:
  239. if int(message.document.file_size) > max_file_size:
  240. return
  241. mime_type = message.document.mime_type
  242. if mime_types:
  243. if mime_type not in mime_types:
  244. return
  245. file_id = message.document.file_id
  246. if message.sticker:
  247. if message.sticker.is_animated:
  248. if not message.sticker.thumbs:
  249. return
  250. file_id = message.sticker.thumbs[0].file_id
  251. else:
  252. file_id = message.sticker.file_id
  253. if message.photo:
  254. file_id = message.photo.file_id
  255. if message.animation:
  256. if not message.animation.thumbs:
  257. return
  258. file_id = message.animation.thumbs[0].file_id
  259. if message.video:
  260. if not message.video.thumbs:
  261. return
  262. file_id = message.video.thumbs[0].file_id
  263. return file_id
  264. def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
  265. keyboard = {}
  266. try:
  267. text = text.strip()
  268. if text.startswith("`"):
  269. text = text[1:]
  270. if text.endswith("`"):
  271. text = text[:-1]
  272. text, keyb = text.split("~")
  273. keyb = findall(r"\[.+\,.+\]", keyb)
  274. for btn_str in keyb:
  275. btn_str = re_sub(r"[\[\]]", "", btn_str)
  276. btn_str = btn_str.split(",")
  277. btn_txt, btn_url = btn_str[0], btn_str[1].strip()
  278. if not get_urls_from_text(btn_url):
  279. continue
  280. keyboard[btn_txt] = btn_url
  281. keyboard = ikb(keyboard, row_width)
  282. except Exception:
  283. return
  284. return text, keyboard
  285. async def get_user_id_and_usernames(client) -> dict:
  286. with client.storage.lock, client.storage.conn:
  287. users = client.storage.conn.execute(
  288. 'SELECT * FROM peers WHERE type in ("user", "bot") AND username NOT null'
  289. ).fetchall()
  290. users_ = {}
  291. for user in users:
  292. users_[user[0]] = user[3]
  293. return users_