def get_token(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    token_body = update.get_message().get_text()

    tokens = Token.objects.filter(key=token_body)

    if tokens.count() == 0:
        bot.sendMessage(chat_id, 'No user with such token.')
        raise ProcessFailure

    token = Token.objects.get(key=token_body.strip())

    user = token.user

    try:

        try:
            tg_user = TelegramUser.objects.get(chat_id=chat_id, )
        except Exception as e:
            bot.sendMessage(chat_id, str(e))

            tg_user = TelegramUser()
            tg_user.chat_id = chat_id
            bot.sendMessage(chat_id, "Chat " + tg_user.chat_id)

        tg_user.user = user

        bot.sendMessage(chat_id,
                        f'Telegram User Username {tg_user.user.username}')

        tg_user.save()

        bot.sendMessage(chat_id, 'You authorized successfully.')
    except Exception as e:
        bot.sendMessage(chat_id, str(e))
Beispiel #2
0
    def handle_update(self, update: Update):
        user = update.get_user()
        chat = update.get_chat()

        if user is not None:
            db_user = self.get_db_user(user.get_id())
        else:
            db_user = None

        if chat is not None:
            db_chat = self.get_db_chat(chat.get_id())
        else:
            db_chat = None

        db_state = self.get_db_state(db_user, db_chat)

        self.pre_processing(update,
                            chat=chat,
                            db_chat=db_chat,
                            user=user,
                            db_user=db_user,
                            state=db_state)

        processors = self.state_manager.get_processors(update, db_state)

        for processor in processors:
            processor(self, update, db_state)

        self.post_processing(update,
                             chat=chat,
                             db_chat=db_chat,
                             user=user,
                             db_user=db_user,
                             state=db_state)
Beispiel #3
0
def get_name(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    name = update.get_message().get_text()
    if len(name) < 3:
        bot.sendMessage(chat_id, 'Name is too short! Try again:')
        raise ProcessFailure

    state.set_memory({'name': name})

    bot.sendMessage(chat_id, 'Beautiful! What is your email address?')
def send_keyboards(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    text = str(update.get_message().get_text())

    if text.lower() in ['normal keyboard', 'regular keyboard']:
        send_normal_keyboard(bot, chat_id)
    elif text.lower() in ['inline keyboard']:
        send_inline_keyboard(bot, chat_id)
    else:
        send_options(bot, chat_id)
Beispiel #5
0
def get_name(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    make = update.get_message().get_text()

    # TODO: Validation should be added here. If not valid raise a ProcessFailure
    # if len(make) < 3:
    #     bot.sendMessage(chat_id, 'Name is too short! Try again:')
    #     raise ProcessFailure

    state.set_memory({'make': make})

    bot.sendMessage(chat_id, 'Beautiful! What is car\'s model?')
Beispiel #6
0
def handle_choice(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    text = update.get_message().get_text()

    if text == 'Register your vehicle':
        bot.sendMessage(
            chat_id,
            'What is your car\'s make?',
            reply_markup=ReplyKeyboardRemove.a(remove_keyboard=True))
        state.set_name('asked_for_make')
    else:
        bot.sendMessage(chat_id, 'I didn\'t get that! Use the keyboard below')
Beispiel #7
0
 def poll_updates_and_handle(self):
     updates = self.getUpdates()
     offset = None
     total_count = 0
     while len(updates) > 0:
         total_count += len(updates)
         for update_json in updates:
             update = Update(update_json)
             self.handle_update(update)
             offset = int(update.get_update_id()) + 1
         updates = self.getUpdates(offset=offset)
     return total_count
Beispiel #8
0
def say_hello(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    bot.sendMessage(chat_id, 'Hello! and welcome to this bot :)')
    bot.sendPhoto(chat_id, open('hello_world_bot/img/welcome.png', 'rb'), upload=True)
    bot.sendMessage(chat_id, 'Have you signed up yet?', reply_markup=ReplyKeyboardMarkup.a(keyboard=[
        [KeyboardButton.a(text='Yes!'), KeyboardButton.a(text='Do it now!')]
    ]))
Beispiel #9
0
def get_email(bot: TelegramBot, update: Update, state):
    chat_id = update.get_chat().get_id()
    model = update.get_message().get_text()

    make = state.get_memory()['make']

    update.get_user()
    create_vehicle(make=make,
                   model=model,
                   number_of_seats=4,
                   telegram_user=bot.get_db_user(update.get_user().id))
    bot.sendMessage(
        chat_id,
        'Thanks! You successfully registered your vehicle with detail:\nMake: {}\nModel: {}'
        .format(make, model))

    state.set_memory({})
Beispiel #10
0
def send_group(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    text = str(update.get_message().get_text())
    subj = Subjects.objects.values_list('title', flat=True)
    all_events = Event.objects.all()
    all_events_stringed = list(map(str, all_events))
    print(bot.getUpdates())
    if text == 'start':
        send_options(bot, chat_id)
    elif text in all_events_stringed:
        state.set_memory({'name': text})
        bot.sendMessage(
            chat_id,
            text=
            'Before sending message type first string- `Message`\nExample: Message: Uroka ne budet!\nSend message for a '
            + text,
            parse_mode=bot.PARSE_MODE_MARKDOWN)
    elif text in subj:
        d = Subjects.objects.get(title=text)
        events = Event.objects.filter(subject=d)
        events_buttons = list()
        for i in events:
            events_buttons.append([KeyboardButton.a(str(i))])
        bot.sendMessage(
            chat_id,
            text=
            'Here is a list of events, choose for which one you want to edit a message.',
            reply_markup=ReplyKeyboardMarkup.a(one_time_keyboard=True,
                                               resize_keyboard=True,
                                               keyboard=events_buttons),
            parse_mode=bot.PARSE_MODE_MARKDOWN)
    elif text[:8] == 'Message:':
        kekw = state.get_memory()['name']
        for i in all_events:
            if str(i) == kekw:
                kekw = i
                kekw.message = text[8:]
                kekw.save()
        bot.sendMessage(chat_id,
                        text='All done, checkout the schedule!',
                        parse_mode=bot.PARSE_MODE_MARKDOWN)
    else:
        bot.sendMessage(chat_id,
                        text='Send start to continue',
                        parse_mode=bot.PARSE_MODE_MARKDOWN)
Beispiel #11
0
 def get_processors(self, update: Update, state: AbstractTelegramState):
     """
     Searches through all of the processors and creates a list of those that handle the current state
     :param update: The received update
     :param state: The current state
     :return: a list of processors
     """
     message = update.get_message()
     message_type = message.type() if message is not None else None
     update_type = update.type()
     state_name = state.name
     processors = []
     for handling_state in self.handling_states.keys():
         if handling_state.matches(state_name=state_name,
                                   update_type=update_type,
                                   message_type=message_type):
             processors.append(self.handling_states[handling_state])
     return processors
Beispiel #12
0
def say_hello(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()
    bot.sendMessage(chat_id, 'Hello! and welcome to Guide Addis bot :)')
    bot.sendPhoto(chat_id,
                  open('guide_addis_bot/img/logo.png', 'rb'),
                  upload=True)
    bot.sendMessage(chat_id,
                    'What do you want to do?',
                    reply_markup=ReplyKeyboardMarkup.a(keyboard=[[
                        KeyboardButton.a(text='Register your vehicle'),
                        KeyboardButton.a(text='Browse car listings')
                    ]]))
Beispiel #13
0
def handle_bot_request(request):
    update = Update(request.body.decode("utf-8"))
    """
    All of the processing will happen in this part. It is wrapped in try-except block
    to make sure the returned HTTP status is 200. Otherwise, if your processors raise Exceptions
    causing this function to raise Exception and not return 200 status code, Telegram will stop
    sending updates to your webhook after a few tries. Instead, take the caught exception and handle it
    or log it to use for debugging later.
    """
    try:
        bot.handle_update(update)
    except Exception:
        pass
    return HttpResponse("OK")
Beispiel #14
0
def hello_world(bot: TelegramBot, update: Update, state: TelegramState):
    bot.sendMessage(update.get_chat().get_id(), 'Hello!')