Beispiel #1
0
 def pedir_error(self, bot, update, user_data):
     chat_id = str(update.message.chat_id)
     text = update.message.text
     logging.info('STATS [%s] [pedir-error] %s' % (chat_id, text))
     txt = ('Parece que hubo un error, usa /help para ver la ayuda '
            'e intenta emplear únicamente los comandos propuestos. ')
     update.message.reply_text(txt, reply_markup=ReplyKeyboardHide())
     user_data.clear()
     return ConversationHandler.END
Beispiel #2
0
 def build_keyboard(self, keyboard):
     built_keyboard = []
     if keyboard:
         built_keyboard = InlineKeyboardMarkup(
             [[self._create_keyboard_button(element)]
              for element in traverse(ast.literal_eval(keyboard))])
     else:
         built_keyboard = ReplyKeyboardHide()
     return built_keyboard
Beispiel #3
0
def gender(bot, update):
    user = update.message.from_user
    logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
    update.message.reply_text(
        'I see! Please send me a photo of yourself, '
        'so I know what you look like, or send /skip if you don\'t want to.',
        reply_markup=ReplyKeyboardHide())

    return PHOTO
Beispiel #4
0
def register(bot, update):
    pytrtbot.writedb(update.message.to_dict())
    db = pickledb.load('db/users.db', False)
    db.set(update.message.from_user.id, REG)
    db.dump()
    reply_markup = ReplyKeyboardHide()
    bot.sendMessage(update.message.chat_id,
                    text='Send your public API Key and API ' +
                    'secret, with a space between them.',
                    reply_markup=reply_markup)
Beispiel #5
0
def close_pineapple_command(bot, update):
    chat_id = update.message.chat_id
    logger.info("Close pineapple on %s" % chat_id)

    if not Pineapple.is_open(chat_id):
        logger.info("Pineapple already closed")
        send_message(bot, chat_id, MESSAGE.NOT_YET_OPEN)
        return

    message = Pineapple.get(chat_id).get_close_message()
    Pineapple.close(chat_id)
    send_message(bot, chat_id, message, reply_markup=ReplyKeyboardHide())
Beispiel #6
0
 def start(self, bot, update):
     chat_id = update.message.chat_id
     auth_url = self.vk.get_auth_url()
     # Send first info messages
     bot.sendMessage(chat_id=chat_id,
                     text=message.WELCOME(auth_url),
                     reply_markup=ReplyKeyboardHide())
     bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN)
     # Create new client
     client = Client(next_action=action.ACCESS_TOKEN, chat_id=chat_id)
     self.clients[chat_id] = client
     client.persist()
Beispiel #7
0
    def start(self, bot, update):
        chat_id = str(update.message.chat_id)
        if chat_id not in self.users.sections():
            logging.info('STATS [%s] [nuevo]' % chat_id)
            self.users.add_section(chat_id)
            self.users.set(chat_id, 'news', 'True')
            self.users.set(chat_id, 'ignore', 'False')
            self.users.set(chat_id, 'admin', 'False')
            self.users.set(chat_id, 'votados', '')

            nicks = codecs.open(self.file_nicks, 'r', 'utf-8')\
                          .read()\
                          .splitlines()
            # Comprobamos que haya nicks libres
            libres = 0
            for line in nicks:
                nick, taken = line.split(',')
                if taken == '0':
                    libres += 1

            if libres > 0:
                nick_taken = '1'
                while nick_taken == '1':
                    nick, nick_taken = random.choice(nicks).split(",")
                # Hay que guardar el nick usado
                f = codecs.open(self.file_nicks, 'w', 'utf-8')
                for line in nicks:
                    if nick not in line:
                        f.write(line + "\n")
                    else:
                        f.write(nick + ",1\n")
                f.close()
            else:
                self.po_client.send_message("Se ha acabado la lista de nicks",
                                            title="Nicks agotados")
                logging.info('No hay nicks disponibles')
                nick = 'N' + ''.join(
                    random.SystemRandom().choice(string.digits)
                    for _ in range(10))

            self.users.set(chat_id, 'nick', nick)
            update.message.reply_text(
                '¡Hola! Por defecto, noticias y curiosidades activadas '
                '(usa el comando /help para ayuda). Te ha tocado el nick ' +
                nick + ', puedes usar el comando /start para recordarlo ')
            self.save_config_users()
        else:
            logging.info('STATS [%s] [reinicia]' % chat_id)
            update.message.reply_text('Hola de nuevo, tu nick es %s' %
                                      self.users.get(chat_id, 'nick'),
                                      reply_markup=ReplyKeyboardHide())
            return ConversationHandler.END
