functions.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. import aiofiles
  29. import aiohttp
  30. import speedtest
  31. from PIL import Image, ImageDraw, ImageFilter, ImageFont
  32. from pyrogram.types import Message
  33. from wget import download
  34. from wbb import aiohttpsession as aiosession
  35. from wbb import arq
  36. from wbb.utils import aiodownloader
  37. from wbb.utils.http import get
  38. """
  39. Just import 'downloader' anywhere and do downloader.download() to
  40. download file from a given url
  41. """
  42. downloader = aiodownloader.Handler()
  43. # Another downloader, but with wget
  44. async def download_url(url: str):
  45. loop = get_running_loop()
  46. file = await loop.run_in_executor(None, download, url)
  47. return file
  48. def generate_captcha():
  49. # Generate one letter
  50. def gen_letter():
  51. return chr(randint(65, 90))
  52. def rndColor():
  53. return (randint(64, 255), randint(64, 255), randint(64, 255))
  54. def rndColor2():
  55. return (randint(32, 127), randint(32, 127), randint(32, 127))
  56. # Generate a 4 letter word
  57. def gen_wrong_answer():
  58. word = ""
  59. for _ in range(4):
  60. word += gen_letter()
  61. return word
  62. # Generate 8 wrong captcha answers
  63. wrong_answers = []
  64. for _ in range(8):
  65. wrong_answers.append(gen_wrong_answer())
  66. width = 80 * 4
  67. height = 100
  68. correct_answer = ""
  69. font = ImageFont.truetype("assets/arial.ttf", 55)
  70. file = f"assets/{randint(1000, 9999)}.jpg"
  71. image = Image.new("RGB", (width, height), (255, 255, 255))
  72. draw = ImageDraw.Draw(image)
  73. # Draw random points on image
  74. for x in range(width):
  75. for y in range(height):
  76. draw.point((x, y), fill=rndColor())
  77. for t in range(4):
  78. letter = gen_letter()
  79. correct_answer += letter
  80. draw.text(
  81. (60 * t + 50, 15), letter, font=font, fill=rndColor2()
  82. )
  83. image = image.filter(ImageFilter.BLUR)
  84. image.save(file, "jpeg")
  85. return [file, correct_answer, wrong_answers]
  86. def test_speedtest():
  87. def speed_convert(size):
  88. power = 2 ** 10
  89. zero = 0
  90. units = {0: "", 1: "Kb/s", 2: "Mb/s", 3: "Gb/s", 4: "Tb/s"}
  91. while size > power:
  92. size /= power
  93. zero += 1
  94. return f"{round(size, 2)} {units[zero]}"
  95. speed = speedtest.Speedtest()
  96. info = speed.get_best_server()
  97. download = speed.download()
  98. upload = speed.upload()
  99. return [speed_convert(download), speed_convert(upload), info]
  100. async def file_size_from_url(url: str) -> int:
  101. async with aiosession.head(url) as resp:
  102. size = int(resp.headers["content-length"])
  103. return size
  104. async def get_http_status_code(url: str) -> int:
  105. async with aiosession.head(url) as resp:
  106. return resp.status
  107. async def make_carbon(code):
  108. url = "https://carbonara.vercel.app/api/cook"
  109. async with aiosession.post(url, json={"code": code}) as resp:
  110. image = BytesIO(await resp.read())
  111. image.name = "carbon.png"
  112. return image
  113. async def transfer_sh(file_or_message):
  114. if isinstance(file_or_message, Message):
  115. file_or_message = await file_or_message.download()
  116. file = file_or_message
  117. async with aiofiles.open(file, "rb") as f:
  118. params = {file: await f.read()}
  119. async with aiohttp.ClientSession() as session:
  120. async with session.post(
  121. "https://transfer.sh/", data=params
  122. ) as resp:
  123. download_link = str(await resp.text()).strip()
  124. return download_link
  125. def obj_to_str(object):
  126. if not object:
  127. return False
  128. string = codecs.encode(pickle.dumps(object), "base64").decode()
  129. return string
  130. def str_to_obj(string: str):
  131. object = pickle.loads(codecs.decode(string.encode(), "base64"))
  132. return object
  133. async def calc_distance_from_ip(ip1: str, ip2: str) -> float:
  134. Radius_Earth = 6371.0088
  135. data1, data2 = await gather(
  136. get(f"http://ipinfo.io/{ip1}"),
  137. get(f"http://ipinfo.io/{ip2}"),
  138. )
  139. lat1, lon1 = data1["loc"].split(",")
  140. lat2, lon2 = data2["loc"].split(",")
  141. lat1, lon1 = radians(float(lat1)), radians(float(lon1))
  142. lat2, lon2 = radians(float(lat2)), radians(float(lon2))
  143. dlon = lon2 - lon1
  144. dlat = lat2 - lat1
  145. a = (
  146. sin(dlat / 2) ** 2
  147. + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
  148. )
  149. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  150. distance = Radius_Earth * c
  151. return distance
  152. def get_urls_from_text(text: str) -> bool:
  153. # TODO This also matches ip address, fix soon
  154. regex = r"""(?i)\b((?:https?:\/\/|(www|\w+)\d{0,3}[.]|[a-z
  155. 0-9.\-][.][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 extract_userid(message, text: str):
  160. text = text.strip()
  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 == "mention":
  167. return (await app.get_users(text)).id
  168. if entity.type == "text_mention":
  169. return entity.user.id
  170. return None
  171. async def extract_user_and_reason(message):
  172. args = message.text.strip().split()
  173. text = message.text
  174. user = None
  175. reason = None
  176. if message.reply_to_message:
  177. reply = message.reply_to_message
  178. # if reply to a message and no reason is given
  179. if not reply.from_user:
  180. return None, None
  181. if len(args) < 2:
  182. reason = None
  183. else:
  184. reason = text.split(None, 1)[1]
  185. return reply.from_user.id, reason
  186. # if not reply to a message and no reason is given
  187. if len(args) == 2:
  188. user = text.split(None, 1)[1]
  189. return await extract_userid(message, user), None
  190. # if reason is given
  191. elif len(args) > 2:
  192. user, reason = text.split(None, 2)[1:]
  193. return await extract_userid(message, user), reason
  194. return user, reason
  195. async def extract_user(message):
  196. return (await extract_user_and_reason(message))[0]
  197. async def test_ARQ(message):
  198. results = ""
  199. funcs = {
  200. "deezer": arq.deezer("attention", 1),
  201. "image": arq.image("something"),
  202. "luna": arq.luna("hello"),
  203. "lyrics": arq.lyrics("attention"),
  204. "nlp": arq.nlp("bitcoin"),
  205. "nsfw_scan": arq.nsfw_scan(
  206. url="https://www.pixsy.com/wp-content/uploads/2021/04/ben-sweet-2LowviVHZ-E-unsplash-1.jpeg"
  207. ),
  208. "pornhub": arq.pornhub("something"),
  209. "proxy": arq.proxy(),
  210. "pypi": arq.pypi("python-arq"),
  211. "reddit": arq.reddit("badcode"),
  212. "quotly": arq.quotly(message),
  213. "saavn": arq.saavn("attention"),
  214. "stats": arq.stats(),
  215. "tmdb": arq.tmdb("flash"),
  216. "torrent": arq.torrent("porn"),
  217. "translate": arq.translate("hello"),
  218. "urbandict": arq.urbandict("wtf"),
  219. "wall": arq.wall("anime"),
  220. "wiki": arq.wiki("cat"),
  221. "youtube": arq.youtube("never gonna give you up"),
  222. }
  223. for key, value in funcs.items():
  224. try:
  225. t1 = time()
  226. result = await value
  227. t2 = time()
  228. if result.ok:
  229. results += f"**{key.capitalize()}:** `{t2-t1}`\n"
  230. else:
  231. results += f"**{key.capitalize()}:** `Failed`\n"
  232. except Exception:
  233. results += f"**{key.capitalize()}:** `Failed`\n"
  234. return results