def delete_contact_confirmation(update, context) -> int:
    global sql_dict, DB_PATH
    # if the user replied with 'Yes, go ahead!' delete the row with contact_id
    if update.message.text == "Yes, go ahead!":
        try:
            db = connect_database(DB_PATH)
            cur = db.cursor()
            sql = '''DELETE FROM contacts WHERE contact_id = ?'''
            cur.execute(sql, (sql_dict["contact_id"], ))
            db.commit()
            db.close()
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text="Done. {} {} has been deleted".format(
                    sql_dict["first_name"], sql_dict["last_name"]),
                reply_markup=telegram.ReplyKeyboardRemove())
        except sqlite3.Error as e:
            print(e)
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text=
                "Oops, something went wrong when deleting your contact from the database",
                reply_markup=telegram.ReplyKeyboardRemove())
            return ConversationHandler.END
    else:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="I am happy that you made up your mind and want to keep {} {} "
            "as your contact".format(sql_dict["first_name"],
                                     sql_dict["last_name"]),
            reply_markup=telegram.ReplyKeyboardRemove())
    return ConversationHandler.END
def deactivate(update, context):
    # determine if user is registered and set is_active to 1
    global DB_PATH
    if is_registered(DB_PATH, update.effective_chat.id):
        # update database
        sql = ''' UPDATE users SET is_active = ? WHERE chat_id = ?'''
        db = connect_database(DB_PATH)
        cur = db.cursor()
        cur.execute(sql, (0, update.effective_chat.id))
        db.commit()
        # retrieve all jobs having the chat_id as name
        current_jobs = context.job_queue.get_jobs_by_name(
            str(update.effective_chat.id))
        # current_jobs is a tuple which should ideally only have one item. Disable it
        for job in current_jobs:
            job.enabled = False
        # query reminder time value for reply message to user
        sql = ''' SELECT reminder_time FROM users WHERE chat_id = ?'''
        cur.execute(sql, (update.effective_chat.id, ))
        reminder_time = cur.fetchone()[0]
        msg = "Daily reminders at {} have been deactivated. To activate them use " \
              "the /activate command".format(reminder_time)
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
    else:  # if user is not registered, send back error message
        msg = "You are not a registered user. Please register first using the /register command"
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
def edit_contact_interval(update, context) -> int:
    global sql_dict, DB_PATH
    try:
        interval = int(365 / int(update.message.text))
    except Exception as ex:
        print(ex)
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            "You entered {}. But I asked you how often per year you want to get in "
            "touch with your contact. You have to enter a number. Let's try "
            "it again. How often per year do you want to get in touch with "
            "him or her.".format(update.message.text),
            reply_markup=telegram.ReplyKeyboardRemove())
        # point to edit_contact_interval
        return 1
    sql_dict["interval"] = interval
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text=
        "Got it. So you want to get in touch with {0} {1} roughly every {2} days.\n"
        "If you remember the date when you had contact with {0} {1} for the last "
        "time, please write it back in the format YYYY-MM-DD. If you respond anything "
        "else, I will simply assume that you want to keep the old date".format(
            sql_dict["first_name"], sql_dict["last_name"],
            sql_dict["interval"]),
        reply_markup=telegram.ReplyKeyboardRemove())
    # point to edit_contact_last_contact
    return 2
