コード例 #1
0
def getUserKeyboard():
    db = DBwrapper.get_instance()
    usedNumbers = [x[0] for x in db.get_used_numbers()]

    allNumbers = [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
        21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39,
        40, 41
    ]

    availableNumbers = [x for x in allNumbers if x not in usedNumbers]

    buttons = list()
    for userNumber in availableNumbers:
        buttons.append(
            InlineKeyboardButton(text=str(userNumber).zfill(2),
                                 callback_data=str(userNumber)))

    lastRowButton = [
        InlineKeyboardButton(text=translate("cancelMsg"),
                             callback_data="cancel")
    ]

    reply_mrk = InlineKeyboardMarkup(build_menu(buttons,
                                                n_cols=4,
                                                footer_buttons=lastRowButton),
                                     one_time_keyboard=True)

    return reply_mrk
コード例 #2
0
def start(bot, update):
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    message_id = update.message.message_id
    first_name = update.message.from_user.first_name
    last_name = update.message.from_user.last_name
    username = update.message.from_user.username
    db = DBwrapper.get_instance()

    if not (db.is_user_saved(user_id)):
        # ask user for language:
        logger.info("New user")
        db.write(user_id, "en", first_name, last_name, username)
        language(bot, update)
        return

    # check if user already has got a game (in the same chat):
    game_index = game_handler.get_index_by_chatid(chat_id)
    if game_index == -1:
        logger.debug("Creating a game")
        lang_id = db.get_lang_id(user_id)
        bj = BlackJack(chat_id, user_id, lang_id, first_name, game_handler, message_id, send_message)
        game_handler.add_game(bj)
    else:
        logger.debug("Game already existing")
        game = game_handler.get_game_by_index(game_index)
        game.start_game()
コード例 #3
0
def add_game_played(user_id):
    db = DBwrapper.get_instance()
    games_played = int(db.get_played_games(user_id))
    games_played = games_played + 1
    logger.debug("Add game played for userID: " + str(user_id))
    db.insert("gamesPlayed", str(games_played), user_id)
    db.insert("lastPlayed", int(time()), user_id)
コード例 #4
0
def answer(bot, update):
    sender_id = update.message.from_user.id
    reply_to_message = update.message.reply_to_message
    text = str(update.message.text[8:])
    db = DBwrapper.get_instance()

    if reply_to_message is None:
        bot.sendMessage(sender_id,
                        text="⚠ You need to reply to the user's comment!")
        return

    try:
        last_line = reply_to_message.text.split("\n")
        ll_list = last_line[-1].split(" | ")
        user_id = ll_list[0]
    except ValueError:
        return

    if not re.match("[0-9]+", user_id):
        bot.sendMessage(
            sender_id,
            "⚠ The user_id is not valid. Are you sure you replied to a user comment?"
        )
        return

    answer_text = "{}\n\n{}".format(
        translate("answerFromDev", db.get_lang_id(user_id)), text)
    bot.sendMessage(chat_id=user_id, text=answer_text)
    bot.sendMessage(chat_id=sender_id, text="Message sent!")
コード例 #5
0
def help_cmd(bot, update):
    # Explains commands to user
    db = DBwrapper.get_instance()
    lang_id = db.get_lang_id(update.message.from_user.id)

    start_description = translate("start_description", lang_id)
    stop_description = translate("stop_description", lang_id)
    help_description = translate("help_description", lang_id)
    language_description = translate("language_description", lang_id)
    stats_description = translate("stats_description", lang_id)
    hide_description = translate("hide_description", lang_id)
    text = "/start - {}\n" \
           "/stop - {}\n" \
           "/help - {}\n" \
           "/language - {}\n" \
           "/stats - {}\n" \
           "/hide - {}" \
        .format(start_description,
                stop_description,
                help_description,
                language_description,
                stats_description,
                hide_description
                )

    update.message.reply_text(text)
