<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
A Telegram bot that tag your favorite stickers.
"""
from __future__ import division, absolute_import, print_function, unicode_literals

import json
import logging
import sqlite3
from uuid import uuid4

from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineQueryResultCachedSticker
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler, InlineQueryHandler)
from telegram.ext.dispatcher import run_async

# Load config file
with open('config.json') as config_file:
    CONFIGURATION = json.load(config_file)

# The database object
conn = None  # pylint: disable=invalid-name

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

STICKER, TAGGING, UPDATE, CONFIRM_UPDATE, CONFIRM_TAG = range(5)

def start(bot, update):  # pylint: disable=unused-argument
    """Handler for the /start command"""
    update.message.reply_text("Hi! I'm a bot that can help you find and send your "
                              "favorite stickers using custom tags. "
                              "Send me a sticker to start!")
    return STICKER

def get_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """ Handler for a sticker message.

        Stores the sticker file id in the user_data to be tagged in the next state.
    """
    user_data['sticker'] = {'file_id': None, 'emoji': None}
    user_data['sticker']['file_id'] = update.message.sticker.file_id
    user_data['sticker']['emoji'] = update.message.sticker.emoji

    # Check if the user has already tagged this sticker
    cursor = conn.cursor()
    cursor.execute("SELECT USER_STICKER.rowid, * "
                   "FROM USER_STICKER, USER, STICKER "
                   "WHERE USER_STICKER.user_rowid = USER.rowid "
                   "AND USER_STICKER.sticker_rowid = STICKER.rowid "
                   "AND USER.id=? AND STICKER.file_id=?",
                   (str(update.message.from_user.id),
                    user_data['sticker']['file_id']))
    query = cursor.fetchone()
    if query:
        update.message.reply_text("You have already tagged this sticker, "
                                  "want to edit the tags or remove it?",
                                  reply_markup=ReplyKeyboardMarkup([["Edit", "Cancel", "Remove"]],
                                                                   one_time_keyboard=True))
        user_data["modify"] = True
        user_data["modify_id"] = query["rowid"] # This is the USER_STICKER.rowid
        return CONFIRM_UPDATE
    else:
        user_data["modify"] = False
        user_data["modify_id"] = None
        update.message.reply_text("Cool, now send me words to tag your sticker.\n"
                                  "You can use more tags, just send them separated by commas (,)\n"
                                  "Example: dank, meme")
        return TAGGING


def confirm_update(bot, update, user_data):
    """Handler for a message that begins with Edit, Cancel or Remove.
       Confirm what the user want to do when an already tagged sticker was sent.
    """
    if update.message.text == "Edit":
        update.message.reply_text("Cool, send me the new tags to your sticker",
                                  reply_markup=ReplyKeyboardRemove())
        return TAGGING
    elif update.message.text == "Cancel":
        return cancel(bot, update, user_data)
    elif update.message.text == "Remove":
        return remove_sticker(bot, update, user_data)

def tag_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """Handler for a text message with the user tags.
       Store tags in the user data.
    """
    user_data['tags'] = update.message.text
    update.message.reply_text("You wanna tag your sticker with the following words:\n"
                              "<b>{}</b>\n".format(user_data["tags"]) + "Is that right?",
                              parse_mode="HTML",
                              reply_markup=ReplyKeyboardMarkup([["Yes", "No"]],
                                                               one_time_keyboard=True))
    return CONFIRM_TAG

def remove_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """Removes a sticker from the database"""
    cursor = conn.cursor()
    cursor.execute("DELETE FROM USER_STICKER WHERE rowid=?",
                   (user_data["modify_id"],))
    cursor.execute("DELETE FROM STICKER_TAG WHERE user_sticker_rowid=?",
                   (user_data["modify_id"],))
    conn.commit()
    update.message.reply_text("Sticker removed successfully!")

    return ConversationHandler.END

def confirm_tag(bot, update, user_data):  # pylint: disable=unused-argument
    """Handler for a message that begins with Yes or No.
       Confirm the tags and modify the database.
    """
    if update.message.text == "Yes":
        cursor = conn.cursor()
        if user_data["modify"]:
            for tag in user_data['tags'].split(","):
                tag = tag.strip()
                if tag == "":
                    continue
                # Insert tag if not exist
                cursor.execute("INSERT INTO TAG(tag) SELECT ?"
                               " WHERE NOT EXISTS(SELECT tag FROM TAG WHERE tag=?)",
                               (tag, tag))
                # Get the tag rowid
                cursor.execute("SELECT rowid, tag FROM TAG WHERE tag=?", (tag,))
                tag_rowid = cursor.fetchone()["rowid"]

                cursor.execute("UPDATE STICKER_TAG SET tag_rowid=? WHERE user_sticker_rowid=?",
                               (tag_rowid,
                                user_data["modify_id"]))
            conn.commit()

            update.message.reply_text("Yay! Tags updated successfully!")<commit_msg>Fix a bug in edit tag mode<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
A Telegram bot that tag your favorite stickers.
"""
from __future__ import division, absolute_import, print_function, unicode_literals

import json
import logging
import sqlite3
from uuid import uuid4

