Exemplo n.º 1
0
def delete_queue_command(update: Update, context: CallbackContext):
    """Handler for '/delete_queue <queue_name>' command"""

    chat_id = update.effective_chat.id
    queue_name = ' '.join(context.args)
    if not queue_name:
        logger.info("Deletion a queue with empty name.")
        update.effective_chat.send_message(**delete_queue_empty_name())
    else:
        session = create_session()
        queue: Queue = session.query(Queue).filter(
            Queue.chat_id == chat_id, Queue.name == queue_name).first()
        if queue is None:
            logger.info("Deletion nonexistent queue.")
            update.effective_chat.send_message(**queue_not_exist(
                queue_name=queue_name))
        else:
            session.delete(queue)
            session.commit()
            logger.info(f"Deleted queue: \n\t{queue}")
            update.effective_chat.send_message(**deleted_queue_message())

            if context.bot.get_chat_member(chat_id,
                                           context.bot.id).can_pin_messages:
                try:
                    context.bot.unpin_chat_message(
                        chat_id, message_id=queue.message_id_to_edit)
                except BadRequest as e:
                    logger.warning(
                        f"ERROR when tried to unpin "
                        f"message({queue.message_id_to_edit}) in queue({queue.queue_id}):\n\t"
                        f"{e}")
            else:
                update.effective_chat.send_message(
                    **no_rights_to_unpin_message())
Exemplo n.º 2
0
def __get_queue_members(queue: Queue) -> List[str]:
    session = create_session()
    members = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id).order_by(
            QueueMember.user_order).all())
    member_names = [member.fullname for member in members]
    return member_names
Exemplo n.º 3
0
def skip_me_command(update: Update, context: CallbackContext, queue):
    chat_id = update.effective_chat.id
    session = create_session()

    member: QueueMember = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id,
        QueueMember.user_id == update.effective_user.id).first())
    if member is None:
        logger.info('Not yet in the queue')
        update.effective_message.reply_text(**not_in_the_queue_yet())
    else:
        next_member: QueueMember = (session.query(QueueMember).filter(
            QueueMember.queue_id == queue.queue_id,
            QueueMember.user_order == member.user_order + 1).first())
        if next_member is not None:
            member.user_order = member.user_order + 1
            next_member.user_order = next_member.user_order - 1
            session.add_all([member, next_member])
            session.commit()
            logger.info(
                f'Skip queue_member({member.user_id}) in the queue({queue.queue_id})'
            )

            __edit_queue_members_message(queue, chat_id, context.bot)
        else:
            logging.info(
                f'Cancel skipping because of no other members in queue({queue.queue_id})'
            )
            update.effective_message.reply_text(**cannot_skip())
Exemplo n.º 4
0
def add_me_command(update: Update, context: CallbackContext, queue: Queue):
    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    session = create_session()
    member = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id,
        QueueMember.user_id == user_id).first())
    if member is not None:
        logger.info("Already in the queue.")
        update.effective_message.reply_text(**already_in_the_queue())
        return

    last_member: QueueMember = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id).order_by(
            QueueMember.user_order.desc()).first())
    if last_member is None:
        user_order = 1
    else:
        user_order = last_member.user_order + 1
    member = QueueMember(user_id=user_id,
                         fullname=update.effective_user.full_name,
                         user_order=user_order,
                         queue_id=queue.queue_id)
    session.add(member)
    session.commit()
    logger.info(f"Added member to queue: \n\t{member}")

    __edit_queue_members_message(queue, chat_id, context.bot)
Exemplo n.º 5
0
def show_queues_command(update: Update, context: CallbackContext):
    """Handler for '/show_queues' command"""

    chat_id = update.effective_chat.id
    session = create_session()
    queues = session.query(Queue).filter(Queue.chat_id == chat_id).all()
    if not queues:
        update.effective_chat.send_message(**show_queues_message_empty())
    else:
        queue_names = [queue.name for queue in queues]
        update.effective_chat.send_message(**show_queues_message(queue_names))
Exemplo n.º 6
0
def left_group_member_handler(update: Update, context: CallbackContext):
    """
    Triggered when someone left the group.
    Also triggered, when this bot is removed from the group and, in that case,
    deleting the chat and all related info from DB.

    Note:
        If someone has left the group and the bot remained in it alone,
        the bot will leave the group too.

    Args:
        update: :class:`telegram.Update`
        context: :class:`telegram.CallbackContext`
    """
    is_me = update.effective_message.left_chat_member.id == context.bot.id
    chat_id = update.effective_chat.id

    # If the bot was kicked from the chat, he can't get the number of the members left
    try:
        members_left = update.effective_chat.get_members_count()
    except Unauthorized as e:
        logger.warning(f'Cannot get the number of the members left int chat({chat_id}): {e}')
        members_left = None

    logger.info(f"left member: "
                f"\n\tis_me: {is_me}"
                f"\n\t[chat_id: {chat_id}; "
                f"\n\tleft_chat_member: {update.effective_message.left_chat_member}; "
                f"\n\tfrom: {update.effective_message.from_user}"
                f"\n\tmembers left: {members_left}]")

    if is_me or members_left == 1:
        if members_left == 1:
            logger.info(f'The bot has left from the chat({chat_id}) because only it left in the group.')
        else:
            logger.info(f"Removed from chat_id {chat_id}")

        session = create_session()
        chat = session.query(Chat).filter(Chat.chat_id == chat_id).first()
        if chat is None:
            logger.warning(f"Expected the chat(id={chat_id}) was in DB, but it wasn't found.")
            return
        else:
            session.delete(chat)
            session.commit()
            logger.info(f"Chat removed from DB ({chat.chat_id})")