コード例 #6
0
    def test_start_game(self):
        chat_id = -122345
        user_id = 234091
        user_id_2 = 12398
        self.setup_blackJack_game(user_id=user_id,
                                  chat_id=chat_id,
                                  message_id=1111,
                                  first_name="John",
                                  lang_id="en")
        # add user to database:
        database = DBwrapper.get_instance()
        database.add_user(user_id, "en", "John", "Doe", "username")
        database.add_user(user_id_2, "en", "Carl", "Doe", "username2")
        self.blackJackGame.start_game()

        # When user is alone in group, he shouldn't be able to play
        self.assertFalse(self.blackJackGame.game_running)
        self.assertEqual(len(self.blackJackGame.players[0].cards), 0)

        # Adding another player to the game
        self.blackJackGame.add_player(user_id_2, "Carl", 555666)

        self.blackJackGame.deck = self.CardDeckMockup("en")

        self.blackJackGame.start_game()
        self.assertTrue(self.blackJackGame.game_running)
        self.assertTrue(len(self.blackJackGame.players[0].cards) > 0)
コード例 #7
0
def comment_cmd(bot, update, args):
    user_id = update.message.from_user.id
    chat_id = update.message.chat_id
    first_name = update.message.from_user.first_name
    last_name = update.message.from_user.last_name
    username = update.message.from_user.username
    db = DBwrapper.get_instance()
    lang_id = db.get_lang_id(user_id)

    state_handler = StateHandler.get_instance()
    user = state_handler.get_user(user_id)

    if user.get_state() == UserState.IDLE:
        if len(args) > 1:
            text = " ".join(args)
            logger.debug("New comment! {}!".format(user_id))

            bot.sendMessage(chat_id=chat_id, text=translate("userComment", lang_id))
            for admin_id in db.get_admins():
                bot.sendMessage(admin_id,
                                "New comment:\n\n{}\n\n{} | {} | {} | @{} | {}".format(text, user_id, first_name,
                                                                                       last_name, username,
                                                                                       lang_id))
            user.set_state(UserState.IDLE)
        else:
            # The user just wrote "/comment" -> Ask him to send a message
            logger.debug("Add {} to comment_list!".format(user_id))

            keyboard = [[InlineKeyboardButton(text=translate("cancel", lang_id), callback_data="cancel_comment")]]
            reply_markup = InlineKeyboardMarkup(keyboard)

            bot.sendMessage(chat_id=chat_id, text=translate("sendCommentNow", lang_id), reply_markup=reply_markup)
            user.set_state(UserState.COMMENTING)
コード例 #8
0
def multiplayer(bot, update):
    chat_id = update.message.chat_id
    user_id = update.message.from_user.id
    message_id = update.message.message_id
    first_name = update.message.from_user.first_name
    # last_name = update.message.from_user.last_name
    # username = update.message.from_user.username
    db = DBwrapper.get_instance()

    game_index = game_handler.get_index_by_chatid(chat_id)
    if game_index is None:
        logger.debug("Creating a game")
        lang_id = db.get_lang_id(user_id)
        game_id = game_handler.generate_id()
        bj = BlackJackGame(chat_id,
                           user_id,
                           lang_id,
                           first_name,
                           game_handler,
                           message_id,
                           send_mp_message,
                           multiplayer=True,
                           game_id=game_id)
        game_handler.add_game(bj)
        bot.sendMessage(chat_id, "Your game_id: {}".format(bj.game_id))
    else:
        logger.debug("Game already existing")
コード例 #9
0
ファイル: main.py プロジェクト: Poolitzer/Python-BlackJackBot
def change_language(bot, update, lang_id):
    bot.editMessageText(chat_id=update.callback_query.message.chat_id,
                        text=translate("langChanged", lang_id),
                        message_id=update.callback_query.message.message_id,
                        reply_markup=None)
    db = DBwrapper.get_instance()
    db.insert("languageID", lang_id, update.callback_query.from_user.id)
コード例 #10
0
def users(bot, update):
    sender_id = update.message.from_user.id
    db = DBwrapper.get_instance()
    players = db.get_recent_players()

    text = "Last 24 hours: {}".format(len(players))

    bot.sendMessage(chat_id=sender_id, text=text)
コード例 #11
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def unsubscribe_entity(user, entity):
    db = DBwrapper.get_instance()
    if entity.TYPE == EntityType.WISHLIST:
        db.unsubscribe_wishlist(user.id, entity.id)
    elif entity.TYPE == EntityType.PRODUCT:
        db.unsubscribe_product(user.id, entity.id)
    else:
        raise ValueError("Unknown EntityType")
コード例 #12
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def rm_entity(entity):
    db = DBwrapper.get_instance()
    if entity.TYPE == EntityType.WISHLIST:
        db.rm_wishlist(entity.id)
    elif entity.TYPE == EntityType.PRODUCT:
        db.rm_product(entity.id)
    else:
        raise ValueError("Unknown EntityType")
