Example #1
0
def get_permanent_reply_keyboard_markup():
    button_list = [
        [KeyboardButton(text="/random"),
         KeyboardButton(text="/saved")]
        #[ KeyboardButton(text="/all"), KeyboardButton(text="/help")]
    ]
    return ReplyKeyboardMarkup(keyboard=button_list)
Example #2
0
def sendMessageForSingleChargePoint(bot, update, index):
    urld = 'https://kaart.amsterdam.nl/datasets/datasets-item/t/parkeerlocaties-1/export/json'
    r = urllib.request.urlopen(urld)
    data = json.loads(r.read().decode(r.info().get_param('charset') or 'utf-8'))
    reverse_geocode_result = main.gmaps.reverse_geocode((data['features'][int(index)]['geometry']['coordinates'][1], data['features'][int(index)]['geometry']['coordinates'][0]))
    addressName = reverse_geocode_result[0]['address_components'][1]['short_name'] + " " + reverse_geocode_result[0]['address_components'][0]['short_name']
    parkingCost = checkElectricChargeCost(addressName)
    message = "<b>The charge point is: </b>" + data['features'][int(index)]['properties']['title'] + "\n"
    electricChargeCost = checkElectricChargeCost(addressName)
    message += "<b>The address of the charge point is: </b>" + reverse_geocode_result[0]['formatted_address'] + "\n"
    if parkingCost is not "":
        message += "<b>Cost: </b>" + parkingCost 
    bot.sendLocation(update.message.chat_id, data['features'][int(index)]['geometry']['coordinates'][1], data['features'][int(index)]['geometry']['coordinates'][0]) 
    bot.sendMessage(chat_id=update.message.chat_id, text = message, parse_mode='HTML')
    latid = data['features'][int(index)]['geometry']['coordinates'][1]
    long = data['features'][int(index)]['geometry']['coordinates'][0]
    User.objects.filter(chat_id=update.message.chat_id).update(lat=latid, lon=long)
    User.objects.filter(chat_id=update.message.chat_id).update(lastCommand = "chargePoint.afterDetails")
    User.objects.filter(chat_id=update.message.chat_id).update(positionName = reverse_geocode_result[0]['formatted_address'])
    btn_keyboard1 = KeyboardButton(text="Find another electric charge point")
    btn_keyboard2 = KeyboardButton(text="Find closest parking")
    btn_keyboard3 = KeyboardButton(text="That's all, thanks")
    custom_keyboard = [[btn_keyboard1],[btn_keyboard2],[btn_keyboard3]]
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
    userHandler.setUserBotActived(update.message.chat_id, True)
    bot.sendMessage(chat_id = update.message.chat_id, text="What do you want to do now ?", reply_markup=reply_markup)