Exemple #4
0
def selectShow(bot, update):
    db = TinyDB('data.json')
    table = db.table(str(update.message.chat_id))
    Q = Query()
    try:
        show = table.get(Q.name == update.message.text)
        timeTuple = show['time']
        showTime = ShowTime()
        errorLoadingTimes = showTime.loadTimes(timeTuple)
        if errorLoadingTimes:
            update.message.reply_text(
                'Times do not work out. Error: %s \n'
                'Remove %s from show list.' %
                (goodLoadTime, update.message.text),
                reply_markup=telegram.ReplyKeyboardRemove())

            return ConversationHandler.END

        timeDiff = showTime.timeDifference()
        update.message.reply_text(timeDiff,
                                  reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END

    except Exception as e:
        update.message.reply_text('Error: %s' % e,
                                  reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
Exemple #5
0
def registerHouse(bot, update):
    text = update.message.text
    chat_id = update.message.chat_id
    if (chatDB.is_house_registered(text)):
        update.message.reply_text(
            text=
            "What! This house has already been registered. Wanna check again? Type '/start' to choose another house",
            reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
    elif (chatDB.is_chat_registered(chat_id)):
        update.message.reply_text(
            text=
            "This chat has already been assigned a house! Type '/remove' to remove this chat's house, then '/start' to register a house.",
            reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
    else:
        # reply_keyboard = [["/my_house_letters", "/all_house_letters"]]
        # reply_markup = telegram.ReplyKeyboardMarkup(reply_keyboard)
        chatDB.add_house(chat_id, text)
        house = chatDB.get_house(chat_id)
        logger.info("Team %s has been registered by %s.", text,
                    update.message.from_user.first_name)
        update.message.reply_text(
            text="AWESOME! {} will be my favourite house now!".format(text))
        # bot.sendMessage(chat_id=chat_id,text = "Press '/my_house_letters' to see the letter(s) {} has collected.\n\nPress '/all_house_letters' to see the letter(s) that other houses have collected.".format(house), replymark_up=reply_markup)
        bot.sendMessage(
            chat_id=chat_id,
            text="Press '/help' to see a list of commands and instructions.")
def start(update, context):
    # query database for chat id to determine which message to send
    global DB_PATH
    is_registered_user = is_registered(DB_PATH, update.effective_chat.id)
    if is_registered_user is True:
        msg = "Welcome back. You are a registered user of my stay-in-touch reminder service.\n" \
              "You can type /help in order to find out by which commands you can interact with me."
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
    elif is_registered_user is False:
        msg = "Welcome! I am the stay-in-touch bot. I can help you remember with whom you want to stay in" \
              "contact by sending you daily reminders for reaching out to a list of people which you" \
              "can freely define. You can also specify how often you want to contact each individual person.\n" \
              "Sounds good? I need to register your chat_id in order to get started.\n" \
              "Please also be aware that all the (personal) information such as contact names will be" \
              "stored without encryption in my database. So use at your own risk. I cannot take any" \
              "responsibility for your actions.\n" \
              "So, do you want to become an active user?"
        custom_keyboard = [['Please register me!'], ['No, thank you!']]
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardMarkup(
                                     custom_keyboard, one_time_keyboard=True))
    else:
        msg = "Sorry. An error occurred. Please try again later."
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
def print_contacts(update, context):
    global DB_PATH
    try:
        db = connect_database(DB_PATH)
        cur = db.cursor()
        sql = '''SELECT user_id FROM users WHERE chat_id = ?'''
        cur.execute(sql, (update.effective_chat.id, ))
        result = cur.fetchone()
        if result is None:
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text="You don't seem to be a registered user. Please register "
                "first using the /register command.",
                reply_markup=telegram.ReplyKeyboardRemove())
            return
        else:
            user_id = result[0]
        sql = ''' SELECT contact_id, first_name, last_name FROM contacts
        WHERE user_id = ?'''
        msg = ''
        for row in cur.execute(sql, (user_id, )):
            msg += "{}. {} {}\n".format(row[0], row[1], row[2])
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
    except sqlite3.Error as e:
        print(e)
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            "Oops. Something went wrong. I could not add your contact to the database."
            "Please try again.",
            reply_markup=telegram.ReplyKeyboardRemove())
def register(update, context) -> int:
    # query database for chat id to see if chat_id is registered already
    chat_id = update.effective_chat.id
    global DB_PATH
    db = connect_database(DB_PATH)
    sql = ''' SELECT user_id FROM users WHERE chat_id = ?'''
    try:
        cur = db.cursor()
        cur.execute(sql, (chat_id, ))
        is_registered_user = True if cur.fetchone() is not None else False
    except sqlite3.Error as e:
        print(e)
        return ConversationHandler.END
    db.close()
    # if user is registered already, user cannot be registered again
    if is_registered_user:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=
            'You are already a registered user. If you want to activate or deactivate '
            'your reminder settings, please use the /activate and /deactivate command.',
            reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
    # otherwise start the registration converation.
    else:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text='Cool! Then I will register our mutual '
            'chat ID in my database and set you as an '
            'active user. At what time each day '
            'would you like to be reminded of your '
            'due contacts? Please answer in HH:MM:SS format.',
            reply_markup=telegram.ReplyKeyboardRemove())
        # REMINDER_TIME = 0
        return 0