Exemplo n.º 7
0
def __show_members(chat_id: int, queue: Queue, bot):
    member_names = __get_queue_members(queue)
    message = bot.send_message(chat_id=chat_id,
                               **show_queue_members(queue.name, member_names,
                                                    queue.current_order))
    if message:
        try:
            bot.delete_message(chat_id=chat_id,
                               message_id=queue.message_id_to_edit)
        except BadRequest as e:
            logger.exception(
                f'Error when deleting the previously sent message: {e}')
        queue.message_id_to_edit = message.message_id

        session = create_session()
        session.add(queue)
        session.commit()

        logger.info(f'Updated message_to_edit_id in queue:\n\t{queue}')
Exemplo n.º 8
0
def notify_all_command(update: Update, context: CallbackContext):
    chat_id = update.effective_chat.id
    session = create_session()
    chat: Chat = session.query(Chat).filter(Chat.chat_id == chat_id).first()
    if chat:
        if chat.notify:
            chat.notify = False
            session.commit()
            update.effective_chat.send_message(**notify_all_disabled_message())
        else:
            chat.notify = True
            session.commit()
            update.effective_chat.send_message(**notify_all_enabled_message())
        logger.info(
            f'Changed notify setting to {chat.notify} in chat({chat_id})')
    else:
        logging.error(
            f'Error fetching chat by chat_id({chat_id}) in active chat. '
            'The chat must be in the DB, but doesn\'t.')
Exemplo n.º 9
0
def __save_chat_to_db(chat_id: int, chat_title: str):
    """
    Saves chat to DB with given ``chat_id`` and ``chat_title``.

    Args:
        chat_id: id of the chat that was created
        chat_title: name of the chat that was created
    """
    chat = Chat(chat_id=chat_id, name=chat_title)

    session = create_session()
    try:
        session.add(chat)
        session.commit()
        logger.info(f"Chat saved to DB ({chat.chat_id})")
    except IntegrityError as e:
        logger.error("ERROR while adding to DB:\n" + str(e) + '\n')
        session.rollback()
        logger.warning("Session was rolled back.")
Exemplo n.º 10
0
def create_queue_command(update: Update, context: CallbackContext):
    """Handler for '/create_queue <queue_name>' command"""

    chat_id = update.effective_chat.id
    queue_name = ' '.join(context.args)
    if not queue_name:
        logger.info("Creation a queue with empty name.")
        update.effective_chat.send_message(**create_queue_empty_name())
    else:
        session = create_session()
        count = session.query(Queue).filter(Queue.chat_id == chat_id,
                                            Queue.name == queue_name).count()
        if count == 1:
            logger.info("Creating a queue with an existing name")
            update.effective_chat.send_message(**create_queue_exist(
                queue_name=queue_name))
        else:
            queue = Queue(name=queue_name, chat_id=chat_id)
            message = update.effective_chat.send_message(
                **show_queue_members(queue_name))
            try:
                queue.message_id_to_edit = message.message_id

                session.add(queue)
                session.commit()
                logger.info(f"New queue created: \n\t{queue}")

                # Checking if the bot has rights to pin the message.
                if context.bot.get_chat_member(
                        chat_id, context.bot.id).can_pin_messages:
                    if queue.chat.notify:
                        message.pin()
                # If the message should be pinned, but the bot hasn't got rights.
                elif queue.chat.notify:
                    update.effective_chat.send_message(
                        **no_rights_to_pin_message())
            except Exception as e:
                logger.exception(f"ERROR when creating queue: \n\t{queue} "
                                 f"with message: \n{e}")
                update.effective_chat.send_message(**unexpected_error())
                message.delete()
Exemplo n.º 11
0
        def insert_queue_from_context_wrapper(update: Update,
                                              context: CallbackContext):
            chat_id = update.effective_chat.id
            queue: Optional[Queue] = None

            session = create_session()
            # Trying to get the queue from message_id, that user replied to.
            if update.effective_message.reply_to_message:
                replied_message_id = update.effective_message.reply_to_message.message_id
                logger.info(f'Replied to message({replied_message_id})')
                queue = (session.query(Queue).filter(
                    Queue.chat_id == chat_id,
                    Queue.message_id_to_edit == replied_message_id).options(
                        joinedload(Queue.members)).first())
                # User replied to the wrong message (not with members) or to deleted queue.
                if not queue:
                    logger.info(
                        'Replied to wrong message or to the deleted queue.')
                    update.effective_message.reply_text(
                        **reply_to_wrong_message_message())

            # User didn't reply to the message or replied to the wrong message.
            # Checks if there name specified in command arguments.
            queue_name = ' '.join(context.args)
            if context.args and not queue:
                queue = (session.query(Queue).filter(
                    Queue.chat_id == chat_id,
                    Queue.name == queue_name).options(joinedload(
                        Queue.members)).first())
            if queue:
                return command_handler_function(update, context, queue)
            # The name was specified but queue with this name wasn't found in DB
            elif not queue and context.args:
                logger.info(on_not_exist_log)
                update.effective_message.reply_text(**queue_not_exist(
                    queue_name=queue_name))
            else:
                logger.info(on_no_queue_log)
                update.effective_message.reply_text(**on_no_queue_reply)
