Queer European MD passionate about IT

helper.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """Make a self-consistent bot help section."""
  2. # Third party modules
  3. from davtelepot.utilities import (
  4. extract, get_cleaned_text, json_read, make_inline_keyboard,
  5. make_lines_of_buttons, make_button, MyOD
  6. )
  7. # Project modules
  8. from . import roles
  9. DENY_MESSAGE = (
  10. "Chiedi di essere autorizzato: se la tua richiesta verrà accolta, "
  11. "ripeti il comando /help per leggere il messaggio di aiuto."
  12. )
  13. def get_command_description(bot, update, user_record):
  14. """Get a string description of `bot` commands.
  15. Show only commands available for `update` sender.
  16. """
  17. user_role = roles.get_role(bot=bot, update=update, user_record=user_record)
  18. return "\n".join(
  19. [
  20. "/{}: {}".format(
  21. command,
  22. details['description']
  23. )
  24. for command, details in sorted(
  25. bot.commands.items(),
  26. key=lambda x:x[0]
  27. )
  28. if details['description']
  29. and user_role <= roles.get_privilege_code(
  30. details['authorization_level']
  31. )
  32. ]
  33. )
  34. def _make_button(x, y):
  35. if not y.startswith('help:///'):
  36. y = 'help:///{}'.format(y)
  37. return make_button(x, y)
  38. HELP_MENU_BUTTON = make_inline_keyboard(
  39. [
  40. _make_button(
  41. 'Torna al menu Guida 📖',
  42. 'menu'
  43. )
  44. ],
  45. 1
  46. )
  47. def get_help_buttons(bot, update, user_record):
  48. """Get `bot` help menu inline keyboard.
  49. Show only buttons available for `update` sender.
  50. """
  51. user_role = roles.get_role(bot=bot, update=update, user_record=user_record)
  52. buttons_list = [
  53. _make_button(
  54. section['label'],
  55. section['abbr']
  56. )
  57. for section in bot.help_sections.values()
  58. if 'auth' in section
  59. and user_role <= roles.get_privilege_code(
  60. section['auth']
  61. )
  62. ]
  63. return dict(
  64. inline_keyboard=(
  65. make_lines_of_buttons(buttons_list, 3)
  66. + make_lines_of_buttons(
  67. [
  68. _make_button('Comandi 🤖', 'commands')
  69. ],
  70. 1
  71. )
  72. + (
  73. bot.help_buttons
  74. if bot.authorization_function(update=update,
  75. authorization_level='user')
  76. else []
  77. )
  78. )
  79. )
  80. async def _help_command(bot, update, user_record):
  81. if not bot.authorization_function(update=update,
  82. authorization_level='everybody'):
  83. return DENY_MESSAGE
  84. reply_markup = get_help_buttons(bot, update, user_record)
  85. return dict(
  86. text=bot.help_message.format(bot=bot),
  87. parse_mode='HTML',
  88. reply_markup=reply_markup,
  89. disable_web_page_preview=True
  90. )
  91. async def _help_button(bot, update, user_record):
  92. data = update['data']
  93. command = extract(data, ':///')
  94. result, text, rm = '', '', None
  95. if command == 'commands':
  96. text = "<b>Comandi di {bot.name}</b>\n\n{cd}".format(
  97. bot=bot,
  98. cd=get_command_description(bot, update, user_record)
  99. )
  100. rm = HELP_MENU_BUTTON
  101. elif command == 'menu':
  102. text = bot.help_message.format(bot=bot)
  103. rm = get_help_buttons(bot, update, user_record)
  104. else:
  105. for code, section in bot.help_sections.items():
  106. if section['abbr'] == command:
  107. if not bot.authorization_function(
  108. update=update,
  109. authorization_level=section['auth']
  110. ):
  111. return "Non sei autorizzato!"
  112. rm = HELP_MENU_BUTTON
  113. text = (
  114. '<b>{s[label]}</b>\n\n{s[descr]}'
  115. ).format(
  116. s=section
  117. ).format(
  118. bot=bot
  119. )
  120. break
  121. if text or rm:
  122. return dict(
  123. text=result,
  124. edit=dict(
  125. text=text,
  126. parse_mode='HTML',
  127. reply_markup=rm,
  128. disable_web_page_preview=True
  129. )
  130. )
  131. return result
  132. async def _start_command(bot, update, user_record):
  133. text = get_cleaned_text(update=update, bot=bot, replace=['start'])
  134. if not text:
  135. return await _help_command(bot, update, user_record)
  136. update['text'] = text
  137. await bot.text_message_handler(
  138. update=update,
  139. user_record=None
  140. )
  141. return
  142. def init(bot, help_message="<b>Guida</b>",
  143. help_sections_file='data/help.json', help_buttons=[]):
  144. """Assign parsers, commands, buttons and queries to given `bot`."""
  145. bot.help_message = help_message
  146. bot.help_buttons = help_buttons
  147. bot.help_sections = MyOD()
  148. for code, section in enumerate(
  149. json_read(
  150. help_sections_file,
  151. default=[]
  152. )
  153. ):
  154. bot.help_sections[code] = section
  155. @bot.command("/start", authorization_level='everybody')
  156. async def start_command(bot, update, user_record):
  157. return await _start_command(bot, update, user_record)
  158. @bot.command(command='/help', aliases=['Guida 📖', '00help'],
  159. show_in_keyboard=True, description="Aiuto",
  160. authorization_level='everybody')
  161. async def help_command(bot, update, user_record):
  162. result = await _help_command(bot, update, user_record)
  163. return result
  164. @bot.button(prefix='help:///', authorization_level='everybody')
  165. async def help_button(bot, update, user_record):
  166. return await _help_button(bot, update, user_record)