functions.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. """
  2. MIT License
  3. Copyright (c) 2024 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, search
  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 import errors
  33. from pyrogram.enums import MessageEntityType
  34. from pyrogram.types import Message
  35. from wbb import aiohttpsession as aiosession
  36. from wbb.utils.dbfunctions import start_restart_stage
  37. from wbb.utils.http import get, post
  38. async def restart(m: Message):
  39. if m:
  40. await start_restart_stage(m.chat.id, m.id)
  41. execvp(executable, [executable, "-m", "wbb"])
  42. def generate_captcha():
  43. # Generate one letter
  44. def gen_letter():
  45. return chr(randint(65, 90))
  46. def rndColor():
  47. return randint(64, 255), randint(64, 255), randint(64, 255)
  48. def rndColor2():
  49. return randint(32, 127), randint(32, 127), randint(32, 127)
  50. # Generate a 4 letter word
  51. def gen_wrong_answer():
  52. word = ""
  53. for _ in range(4):
  54. word += gen_letter()
  55. return word
  56. # Generate 8 wrong captcha answers
  57. wrong_answers = []
  58. for _ in range(8):
  59. wrong_answers.append(gen_wrong_answer())
  60. width = 80 * 4
  61. height = 100
  62. correct_answer = ""
  63. font = ImageFont.truetype("assets/arial.ttf", 55)
  64. file = f"assets/{randint(1000, 9999)}.jpg"
  65. image = Image.new("RGB", (width, height), (255, 255, 255))
  66. draw = ImageDraw.Draw(image)
  67. # Draw random points on image
  68. for x in range(width):
  69. for y in range(height):
  70. draw.point((x, y), fill=rndColor())
  71. for t in range(4):
  72. letter = gen_letter()
  73. correct_answer += letter
  74. draw.text((60 * t + 50, 15), letter, font=font, fill=rndColor2())
  75. image = image.filter(ImageFilter.BLUR)
  76. image.save(file, "jpeg")
  77. return [file, correct_answer, wrong_answers]
  78. def test_speedtest():
  79. def speed_convert(size):
  80. power = 2**10
  81. zero = 0
  82. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  83. while size > power:
  84. size /= power
  85. zero += 1
  86. return f"{round(size, 2)} {units[zero]}"
  87. speed = speedtest.Speedtest()
  88. info = speed.get_best_server()
  89. download = speed.download()
  90. upload = speed.upload()
  91. return [speed_convert(download), speed_convert(upload), info]
  92. async def get_http_status_code(url: str) -> int:
  93. async with aiosession.head(url) as resp:
  94. return resp.status
  95. async def make_carbon(code):
  96. url = "https://carbonara.solopov.dev/api/cook"
  97. async with aiosession.post(url, json={"code": code}) as resp:
  98. image = BytesIO(await resp.read())
  99. image.name = "carbon.png"
  100. return image
  101. async def transfer_sh(file_or_message):
  102. if isinstance(file_or_message, Message):
  103. file_or_message = await file_or_message.download()
  104. file = file_or_message
  105. async with aiofiles.open(file, "rb") as f:
  106. params = {file: await f.read()}
  107. resp = await post("https://transfer.sh/", data=params)
  108. url = resp.strip()
  109. return url
  110. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  111. Radius_Earth = 6371.0088
  112. data1, data2 = await gather(
  113. get(f"http://ipinfo.io/{ip1}"),
  114. get(f"http://ipinfo.io/{ip2}"),
  115. )
  116. lat1, lon1 = data1["loc"].split(",")
  117. lat2, lon2 = data2["loc"].split(",")
  118. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  119. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  120. dlon = lon2 - lon1
  121. dlat = lat2 - lat1
  122. a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  123. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  124. distance = Radius_Earth * c
  125. return distance
  126. def get_urls_from_text(text: str) -> bool:
  127. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  128. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  129. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  130. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  131. return [x[0] for x in findall(regex, str(text))]
  132. async def time_converter(message: Message, time_value: str) -> datetime:
  133. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  134. check_unit = "".join(list(filter(time_value[-1].lower().endswith, unit)))
  135. currunt_time = datetime.now()
  136. time_digit = time_value[:-1]
  137. if not time_digit.isdigit():
  138. return await message.reply_text("Incorrect time specified")
  139. if check_unit == "m":
  140. temp_time = currunt_time + timedelta(minutes=int(time_digit))
  141. elif check_unit == "h":
  142. temp_time = currunt_time + timedelta(hours=int(time_digit))
  143. elif check_unit == "d":
  144. temp_time = currunt_time + timedelta(days=int(time_digit))
  145. else:
  146. return await message.reply_text("Incorrect time specified.")
  147. return temp_time
  148. async def extract_userid(message, text: str):
  149. """
  150. NOT TO BE USED OUTSIDE THIS FILE
  151. """
  152. def is_int(text: str):
  153. try:
  154. int(text)
  155. except ValueError:
  156. return False
  157. return True
  158. text = text.strip()
  159. if is_int(text):
  160. return int(text)
  161. entities = message.entities
  162. app = message._client
  163. if len(entities) < 2:
  164. return (await app.get_users(text)).id
  165. entity = entities[1]
  166. if entity.type == MessageEntityType.MENTION:
  167. return (await app.get_users(text)).id
  168. if entity.type == MessageEntityType.TEXT_MENTION:
  169. return entity.user.id
  170. return None
  171. async def extract_user_and_reason(message, sender_chat=False):
  172. args = message.text.strip().split()
  173. text = message.text
  174. user = None
  175. reason = None
  176. try:
  177. if message.reply_to_message:
  178. reply = message.reply_to_message
  179. # if reply to a message and no reason is given
  180. if not reply.from_user:
  181. if (
  182. reply.sender_chat
  183. and reply.sender_chat != message.chat.id
  184. and sender_chat
  185. ):
  186. id_ = reply.sender_chat.id
  187. else:
  188. return None, None
  189. else:
  190. id_ = reply.from_user.id
  191. if len(args) < 2:
  192. reason = None
  193. else:
  194. reason = text.split(None, 1)[1]
  195. return id_, reason
  196. # if not reply to a message and no reason is given
  197. if len(args) == 2:
  198. user = text.split(None, 1)[1]
  199. return await extract_userid(message, user), None
  200. # if reason is given
  201. if len(args) > 2:
  202. user, reason = text.split(None, 2)[1:]
  203. return await extract_userid(message, user), reason
  204. return user, reason
  205. except errors.UsernameInvalid:
  206. return "", ""
  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_types and 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. if "~~" in text:
  249. text = text.replace("~~", "¤¤")
  250. text, keyb = text.split("~")
  251. if "¤¤" in text:
  252. text = text.replace("¤¤", "~~")
  253. keyb = findall(r"\[.+\,.+\]", keyb)
  254. for btn_str in keyb:
  255. btn_str = re_sub(r"[\[\]]", "", btn_str)
  256. btn_str = btn_str.split(",")
  257. btn_txt, btn_url = btn_str[0], btn_str[1].strip()
  258. if not get_urls_from_text(btn_url):
  259. continue
  260. keyboard[btn_txt] = btn_url
  261. keyboard = ikb(keyboard, row_width)
  262. except Exception:
  263. return
  264. return text, keyboard
  265. async def check_format(ikb, raw_text: str):
  266. keyb = findall(r"\[.+\,.+\]", raw_text)
  267. if keyb and not "~" in raw_text:
  268. raw_text = raw_text.replace("button=", "\n~\nbutton=")
  269. return raw_text
  270. if "~" in raw_text and keyb:
  271. if not extract_text_and_keyb(ikb, raw_text):
  272. return ""
  273. else:
  274. return raw_text
  275. else:
  276. return raw_text
  277. async def get_data_and_name(replied_message, message):
  278. text = message.text.markdown if message.text else message.caption.markdown
  279. name = text.split(None, 1)[1].strip()
  280. text = name.split(" ", 1)
  281. if len(text) > 1:
  282. name = text[0]
  283. data = text[1].strip()
  284. if replied_message and (
  285. replied_message.sticker or replied_message.video_note
  286. ):
  287. data = None
  288. else:
  289. if replied_message and (
  290. replied_message.sticker or replied_message.video_note
  291. ):
  292. data = None
  293. elif (
  294. replied_message
  295. and not replied_message.text
  296. and not replied_message.caption
  297. ):
  298. data = None
  299. else:
  300. data = (
  301. replied_message.text.markdown
  302. if replied_message.text
  303. else replied_message.caption.markdown
  304. )
  305. command = message.command[0]
  306. match = f"/{command} " + name
  307. if not message.reply_to_message and message.text:
  308. if match == data:
  309. data = "error"
  310. elif not message.reply_to_message and not message.text:
  311. if match == data:
  312. data = None
  313. return data, name
  314. async def get_user_id_and_usernames(client) -> dict:
  315. with client.storage.conn:
  316. query = """
  317. SELECT usernames.id, usernames.username
  318. FROM usernames
  319. WHERE usernames.id IN (
  320. SELECT peers.id
  321. FROM peers
  322. WHERE peers.type IN ("user", "bot") AND username IS NOT NULL
  323. )
  324. """
  325. result = client.storage.conn.execute(query).fetchall()
  326. users_ = {}
  327. for row in result:
  328. user_id = row[0]
  329. username = row[1]
  330. users_[user_id] = username
  331. return users_