Example #3
0
def archive_poll_menu_processor(user, bot, update):
    poll = polls_repo.find_one({'name': update.message.text, 'archived': True})
    if poll:
        bot.send_message(chat_id=update.message.chat_id,
                         text="Опрос в архиве")
        # user['state'] = 'on_archive_poll'
        # user = users_repo.update(user)
    elif update.message.text == 'Вернуться в главное меню':
        user['state'] = 'on_polls_main_menu'
        user = users_repo.update(user)
        main_menu_processor(user, bot, update)
    else:
        button_list = []
        archive_polls = polls_repo.get_cursor({'archived': True})

        for poll in archive_polls:
            if (not poll['participants']) or (poll['participants'] and user['username'] in poll['participants']):
                button_list.append(KeyboardButton(poll['name']))
        button_list.append(KeyboardButton('Вернуться в главное меню'))

        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        if len(button_list) > 1:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Эти опросы нельзя пройти",
                             reply_markup=reply_markup)
        else:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Архивных опросов нет",
                             reply_markup=reply_markup)
    def __init__(self,
                 chat_id: int,
                 user_id: int,
                 lang_id: str,
                 first_name: str,
                 game_handler: object,
                 message_id: int,
                 send_message: callable,
                 multiplayer: bool = None,
                 game_id: str = None):
        # declare variables and set initial values
        self.players = []
        self.chat_id = chat_id
        self.__game_id = game_id
        self.lang_id = lang_id
        self.deck = CardDeck(lang_id)
        # TODO language of the cards & dealer cannot be changed
        # TODO especially with new multiplayer important!
        self.dealer = Dealer(translate("dealerName", lang_id), self.deck)
        self.game_running = False
        self.current_player = 0
        self.game_handler = game_handler
        self.send_message = send_message
        self.logger = logging.getLogger(__name__)

        if multiplayer:
            self.game_type = self.MULTIPLAYER_GAME
            chat_id = 0
        elif chat_id >= 0:
            self.game_type = self.PRIVATE_CHAT
        else:
            self.game_type = self.GROUP_CHAT

        one_more_button = KeyboardButton(
            translate("keyboardItemOneMore", lang_id))
        no_more_button = KeyboardButton(
            translate("keyboardItemNoMore", lang_id))
        stop_button = KeyboardButton(translate("keyboardItemStop", lang_id))
        self.keyboard_running = ReplyKeyboardMarkup(
            keyboard=[[one_more_button, no_more_button], [stop_button]],
            selective=True)

        self.add_player(user_id, first_name, message_id, silent=True)

        # Only send a "Please join the game" message, when it's a group chat
        if self.game_type == self.GROUP_CHAT:
            keyboard = [[
                InlineKeyboardButton(text=translate("join",
                                                    self.lang_id).capitalize(),
                                     callback_data="join_game")
            ]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            send_message(chat_id,
                         translate("newRound", lang_id),
                         message_id=message_id,
                         reply_markup=reply_markup)
        elif self.game_type == self.MULTIPLAYER_GAME:
            pass
        else:
            self.start_game()
Example #5
0
def showKeyboardTypeOfParking(bot,update):
    user = userHandler.getUser(update.message.chat_id)
    buttonPrivateParking = KeyboardButton(text="Private Parking")
    buttonStreetParking = KeyboardButton(text="Street Parking")
    custom_keyboard = [[buttonStreetParking],[buttonPrivateParking]]
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard , resize_keyboard=True,one_time_keyboard=True) 
    bot.sendMessage(chat_id=update.message.chat_id , text="Can you choose the parking's type ?" , reply_markup = reply_markup)
    userHandler.setUserLastCommand(update.message.chat_id, "parking.type")
Example #6
0
def sendMessageForSingleParking(bot, update, index):
    urld = 'http://api.citysdk.waag.org/layers/parking.garage/objects?per_page=25'
    r = urllib.request.urlopen(urld)
    data = json.loads(r.read().decode(r.info().get_param('charset')
                                      or 'utf-8'))
    reverse_geocode_result = main.gmaps.reverse_geocode(
        (data['features'][int(index)]['geometry']['coordinates'][1],
         data['features'][int(index)]['geometry']['coordinates'][0]))
    addressName = reverse_geocode_result[0]['address_components'][1][
        'short_name'] + " " + reverse_geocode_result[0]['address_components'][
            0]['short_name']
    parkingCost = checkParkingCost(addressName)
    message = "<b>The parking is: </b>" + data['features'][int(
        index)]['properties']['title'] + "\n"
    try:
        message += "<b>Free short parkings: </b>" + str(
            data['features'][int(index)]['properties']['layers']
            ['parking.garage']['data']['FreeSpaceShort']) + "\n"
    except KeyError:
        message += "<b>Free short parkings: </b>" + '---' + "\n"
    try:
        message += "<b>Free long parkings: </b>" + str(
            data['features'][int(index)]['properties']['layers']
            ['parking.garage']['data']['FreeSpaceLong']) + "\n"
    except KeyError:
        message += "<b>Free long parkings: </b>" + '---' + "\n"
    message += "<b>The address of the parking is: </b>" + reverse_geocode_result[
        0]['formatted_address'] + "\n"
    if parkingCost is not "":
        message += "<b>Cost: </b>" + parkingCost
    bot.sendLocation(
        update.message.chat_id,
        data['features'][int(index)]['geometry']['coordinates'][1],
        data['features'][int(index)]['geometry']['coordinates'][0])
    bot.sendMessage(chat_id=update.message.chat_id,
                    text=message,
                    parse_mode='HTML')
    latid = data['features'][int(index)]['geometry']['coordinates'][1]
    long = data['features'][int(index)]['geometry']['coordinates'][0]
    User.objects.filter(chat_id=update.message.chat_id).update(lat=latid,
                                                               lon=long)
    User.objects.filter(chat_id=update.message.chat_id).update(
        lastCommand="parking.afterDetails")
    User.objects.filter(chat_id=update.message.chat_id).update(
        positionName=reverse_geocode_result[0]['formatted_address'])
    btn_keyboard1 = KeyboardButton(text="Find another parking")
    btn_keyboard2 = KeyboardButton(text="Find closest electric charge point")
    btn_keyboard3 = KeyboardButton(text="Show my profile")
    btn_keyboard4 = KeyboardButton(text="That's all, thanks")
    custom_keyboard = [[btn_keyboard1], [btn_keyboard2], [btn_keyboard3],
                       [btn_keyboard4]]
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard,
                                                resize_keyboard=True,
                                                one_time_keyboard=True)
    userHandler.setUserBotActived(update.message.chat_id, True)
    bot.sendMessage(chat_id=update.message.chat_id,
                    text="What do you want to do now ?",
                    reply_markup=reply_markup)