Exemple #9
0
def weather_handler(update, context):
    if update.message.text == WEATHER_CONVERSATION_COMMANDS[0]:
        update.message.reply_text(weather_api.get_current_weather(*context.user_data["location"]),
                                  reply_markup=telegram.ReplyKeyboardRemove())
    elif update.message.text == WEATHER_CONVERSATION_COMMANDS[1]:
        update.message.reply_text(weather_api.get_current_weather(*context.user_data["location"]),
                                  reply_markup=telegram.ReplyKeyboardRemove())
    return ConversationHandler.END
def reminder(context: telegram.ext.CallbackContext) -> None:
    # retrieve contacts of user
    # chat_id is passed as context of the job so it can be accessed as
    chat_id = context.job.context
    global DB_PATH
    due_contacts = []
    try:
        # get user_id which belongs to chat_id
        db = connect_database(DB_PATH)
        cur = db.cursor()
        sql = '''SELECT user_id FROM users WHERE chat_id = ?'''
        cur.execute(sql, (chat_id, ))
        result = cur.fetchone()
        if result is None:
            context.bot.send_message(
                chat_id=chat_id,
                text="You don't seem to be a registered user. Please register "
                "first using the /register command.",
                reply_markup=telegram.ReplyKeyboardRemove())
            return
        else:
            user_id = result[0]

        # get list of contacts with all data
        sql = '''SELECT first_name, last_name, interval, last_contact FROM
        contacts WHERE user_id = ?'''
        msg = "Hi there. Here is today's list of people who you want to stay in touch with:\n"
        ii = 1
        # determine for which contacts contacting is overdue
        for row in cur.execute(sql, (user_id, )):
            interval = row[2]
            last_contact = datetime.datetime.strptime(row[3], '%Y_%m_%d')
            if (last_contact + datetime.timedelta(days=interval)
                ).date() <= datetime.date.today():
                # append contacts to due_contacts list and
                due_contacts.append(row[0] + ' ' + row[1])
                msg += "{}: {} {}\n".format(ii, row[0], row[1])
                ii += 1
        db.close()
    except sqlite3.Error as e:
        print(e)
        context.bot.send_message(
            chat_id=chat_id,
            text=
            "Oops. Something went wrong when retrieving your list of contacts.",
            reply_markup=telegram.ReplyKeyboardRemove())
        return
    # check if there are due contacts and only send a reminder if that is the case
    if len(due_contacts) > 0:
        # send a message to the user with his due contacts and offer him a keyboard to mark users which have
        # been contacted
        custom_keyboard = [['I contacted ' + name + ' today!']
                           for name in due_contacts]
        custom_keyboard.append(["Nope, that's it for today"])
        context.bot.send_message(chat_id=chat_id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardMarkup(
                                     custom_keyboard, one_time_keyboard=True))
Exemple #11
0
    def modify_database(self, update, context):
        def dump_db(self, update, context):
            if self.accesslevel(update.effective_chat.id) == 2:
                context.bot.send_document(
                    chat_id=update.effective_chat.id,
                    document=open(self.cf["ADMIN"]["database_file"], 'rb'))

        def load_db(self, update, context):
            if self.accesslevel(update.effective_chat.id) == 2:
                if fileExtenstion(update) == "json":
                    #TODO: check if JSON is valid
                    context.bot.get_file(
                        update.message.document.file_id).download(
                            self.cf["ADMIN"]["database_file"])
                    return False,
                else:
                    return True, "database_new_invalid"

        if self.accesslevel(update.effective_chat.id) != 2:
            self.send_message(update, context, "register_unauthorized")
            return

        if self.state == "database_modify":
            if update.message.text == self.lang["database_load"]:
                self.state = "database_modify_load"
                self.tell_daddy(context,
                                "confirm_ask",
                                reply_markup=telegram.ReplyKeyboardMarkup(
                                    [[self.lang["confirm_pos"]],
                                     [self.lang["confirm_neg"]]]))
            elif update.message.text == self.lang["database_dump"]:
                self.tell_daddy(context,
                                "here_you_go",
                                reply_markup=telegram.ReplyKeyboardRemove())
                dump_db(self, update, context)
                self.state = "normal"
            else:
                self.command_cancel(update, context)

        elif self.state == "database_modify_load":
            if update.message.text == self.lang["confirm_pos"]:
                self.state = "database_modify_load_confirmed"
            elif update.message.text == self.lang["confirm_neg"]:
                self.command_cancel(update, context)
            else:
                self.command_cancel(update, context)

        elif self.state == "database_modify_load_confirmed":
            r = load_db(self, update, context)
            if not r[0]:
                self.tell_daddy(context,
                                "database_new_loaded",
                                reply_markup=telegram.ReplyKeyboardRemove())
            else:
                self.tell_daddy(context,
                                r[1],
                                reply_markup=telegram.ReplyKeyboardRemove())
            self.state = "normal"
