add.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """Add player conversation"""
  2. import random
  3. import string
  4. from telegram import ParseMode
  5. from telegram.ext import MessageHandler, CommandHandler, Filters, ConversationHandler
  6. from app import api, functions, database, HEADERS, BASE_URL, LOGGER
  7. PLAYER_ID, CHOOSE, CONFIRM, VERIFICATION = range(4)
  8. def conv_ask_player_id(update, context):
  9. """Ask player id"""
  10. LOGGER.info('"@%s" start add account conversation', update.message.from_user.username)
  11. update.message.reply_text(
  12. 'Starting add account conversation, use /cancel to stop.' +
  13. ' Send me your Rival Regions account name or ID.'
  14. )
  15. return PLAYER_ID
  16. def conv_player_choose(update, context):
  17. """Ask max resource"""
  18. player_name = update.message.text
  19. LOGGER.info(
  20. '"@%s" searching for player name "%s"',
  21. update.message.from_user.username,
  22. player_name
  23. )
  24. update.message.reply_text(
  25. 'Searching for \'{}\', this might take a couple seconds.'.format(player_name)
  26. )
  27. players = api.get_players_by_name(player_name)
  28. if len(players) == 0:
  29. update.message.reply_text('No accounts found witht that name, try again.')
  30. return PLAYER_ID
  31. if len(players) == 1:
  32. player = players[0]
  33. player_id = player['id']
  34. if database.is_connected(update.message.from_user.id, player_id):
  35. update.message.reply_text('Account already connected.')
  36. context.user_data.clear()
  37. return ConversationHandler.END
  38. context.user_data['player_id'] = player_id
  39. ask_confirmation(update, player_id)
  40. return CONFIRM
  41. context.user_data['player_list'] = players
  42. message = 'Choose from list:\n'
  43. for num, player in enumerate(players, start=1):
  44. message += '{}) {} ({})\n'.format(num, player['name'], player['level'])
  45. update.message.reply_text(message)
  46. return CHOOSE
  47. def conv_player_number_error(update, context):
  48. """Wrong input error"""
  49. incorrect_input = update.message.text
  50. LOGGER.info(
  51. '"@%s" incorrect number number "%s"',
  52. update.message.from_user.username,
  53. incorrect_input
  54. )
  55. update.message.reply_text(
  56. '{}, I don\'t recognize that. What number?'.format(
  57. incorrect_input
  58. )
  59. )
  60. return CHOOSE
  61. def conv_player_id_confirm(update, context):
  62. """Confirm player """
  63. player_id = int(update.message.text)
  64. if player_id <= 25:
  65. player_index = player_id-1
  66. if player_index >= len(context.user_data['player_list']):
  67. update.message.reply_text('{} is not an option, try again.'.format(player_id),)
  68. return CHOOSE
  69. player = context.user_data['player_list'][player_index]
  70. player_id = player['id']
  71. if database.is_connected(update.message.from_user.id, player_id):
  72. update.message.reply_text('Account already connected.')
  73. context.user_data.clear()
  74. return ConversationHandler.END
  75. context.user_data['player_id'] = player_id
  76. update.message.reply_text(
  77. 'Retreiving account from Rival Regions, this might take a couple seconds.'
  78. )
  79. ask_confirmation(update, player_id)
  80. return CONFIRM
  81. def ask_confirmation(update, player_id):
  82. """Get account and ask for confirmation"""
  83. LOGGER.info(
  84. '"@%s" Ask for confirmation RR account id "%s"',
  85. update.message.from_user.username,
  86. player_id
  87. )
  88. player = api.get_rr_player(player_id)
  89. message_list = [
  90. '*Player details*',
  91. '*ID*: {}'.format(player_id),
  92. '*Name*: {}'.format(functions.escape_text(player['name'])),
  93. '*Region*: {}'.format(player['region']),
  94. '*Residency*: {}'.format(player['residency']),
  95. '*Registration date*: {}'.format(player['registation_date']),
  96. ]
  97. update.message.reply_text(
  98. '\n'.join(message_list),
  99. parse_mode=ParseMode.MARKDOWN
  100. )
  101. update.message.reply_text('Please confirm this is your account by typing \'confirm\'.')
  102. def conv_verification(update, context):
  103. """Sending announcement"""
  104. update.message.reply_text(
  105. 'Verification code will be send to your Rival Region player in a couple of secconds. ' + \
  106. 'Check your personal messages for a verification code and send it here.',
  107. parse_mode=ParseMode.MARKDOWN
  108. )
  109. letters = string.ascii_lowercase
  110. verification_code = ''.join(random.choice(letters) for i in range(5))
  111. LOGGER.info(
  112. '"@%s" verification code "%s"',
  113. update.message.from_user.username,
  114. verification_code
  115. )
  116. message = 'Your verification code:\n{}\n\n'.format(verification_code) + \
  117. 'Telegram user @{} tried to add this account. '.format(
  118. update.message.from_user.username
  119. ) + \
  120. 'Please don\'t share this code except with @rr_verification_bot on Telegram.'
  121. api.send_personal_message(context.user_data['player_id'], message)
  122. context.user_data['verification_code'] = verification_code
  123. return VERIFICATION
  124. def conv_finish(update, context):
  125. """Sending announcement"""
  126. verification_code = update.message.text
  127. if verification_code != context.user_data['verification_code']:
  128. LOGGER.info(
  129. '"@%s" wrong verification code try "%s"',
  130. update.message.from_user.username,
  131. verification_code,
  132. )
  133. if 'tries' not in context.user_data:
  134. context.user_data['tries'] = 0
  135. context.user_data['tries'] += 1
  136. if context.user_data['tries'] >= 3:
  137. LOGGER.info(
  138. '"@%s" too many wrong verification tries',
  139. update.message.from_user.username
  140. )
  141. update.message.reply_text(
  142. 'Failed verification to many times, canceled action.',
  143. parse_mode=ParseMode.MARKDOWN
  144. )
  145. context.user_data.clear()
  146. return ConversationHandler.END
  147. update.message.reply_text(
  148. 'Verificated code doesn\'t match, try again.',
  149. parse_mode=ParseMode.MARKDOWN
  150. )
  151. return VERIFICATION
  152. player_id = context.user_data['player_id']
  153. LOGGER.info(
  154. '"@%s" succesfully verified RR player "%s"',
  155. update.message.from_user.username,
  156. player_id,
  157. )
  158. database.verify_rr_player(update.message.from_user.id, player_id)
  159. update.message.reply_text(
  160. 'Verificated your Rival Region player to Telegram. Type /accounts to see your accounts',
  161. parse_mode=ParseMode.MARKDOWN
  162. )
  163. context.user_data.clear()
  164. return ConversationHandler.END
  165. def conv_error_finish(update, context):
  166. """Wrong verification code"""
  167. incorrect_input = update.message.text
  168. update.message.reply_text(
  169. '"{}" not recognized. Send me the verification code.\n/cancel to cancel'.format(
  170. incorrect_input
  171. ),
  172. )
  173. return VERIFICATION
  174. def conv_cancel(update, context):
  175. """Cancel announcement"""
  176. update.message.reply_text('Canceled action.')
  177. context.user_data.clear()
  178. return ConversationHandler.END
  179. # announcement conversation
  180. ADD_CONV = ConversationHandler(
  181. entry_points=[CommandHandler('add', conv_ask_player_id)],
  182. states={
  183. PLAYER_ID: [
  184. MessageHandler(Filters.regex(r'^\d*$'), conv_player_id_confirm),
  185. MessageHandler(Filters.text, conv_player_choose),
  186. ],
  187. CHOOSE: [
  188. MessageHandler(Filters.regex(r'^\d*$'), conv_player_id_confirm),
  189. MessageHandler(Filters.text, conv_player_choose),
  190. ],
  191. CONFIRM: [
  192. MessageHandler(Filters.regex('(?i)confirm'), conv_verification),
  193. MessageHandler(Filters.text, conv_cancel),
  194. ],
  195. VERIFICATION: [
  196. MessageHandler(Filters.regex(r'^([a-z]|\d)+$'), conv_finish),
  197. MessageHandler(Filters.text, conv_error_finish),
  198. ],
  199. },
  200. fallbacks=[CommandHandler('cancel', conv_cancel)]
  201. )