Example #7
0
def chargePoint(bot, update):
    user = User.objects.get(chat_id=update.message.chat_id)
    User.objects.filter(chat_id=update.message.chat_id).update(lastCommand = "chargePoint")
    cronologyHandler.createCronology(bot, update, user)
    locationGPS_keyboard = KeyboardButton(text="Send my GPS location", request_location=True)
    locationUser_keyboard = KeyboardButton(text="Choose another location")
    custom_keyboard = [[ locationGPS_keyboard], [locationUser_keyboard]]
    addPreferencesKeyboard(custom_keyboard, user)
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
    bot.sendMessage(chat_id=update.message.chat_id, text="Would you mind sharing your location to search the closest charge point?", reply_markup=reply_markup)
Example #8
0
def accept_cancel_keyboard(language_code: str):
    accept_cancel = localization.accept_cancel_menu(language_code)

    button_list = [
        KeyboardButton(accept_cancel[ACCEPT_BUTTON]),
        KeyboardButton(accept_cancel[CANCEL_BUTTON])
    ]

    reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=1),
                                       resize_keyboard=True)
    return reply_markup
Example #9
0
def savePreferences(bot, update):
    yes_keyboard = KeyboardButton(text="YES")
    no_keyboard = KeyboardButton(text="NO")
    custom_keyboard = [[yes_keyboard], [no_keyboard]]
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard,
                                                resize_keyboard=True,
                                                one_time_keyboard=True)
    user = User.objects.get(chat_id=update.message.chat_id)
    newCommand = user.lastCommand + ".choose"
    User.objects.filter(chat_id=update.message.chat_id).update(
        lastCommand=newCommand)
    bot.sendMessage(
        chat_id=update.message.chat_id,
        text="Do you want to save this location for future searches?",
        reply_markup=reply_markup)
Example #10
0
def rating_processor(user, bot, update):
    current_ratings_record = next(
        record for record in user['ratings'] if record['poll_id'] == str(user['current_poll']))
    if update.message.text == '+1':
        question_to_rate = next(
            question for question in current_ratings_record['questions'] if not question.get('rate'))
        question_to_rate['rate'] = 1
        current_ratings_record['questions_rated'] += 1
        users_repo.update(user)
    elif update.message.text == '-1':
        question_to_rate = next(
            question for question in current_ratings_record['questions'] if not question.get('rate'))
        question_to_rate['rate'] = -1
        current_ratings_record['questions_rated'] += 1
        users_repo.update(user)

    try:
        question_to_rate = next(
            question for question in current_ratings_record['questions'] if not question.get('rate'))
        button_list = [
            KeyboardButton('+1'),
            KeyboardButton('-1')
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text='Вопрос: ' + question_to_rate['question'] + '\n' + 'Ответ: ' + question_to_rate['answer'],
                         reply_markup=reply_markup)

    except StopIteration:
        for question in current_ratings_record['questions']:
            true_answer_record = answers_repo.find_one({'_id': ObjectId(question['answer_id'])})
            answer = next(
                answer for answer in true_answer_record['answers'] if answer['question_text'] == question['question'])
            if question['rate'] == -1:
                answer['dislikes'] += 1
            elif question['rate'] == 1:
                answer['likes'] += 1
            answers_repo.update(true_answer_record)

        user['state'] = 'on_poll_end'
        user = users_repo.update(user)
        bot.send_message(chat_id=update.message.chat_id,
                         text="Спасибо за участие в оценке ответов!\n\nПриглашаем стать участником"
                              " сообщества по обсуждению вопросов регулирования"
                              " технологий блокчейн, криптовалют и ICO:\n\n"
                              "https://t.me/InnoExpert",
                         reply_markup={'hide_keyboard': True})
        end_poll_processor(user, bot, update)