from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineQueryResultCachedSticker
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler, InlineQueryHandler)
from telegram.ext.dispatcher import run_async

# Load config file
with open('config.json') as config_file:
    CONFIGURATION = json.load(config_file)

# The database object
conn = None  # pylint: disable=invalid-name

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

STICKER, TAGGING, UPDATE, CONFIRM_UPDATE, CONFIRM_TAG = range(5)

def start(bot, update):  # pylint: disable=unused-argument
    """Handler for the /start command"""
    update.message.reply_text("Hi! I'm a bot that can help you find and send your "
                              "favorite stickers using custom tags. "
                              "Send me a sticker to start!")
    return STICKER

def get_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """ Handler for a sticker message.

        Stores the sticker file id in the user_data to be tagged in the next state.
    """
    user_data['sticker'] = {'file_id': None, 'emoji': None}
    user_data['sticker']['file_id'] = update.message.sticker.file_id
    user_data['sticker']['emoji'] = update.message.sticker.emoji

    # Check if the user has already tagged this sticker
    cursor = conn.cursor()
    cursor.execute("SELECT USER_STICKER.rowid, * "
                   "FROM USER_STICKER, USER, STICKER "
                   "WHERE USER_STICKER.user_rowid = USER.rowid "
                   "AND USER_STICKER.sticker_rowid = STICKER.rowid "
                   "AND USER.id=? AND STICKER.file_id=?",
                   (str(update.message.from_user.id),
                    user_data['sticker']['file_id']))
    query = cursor.fetchone()
    if query:
        update.message.reply_text("You have already tagged this sticker, "
                                  "want to edit the tags or remove it?",
                                  reply_markup=ReplyKeyboardMarkup([["Edit", "Cancel", "Remove"]],
                                                                   one_time_keyboard=True))
        user_data["modify"] = True
        user_data["modify_id"] = query["rowid"] # This is the USER_STICKER.rowid
        return CONFIRM_UPDATE
    else:
        user_data["modify"] = False
        user_data["modify_id"] = None
        update.message.reply_text("Cool, now send me words to tag your sticker.\n"
                                  "You can use more tags, just send them separated by commas (,)\n"
                                  "Example: dank, meme")
        return TAGGING


def confirm_update(bot, update, user_data):
    """Handler for a message that begins with Edit, Cancel or Remove.
       Confirm what the user want to do when an already tagged sticker was sent.
    """
    if update.message.text == "Edit":
        update.message.reply_text("Cool, send me the new tags to your sticker",
                                  reply_markup=ReplyKeyboardRemove())
        return TAGGING
    elif update.message.text == "Cancel":
        return cancel(bot, update, user_data)
    elif update.message.text == "Remove":
        return remove_sticker(bot, update, user_data)

def tag_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """Handler for a text message with the user tags.
       Store tags in the user data.
    """
    user_data['tags'] = update.message.text
    update.message.reply_text("You wanna tag your sticker with the following words:\n"
                              "<b>{}</b>\n".format(user_data["tags"]) + "Is that right?",
                              parse_mode="HTML",
                              reply_markup=ReplyKeyboardMarkup([["Yes", "No"]],
                                                               one_time_keyboard=True))
    return CONFIRM_TAG

def remove_sticker(bot, update, user_data):  # pylint: disable=unused-argument
    """Removes a sticker from the database"""
    cursor = conn.cursor()
    cursor.execute("DELETE FROM USER_STICKER WHERE rowid=?",
                   (user_data["modify_id"],))
    cursor.execute("DELETE FROM STICKER_TAG WHERE user_sticker_rowid=?",
                   (user_data["modify_id"],))
    conn.commit()
    update.message.reply_text("Sticker removed successfully!")

    return ConversationHandler.END

def confirm_tag(bot, update, user_data):  # pylint: disable=unused-argument
    """Handler for a message that begins with Yes or No.
       Confirm the tags and modify the database.
    """
    if update.message.text == "Yes":
        cursor = conn.cursor()
        if user_data["modify"]:
            # Delete the previous defined tags
            cursor.execute("DELETE FROM STICKER_TAG WHERE user_sticker_rowid=?",
                           (user_data["modify_id"],))
            # Insert the new ones
            for tag in user_data['tags'].split(","):
                tag = tag.strip()
                if tag == "":
                    continue
                # Insert tag if not exist
                cursor.execute("INSERT INTO TAG(tag) SELECT ?"
                               " WHERE NOT EXISTS(SELECT tag FROM TAG WHERE tag=?)",
                               (tag, tag))
                # Get the tag rowid
                cursor.execute("SELECT rowid, tag FROM TAG WHERE tag=?", (tag,))
                tag_rowid = cursor.fetchone()["rowid"]

                cursor.execute("INSERT INTO STICKER_TAG VALUES (?, ?)",
                               (user_data["modify_id"], tag_rowid))

            conn.commit()

            update.message.reply_text("Yay! Tags updated successfully!")
{'fraction_non_alphanumeric': 0.10349926071956629, 'fraction_numerical': 0.0006571381632988336, 'mean_word_length': 2.1713988017712946, 'pattern_counts': {'":': 10, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4762644', 'n_tokens_mistral': 3464, 'n_tokens_neox': 3350, 'n_words': 942}