Exemplo n.º 12
0
def next_command(update: Update, context: CallbackContext, queue):
    order = queue.current_order + 1
    queue.current_order = order

    session = create_session()
    member: QueueMember = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id,
        QueueMember.user_order == queue.current_order).first())
    if member is None:
        logger.info(f"Reached the end of the queue({queue.queue_id})")
        update.effective_chat.send_message(**next_reached_queue_end())
    else:
        logging.info(f'Next member: {member}')
        update.effective_chat.send_message(
            **next_member_notify(member.fullname, member.user_id, queue.name))

        session.merge(queue)
        session.commit()
        logger.info(f'Updated current_order: \n\t{queue}')

        __edit_queue_members_message(queue, update.effective_chat.id,
                                     context.bot)
Exemplo n.º 13
0
def remove_me_command(update: Update, context: CallbackContext, queue):
    chat_id = update.effective_chat.id
    user_id = update.effective_user.id

    session = create_session()
    member: QueueMember = (session.query(QueueMember).filter(
        QueueMember.queue_id == queue.queue_id,
        QueueMember.user_id == user_id).first())
    if member is None:
        logger.info('Not yet in the queue')
        update.effective_message.reply_text(**not_in_the_queue_yet())
    else:
        # If it was the last member return turn to the previous one
        last_member: QueueMember = (session.query(QueueMember).filter(
            QueueMember.queue_id == queue.queue_id).order_by(
                QueueMember.user_order.desc()).first())
        if queue.current_order == last_member.user_order:
            queue.current_order = queue.current_order - 1
            session.add(queue)
            logger.info(f'Updated current_order in queue: \n\t{queue}')

        session.delete(member)
        # Updating user_order in queue_members table
        # to move down all users with user_order greater than the value of deleted user
        update_stmt: TextClause = text(
            'UPDATE queue_member '
            'SET user_order = user_order - 1 '
            'WHERE user_order > :deleted_user_order;')
        session.execute(update_stmt, {'deleted_user_order': member.user_order})

        session.commit()

        logger.info(f'User removed from queue (queue_id={queue.queue_id})')
        logger.info(
            f'Updated user_order in queue({queue.queue_id}) for users(order>{member.user_order})'
        )

        __edit_queue_members_message(queue, chat_id, context.bot)
Exemplo n.º 14
0
def group_migrated_handler(update: Update, context: CallbackContext):
    """
    Triggers when the group migrated from the normal group to supergroup
    and updates the group id in the DB.

    Note:
        This method triggers twice:

        * first time ``update.effective_chat.id`` contains id assigned to normal group
            and ``update.effective_message.migrate_to_chat_id`` contains id that chat will migrate to.

        * second time ``update.effective_chat.id`` contains id assigned to supergroup
            and ``update.effective_message.migrate_from_chat_id`` contains an id
            that was assigned to the group before migration.

    Args:
        update: :class:`telegram.Update`
        context: :class:`telegram.CallbackContext`
    """
    if update.effective_message.migrate_to_chat_id:
        logger.info(f'Migrated to '
                    f'supergroup(id={update.effective_message.migrate_to_chat_id}) '
                    f'from group(id={update.effective_chat.id}).')
    else:
        logger.info(f'Migrated '
                    f'from group(id={update.effective_message.migrate_from_chat_id}) '
                    f'to supergroup(id={update.effective_chat.id})')

        session = create_session()
        chat = session.query(Chat).filter(Chat.chat_id == update.effective_message.migrate_from_chat_id).first()
        if chat is None:
            __save_chat_to_db(update.effective_chat.id, update.effective_chat.title)
        else:
            chat.chat_id = update.effective_chat.id
            session.commit()
            logger.info(f'Updated chat_id for chat({update.effective_chat.id})')
Exemplo n.º 15
0
from sql import Event, Tweet, create_session
import json

session = create_session()

def load_json():
    for row in session.query(Tweet).order_by(Tweet.id):
        tweet = json.loads(row.json)
        for url in tweet["entities"]["urls"]:
            print url["expanded_url"]
            print tweet["id"], tweet["text"]


def push_to_queue():
    import redis
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    for row in session.query(Event).order_by(Event.id):
        r.lpush("tweet_urls", row.url)

if __name__ == "__main__":
    push_to_queue()