Exemple #12
0
def weather_handler(update, context):
    if update.message.text == WEATHER_CONVERSATION_COMMANDS[0]:
        update.message.reply_text('current weather',
                                  reply_markup=telegram.ReplyKeyboardRemove())
        # TODO: send a current weather from yandex there
    elif update.message.text == WEATHER_CONVERSATION_COMMANDS[1]:
        update.message.reply_text('forecast',
                                  reply_markup=telegram.ReplyKeyboardRemove())
        # TODO: send a forecast of weather from yandex there
    return ConversationHandler.END
Exemple #13
0
def remove(update: Update, context: CallbackContext) -> None:
    """Remove user token"""

    if 'token' in context.user_data:
        context.user_data.pop('token', None)
        update.message.reply_text('Your user data has been removed',
                                  reply_markup=telegram.ReplyKeyboardRemove())
    else:
        update.message.reply_text('You don\'t have any data to be removed',
                                  reply_markup=telegram.ReplyKeyboardRemove())
    return ConversationHandler.END
def edit_contact_last_contact(update, context) -> int:
    global sql_dict
    # try converting user input to datetime object and if successful update sql_dict
    try:
        last_contact_datetime = datetime.datetime.strptime(
            update.message.text, "%Y-%m-%d")
        sql_dict["last_contact"] = last_contact_datetime.strftime("%Y_%m_%d")
    # if this not successfull we won't touch sql_dict
    except ValueError as e:
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="Ok. We will simply keep your last contact date.",
            reply_markup=telegram.ReplyKeyboardRemove())
    # then update the database
    try:
        db = connect_database(DB_PATH)
        cur = db.cursor()
        sql = ''' SELECT user_id FROM users WHERE chat_id = ?'''
        cur.execute(sql, (update.effective_chat.id, ))
        result = cur.fetchone()
        if result is None:
            context.bot.send_message(
                chat_id=update.effective_chat.id,
                text="You don't seem to be a registered user. Please register "
                "first using the /register command.",
                reply_markup=telegram.ReplyKeyboardRemove())
            return
        else:
            sql_dict["user_id"] = result[0]
        sql = '''UPDATE contacts
        SET interval = ?, last_contact = ?
        WHERE user_id = ? AND first_name = ? and last_name = ?'''
        cur.execute(sql, (sql_dict["interval"], sql_dict["last_contact"],
                          sql_dict["user_id"], sql_dict["first_name"],
                          sql_dict["last_name"]))
        db.commit()
        db.close()

        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="Done. {} {} has been updated".format(
                                     sql_dict["first_name"],
                                     sql_dict["last_name"]),
                                 reply_markup=telegram.ReplyKeyboardRemove())
    except sqlite3.Error as e:
        print(e)
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text="Oops. Something went wrong. I could not update your contact. "
            "Please try again.",
            reply_markup=telegram.ReplyKeyboardRemove())
    return ConversationHandler.END