Example #11
0
def active_polls_menu_processor(user, bot, update):
    poll = polls_repo.find_one({'name': update.message.text, 'archived': False})

    if poll:
        answer = answers_repo.find_one({'poll_id': str(poll['_id']), 'user_id': str(user['_id'])})
        if answer:
            user['state'] = 'on_poll_end'
            user['current_poll'] = str(poll['_id'])
            user['current_questions_answers'] = []
            user = users_repo.update(user)
            end_poll_processor(user, bot, update)
        else:
            if poll.get('type') and poll['type'] == 'kompas':
                for participant in poll['participants']:
                    user['questions'].append(str(participant))
                    options_list = ['0%', '10%', '20%', '30%', '40%', '50%',
                                    '60%', '70%', '80%', '90%', '100%']
                    user['questions'].append(options_list)
                user['sum'] = 0
            user['state'] = 'on_poll_start'
            user['current_poll'] = str(poll['_id'])
            user['current_questions_answers'] = []
            user = users_repo.update(user)
            poll_start_processor(user, bot, update)

    elif update.message.text == 'Вернуться в главное меню':
        user['state'] = 'on_polls_main_menu'
        user = users_repo.update(user)
        main_menu_processor(user, bot, update)

    else:
        button_list = []
        active_polls = polls_repo.get_cursor({'archived': False})
        for poll in active_polls:
            if (not poll['participants']) \
                    or (poll['participants'] and user['username'] in poll['participants']):
                button_list.append(KeyboardButton(poll['name']))
        button_list.append(KeyboardButton('Вернуться в главное меню'))

        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        if len(button_list) > 1:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Выберите опрос для прохождения",
                             reply_markup=reply_markup)
        else:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Активных опросов нет",
                             reply_markup=reply_markup)
Example #12
0
def poll_start_processor(user, bot, update):
    poll = polls_repo.find_one({'_id': ObjectId(user['current_poll'])})
    if poll.get('welcome_message'):
        bot.send_message(chat_id=update.message.chat_id,
                         text=poll['welcome_message'],
                         reply_markup={'hide_keyboard': True})
    bot.send_message(chat_id=update.message.chat_id,
                     text='Сейчас вам будут задаваться вопросы.',
                     reply_markup={'hide_keyboard': True})
    if poll.get('type') and poll['type'] == 'kompas':
        user['state'] = 'on_bounty'
        question = user['questions'][0] +\
                   ": напиши, за какие заслуги, ты премируешь его за прошедшую неделю"
        bot.send_message(chat_id=update.message.chat_id,
                         text=question,
                         reply_markup={'hide_keyboard': True})
    else:
        user['state'] = 'on_poll'
        question = poll['questions'][0]
        if question['type'] == 'open':
            bot.send_message(chat_id=update.message.chat_id,
                             text=question['text'],
                             reply_markup={'hide_keyboard': True})
        elif question['type'] in ['select', 'multiselect']:
            button_list = []
            for option in question['options']:
                button_list.append(KeyboardButton(option))
            reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
            bot.send_message(chat_id=update.message.chat_id,
                             text=question['text'],
                             reply_markup=reply_markup)
    user = users_repo.update(user)
Example #13
0
def end_poll_processor(user, bot, update, come_from=None):
    poll = polls_repo.find_one({'name': update.message.text, 'archived': False})
    if come_from and come_from == 'start_rating_processor':
        button_list = [
            KeyboardButton("Показать мои ответы"),
            KeyboardButton("Вернуться в главное меню")
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text="Вы вернулись в меню пройденного опроса",
                         reply_markup=reply_markup)
    elif come_from and come_from == 'poll_processor':
        button_list = [
            KeyboardButton("Показать мои ответы"),
            KeyboardButton("Вернуться в главное меню")
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text="Опрос пройден успешно!",
                         reply_markup=reply_markup)
    elif update.message.text == 'Показать мои ответы':
        answers_record = answers_repo.find_one({'poll_id': str(user['current_poll']), 'user_id': str(user['_id'])})
        message = 'Хэш транзакции: ' + answers_record['hash'] + '\n'
        for answer in answers_record['answers']:
            message += 'Вопрос: ' + answer['question_text'] + '\n'
            message += 'Ответ: ' + str(answer['answer']) + '\n'

        bot.send_message(chat_id=update.message.chat_id,
                         text=message)

    elif update.message.text == 'Оценить ответы других участников':
        user['state'] = 'on_rating_start'
        user = users_repo.update(user)
        rating_start_processor(user, bot, update)
        return
    elif update.message.text == 'Вернуться в главное меню':
        user['state'] = 'on_polls_main_menu'
        user = users_repo.update(user)
        main_menu_processor(user, bot, update)
    elif poll:
        button_list = [
            KeyboardButton("Показать мои ответы"),
            KeyboardButton("Вернуться в главное меню")
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text="Вы уже проходили данный опрос!",
                         reply_markup=reply_markup)
    else:
        button_list = [
            KeyboardButton("Показать мои ответы"),
            KeyboardButton("Вернуться в главное меню")
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text="Вы вернулись в меню пройденного опроса",
                         reply_markup=reply_markup)