Beispiel #8
0
    def run(self):

        # try to add the non-existent show
        add_or_update_show(self.show_title.encode('utf-8'))

        try:
            show = Show.nodes.get(title_lower=self.show_title)
            response = _('We\'ve found a show "%s" that you are looking for.') % self.show_title
        except DoesNotExist:
            response = _('We can\'t found a show "%s" that you are looking for.') % self.show_title

        self.bot.sendMessage(chat_id=self.chat_id,
                             text=response,
                             reply_markup=ReplyKeyboardHide())
Beispiel #9
0
 def start_command(self, bot, update, args):
     user_id = update.message.from_user.id
     if len(args) == 0:
         if str(user_id) in allowed_users.values():
             self.store.new_draft(user_id)
             bot.sendMessage(update.message.chat_id,parse_mode='Markdown',
                         text="Crearem un esdeveniment per a una excursió.\n\n\u0031\u20E3 El primer que heu de fer és enviar-me el *nom de l\'excursió*.\n\nSi no voleu continuar amb el procés, envieu /cancel.",
                         reply_markup=ReplyKeyboardHide())
         else:
             f_name = update.message.from_user.first_name
             bot.sendMessage(update.message.chat_id,
                         text= str(f_name) + ", no teniu permisos per crear excursions \U0001F622.\nSi necessiteu permisos, us caldrà el vostre identificador d'usuari.\n\U0001F194 = " + str(user_id) + ".")
     elif len(args) == 1 and args[0] == 'convida-al-canal':
         self.invite_channel(bot, update)
Beispiel #10
0
    def send_message(self, user, message):
        reply_markup = ReplyKeyboardHide(True)
        if persistence_controller.is_registered(user):
            ply = persistence_controller.get_ply(user)
            for notification in self.notifications:
                if ply.last_read_notification_id < notification["id"]:
                    ply.last_read_notification_id = notification["id"]
                    message += "\n" + notification["text"]

            reply_markup = self.get_reply_markup(user)

        if reply_markup:
            self.api.sendMessage(user.id, message, None, None, reply_markup)
        else:
            self.api.sendMessage(user.id, message)
