utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from uuid import uuid4
  2. from enum import IntEnum
  3. from collections import namedtuple
  4. from telethon.utils import get_display_name
  5. Command = namedtuple(
  6. 'Command',
  7. 'name argc args args_string'
  8. )
  9. class Kind(IntEnum):
  10. CANNOT_APPLY_TO_SELF = 0
  11. CAN_APPLY_TO_SELF = 1
  12. NO_TARGET = 2
  13. def parse_command(text):
  14. text = text.strip()
  15. if not text.startswith('/'):
  16. raise ValueError
  17. text = text.split(' ')
  18. if len(text) < 1:
  19. raise ValueError
  20. command = text[0][1:].lower()
  21. if '@' in command:
  22. command = command.split('@')
  23. command = command[0]
  24. args = text[1:]
  25. argc = len(args)
  26. args_string = ' '.join(args)
  27. return Command(
  28. name=command,
  29. argc=argc,
  30. args=args,
  31. args_string=args_string
  32. )
  33. def get_link_to_user(user):
  34. full_name = get_display_name(user)
  35. if not full_name:
  36. full_name = user.username
  37. if not full_name:
  38. full_name = '?'
  39. if user.username:
  40. return f'[{full_name}](@{user.username})'
  41. return full_name
  42. def is_valid_name(name):
  43. return name.isidentifier()
  44. def make_temporary_filename(ext):
  45. uid = uuid4().hex
  46. return f'tmp_{uid}.{ext}'
  47. def parse_kind(kind):
  48. kind = int(kind)
  49. if kind < 0 or kind > 2:
  50. raise ValueError
  51. return kind