Example #14
0
def get_main_menu(language_code: str):
    """
    Creates a KeyboardMarkup for the main menu and returns it.
    """

    # The dict of the menus
    main_menu = localization.main_menu(language_code)

    button_list = [
        KeyboardButton(main_menu[ADD_LIST_BUTTON]),
        KeyboardButton(main_menu[SETTINGS_BUTTON]),
        KeyboardButton(main_menu[EDIT_LISTS_BUTTON]),
        KeyboardButton(main_menu[STOP_BOT_BUTTON])
    ]

    reply_markup = ReplyKeyboardMarkup(build_menu(button_list, n_cols=1),
                                       resize_keyboard=True)
    return reply_markup
Example #15
0
def ShowMainMenu(bot, update, self):
    button_list = [[
        KeyboardButton("🏪 Магазин"),
        KeyboardButton("🛒 Корзина"),
        KeyboardButton("📖 О нас")
    ], [KeyboardButton("🤝 Сотрудничество"),
        KeyboardButton("🔍 Как нас найти")]]
    reply_markup = ReplyKeyboardMarkup(button_list, resize_keyboard=True)
    chat_id = ''
    try:
        chat_id = update.callback_query.message.chat_id
    except:
        chat_id = update.message.chat_id
    bot.send_message(
        chat_id=chat_id,
        text=
        '<b>Выбирай:</b>\nМагазин - тут наши скульптуры\nКорзина - активна после покупки\nО нас - тут все понятно\nАкции / События - держим вас в курсе\nПартнерство - если хочешь продавать нас Как нас найти ? -без комментариев',
        parse_mode=ParseMode.HTML,
        reply_markup=reply_markup)
Example #16
0
def main_menu_processor(user, bot, update):
    if update.message.text == 'Показать активные опросы':
        user['state'] = 'on_active_polls'
        user = users_repo.update(user)
        active_polls_menu_processor(user, bot, update)

    elif update.message.text == 'Показать архив':
        user['state'] = 'on_archive_polls'
        user = users_repo.update(user)
        archive_poll_menu_processor(user, bot, update)
    else:
        button_list = [
            KeyboardButton("Показать активные опросы"),
            KeyboardButton("Показать архив")
        ]
        reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
        bot.send_message(chat_id=update.message.chat_id,
                         text="Какие опросы вы хотите посмотреть?",
                         reply_markup=reply_markup)
Example #17
0
def AskContact(bot, update, self):
    contact_keyboard = KeyboardButton(
        text="Поделиться контактом",
        request_contact=True,
    )
    custom_keyboard = [[contact_keyboard]]
    reply_markup = ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     parse_mode=ParseMode.HTML,
                     reply_markup=reply_markup)