Exemple #15
0
def discabon(bot, update, section):
    """Defining the command to enable notification for discab"""

    if update.message.chat_id not in utils.USERS[section]:
        utils.subscribe_user(update.message.chat_id, section)
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(update.message.chat_id,
                        text='Le notifiche sono già abilitate!',
                        reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END
Exemple #16
0
 def handle_command(self):
     """
     处理发送过来的命令(“/”开头)
     :return:
     """
     try:
         text = self.text
         if text.find("@") > -1:
             text = text.split("@")[0]
         if text.startswith("/faq"):
             if len(text) == 4:
                 bot.sendMessage(
                     chat_id=self.chat.id,
                     reply_to_message_id=int(self.message_id),
                     text=get_faq_introduce(),
                     parse_mode='HTML',
                     reply_markup=telegram.ReplyKeyboardMarkup(keyboard=get_keyboard(text), selective=True))
             else:
                 tmp = text.split(" ", 1)
                 second_command = tmp[1].encode('utf-8')
                 if second_command not in settings.command['/faq'].keys():
                     raise BotException.CommandException()
                 else:
                     bot.sendMessage(
                         chat_id=self.chat.id,
                         reply_to_message_id=int(self.message_id),
                         text=settings.command['/faq'][second_command],
                         parse_mode='HTML',
                         reply_markup=telegram.ReplyKeyboardRemove(selective=True))
         elif text == "/activity":
             bot.sendMessage(
                 chat_id=self.chat.id,
                 reply_to_message_id=int(self.message_id),
                 text=get_activity(),
                 parse_mode='HTML',
                 reply_markup=telegram.ReplyKeyboardMarkup(keyboard=get_keyboard(text), selective=True)
             )
         elif text in settings.command.keys():
             bot.sendMessage(
                 chat_id=self.chat.id,
                 reply_to_message_id=int(self.message_id),
                 text=settings.command[text],
                 parse_mode='HTML',
                 reply_markup=telegram.ReplyKeyboardRemove(selective=True))
         else:
             raise BotException.CommandException()
     except BotException.CommandException, ce:
         bot.sendMessage(chat_id=self.chat.id, reply_to_message_id=int(self.message_id), text=ce.message,
                     parse_mode='HTML')
Exemple #17
0
def discaboff(bot, update, section):
    """Defining the command to disable notification for discab"""

    if update.message.chat_id in utils.USERS[section]:
        utils.unsubscribe_user(update.message.chat_id, section)
        bot.sendMessage(update.message.chat_id,
                        text='Notifiche Disattivate!',
                        reply_markup=telegram.ReplyKeyboardRemove())
    else:
        bot.sendMessage(
            update.message.chat_id,
            text='Per disattivare le notifiche dovresti prima attivarle.',
            reply_markup=telegram.ReplyKeyboardRemove())

    return ConversationHandler.END
def edit_reminder_time_start(update, context) -> int:
    global DB_PATH
    if is_registered(DB_PATH, update.effective_chat.id):
        msg = "Sure, let's update your reminder time. Things in life can change. Please tell me your new " \
              "desired reminder time in HH:MM:SS format."
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
        return 0
    else:
        msg = "You are not a registered user. Please register first using the /register command"
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
def new_contact(update, context) -> int:
    global DB_PATH
    if not is_registered(DB_PATH, update.effective_chat.id):
        msg = "You are not a registered user. Please register first using the /register command"
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text=msg,
                                 reply_markup=telegram.ReplyKeyboardRemove())
        return ConversationHandler.END
    context.bot.send_message(
        chat_id=update.effective_chat.id,
        text="Ok. Let's add a new contact to your reminder database.\n"
        "What is his or her first name?",
        reply_markup=telegram.ReplyKeyboardRemove())
    # FIRST_NAME = 0
    return 0
def select_game(bot, update):
    if update.message.text == 'cancel':
        update.message.reply_text(
            'Canceled',
            reply_markup=telegram.ReplyKeyboardRemove()
        )
        return ConversationHandler.END

    user = User.get_or_none(User.id == update.message.from_user.id)

    games = gmr.get_games(user.steam_id, user.authorization_key)
    games_data = [g for g in games if g['Name'] == update.message.text]

    if len(games_data) == 0:
        update.message.reply_text(
            'Game does not exist',
            reply_markup=telegram.ReplyKeyboardRemove()
        )
        return ConversationHandler.END
    game_data = games_data[0]

    if Game.select().where(Game.id == game_data['GameId']).exists():
        update.message.reply_text(
            'Game already registered',
            reply_markup=telegram.ReplyKeyboardRemove()
        )
        return ConversationHandler.END

    game = Game.create(
        id=game_data['GameId'],
        owner=user,
        name=game_data['Name'],
        current_steam_id=game_data['CurrentTurn']['UserId']
    )

    for player in game_data['Players']:
        Player.create(
            steam_id=player['UserId'],
            game=game,
            order=player['TurnOrder']
        )

    update.message.reply_text(
        f'Game {game.name} registered',
        reply_markup=telegram.ReplyKeyboardRemove()
    )

    return ConversationHandler.END