コード例 #13
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def add_product_if_new(product):
    """Save a product to the database, if it is not already stored"""
    db = DBwrapper.get_instance()

    if not db.is_product_saved(product.id):
        db.add_product(product.id, product.name, product.price, product.url)
    else:
        pass
コード例 #14
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def update_entity_name(entity, name):
    """Update the name of an entity"""
    db = DBwrapper.get_instance()
    if entity.TYPE == EntityType.WISHLIST:
        db.update_wishlist_name(entity.id, name)
    elif entity.TYPE == EntityType.PRODUCT:
        db.update_product_name(entity.id, name)
    else:
        raise ValueError("Unknown EntityType")
コード例 #15
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def get_entity_subscribers(entity):
    """Returns the subscribers of an entity"""
    db = DBwrapper.get_instance()
    if entity.TYPE == EntityType.WISHLIST:
        return db.get_userids_for_wishlist(entity.id)
    elif entity.TYPE == EntityType.PRODUCT:
        return db.get_userids_for_product(entity.id)
    else:
        raise ValueError("Unknown EntityType")
コード例 #16
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def get_product(id):
    """Returns the product object for an id"""
    db = DBwrapper.get_instance()
    product = db.get_product_info(id)

    if product is None:
        raise ProductNotFoundException

    return product
コード例 #17
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def get_all_entities_with_subscribers():
    """Returns all the entities with subscribers in the database"""
    db = DBwrapper.get_instance()
    wishlists = db.get_all_subscribed_wishlists()
    products = db.get_all_subscribed_products()

    entities = wishlists + products

    return entities
コード例 #18
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def add_wishlist_if_new(wishlist):
    """Save a wishlist to the database, if it is not already stored"""
    db = DBwrapper.get_instance()

    if not db.is_wishlist_saved(wishlist.id):
        # logger.debug("URL not in database!")
        db.add_wishlist(wishlist.id, wishlist.name, wishlist.price, wishlist.url)
    else:
        pass
コード例 #19
0
def get_all_entities():
    """Returns all the entities in the database"""
    db = DBwrapper.get_instance()
    wishlists = db.get_all_wishlists()
    products = db.get_all_products()

    entities = wishlists + products

    return entities
コード例 #20
0
def add_user_if_new(user):
    """Save a user to the database, if the user is not already stored"""
    db = DBwrapper.get_instance()
    if not db.is_user_saved(user.user_id):
        db.add_user(user_id=user.user_id,
                    first_name=user.first_name,
                    last_name=user.last_name,
                    username=user.username,
                    lang_code=user.lang_code)
コード例 #21
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def get_wishlist(id):
    """Returns the wishlist object for an id"""
    db = DBwrapper.get_instance()
    wishlist = db.get_wishlist_info(id)

    if wishlist is None:
        raise WishlistNotFoundException

    return wishlist
コード例 #22
0
def change_language(bot, update, lang_id):
    logger.info("Language changed to '{}' for user {}".format(
        lang_id, update.effective_user.id))
    bot.editMessageText(chat_id=update.callback_query.message.chat_id,
                        text=translate("langChanged", lang_id),
                        message_id=update.callback_query.message.message_id,
                        reply_markup=None)
    db = DBwrapper.get_instance()
    db.insert("languageID", lang_id, update.callback_query.from_user.id)
コード例 #23
0
 def admin_check(bot, update):
     db = DBwrapper.get_instance()
     user = update.message.from_user
     if user.id in db.get_admins():
         return func(bot, update)
     else:
         update.message.reply_text('You have not the needed permissions to do that!')
         logger.warning(
             "User {} ({}, @{}) tried to use admin function '{}'!".format(user.id, user.first_name, user.username,
                                                                          func.__name__))
コード例 #24
0
def error(bot, update, error):
    """Log Errors caused by Updates."""
    if update is None:
        return

    logger.warning('Update "%s" caused error "%s"', update, error)

    db = DBwrapper.get_instance()
    for admin_id in db.get_admins():
        send_message(admin_id, "Update '{0}' caused error '{1}'".format(update, error))
