functions.py 9.4 KB

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