Exemple #21
0
def common_message(update, context):
    """General response handler"""

    msg = update.message
    user = msg.from_user
    debug(f'Message received from {user.id} @{user.username}: {msg.text}')

    if AUTHORIZED_USERS and user.username not in AUTHORIZED_USERS:
        return

    if 'quiz' not in context.user_data:

        info(f'Quiz started by {user.id} @{user.username}')

        context.user_data['quiz'] = {}
        context.user_data['quiz']['answers'] = {}
        starttime = datetime.now()
        context.user_data['quiz']['starttime'] = starttime

        msg.bot.send_message(msg.chat_id,
                             text=f'Тест начат в {starttime}',
                             reply_markup=telegram.ReplyKeyboardRemove())

    else:
        # save response
        context.user_data['quiz']['answers'][context.user_data['quiz']
                                             ['current_qid']] = msg.text

    # ask the question

    questions_left = set(QUESTIONS) - set(context.user_data['quiz']['answers'])

    if len(questions_left) > 0:

        question = QUESTIONS[random.sample(questions_left, 1)[0]]

        msg.bot.send_message(msg.chat_id,
            text=f'{question.text}\n' + \
                '\n'.join(f'{aid}. {text}' for aid, text in sorted(question.answers.items())),
            reply_markup=telegram.ReplyKeyboardMarkup([[aid for aid in sorted(question.answers)]]))

        context.user_data['quiz']['current_qid'] = question.qid

    else:
        msg.bot.send_message(msg.chat_id,
                             text=f'Тест пройден!',
                             reply_markup=telegram.ReplyKeyboardRemove())
        context.user_data['quiz']['current_qid'] = None
Exemple #22
0
    def jugar(bot, update):
        imagen = api.obtener_imagen()
        bot.send_photo(chat_id=update.message.chat_id, photo=imagen['url'])
        bot.send_message(chat_id=update.message.chat_id, text="¿Qué raza es?")
        opciones = random.choices(razas, k=2)
        opciones.append(imagen['raza'])
        random.shuffle(opciones)

        teclado = []
        for opcion in opciones:
            correcto = 'N'
            if opcion == imagen['raza']:
                correcto = 'S'

            teclado.append([
                telegram.InlineKeyboardButton(text=opcion.replace('-',
                                                                  ' ').title(),
                                              callback_data=correcto)
            ])

        reply_markup = telegram.InlineKeyboardMarkup(teclado)
        bot.send_message(chat_id=update.message.chat_id,
                         text="Elegí tu respuesta",
                         reply_markup=reply_markup)

        telegram.ReplyKeyboardRemove()
Exemple #23
0
    def on_open_up(self):  # Func runs on "Вскрываемся!"
        dice_map = self.dice_manager.get_dice_map()
        res_count = dice_map[self.prev_move.value - 1]

        use_cheat = not self.is_maputa and not self.prev_move.value == CHEAT_CARD_VALUE
        res_count += dice_map[CHEAT_CARD_VALUE - 1] if use_cheat else 0

        player_to_lose_ind = self.current_player - (0 if res_count >= self.prev_move.count else 1)
        player = self.players[player_to_lose_ind]

        mess_args1 = Phrase.on_end_round_1(res_count, self.prev_move.value, use_cheat)

        s = self.dice_manager.str_dice_dict()
        self.send_message(text=s)

        self.send_message(**mess_args1, reply_markup=telegram.ReplyKeyboardRemove(), )
        self.send_message(**Phrase.on_lose(player.name))

        self.current_player = player_to_lose_ind

        try:
            self.dice_manager.pop_dice_from(player.id)
        except KickPLayerException:
            try:
                self.kick_player(player)
                self.is_maputa = False
                self.new_round()
                return

            except GameEndException:
                return

        self.is_maputa = len(self.dice_manager[player.id]) == 1 and len(self.players) > 2
        self.new_round()
