functions.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. import codecs
  21. import pickle
  22. from asyncio import gather, get_running_loop
  23. from io import BytesIO
  24. from math import atan2, cos, radians, sin, sqrt
  25. from random import randint
  26. from re import findall
  27. from time import time
  28. from datetime import timedelta, datetime
  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 import arq
  37. from wbb.utils import aiodownloader
  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. def generate_captcha():
  50. # Generate one letter
  51. def gen_letter():
  52. return chr(randint(65, 90))
  53. def rndColor():
  54. return (randint(64, 255), randint(64, 255), randint(64, 255))
  55. def rndColor2():
  56. return (randint(32, 127), randint(32, 127), randint(32, 127))
  57. # Generate a 4 letter word
  58. def gen_wrong_answer():
  59. word = ""
  60. for _ in range(4):
  61. word += gen_letter()
  62. return word
  63. # Generate 8 wrong captcha answers
  64. wrong_answers = []
  65. for _ in range(8):
  66. wrong_answers.append(gen_wrong_answer())
  67. width = 80 * 4
  68. height = 100
  69. correct_answer = ""
  70. font = ImageFont.truetype("assets/arial.ttf", 55)
  71. file = f"assets/{randint(1000, 9999)}.jpg"
  72. image = Image.new("RGB", (width, height), (255, 255, 255))
  73. draw = ImageDraw.Draw(image)
  74. # Draw random points on image
  75. for x in range(width):
  76. for y in range(height):
  77. draw.point((x, y), fill=rndColor())
  78. for t in range(4):
  79. letter = gen_letter()
  80. correct_answer += letter
  81. draw.text(
  82. (60 * t + 50, 15), letter, font=font, fill=rndColor2()
  83. )
  84. image = image.filter(ImageFilter.BLUR)
  85. image.save(file, "jpeg")
  86. return [file, correct_answer, wrong_answers]
  87. def test_speedtest():
  88. def speed_convert(size):
  89. power = 2 ** 10
  90. zero = 0
  91. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  92. while size > power:
  93. size /= power
  94. zero += 1
  95. return f"{round(size, 2)} {units[zero]}"
  96. speed = speedtest.Speedtest()
  97. info = speed.get_best_server()
  98. download = speed.download()
  99. upload = speed.upload()
  100. return [speed_convert(download), speed_convert(upload), info]
  101. async def file_size_from_url(url: str) -> int:
  102. async with aiosession.head(url) as resp:
  103. size = int(resp.headers["content-length"])
  104. return size
  105. async def get_http_status_code(url: str) -> int:
  106. async with aiosession.head(url) as resp:
  107. return resp.status
  108. async def make_carbon(code):
  109. url = "https://carbonara.vercel.app/api/cook"
  110. async with aiosession.post(url, json={"code": code}) as resp:
  111. image = BytesIO(await resp.read())
  112. image.name = "carbon.png"
  113. return image
  114. async def transfer_sh(file_or_message):
  115. if isinstance(file_or_message, Message):
  116. file_or_message = await file_or_message.download()
  117. file = file_or_message
  118. async with aiofiles.open(file, "rb") as f:
  119. params = {file: await f.read()}
  120. async with aiohttp.ClientSession() as session:
  121. async with session.post(
  122. "https://transfer.sh/", data=params
  123. ) as resp:
  124. download_link = str(await resp.text()).strip()
  125. return download_link
  126. def obj_to_str(object):
  127. if not object:
  128. return False
  129. string = codecs.encode(pickle.dumps(object), "base64").decode()
  130. return string
  131. def str_to_obj(string: str):
  132. object = pickle.loads(codecs.decode(string.encode(), "base64"))
  133. return object
  134. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  135. Radius_Earth = 6371.0088
  136. data1, data2 = await gather(
  137. get(f"http://ipinfo.io/{ip1}"),
  138. get(f"http://ipinfo.io/{ip2}"),
  139. )
  140. lat1, lon1 = data1["loc"].split(",")
  141. lat2, lon2 = data2["loc"].split(",")
  142. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  143. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  144. dlon = lon2 - lon1
  145. dlat = lat2 - lat1
  146. a = (
  147. sin(dlat / 2) ** 2
  148. + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  149. )
  150. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  151. distance = Radius_Earth * c
  152. return distance
  153. def get_urls_from_text(text: str) -> bool:
  154. regex = r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]
  155. [.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(
  156. \([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\
  157. ()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""".strip()
  158. return [x[0] for x in findall(regex, text)]
  159. async def time_converter(message: Message, time_value: str) -> int:
  160. unit = ["m", "h", "d"] # m == minutes | h == hours | d == days
  161. check_unit = ''.join(list(filter(time_value[-1].lower().endswith, unit)))
  162. currunt_time = datetime.now()
  163. time_digit = time_value[:-1]
  164. if not time_digit.isdigit():
  165. return await message.reply_text("Incorrect time specified")
  166. if check_unit == "m":
  167. temp_time = currunt_time + timedelta(
  168. minutes=int(time_digit)
  169. )
  170. elif check_unit == "h":
  171. temp_time = currunt_time + timedelta(
  172. hours=int(time_digit)
  173. )
  174. elif check_unit == "d":
  175. temp_time = currunt_time + timedelta(
  176. days=int(time_digit)
  177. )
  178. else:
  179. return await message.reply_text("Incorrect time specified.")
  180. return int(datetime.timestamp(temp_time))
  181. async def extract_userid(message, text: str):
  182. text = text.strip()
  183. entities = message.entities
  184. app = message._client
  185. if len(entities) < 2:
  186. return (await app.get_users(text)).id
  187. entity = entities[1]
  188. if entity.type == "mention":
  189. return (await app.get_users(text)).id
  190. if entity.type == "text_mention":
  191. return entity.user.id
  192. return None
  193. async def extract_user_and_reason(message):
  194. args = message.text.strip().split()
  195. text = message.text
  196. user = None
  197. reason = None
  198. if message.reply_to_message:
  199. reply = message.reply_to_message
  200. # if reply to a message and no reason is given
  201. if not reply.from_user:
  202. return None, None
  203. if len(args) < 2:
  204. reason = None
  205. else:
  206. reason = text.split(None, 1)[1]
  207. return reply.from_user.id, reason
  208. # if not reply to a message and no reason is given
  209. if len(args) == 2:
  210. user = text.split(None, 1)[1]
  211. return await extract_userid(message, user), None
  212. # if reason is given
  213. elif len(args) > 2:
  214. user, reason = text.split(None, 2)[1:]
  215. return await extract_userid(message, user), reason
  216. return user, reason
  217. async def extract_user(message):
  218. return (await extract_user_and_reason(message))[0]
  219. async def test_ARQ(message):
  220. results = ""
  221. funcs = {
  222. "deezer": arq.deezer("attention", 1),
  223. "image": arq.image("something"),
  224. "luna": arq.luna("hello"),
  225. "lyrics": arq.lyrics("attention"),
  226. "nlp": arq.nlp("bitcoin"),
  227. "nsfw_scan": arq.nsfw_scan(
  228. url="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
  229. ),
  230. "pornhub": arq.pornhub("something"),
  231. "proxy": arq.proxy(),
  232. "pypi": arq.pypi("python-arq"),
  233. "reddit": arq.reddit("badcode"),
  234. "quotly": arq.quotly(message),
  235. "saavn": arq.saavn("attention"),
  236. "stats": arq.stats(),
  237. "tmdb": arq.tmdb("flash"),
  238. "torrent": arq.torrent("porn"),
  239. "translate": arq.translate("hello"),
  240. "urbandict": arq.urbandict("wtf"),
  241. "wall": arq.wall("anime"),
  242. "wiki": arq.wiki("cat"),
  243. "youtube": arq.youtube("never gonna give you up"),
  244. }
  245. for key, value in funcs.items():
  246. try:
  247. t1 = time()
  248. result = await value
  249. t2 = time()
  250. if result.ok:
  251. results += f"**{key.capitalize()}:** `{t2-t1}`\n"
  252. else:
  253. results += f"**{key.capitalize()}:** `Failed`\n"
  254. except Exception:
  255. results += f"**{key.capitalize()}:** `Failed`\n"
  256. return results