functions.py 9.7 KB

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