Exemple #24
0
def custom_scan_id_input(bot, update):
    print "inside input method with data: " + update.message.text
    customId = update.message.text
    try:
        int(customId)
    except ValueError:
        print "invalid number"
        update.message.reply_text("Not a valid number")
    else:
        print "valid number"
        connection = MySQLdb.connect(host=credentials.database_server, user=credentials.database_username,
                                     passwd=credentials.database_password, db=credentials.database_name)
        cursor = connection.cursor()
        cursor.execute("SELECT EndDate FROM scans where scanID = %s", (customId))
        data = cursor.fetchall()
        cursor.close()
        connection.close()
        if data:
            print "scan ID was found in the db"
            print "data[0][0] is: " + str(data[0][0])
            if data[0][0] == None:
                print "EndDate of scan is empty"
                update.message.reply_text("This scan hasn't finished yet")
            else:
                print "Valid scan found"
                reply_markup = telegram.ReplyKeyboardRemove()
                update.message.reply_text("Showing scan from scan " + str(customId), reply_markup=reply_markup)
                os.system(
                    "python " + os.path.dirname(os.path.abspath(__file__)) + "/notify.py " + str(customId) + " true")
                return ConversationHandler.END
        else:
            print "Scan ID not found in db"
            update.message.reply_text("This scan ID doesn't exist")
Exemple #25
0
def parseLocation(bot, update, chat_data):
    reply_markup = telegram.ReplyKeyboardRemove()
    lock.acquire()
    if not 'red' in chat_data or chat_data['red'] == 'NONE':
        bot.send_message(chat_id=update.message.chat_id,
                         text="To get the nearest ATMs type /banelco or /link",
                         reply_markup=reply_markup)
    else:
        bankingNetwork = chat_data['red']
        chat_data['red'] = 'NONE'
        msgAndURL = getNearestAtms(update.message.location, bankingNetwork)
        listOfAtms = msgAndURL[0]
        url = msgAndURL[1]
        print(url)
        if len(listOfAtms) == 0:
            bot.send_message(chat_id=update.message.chat_id,
                             text="There are no nearby " + bankingNetwork +
                             " ATMs",
                             reply_markup=reply_markup)
        else:
            msg = "Nearby " + bankingNetwork + " ATMs \n"
            msg += listOfAtms
            bot.send_message(chat_id=update.message.chat_id, text=msg)
            bot.send_photo(chat_id=update.message.chat_id, photo=url)
    lock.release()
def nombre_liga(bot, update):
    try:
        logger = _get_logger()
        liga = find_one(LEAGUES_COLLECTION, {
            "__$STATE": "CONFIG",
            "__$organizador.id": update.message.from_user.id
        })
        if not liga:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Mi no entender")
            return
        liga["config"]["nombre_liga"] = str(update.message.text)[11:]
        liga["__$STATE"] = "JOINING"
        update_doc(LEAGUES_COLLECTION, {
            "__$STATE": "CONFIG",
            "__$organizador.id": update.message.from_user.id
        }, liga)
        reply_markup = telegram.ReplyKeyboardRemove()
        bot.send_message(chat_id=liga["__$grupo"],
                         text="@" + str(liga['__$organizador']["name"]) +
                         " da inicio a la liga: " +
                         str(update.message.text)[11:])
        bot.send_message(chat_id=liga["__$grupo"],
                         text='Escribí /joinliga para unirte a la liga')
        bot.send_message(chat_id=update.message.chat_id,
                         text='Configuracion terminada',
                         reply_markup=reply_markup)
    except Exception as ex:
        bot.send_message(chat_id=update.message.chat_id, text=str(ex))
        logger.exception(ex)
        return
