From e27b55fe01d0c07fae54fa74b24c17d123daeed5 Mon Sep 17 00:00:00 2001 From: Ceda EI Date: Mon, 7 Jan 2019 00:56:03 +0530 Subject: [PATCH] Complete click. --- bot.py | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 2e2a2d5..f766cc8 100644 --- a/bot.py +++ b/bot.py @@ -4,7 +4,7 @@ import logging import config import sqlite3 -from telegram.ext import Updater, MessageHandler, Filters +from telegram.ext import Updater, MessageHandler, CallbackQueryHandler, Filters from telegram import InlineKeyboardButton, InlineKeyboardMarkup logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - \ @@ -37,6 +37,40 @@ def add_vote(db, callback_id, user=None): db.commit() +def delete_vote(db, callback_id, user): + user_id = user.id + query = "DELETE FROM poll WHERE callback=? AND user_id=?" + cursor.execute(query, (callback_id, user_id)) + db.commit() + + +def check_vote(db, callback_id, user): + user_id = user.id + cursor = db.cursor() + query = ("SELECT * FROM poll WHERE callback=? AND user_id=?") + cursor.execute(query, (callback_id, user_id)) + if cursor.fetchone(): + return True + else: + return False + + +def update_message(bot, db, callback_id): + cursor = db.cursor() + query = "SELECT message_id FROM message_ids WHERE callback = ?" + cursor.execute(query, (callback_id,)) + message_id = cursor.fetchone()[0] + query = "SELECT count(user_id) FROM poll WHERE callback = ?" + cursor.execute(query, (callback_id,)) + count = cursor.fetchone()[0] + keyboard = InlineKeyboardMarkup([[InlineKeyboardButton( + text=f"❤️ {count}", + callback_data=callback_id)]]) + bot.edit_message_reply_markup(chat_id=config.channel_id, + message_id=message_id, + reply_markup=keyboard) + + def post(bot, update, db): chat_id = update.message.chat_id if chat_id in config.allowed_users: @@ -52,6 +86,17 @@ def post(bot, update, db): bot.send_message(chat_id=chat_id, text="Not Authorized") +def click(bot, update, db): + user = update.callback_query.from_user + callback_id = update.callback_query.data + if not check_vote(db, callback_id, user): + add_vote(db, callback_id, user) + else: + delete_vote(db, callback_id, user) + update_message(bot, db, callback_id) + bot.answer_callback_query(update.callback_query.id) + + updater = Updater(token=config.api_key) dispatcher = updater.dispatcher @@ -60,4 +105,5 @@ cursor = db.cursor() dispatcher.add_handler(MessageHandler(Filters.photo, lambda x, y: post(x, y, db))) +dispatcher.add_handler(CallbackQueryHandler(lambda x, y: click(x, y, db))) updater.start_polling()