コード例 #25
0
    def setUp(self):
        self.db_name = "test.db"
        self.db_name_test_create = "test_create.db"
        self.db = DBwrapper.get_instance(self.db_name)

        # Define sample wishlist and product
        self.wl = Wishlist(123456, "Wishlist",
                           "https://geizhals.de/?cat=WL-123456", 123.45)
        self.p = Product(123456, "Product", "https://geizhals.de/a123456",
                         123.45)
コード例 #26
0
ファイル: core.py プロジェクト: h3rm/Python-GeizhalsBot
def get_all_entities():
    """Returns all the entities in the database"""
    # TODO only get wishlists which have subscribers
    db = DBwrapper.get_instance()
    wishlists = db.get_all_wishlists()
    products = db.get_all_products()

    entities = wishlists + products

    return entities
コード例 #27
0
def get_user_stats(user_id):
    db = DBwrapper.get_instance()
    user = db.get_user(user_id)

    played_games = int(user[5])
    if played_games == 0:
        played_games = 1
    statistics_string = "Here are your statistics  📊:\n\nPlayed Games: " + str(played_games) + "\nWon Games : " + str(user[6]) + \
                        "\nLast Played: " + datetime.fromtimestamp(int(user[8])).strftime('%d.%m.%y %H:%M') + " CET" + \
                        "\n\n" + get_stats(round(float(user[6]) / float(played_games), 4) * 100) + "\n\nWinning rate: " + \
                        '{percent:.2%}'.format(percent=float(user[6]) / float(played_games))
    return statistics_string
コード例 #28
0
ファイル: main.py プロジェクト: BinaryWorld0101201/Chat-n-bot
def start(bot, update):
    user_id = update.message.from_user.id
    user = update.message.from_user
    db = sqlitedb.get_instance()

    if user_id in db.get_banned_users():
        bot.send_message(
            user_id,
            "{} You have been banned from using this bot!".format(BOT_SENDS),
            parse_mode="Markdown")
        return

    db.add_user(user.id, "en", user.first_name, user.last_name, user.username)

    if (user_id not in searching_users) and (user_already_chatting(user_id)
                                             == -1):
        # search for another "searching" user in searching_users list
        if len(searching_users) > 0:
            # delete the other searching users from the list of searching_users
            logger.debug(
                "Another user is searching now. There are 2 users. Matching them now!"
            )

            with lock:
                partner_id = searching_users[0]
                del searching_users[0]

            # add both users to the list of chatting users with the user_id of the other user.
            chatting_users.append([user_id, partner_id])
            chatting_users.append([partner_id, user_id])

            text = "You are connected to a stranger. Have fun and be nice! Skip stranger with /next."
            bot.send_message(user_id,
                             "{} {}".format(BOT_SENDS, text),
                             parse_mode="Markdown")
            bot.send_message(partner_id,
                             "{} {}".format(BOT_SENDS, text),
                             parse_mode="Markdown")
        else:
            # if no user is searching, add him to the list of searching users.
            # TODO later when you can search for specific gender, this condition must be changed
            searching_users.append(user_id)
            bot.send_message(user_id,
                             "{} {}".format(BOT_SENDS,
                                            "Searching for strangers!"),
                             parse_mode="Markdown")

    elif user_id in searching_users:
        bot.send_message(user_id,
                         "{} {}".format(
                             BOT_SENDS,
                             "You are already searching. Please wait!"),
                         parse_mode="Markdown")
コード例 #29
0
def add_entity_if_new(entity):
    db = DBwrapper.get_instance()
    if entity.TYPE == EntityType.WISHLIST:
        if db.is_wishlist_saved(entity.entity_id):
            return
        db.add_wishlist(entity.entity_id, entity.name, entity.price,
                        entity.url)
    elif entity.TYPE == EntityType.PRODUCT:
        if db.is_product_saved(entity.entity_id):
            return
        db.add_product(entity.entity_id, entity.name, entity.price, entity.url)
    else:
        raise ValueError("Unknown EntityType")
コード例 #30
0
ファイル: main.py プロジェクト: BinaryWorld0101201/Chat-n-bot
def broadcast(bot, update, args):
    """Sends a broadcast message to all known users"""
    if len(args) == 0:
        return
    text = " ".join(args)
    db = sqlitedb.get_instance()

    users = db.get_all_users()
    print(users)

    for user_id in users:
        bot.send_message(user_id,
                         "{} {}".format(BOT_BROADCAST, text),
                         parse_mode="Markdown")