def cruces_partidos(bot, update):
    try:
        logger = _get_logger()
        liga = find_one(LEAGUES_COLLECTION, {
            "__$STATE": "CONFIG",
            "__$organizador.id": update.message.from_user.id
        })
        if not liga:
            bot.send_message(chat_id=update.message.chat_id,
                             text="Mi no entender")
            return
        print(liga)
        cant_partidos = 1 if update.message.text == "Solo ida" else 2
        liga["config"]["cant_partidos"] = cant_partidos
        update_doc(LEAGUES_COLLECTION, {
            "__$STATE": "CONFIG",
            "__$organizador.id": update.message.from_user.id
        }, liga)
        reply_markup = telegram.ReplyKeyboardRemove()
        bot.send_message(
            chat_id=update.message.from_user.id,
            text=
            'Ingrese nombre de la liga (con el formato"NombreLiga:*nombre de la liga")',
            reply_markup=reply_markup)
    except Exception as ex:
        bot.send_message(chat_id=update.message.chat_id, text=str(ex))
        logger.exception(ex)
        return
Exemple #28
0
def test(bot, update, args):
    m = update.message  # type: telegram.Message

    if len(args) > 0:
        reply_markup = telegram.ReplyKeyboardRemove()
        bot.send_message(chat_id=m.chat_id,
                         text=args[0],
                         reply_markup=reply_markup)
    else:
        button_list = [
            InlineKeyboardButton("test", callback_data='xxx'),
            InlineKeyboardButton("ajab", url='http://yahoo.com'),
            InlineKeyboardButton("row 2", url='http://jjo.ir')
        ]
        print('x')
        print('x')
        print(button_list)
        print(build_menu(button_list, n_cols=2))
        print('x')
        print('x')
        # some_strings = ["col1", "col2", "row2"]
        # button_list = [InlineKeyboardButton(s) for s in some_strings]
        reply_markup = telegram.InlineKeyboardMarkup(
            build_menu(button_list, n_cols=2))

        bot.send_message(chat_id=m.chat_id,
                         text="A two-column menu",
                         reply_markup=reply_markup)
Exemple #29
0
def start(bot, update):
    chat_id = update.message.chat_id
    username = update.message.chat.username

    telegram.ReplyKeyboardRemove(remove_keyboard = True)
    

    global points
    send_bot(
        'Здравствуйте, {}. Я - умный голосовой бот, который поможет вам в использовании приложения Senim. \n'.format(update.message.from_user.first_name), update.message.chat_id)
    bot.send_message(chat_id = update.message.chat_id, text = '/about - больше информации,\n/near - ближайшие точки')
    
    url = "https://senimbot-1505821861966.firebaseio.com/telegram.json"

    

    payload = "{\n\t\"chat_id\":\"%s\",\n\t\"username\":\"%s\"\n}" % (chat_id,username)

    print(payload)
    headers = {
        'content-type': "application/json, charset=utf-8"
        }

    response = requests.request("POST", url, data=payload, headers=headers)

    print(response.text)
Exemple #30
0
def guessing_game(update, chat_id, context, text):
    if text == 'Yup':
        context.bot.send_photo(chat_id=chat_id, photo=open('iwin.gif', 'rb'))
        context.user_data['playing'] = False
        reply_markup = telegram.ReplyKeyboardRemove()
        context.bot.send_message(chat_id=chat_id,
                                 text="Wanna play again?",
                                 reply_markup=reply_markup)
        return
    if context.user_data['start'] == context.user_data[
            'guess'] or context.user_data['end'] == context.user_data['guess']:
        context.bot.send_message(
            chat_id=chat_id,
            text=
            f"No lying allowed\n Is the number {context.user_data['guess']}?")
        context.bot.send_photo(chat_id=chat_id, photo=open('pin.jpg', 'rb'))
        return
    if text != 'Higher' and text != 'Lower':
        context.bot.send_message(
            chat_id=chat_id,
            text=f"Is the number {context.user_data['guess']}?")
        return
    else:
        if text == 'Higher':
            context.user_data['start'] = context.user_data['guess']
        elif text == 'Lower':
            context.user_data['end'] = context.user_data['guess']

        context.user_data['guess'] = context.user_data['start'] + (
            (context.user_data['end'] - context.user_data['start']) // 2)
    context.bot.send_message(
        chat_id=chat_id, text=f"Is the number {context.user_data['guess']}?")
    high_low_keyboard(update, chat_id, context, text)