functions.py 10 KB

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