functions.py 10 KB

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