tasks.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """
  2. MIT License
  3. Copyright (c) present 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 Lock, create_task
  21. from time import time
  22. from pyrogram import filters
  23. from pyrogram.types import Message
  24. from wbb import BOT_ID, SUDOERS, USERBOT_PREFIX, app2
  25. from wbb.core.sections import bold, section, w
  26. tasks = {}
  27. TASKS_LOCK = Lock()
  28. arrow = lambda x: (x.text if x else "") + "\n`→`"
  29. def all_tasks():
  30. return tasks
  31. async def add_task(
  32. taskFunc,
  33. task_name,
  34. *args,
  35. **kwargs,
  36. ):
  37. async with TASKS_LOCK:
  38. global tasks
  39. task_id = (list(tasks.keys())[-1] + 1) if tasks else 0
  40. task = create_task(
  41. taskFunc(*args, **kwargs),
  42. name=task_name,
  43. )
  44. tasks[task_id] = task, int(time())
  45. return task, task_id
  46. async def rm_task(task_id=None):
  47. global tasks
  48. async with TASKS_LOCK:
  49. for key, value in list(tasks.items()):
  50. if value[0].done() or value[0].cancelled():
  51. del tasks[key]
  52. if (task_id is not None) and (task_id in tasks):
  53. task = tasks[task_id][0]
  54. if not task.done():
  55. task.cancel()
  56. del tasks[task_id]
  57. async def _get_tasks_text():
  58. await rm_task() # Clean completed tasks
  59. if not tasks:
  60. return f"{arrow('')} No pending task"
  61. text = bold("Tasks") + "\n"
  62. for i, task in enumerate(list(tasks.items())):
  63. indent = w * 4
  64. t, started = task[1]
  65. elapsed = round(time() - started)
  66. info = t._repr_info()
  67. id = task[0]
  68. text += section(
  69. f"{indent}Task {i}",
  70. body={
  71. "Name": t.get_name(),
  72. "Task ID": id,
  73. "Status": info[0].capitalize(),
  74. "Origin": info[2].split("/")[-1].replace(">", ""),
  75. "Running since": f"{elapsed}s",
  76. },
  77. indent=8,
  78. )
  79. return text
  80. @app2.on_message(
  81. SUDOERS
  82. & ~filters.forwarded
  83. & ~filters.via_bot
  84. & filters.command("lsTasks", prefixes=USERBOT_PREFIX)
  85. )
  86. async def task_list(_, message: Message):
  87. if message.from_user.is_self:
  88. await message.delete()
  89. results = await app2.get_inline_bot_results(
  90. BOT_ID,
  91. "tasks",
  92. )
  93. await app2.send_inline_bot_result(
  94. message.chat.id,
  95. results.query_id,
  96. results.results[0].id,
  97. )