Example #18
0
def location(bot, update):
    # Colors: Red, Blue, Purple, Green, Yellow, Brown, Orange, Grey   
    listOfColor = ['#8B0000', '#0000FF', '#8A2BE2', '#228B22', '#FFD700', '#8B4513', '#D2691E', '#808080'
    user = User.objects.get(chat_id=update.message.chat_id)
    point = Point(user.lon, user.lat)
    # Distance in KM to search the parkings close by
    radius = 0.5
    radius = radius / 40000 * 360
    circle = point.buffer(radius)
    shape = multiPolygonHandler.getMultiPolygonByPoint(point)
    m = StaticMap(600, 800, 12, 12, tile_size=256)
    marker_outline = CircleMarker((user.lon, user.lat), 'white', 22)
    marker = CircleMarker((user.lon, user.lat), 'Red', 18)
    m.add_marker(marker_outline)
    m.add_marker(marker)
    circleLine = Line(circle[0], color='red', width=3)
    geoCircle = GEOPolygon(circle[0])
    # Draw the circle for compare it with closest parkings
    m.add_line(circleLine)
    listPolygon, listOfColor2, listOfMultiPolygon = getAllPolygonsInCircleArea(geoCircle)
    i = 0
    if len(listPolygon) is not 0:
        for p in listPolygon:
            polygonLine = Line(p[0], color=listOfColor[i], width=3)
            m.add_line(polygonLine)
            i = i + 1
        image = m.render(zoom=14)
        fileName = 'ParkingStreet' + str(update.message.chat_id) + '.png'
        image.save(fileName)
        baseDir = settings.BASE_DIR
        picture = open(baseDir + '/' + fileName, 'rb')
        text = buildParkingZoneMessage(listOfMultiPolygon)
        btn_keyboard1 = KeyboardButton(text="Find another parking")
        btn_keyboard2 = KeyboardButton(text="Find closest electric charge point")
        btn_keyboard3 = KeyboardButton(text="Show my profile")
        btn_keyboard4 = KeyboardButton(text="That's all, thanks")
        custom_keyboard = [[btn_keyboard1], [btn_keyboard2], [btn_keyboard3], [btn_keyboard4]]
        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
        bot.sendPhoto(chat_id=update.message.chat_id, photo=picture)
        bot.sendMessage(chat_id=update.message.chat_id, text=text, parse_mode='HTML')
        bot.sendMessage(chat_id=update.message.chat_id, text='What do you want to do now?', reply_markup=reply_markup)
        userHandler.setUserBotActived(update.message.chat_id, True)
    else:
        btn_keyboard1 = KeyboardButton(text="Find another parking")
        btn_keyboard2 = KeyboardButton(text="Find closest electric charge point")
        btn_keyboard3 = KeyboardButton(text="Show my profile")
        btn_keyboard4 = KeyboardButton(text="That's all, thanks")
        custom_keyboard = [[btn_keyboard1], [btn_keyboard2], [btn_keyboard3], [btn_keyboard4]]
        reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
        bot.sendMessage(chat_id=update.message.chat_id, text='There is no parking info close to your position.')
        bot.sendMessage(chat_id=update.message.chat_id, text='What do you want to do now?', reply_markup=reply_markup)
        userHandler.setUserBotActived(update.message.chat_id, True)
Example #19
0
def start(bot, update, args, chat_data):
    name = update.message.from_user["first_name"]
    surname = update.message.from_user["last_name"]
    utente = User()
    utente.name = name
    utente.surname = surname
    utente.lastCommand = "start"
    utente.chat_id = update.message.chat_id
    utente.save()
    settings.USER = utente.chat_id
    cronologyHandler.createCronology(bot, update, utente)
    parking_keyboard = KeyboardButton(text="Can you find me a parking?")
    chargePoint_keyboard = KeyboardButton(text="Can you find me a electric charge point?")
    custom_keyboard = [[ parking_keyboard],[chargePoint_keyboard]]
    reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True, one_time_keyboard=True)
    global lastUpdate 
    lastUpdate= str(update.update_id)
    update.message.reply_text('Hi ' + name + ' ' + surname + ', I\'m Smartbot!')
    bot.sendMessage(chat_id = update.message.chat_id, text="How can i help you?", reply_markup=reply_markup)
    geometryHandler.loadJSON()
Example #20
0
    def __init__(self, chat_id, user_id, lang_id, first_name, game_handler,
                 message_id, send_message):
        # declare variables and set initial values
        self.players = []
        self.join_message_ids = []
        self.chat_id = chat_id
        self.lang_id = lang_id
        self.deck = CardDeck(
            lang_id)  # TODO language of the cards & dealer cannot be changed
        self.dealer = Dealer(translate("dealerName", lang_id), self.deck)
        self.game_running = False
        self.current_player = 0
        self.game_handler = game_handler
        self.send_message = send_message
        self.logger = logging.getLogger(__name__)

        if chat_id >= 0:
            self.game_type = self.PRIVATE_CHAT
        else:
            self.game_type = self.GROUP_CHAT

        one_more_button = KeyboardButton(
            translate("keyboardItemOneMore", lang_id))
        no_more_button = KeyboardButton(
            translate("keyboardItemNoMore", lang_id))
        stop_button = KeyboardButton(translate("keyboardItemStop", lang_id))
        self.keyboard_running = ReplyKeyboardMarkup(
            keyboard=[[one_more_button, no_more_button], [stop_button]],
            selective=True)

        self.add_player(user_id, first_name, message_id, silent=True)

        # Only send a "Please join the game" message, when it's a group chat
        if self.game_type == self.GROUP_CHAT:
            send_message(
                chat_id, translate("newRound", lang_id),
                message_id=message_id)  # keyboard=self.keyboard_not_running
        else:
            self.start_game()
