cust_filter.py 2.1 KB

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