Beispiel #11
0
def execute(bot, update, chat_data):
    try:
        user_id = update.message.from_user.id
        command = update.message.text
        inline = False
    except AttributeError:
        # Using inline
        user_id = update.inline_query.from_user.id
        command = update.inline_query.query
        inline = True

    if command == ADMINMODEDISABLE:
        update.message.reply_text("Admin mode disable",
                                  reply_markup=ReplyKeyboardHide())
        job = chat_data['job']
        job.schedule_removal()
        del chat_data['job']
        update.message.reply_text("Job is die")
        return cancel(bot, update)
    elif command == STOPSERVICE:
        pass
    elif command == STARTSERVICE:
        pass
    elif command == SHOWSTATUS:
        pass
    else:
        return EXECUTE

    if not inline:
        bot.sendChatAction(chat_id=update.message.chat_id,
                           action=ChatAction.TYPING)
    output = subprocess.Popen(command,
                              shell=True,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
    output = output.stdout.read().decode('utf-8')
    output = '`{0}`'.format(output)

    if not inline:
        bot.sendMessage(chat_id=update.message.chat_id,
                        text=output,
                        parse_mode="Markdown")
        return EXECUTE
    else:
        return output
Beispiel #12
0
def message_handler(bot, update):
    db.update_user(update.message.from_user)
    if update.message.text == "Close Keyboard":
        text = "Keyboard is down."
        reply_markup = ReplyKeyboardHide()
        update.message.reply_text(text=text,
                                  reply_markup=reply_markup,
                                  parse_mode=ParseMode.HTML,
                                  disable_web_page_preview=True)
    else:
        device = db.get_device(update.message.text)
        if "error" not in device:
            links = db.get_links(device["id"])
            if "error" not in links:
                text = group_links(links, device["name"])
                update.message.reply_text(text=text,
                                          parse_mode=ParseMode.HTML,
                                          disable_web_page_preview=True)
Beispiel #13
0
def start(bot, update):
    ''' Returns the standard greeting with a list of commands. '''

    chat = Chat.get_or_create(id=update.message.chat_id)
    chat.referer = ''
    chat.save()

    response = (_('You can control me by sending these commands:') + '\n',
                '/showlist - %s' % _('show list of available TV shows'),
                '/subscriptions - %s' % _('show active subscriptions'),
                '/subscribe - %s' % _('subscribe to a TV show'),
                '/unsubscribe - %s' % _('unsubscribe from a TV show'),
                '/setlanguage - %s' % _('change language'),
                '/watch - %s' % _('find any available episode'))

    bot.sendMessage(chat_id=update.message.chat_id,
                    text='\n'.join(response),
                    reply_markup=ReplyKeyboardHide())
Beispiel #14
0
def meal(bot, update):
    reply_markup = ReplyKeyboardHide()
    reply_keyboard = [['Yes', 'One more !']]
    user = update.message.from_user
    logger.info("Meal that %s wants is %s" %
                (user.first_name, update.message.text))
    preferences['meal'] = update.message.text
    bot.sendMessage(update.message.chat_id,
                    text=conversations['think'][randint(0, 2)] %
                    user.first_name,
                    reply_markup=reply_markup)

    # Retrieve recipe from Pinterest.
    try:
        recipe = get_recipe(preferences)
    except Exception, e:
        bot.sendMessage(update.message.chat_id,
                        text=conversations['problem'][randint(0, 2)])
        return ConversationHandler.END
Beispiel #15
0
def showlist(bot, update):
    ''' Returns list of available TV shows. '''

    chat = Chat.get_or_create(id=update.message.chat_id)
    chat.referer = ''
    chat.save()

    response_lines = [
        unicode(_('List of available TV shows:') + '\n', 'utf-8')
    ] + [
        ' '.join([
            unicode(
                Emoji.BLACK_SMALL_SQUARE if chat in s.subscribers.all() else
                Emoji.WHITE_SMALL_SQUARE, 'utf-8'), s.title
        ]) for s in sorted(Show.nodes.all(), key=lambda x: x.title)
    ]

    bot.sendMessage(chat_id=update.message.chat_id,
                    text='\n'.join(response_lines),
                    reply_markup=ReplyKeyboardHide())
Beispiel #16
0
def finger_out_command(bot, update, is_reply=False):
    chat_id = update.message.chat_id
    logger.info("Getting fingers on %s" % chat_id)

    if not Pineapple.is_open(chat_id):
        logger.info("Pineapple not open")
        send_message(bot, chat_id, MESSAGE.NOT_YET_OPEN)
        return

    user_name = get_full_name(update.message.from_user)
    pineapple = Pineapple.get(chat_id)
    pineapple.finger_out(user_name)
    Pineapple.update(chat_id, pineapple)

    message = pineapple.get_short_fingers_list_message()

    if is_reply:
        message_id = update.message.message_id
    else:
        message_id = None
    send_message(bot, chat_id, message, reply_to_message_id=message_id, reply_markup=ReplyKeyboardHide(selective=True))
Beispiel #17
0
def receiver(bot, update):
    """Listen non command replys to bot with a valid poll response"""
    chat_id = update.message.chat_id
    text = update.message.text
    if chat_id in config.act:
        if config.act[chat_id]['act']:
            if text in config.act[chat_id]['resp']:
                config.act[chat_id]['resp'][text] += 1

                sortres = [(v, k)
                           for k, v in config.act[chat_id]['resp'].iteritems()]
                sortres.sort(reverse=True)
                ftext = "Resultado temporal:"
                for val, key in sortres:
                    ftext += ("\n%s: %d" % (key, val))

                reply_markup = ReplyKeyboardHide(selective=True)
                bot.sendMessage(chat_id=chat_id,
                                text=ftext,
                                reply_to_message_id=update.message.message_id,
                                reply_markup=reply_markup)
Beispiel #18
0
def need(bot, update):
    reply_markup = ReplyKeyboardHide()
    user = update.message.from_user
    if update.message.text == 'Recipes':
        bot.sendMessage(
            update.message.chat_id,
            text="What'd you like to cook my dear %s ? (i.e Glutenfree Pizza)"
            % user.first_name,
            use_aliases=True)
        preferences['diet'] = ''
        return MEAL
    else:
        reply_keyboard = [['Normal'], ['Glutenfree'], ['Vegetarian'],
                          ['Vegan']]
        bot.sendMessage(update.message.chat_id,
                        text=emojize(conversations['start'][randint(0, 2)] %
                                     user.first_name,
                                     use_aliases=True),
                        reply_markup=ReplyKeyboardMarkup(
                            reply_keyboard, one_time_keyboard=True))
        return DIET
Beispiel #19
0
 def start_command(self, bot, update, args):
     user_id = str(update.message.from_user.id)
     chat_id = update.message.chat_id
     user_f = update.message.from_user.first_name
     user_u = update.message.from_user.username
     #        if len(args) == 0:
     if str(chat_id) == chats['group']:
         bot.sendMessage(
             chat_id,
             parse_mode='Markdown',
             text=
             "Bon dia! Envieu /ruta si voleu recordar quina és la pròxima ruta. Si voleu crear-ne una, envieu-me un missatge en privat 😉"
         )
     elif chat_id < 0:
         bot.sendMessage(
             chat_id,
             parse_mode='Markdown',
             text=
             "Aquest bot és per a *ús privat*, lamentablement haureu de sol·licitar permís al seu administrador si voleu que siga operatiu al vostre grup."
         )
         bot.leaveChat(chat_id)
     else:
         if str(user_id) in allowed_users.values():
             self.store.new_draft(user_id)
             bot.sendMessage(
                 update.message.chat_id,
                 parse_mode='Markdown',
                 text=
                 "Crearem un esdeveniment per a una excursió.\n\n\u0031\u20E3 El primer que has de fer és enviar-me el *nom de l\'excursió*.\n\nSi no vols continuar amb el procés, envia /cancel.",
                 reply_markup=ReplyKeyboardHide())
         else:
             f_name = update.message.from_user.first_name
             bot.sendMessage(
                 update.message.chat_id,
                 text=str(f_name) +
                 ", no tens permís per a crear excursions \U0001F622.\nSi vols obtindre permisos, parla amb l'administrador (necessitaràs el teu identificador d'usuari.\n\U0001F194 = "
                 + str(user_id) + ").")
             bot.sendMessage(chat_id=allowed_users['admin'],
                             text="L'usuari " + user_f + " (@" + user_u +
                             ", " + user_id + ") ha enviat l'ordre /start.")
Beispiel #20
0
def subscriptions(bot, update):
    ''' Returns active subscriptions of the chat. '''

    chat = Chat.get_or_create(id=update.message.chat_id)
    chat.referer = ''
    chat.save()

    if chat.subscriptions.all():

        response_lines = [
            unicode(_('Active subscriptions:') + '\n', 'utf-8')
        ] + [
            ' '.join([unicode(Emoji.BLACK_SMALL_SQUARE, 'utf-8'), s.title])
            for s in sorted(chat.subscriptions.all(), key=lambda x: x.title)
        ]
        response = '\n'.join(response_lines)
    else:
        response = _('You are not subscribed to any of the series.')

    bot.sendMessage(chat_id=update.message.chat_id,
                    text=response,
                    reply_markup=ReplyKeyboardHide())
def cancel(bot, update):
    user = update.message.from_user
    update.message.reply_text('Bye! I hope we can talk again some day.',
                              reply_markup=ReplyKeyboardHide())

    return ConversationHandler.END
Beispiel #22
0
def changeMarkup(bot, update):
    update.message.reply_text("", reply_markup=ReplyKeyboardHide())
Beispiel #23
0
def selectGame(bot, update):
    selectedGame = update.message.text
    logger.info("Selected Game: " + selectedGame)
    update.message.reply_text(selectedGame + ' added to Wishlist :) ',
                              reply_markup=ReplyKeyboardHide())
    return ConversationHandler.END
Beispiel #24
0
def searchGame(bot, update):
    update.message.reply_text(
        text='Which game do you want to add to your Wishlist ? ',
        reply_markup=ReplyKeyboardHide())
    return CREATEGAMEREPLY
Beispiel #25
0
    def update_draft(self, bot, event, user_id, update, current_field):
        self.store.update_draft(user_id, event, current_field)

        if current_field <= len(FIELDS) - 1:

            if FIELDS[current_field]['name'] == 'type':
                bot.sendMessage(
                    update.message.chat_id,
                    parse_mode='Markdown',
                    text=FIELDS[current_field]['message'],
                    reply_markup=ReplyKeyboardMarkup(
                        keyboard=[['Senderisme', 'Bicicleta', 'Nocturna']],
                        one_time_keyboard=True,
                        resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'month':
                bot.sendMessage(
                    update.message.chat_id,
                    parse_mode='Markdown',
                    text=FIELDS[current_field]['message'],
                    reply_markup=ReplyKeyboardMarkup(
                        keyboard=[['Gener', 'Febrer', 'Març'],
                                  ['Abril', 'Maig', 'Juny'],
                                  ['Juliol', 'Agost', 'Setembre'],
                                  ['Octubre', 'Novembre', 'Desembre']],
                        one_time_keyboard=True,
                        resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day' and event[
                    'month'] == 'Febrer':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day' and event[
                    'month'] == 'Abril':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29', '30']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day' and event[
                    'month'] == 'Juny':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29', '30']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day' and event[
                    'month'] == 'Setembre':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29', '30']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day' and event[
                    'month'] == 'Novembre':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29', '30']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'day':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['01', '02', '03', '04'],
                                              ['05', '06', '07', '08'],
                                              ['09', '10', '11', '12'],
                                              ['13', '14', '15', '16'],
                                              ['17', '18', '19', '20'],
                                              ['21', '22', '23', '24'],
                                              ['25', '26', '27', '28'],
                                              ['29', '30', '31']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'year':
                now = datetime.now()
                now2 = int(now.year)
                now3 = str(now2)
                next1 = str(now2 + 1)
                next2 = str(now2 + 2)
                next3 = str(now2 + 3)
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[[now3], [next1], [next2],
                                              [next3]],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'hour':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['06', '07', '08', '09'],
                                              ['10', '11', '12', '13'],
                                              ['14', '15', '16', '17'],
                                              ['18', '19', '20', '21'],
                                              ['22', '23', '00', '01'],
                                              ['02', '03', '04', '05']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'minute':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[['00', '15'], ['30', '45']],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] == 'date':
                day = event['day']
                year = event['year']
                hour = event['hour']
                minute = event['minute']
                if event['month'] == 'Gener':
                    monthnum = '01'
                elif event['month'] == 'Febrer':
                    monthnum = '02'
                elif event['month'] == 'Març':
                    monthnum = '03'
                elif event['month'] == 'Abril':
                    monthnum = '04'
                elif event['month'] == 'Maig':
                    monthnum = '05'
                elif event['month'] == 'Juny':
                    monthnum = '06'
                elif event['month'] == 'Juliol':
                    monthnum = '07'
                elif event['month'] == 'Agost':
                    monthnum = '08'
                elif event['month'] == 'Setembre':
                    monthnum = '09'
                elif event['month'] == 'Octubre':
                    monthnum = '10'
                elif event['month'] == 'Novembre':
                    monthnum = '11'
                else:
                    monthnum = '12'
                newdate = monthnum + "/" + day + "/" + year + " " + hour + ":" + minute
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardMarkup(
                                    keyboard=[[newdate]],
                                    one_time_keyboard=True,
                                    resize_keyboard=True))

            elif FIELDS[current_field]['name'] != 'month' or FIELDS[
                    current_field]['name'] != 'day' or FIELDS[current_field][
                        'name'] != 'year' or FIELDS[current_field][
                            'name'] != 'hour' or FIELDS[current_field][
                                'name'] != 'minute' or FIELDS[current_field][
                                    'name'] != 'date':
                bot.sendMessage(update.message.chat_id,
                                parse_mode='Markdown',
                                text=FIELDS[current_field]['message'],
                                reply_markup=ReplyKeyboardHide())
        else:
            event['user_id'] = user_id
            self.create_event(bot, update, event)
Beispiel #26
0
    def message(self, bot, update):
        user_id = str(update.message.from_user.id)
        chat_id = update.message.chat_id
        text = update.message.text
        draft = self.store.get_draft(user_id)

        if draft:
            event = draft['event']
            current_field = draft['current_field']
            field = FIELDS[current_field]

            event[field['name']] = parse_fields(field['name'], text)
            if field['name'] == 'day' and event['day'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F No és un dia vàlid, assegura't que és un número entre 1 i 31 i torna a provar-ho."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'month' and event['month'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F No és un mes vàlid, escriu-lo amb lletres i en valencià i torna a provar-ho."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'year' and event['year'] == 'error':
                actualdate = datetime.now()
                actualyear = int(actualdate.year)
                bot.sendMessage(
                    update.message.chat_id,
                    text="\u26A0\uFE0F No és un any vàlid, has d'escriure " +
                    str(actualyear) + ", " + str(actualyear + 1) + ", " +
                    str(actualyear + 2) + " o " + str(actualyear + 3) +
                    " i tornar a provar-ho.")
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'hour' and event['hour'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F No és una hora vàlida, assegura't que és un número entre 0 i 23 i torna a provar-ho."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'minute' and event['minute'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F No és un minut vàlid, assegura't que és un número entre 0 i 59 i torna a provar-ho."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'date' and event['date'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F No és una data vàlida. Si la data és correcta, prem el botó, no escrigues cap text."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'route' and event['route'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F Sembla que l'URL que has enviat no és vàlid, comprova'l i torna a enviar-lo."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'type' and event['type'] == 'error':
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\u26A0\uFE0F Eixe tipus de ruta no és vàlid, usa els botons per triar-ne un."
                )
                current_field += 0
                self.update_draft(bot, event, user_id, update, current_field)

            else:
                current_field += 1

                self.update_draft(bot, event, user_id, update, current_field)

        else:
            if str(chat_id) != chats['group']:
                bot.sendMessage(
                    update.message.chat_id,
                    text=
                    "\U0001F914 No entenc el que em vols dir, però sóc un robot \U0001F916 i funcione de manera molt senzilla:\n\n1. /start per a començar a crear una excursió nova\n2. /help per a saber un poc més sobre mi.",
                    reply_markup=ReplyKeyboardHide())
def link(bot, update):
    print("linking")
    if update.message.text != "Stop linken":
        linkingActive.append(update.message.chat_id)
        
    if update.message.text == "Automaties met Telegram":
        autoLink(bot, update)
    elif update.message.text == "Handmatig met ID":
        manualLinkIDActive.append(update.message.chat_id)
        bot.sendMessage(update.message.chat_id, "Voer nu je ID in met getallen 0-9", reply_markup=ReplyKeyboardHide(hide_keyboard=True, selective=False))
    elif update.message.text == "Handmatig met voor- en achternaam":
        manualLinkActive.append(update.message.chat_id)
        bot.sendMessage(update.message.chat_id, "Voer nu je voornaam en achternaam in  met een punt ertussen\n\nBijvoorbeeld:\nAls je naam Peter Jan de Vries is vul je in\n Peter.Vries", reply_markup=ReplyKeyboardHide(hide_keyboard=True, selective=False))
    elif update.message.chat_id in manualLinkActive:
        manuelLink(bot, update)
    elif update.message.chat_id in manualLinkIDActive:
        manuelLinkID(bot, update)
    elif update.message.text == "Stop linken":
        stoplinking(bot, update)
    else:
        bot.sendMessage(update.message.chat_id, "Voor het door linken kunt u gebruik maken van 3 manieren\n\nAutomaties doormiddel van uw telegram naam\nOf\nHandmatig met uw stallings ID of voor en achternaam\n\nAdvies: Probeer eerst Automaties mocht dat niet werken porbeer dan automaties\nJe kan het doorlinken stoppen met /stoplinking", reply_markup=ReplyKeyboardMarkup([["Automaties met Telegram"], ["Handmatig met ID", "Handmatig met voor- en achternaam"], ["Stop linken"]]))
Beispiel #28
0
def kill_keyboard(bot, update):
    reply_markup = ReplyKeyboardHide()
    bot.sendMessage(update.message.chat_id,
                    text="Okay. \xf0\x9f\x98\xa5",
                    reply_markup=reply_markup)
Beispiel #29
0
    def message(self, bot, update):
        user_id = update.message.from_user.id
        text = update.message.text
        draft = self.store.get_draft(user_id)

        if draft:
            event = draft['event']
            current_field = draft['current_field']
            field = FIELDS[current_field]

            event[field['name']] = parse_fields(field['name'], text)
            if field['name'] == 'day' and event['day'] == 'error':
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F No és un dia vàlid, assegureu-vos què és un nombre entre 1 i 31 i torneu-ho a provar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'month' and event['month'] == 'error':
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F No és un mes vàlid, escriviu-lo amb lletres i en català i torneu-ho a provar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'year' and event['year'] == 'error':
                  actualdate = datetime.now()
                  actualyear = int(actualdate.year)
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F No és un any vàlid, heu d'escriure " + str(actualyear) + ", " + str(actualyear + 1) + ", " + str(actualyear + 2) + " o " + str(actualyear + 3) + " i torneu-ho a provar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'hour' and event['hour'] == 'error':
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F No és una hora vàlida, assegureu-vos que és un nombre entre 0 i 23 i torneu-ho a provar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'minute' and event['minute'] == 'error':
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F No és un minut vàlid, assegureu-vos què és un nombre entre 0 i 59 i torneu-ho a provar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            elif field['name'] == 'route' and event['route'] == 'error':
                  bot.sendMessage(
                  update.message.chat_id,
                  text="\u26A0\uFE0F Sembla que l'URL que heu enviat no és vàlid, comproveu-lo i torneu-lo a enviar."
                  )
                  current_field += 0
                  self.update_draft(bot, event, user_id, update, current_field)

            else:
                  current_field += 1

                  self.update_draft(bot, event, user_id, update, current_field)

        else:
            bot.sendMessage(
            update.message.chat_id,
            text="\U0001F914 No entenc el que em voleu dir, però sóc un robot \U0001F916 i funciono de manera molt senzilla:\n\n1. /start per començar a crear una excursió nova\n2. O per saber una mica més sobre mi, /help.",
            reply_markup=ReplyKeyboardHide()
            )
Beispiel #30
0
def message_handler(bot, update):
    global state
    forward_from = update.message.forward_from
    chat_id = update.message.chat_id
    chat_state = state.get(chat_id, MAIN)
    reply = None
    reply_markup = ReplyKeyboardHide(selective=True)

    with db_session:
        if chat_state is ADD_BELIEVER and forward_from:
            reporter = get_reporter(forward_from)
            if not reporter:
                reporter = Reporter(id=forward_from.id,
                                    first_name=forward_from.first_name,
                                    last_name=forward_from.last_name,
                                    username=forward_from.username)
                track(update, 'new_reporter')

            believer = Believer(added_by=get_admin(update.message.from_user))
            believer.reported_by.add(reporter)
            track(update, 'new_report')
            db.commit()

            reply = "Created report <b>#%d</b>! Please enter trustworthy bitcoin trader " \
                    "information:" % believer.id
            reply_markup = CAT_KEYBOARD
            state[chat_id] = [ADD_INFO, believer.id]

        elif chat_state is EDIT:
            try:
                report_id = int(update.message.text.replace('#', ''))
            except ValueError:
                reply = "Not a valid report number. Try again or use " \
                        "/cancel to abort."
            else:
                believer = Believer.get(id=report_id)

                if believer:
                    reply = "%s\n\nPlease enter new " \
                            "trustworthy bitcoin trader information:" % str(believer)
                    reply_markup = CAT_KEYBOARD
                    state[chat_id] = [ADD_INFO, believer.id]
                else:
                    reply = "Could not find report number. Try again or " \
                            "use /cancel to abort."

        elif chat_state is REMOVE_BELIEVER:
            try:
                report_id = int(update.message.text.replace('#', ''))
            except ValueError:
                reply = "Not a valid report number. Try again or use " \
                        "/cancel to abort."
            else:
                believer = Believer.get(id=report_id)
                if believer:
                    believer.delete()
                    reply = "Deleted report!"
                    del state[chat_id]
                else:
                    reply = "Could not find report number. Try again or " \
                            "use /cancel to abort."
                    reply_markup = ForceReply(selective=True)

        elif chat_state is ADD_ADMIN and forward_from:
            admin = get_admin(forward_from)
            if not admin:
                Admin(id=forward_from.id,
                      first_name=forward_from.first_name,
                      last_name=forward_from.last_name,
                      username=forward_from.username)
                reply = "Successfully added admin"
            else:
                reply = "This user is already an admin"

            del state[chat_id]

        elif chat_state is REMOVE_ADMIN and forward_from:
            admin = get_admin(forward_from)
            if admin and not admin.super_admin:
                admin.delete()
                reply = "Successfully removed admin"
            else:
                reply = "This user is not an admin"

            del state[chat_id]

        elif (isinstance(chat_state, tuple) and chat_state[0] is SEARCH
              and update.message.text):

            issued = chat_state[1]
            if (datetime.now() - issued).seconds > 30:
                reply = "Please send your /search query within 30 seconds."
                del state[chat_id]

            else:
                text = update.message.text.replace('%', '')

                believers = select(
                    s for s in Believer
                    if text in s.phone_nr or text in s.account_nr
                    or text in s.bank_name or text in s.remark).order_by(
                        desc(Believer.created))[0:1]

                good_believers = [
                    item["identifier"] for item in believers
                    if isHoldingESCX(item['id'])
                ]
                if good_believers:
                    believer = believers[0]
                    reply = str(believer)
                    reporter = get_reporter(update.message.from_user)

                    kb = search_keyboard(
                        offset=0,
                        show_download=True,
                        disabled_attachments=[],
                        confirmed=reporter in believer.reported_by
                        if reporter else False,
                        query=text)
                    reply_markup = InlineKeyboardMarkup(kb)
                else:
                    reply = "No search results"

                del state[chat_id]
                track(update, 'search')

        elif isinstance(chat_state, list):  # Additional info
            text = update.message.text

            if chat_state[0] is ADD_INFO and len(chat_state) is 2:
                option = options[text]
                chat_state.append(option)
                state[chat_id] = chat_state

                if option != ATTACHMENT:
                    reply = "Please enter " + update.message.text
                else:
                    reply = "Please send a photo or file to attach to this " \
                            "report"

                reply_markup = ForceReply(selective=True)

            elif chat_state[0] is ADD_INFO:
                believer = Believer.get(id=chat_state[1])
                text = update.message.text
                category = chat_state[2]

                if category is PHONE_NR and text:
                    believer.phone_nr = text

                elif category is ACCOUNT_NR and text:
                    believer.account_nr = text

                elif category is BANK_NAME and text:
                    believer.bank_name = text

                elif category is REMARK and text:
                    believer.remark = text

                elif category is ATTACHMENT:
                    if update.message.photo:
                        believer.attached_file =\
                            'photo:' + update.message.photo[-1].file_id
                    elif update.message.document:
                        believer.attached_file =\
                            'document:' + update.message.document.file_id

                chat_state.pop()  # one menu back
                state[chat_id] = chat_state
                reply_markup = CAT_KEYBOARD
                reply = "Add more info or send /cancel if you're done."

    if reply:
        bot.sendMessage(chat_id,
                        text=reply,
                        parse_mode=ParseMode.HTML,
                        reply_to_message_id=update.message.message_id,
                        reply_markup=reply_markup)