"bot main"

deploy
campi 3 years ago
parent e0d0dba566
commit f921728e87

@ -18,10 +18,10 @@ import database_lib as DB
import libreremo_assets as txt import libreremo_assets as txt
from libreremo_conf import TOKEN, CALIBRE_DIR, MIN_QUERY_LENGTH from libreremo_conf import TOKEN, CALIBRE_DIR, MIN_QUERY_LENGTH
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', logging.basicConfig(
level=logging.INFO) format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
updater = Updater(TOKEN, use_context=True, arbitrary_callback_data=True)
db = DB.Database(CALIBRE_DIR + "metadata.db") db = DB.Database(CALIBRE_DIR + "metadata.db")
@ -29,13 +29,14 @@ def start(update: Update, context: CallbackContext):
update.message.reply_text(txt.INTRO, parse_mode=ParseMode.HTML) update.message.reply_text(txt.INTRO, parse_mode=ParseMode.HTML)
def help(update: Update, context: CallbackContext): def show_help(update: Update, context: CallbackContext):
update.message.reply_text(txt.HELP, parse_mode=ParseMode.HTML) update.message.reply_text(txt.HELP, parse_mode=ParseMode.HTML)
def _ask_resource_type(update, context): def _ask_resource_type(update, context):
keyboard = [[InlineKeyboardButton(text="Titolo", callback_data="titolo")], keyboard = [[InlineKeyboardButton(text="Titolo", callback_data="titolo")],
[InlineKeyboardButton(text="Autore", callback_data="autore")]] [InlineKeyboardButton(text="Autore", callback_data="autore")],
[InlineKeyboardButton(text="\u274C Annulla \u274C", callback_data="stop")]]
reply_markup = InlineKeyboardMarkup(keyboard) reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text( update.message.reply_text(
text="In base a cosa vuoi cercare il tuo libro?", text="In base a cosa vuoi cercare il tuo libro?",
@ -45,10 +46,15 @@ def _ask_resource_type(update, context):
def _get_resource_type(update, context): def _get_resource_type(update, context):
query = update.callback_query query = update.callback_query
query.answer()
if query.data == "stop":
query.edit_message_text("Ricerca annullata", None)
return ConversationHandler.END
context.user_data["resource"] = query.data context.user_data["resource"] = query.data
context.bot.send_message( query.edit_message_text(
chat_id=query.message.chat_id, text="quale <b>{}</b> stai cercando?".format(query.data),
text="quale {} stai cercando?".format(context.user_data["resource"])) parse_mode=ParseMode.HTML
)
return GET_RESOURCE return GET_RESOURCE
@ -70,11 +76,6 @@ def _get_resource(update, context):
text = "Scegli uno di questi autori" text = "Scegli uno di questi autori"
handler = GET_AUTHOR handler = GET_AUTHOR
elif context.user_data["resource"] == "cds":
# result_list = db.select_class(resource)
text = "Scegli uno di questi corsi di studio"
handler = GET_CDS
logging.info("asked resource {res}: {txt}" logging.info("asked resource {res}: {txt}"
.format(res=context.user_data["resource"], txt=resource)) .format(res=context.user_data["resource"], txt=resource))
@ -93,36 +94,43 @@ def _get_resource(update, context):
def _get_author(update: Update, context: CallbackContext): def _get_author(update: Update, context: CallbackContext):
query = update.callback_query query = update.callback_query
result_list = db.select_books_by_author(query.data) query.answer()
if not result_list: if query.data == "stop":
logging.info("cannot find books for requested author") query.edit_message_text("Ricerca annullata", None)
context.bot.send_message( return ConversationHandler.END
chat_id=query.message.chat_id, book_list = db.select_books_by_author(query.data)
if not book_list:
logging.info(f"cannot find books for author: {query.data}")
query.edit_message_text(
text="Mi dispiace ma non riesco a trovare libri per questo autore") text="Mi dispiace ma non riesco a trovare libri per questo autore")
return ConversationHandler.END return ConversationHandler.END
context.bot.send_message( query.edit_message_text(
chat_id=query.message.chat_id, text="Questi sono i libri che abbiamo per <b>{}</b>".format(
text="scegli uno di questi libri", "".join(query.data.split(",")[::-1])),
reply_markup=__format_reply_markup(result_list)) reply_markup=__format_reply_markup(book_list),
return GET_BOOK parse_mode=ParseMode.HTML
)
def _get_cds(update: Update, context: CallbackContext):
query = update.callback_query
# result_list = db.select_books_by_cds(query)
context.bot.send_message(
chat_id=query.message.chat_id,
text="scegli uno di questi libri")
return GET_BOOK return GET_BOOK
def _get_book(update: Update, context: CallbackContext): def _get_book(update: Update, context: CallbackContext):
query = update.callback_query query = update.callback_query
query.answer()
if query.data == "stop":
query.edit_message_text("Ricerca annulata", None)
return ConversationHandler.END
chat_id = query.message.chat_id chat_id = query.message.chat_id
query.edit_message_reply_markup()
query.message.reply_text( query.message.reply_text(
'perfetto, ti invio immediatamente il file, abbi un attimo di pazienza se il libro non arriva subito') "Hai scelto: <b>{}</b>".format("(".join(
try: query.data.split("/", 1)[1]
.split("(")[:-1])),
parse_mode=ParseMode.HTML
)
query.message.reply_text(
'Ti invio immediatamente il file, sii paziente se il tuo libro non arriva')
filepath = CALIBRE_DIR + query.data + "/*.pdf" filepath = CALIBRE_DIR + query.data + "/*.pdf"
try:
for file in glob.glob(filepath): for file in glob.glob(filepath):
with open(file, 'rb') as doc_pdf: with open(file, 'rb') as doc_pdf:
context.bot.send_document(chat_id, doc_pdf) context.bot.send_document(chat_id, doc_pdf)
@ -156,56 +164,56 @@ def search_by_author(update: Update, context: CallbackContext):
return GET_RESOURCE return GET_RESOURCE
def search_by_class(update: Update, context: CallbackContext):
update.message.reply_text("di quale corso di studio stai cercando i libri?")
context.user_data["resource"] = "cds"
return GET_RESOURCE
def unknown(update: Update, context: CallbackContext): def unknown(update: Update, context: CallbackContext):
update.message.reply_text( update.message.reply_text(
"Sorry '%s' is not a valid command" % update.message.text) "{} non è un comando valido, prova con /help".format(update.message.text))
def __format_reply_markup(list_of_res): def __format_reply_markup(list_of_res):
return InlineKeyboardMarkup([ inline_keyboard = [[InlineKeyboardButton(
[InlineKeyboardButton( text=res.format_text(), callback_data=res.format_data())]
text=res.format_text(), for res in list_of_res]
callback_data=res.format_data())] inline_keyboard.append([InlineKeyboardButton(
for res in list_of_res]) text="\u274C Annulla \u274C", callback_data="stop")])
return InlineKeyboardMarkup(inline_keyboard)
def handle_error(update: Update, context: CallbackContext): # def handle_error(update: Update, context: CallbackContext):
context.bot.send_message(chat_id=update.callback_query.message.chat_id, # context.bot.send_message(chat_id=update.callback_query.message.chat_id,
text="Oh no, qualcosa è andato storto, riprova più tardi...") # text="Oh no, qualcosa è andato storto, riprova più tardi...")
return ConversationHandler.END
GET_RESOURCE_TYPE, ASK_RESOURCE, GET_RESOURCE, GET_BOOK, GET_AUTHOR, GET_CDS = range(6) GET_RESOURCE_TYPE, ASK_RESOURCE, GET_RESOURCE, GET_BOOK, GET_AUTHOR = range(5)
cnv_handler = ConversationHandler( cnv_handler = ConversationHandler(
entry_points=[CommandHandler('search', _ask_resource_type), entry_points=[CommandHandler('search', _ask_resource_type),
CommandHandler('search_by_title', search_by_title), CommandHandler('search_by_title', search_by_title),
CommandHandler('search_by_author', search_by_author), CommandHandler('search_by_author', search_by_author),
CommandHandler('search_by_class', search_by_class),
MessageHandler(Filters.text, search_by_title_default)], MessageHandler(Filters.text, search_by_title_default)],
states={ states={
GET_RESOURCE_TYPE: [CallbackQueryHandler(_get_resource_type)], GET_RESOURCE_TYPE: [CallbackQueryHandler(_get_resource_type)],
GET_RESOURCE: [MessageHandler(Filters.text, _get_resource)], GET_RESOURCE: [MessageHandler(Filters.text, _get_resource)],
GET_AUTHOR: [CallbackQueryHandler(_get_author)], GET_AUTHOR: [CallbackQueryHandler(_get_author)],
GET_BOOK: [CallbackQueryHandler(_get_book)], GET_BOOK: [CallbackQueryHandler(_get_book)],
GET_CDS: [CallbackQueryHandler(_get_cds)]
}, },
fallbacks=[CommandHandler('stop', _cnv_stop), fallbacks=[CommandHandler('stop', _cnv_stop),
MessageHandler(Filters.command, _cnv_stop)], MessageHandler(Filters.command, _cnv_stop)],
) )
def main():
updater = Updater(TOKEN, use_context=True, arbitrary_callback_data=True)
updater.dispatcher.add_handler(CommandHandler('start', start)) updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CommandHandler('help', help)) updater.dispatcher.add_handler(CommandHandler('help', show_help))
updater.dispatcher.add_handler(cnv_handler) updater.dispatcher.add_handler(cnv_handler)
updater.dispatcher.add_handler(MessageHandler(Filters.command, unknown)) # Filters out unknown commands updater.dispatcher.add_handler(MessageHandler(Filters.command, unknown)) # Filters out unknown commands
updater.dispatcher.add_error_handler(handle_error) # updater.dispatcher.add_error_handler(handle_error)
updater.start_polling() updater.start_polling()
updater.idle() updater.idle()
if __name__ == '__main__':
main()

Loading…
Cancel
Save