cust_filter.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import shlex
  2. from typing import List
  3. import re
  4. from pyrogram.filters import create
  5. from pyrogram.types import Message
  6. from wbb import Command
  7. from wbb.utils.botinfo import BOT_USERNAME
  8. def command(
  9. commands: str or List[str],
  10. prefixes: str or List[str] = "/",
  11. case_sensitive: bool = False,
  12. ):
  13. """
  14. This is a drop in replacement for the default
  15. cust_filter.command that is included in Pyrogram.
  16. The Pyrogram one does not support /command@botname
  17. type commands, so this custom filter enables that
  18. throughout all groups and private chats. This filter
  19. works exactly the same as the original command filter
  20. even with support for multiple command prefixes and
  21. case sensitivity. Command arguments are given to user
  22. as message.command
  23. """
  24. async def func(flt, _, message: Message):
  25. text: str = message.text or message.caption
  26. message.command = None
  27. if not text:
  28. return False
  29. regex = "^({prefix})+\\b({regex})\\b(\\b@{bot_name}\\b)?(.*)".format(
  30. prefix="|".join(re.escape(x) for x in Command),
  31. regex="|".join(flt.commands).lower(),
  32. bot_name=BOT_USERNAME,
  33. )
  34. matches = re.search(re.compile(regex), text.lower())
  35. if matches:
  36. message.command = [matches.group(2)]
  37. try:
  38. for arg in shlex.split(matches.group(4).strip()):
  39. if arg == BOT_USERNAME:
  40. continue
  41. message.command.append(arg)
  42. except ValueError:
  43. return True
  44. return True
  45. return False
  46. commands = commands if type(commands) is list else [commands]
  47. commands = {c if case_sensitive else c.lower() for c in commands}
  48. prefixes = [] if prefixes is None else prefixes
  49. prefixes = prefixes if type(prefixes) is list else [prefixes]
  50. prefixes = set(prefixes) if prefixes else {""}
  51. return create(
  52. func,
  53. "CustomCommandFilter",
  54. commands=commands,
  55. prefixes=prefixes,
  56. case_sensitive=case_sensitive,
  57. )