jessicacardoso

bot-lista

Feb 17th, 2020
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.72 KB | None | 0 0
  1. import logging
  2. import os
  3. import settings
  4.  
  5.  
  6. import math
  7.  
  8.  
  9. from telegram import InlineKeyboardButton, InlineKeyboardMarkup
  10. from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
  11.  
  12. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
  13.                     level=logging.INFO)
  14. logger = logging.getLogger(__name__)
  15.  
  16.  
  17.  
  18. my_data = {
  19.     'op1': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],
  20.     'op2': [21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]
  21.     }
  22.  
  23.  
  24. def format_search(data, index=0):
  25.     text = "*Numbers*: \n"
  26.     for i in range(index, index + 5):
  27.         text += f"*index*: {data[i]}\n"
  28.     return text
  29.  
  30.  
  31. def start(update, context):
  32.     update.message.reply_text('hello')
  33.  
  34.  
  35. def area(update, context):
  36.  
  37.     args = context.args
  38.     for arg in args:
  39.        print(arg)
  40.  
  41.     ########
  42.     results = my_data['op1']
  43.     query = "op1"
  44.     if args:
  45.         query = "op2"
  46.         results = my_data['op2']
  47.    
  48.     N = len(results)
  49.  
  50.     context.chat_data['results'] = {
  51.         'query': query,
  52.         'size': N
  53.     }
  54.  
  55.     text = format_search(results)
  56.  
  57.     #########
  58.  
  59.     keyboard = [[InlineKeyboardButton("Prev", callback_data=0),
  60.                  InlineKeyboardButton(f"1/{math.ceil(N/5)}", callback_data='nothing'),
  61.                  InlineKeyboardButton("Next", callback_data=5)]]
  62.  
  63.  
  64.     reply_markup = InlineKeyboardMarkup(keyboard)
  65.  
  66.     update.message.reply_text(text, reply_markup=reply_markup, parse_mode='markdown')
  67.  
  68.  
  69. def button(update, context):
  70.     query = update.callback_query
  71.     selected = query.data
  72.     current = 0
  73.  
  74.     print(f"current {selected}")
  75.  
  76.     results = context.chat_data['results']
  77.     key = results['query']
  78.     N = results['size']
  79.  
  80.     data = my_data[key]
  81.    
  82.     if selected == "nothing":
  83.         query.answer("Esse botão não faz nada.")
  84.     else:
  85.         current = int(selected)
  86.  
  87.     if current < 0:
  88.         prev_button = 0
  89.         query.answer("Você está no começo da lista.")  
  90.  
  91.     elif current >= N:
  92.         next_button = N - 5
  93.         query.answer("Você está no fim da lista.")
  94.     else:
  95.         prev_button = current - 5
  96.         next_button = current + 5
  97.  
  98.         keyboard = [[InlineKeyboardButton("Prev", callback_data=prev_button),
  99.                      InlineKeyboardButton(f"{current//5 + 1}/{math.ceil(N/5)}", callback_data='nothing'),
  100.                      InlineKeyboardButton("Next", callback_data=next_button)]]
  101.    
  102.         reply_markup = InlineKeyboardMarkup(keyboard)
  103.  
  104.         text = format_search(data, current)
  105.  
  106.         query.edit_message_text(text=text, reply_markup=reply_markup, parse_mode='markdown')
  107.  
  108.  
  109. def help(update, context):
  110.     update.message.reply_text("Use /start to test this bot.")
  111.  
  112.  
  113. def error(update, context):
  114.     """Log Errors caused by Updates."""
  115.     logger.warning('Update "%s" caused error "%s"', update, context.error)
  116.  
  117.  
  118. def main():
  119.     # Create the Updater and pass it your bot's token.
  120.     # Make sure to set use_context=True to use the new context based callbacks
  121.     # Post version 12 this will no longer be necessary
  122.     updater = Updater(os.getenv("TOKEN"), use_context=True)
  123.  
  124.     updater.dispatcher.add_handler(CommandHandler('start', start))
  125.     updater.dispatcher.add_handler(CommandHandler('area', area, pass_args=True, pass_chat_data=True))
  126.     updater.dispatcher.add_handler(CallbackQueryHandler(button))
  127.     updater.dispatcher.add_handler(CommandHandler('help', help))
  128.     updater.dispatcher.add_error_handler(error)
  129.  
  130.     # Start the Bot
  131.     updater.start_polling()
  132.  
  133.     # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
  134.     # SIGTERM or SIGABRT
  135.     updater.idle()
  136.  
  137.  
  138. if __name__ == '__main__':
  139.     main()
Add Comment
Please, Sign In to add comment