Example #21
0
    def generate_cities_keyboard(self, with_current_location=False):
        # select distinct hometown as city from users union select distinct city from opportunities order by city asc;
        op_cities = self.db.table("opportunities").distinct().select("city")
        cities = self.db.table("users").distinct().select("hometown as city") \
            .union(op_cities).order_by("city", "asc").get()

        keyboard = []

        for c in cities:
            keyboard.append([KeyboardButton(c.city)])

        return ReplyKeyboardMarkup(keyboard,
                                   one_time_keyboard=True,
                                   resize_keyboard=True)
Example #22
0
def SayHello(bot, update, self):
    bot.send_photo(chat_id=update.message.chat_id,
                   photo=open('VaseHead_admin/header.jpg', 'rb'),
                   caption=update.message.from_user.first_name + ', ' +
                   GetSettingsValue(bot_settings.wellcome))
    self.SetMyState(states.Share_contact)
    contact_keyboard = KeyboardButton(
        text="Поделиться контактом",
        request_contact=True,
    )
    custom_keyboard = [[contact_keyboard]]
    reply_markup = ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
    bot.send_message(chat_id=update.message.chat_id,
                     text=GetSettingsValue(bot_settings.littleasking),
                     parse_mode=ParseMode.HTML,
                     reply_markup=reply_markup)
Example #23
0
def poll_processor(user, bot, update):
    poll = polls_repo.find_one({'_id': ObjectId(user['current_poll'])})
    current_question = poll['questions'][len(user['current_questions_answers'])]
    if current_question['type'] == 'open':
        user['current_questions_answers'].append({
            'question_text': current_question['text'],
            'type': current_question['type'],
            'likes': 0,
            'dislikes': 0,
            'answer': update.message.text
        })
        user = users_repo.update(user)
    elif current_question['type'] == 'select':
        if update.message.text in current_question['options']:
            user['current_questions_answers'].append({
                'question_text': current_question['text'],
                'type': current_question['type'],
                'answer': update.message.text
            })
            user = users_repo.update(user)
        else:
            bot.send_message(chat_id=update.message.chat_id,
                             text='Выберите одну из опций',
                             reply_markup={'hide_keyboard': True})
    elif current_question['type'] == 'multiselect':
        if update.message.text in current_question['options']:
            user['current_questions_answers'].append({
                'question_text': current_question['text'],
                'type': current_question['type'],
                'answer': update.message.text,
                'likes': 0,
                'dislikes': 0
            })
            user = users_repo.update(user)
        elif update.message.text == 'Свой вариант':
            user['on_own_answer'] = True
            user = users_repo.update(user)
            bot.send_message(chat_id=update.message.chat_id,
                             text='Напишите свой вариант ответа',
                             reply_markup={'hide_keyboard': True})
            return
        elif user.get('on_own_answer'):
            user['current_questions_answers'].append({
                'question_text': current_question['text'],
                'type': current_question['type'],
                'likes': 0,
                'dislikes': 0,
                'answer': update.message.text,
            })
            user['on_own_answer'] = False
            user = users_repo.update(user)
        else:
            bot.send_message(chat_id=update.message.chat_id,
                             text='Выберите одну из опций',
                             reply_markup={'hide_keyboard': True})

    if len(user['current_questions_answers']) < len(poll['questions']):
        question = poll['questions'][len(user['current_questions_answers'])]
        if question['type'] == 'open':
            bot.send_message(chat_id=update.message.chat_id,
                             text=question['text'],
                             reply_markup={'hide_keyboard': True})
        elif question['type'] == 'select':
            button_list = []
            for option in question['options']:
                button_list.append(KeyboardButton(option))
            reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
            bot.send_message(chat_id=update.message.chat_id,
                             text=question['text'],
                             reply_markup=reply_markup)
        elif question['type'] == 'multiselect':
            button_list = []
            for option in question['options']:
                button_list.append(KeyboardButton(option))
            button_list.append('Свой вариант')
            reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=1))
            bot.send_message(chat_id=update.message.chat_id,
                             text=question['text'],
                             reply_markup=reply_markup)
    else:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Секундочку, сохраняем результаты в блокчейн Ethereum',
                         reply_markup={'hide_keyboard': True})

        q_a = [{'q': answer['question_text'], 'a': answer['answer']}
               for answer in user['current_questions_answers']]
        transaction_hash = save_answers(user['ethereum_wallet'], user['ethereum_password'], q_a)

        answers_repo.insert({
            'poll_id': str(poll['_id']),
            'user_id': str(user['_id']),
            'answers': user['current_questions_answers'],
            'hash': transaction_hash
        })

        user['state'] = 'on_poll_end'
        user['current_questions_answers'] = []
        user = users_repo.update(user)
        bot.send_message(chat_id=update.message.chat_id,
                         text='Ссылка на хэш транзакции в сети: ' + transaction_hash,
                         reply_markup={'hide_keyboard': True})
        end_poll_processor(user, bot, update, come_from='poll_processor')
Example #24
0
def bounty_processor(user, bot, update):
    poll = polls_repo.find_one({'_id': ObjectId(user['current_poll'])})
    question_n = len(user['current_questions_answers'])
    current_question = user['questions'][question_n]
    if (question_n % 2) == 0:
        user['current_questions_answers'].append({
            'question_text': current_question,
            'answer': update.message.text
        })
        user = users_repo.update(user)
    else:
        if update.message.text in current_question:
            option = int(''.join(filter(str.isdigit, update.message.text)))
            user['current_questions_answers'].append({
                'question_text': user['questions'][question_n-1],
                'answer': option
            })
            user['sum'] += option
            user = users_repo.update(user)
        else:
            bot.send_message(chat_id=update.message.chat_id,
                             text='Выберите одну из опций',
                             reply_markup={'hide_keyboard': True})

    if len(user['current_questions_answers']) < len(user['questions']):
        question = user['questions'][len(user['current_questions_answers'])]
        question_n = len(user['current_questions_answers'])
        if (question_n % 2) == 0:
            bot.send_message(chat_id=update.message.chat_id,
                             text=question + ": напиши, за какие заслуги, ты премируешь его за прошедшую неделю",
                             reply_markup={'hide_keyboard': True})
        else:
            button_list = []
            max = int(11 - user['sum'] / 10)
            for i in range(0, max):
                button_list.append(KeyboardButton(question[i]))
            reply_markup = ReplyKeyboardMarkup(utils.build_menu(button_list, n_cols=3))
            bot.send_message(chat_id=update.message.chat_id,
                             text="А ещё напишите, сколько процентов он получит из твоего персонального премиального фонда",
                             reply_markup=reply_markup)
    else:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Секундочку, сохраняем результаты в блокчейн Ethereum',
                         reply_markup={'hide_keyboard': True})

        q_a = [{'q': answer['question_text'], 'a': answer['answer']}
               for answer in user['current_questions_answers']]
        transaction_hash = save_answers(user['ethereum_wallet'], user['ethereum_password'], q_a)

        answers_repo.insert({
            'poll_id': str(poll['_id']),
            'user_id': str(user['_id']),
            'answers': user['current_questions_answers'],
            'hash': transaction_hash
        })

        user['state'] = 'on_poll_end'
        user['current_questions_answers'] = []
        user['questions'] = []
        user['sum'] = 0
        user = users_repo.update(user)
        bot.send_message(chat_id=update.message.chat_id,
                         text='Ссылка на хэш транзакции в сети: ' + transaction_hash,
                         reply_markup={'hide_keyboard': True})
        end_poll_processor(user, bot, update, come_from='poll_processor')
    pass
Example #25
0
 def generate_next_action_keyboard(self):
     keyboard = [[KeyboardButton(self.NEXT_ACTION_KEYBOARD["NEUE_REISE"])],
                 [KeyboardButton(self.NEXT_ACTION_KEYBOARD["FERTIG"])]]
     return ReplyKeyboardMarkup(keyboard)
Example #26
0
def addPreferencesKeyboard(keyboard, user):
    preferences = Preference.objects.filter(bot_user=user)
    for p in preferences:
        button = KeyboardButton(text=p.label)
        keyboard.append([button])