Beispiel #1
0
    def run(self):
        update = self.update
        bot = self.bot

        chat_id = getID(update)
        text = update.message.text
        if chat_id in status:
            state = status[chat_id]
            if state == 'search':
                status.pop(chat_id)
                findmenu(text, update)

            elif state == 'add_step1':
                status.update({chat_id: 'add_step2'})
                add_query_shopname.update({chat_id: preprocess(text)})
                update.message.reply_text(
                    '新增店家名稱為{}\n請傳送未壓縮照片( /hint ) 或重新輸入名稱'.format(
                        add_query_shopname[chat_id]))
                update.message.reply_text(
                    '店家無菜單或傳送完畢請輸入 /add 結束傳送。',
                    reply_markup=ForceReply(selective=True))
            elif state == 'add_step2':
                add_query_shopname.update({chat_id: preprocess(text)})
                update.message.reply_text(
                    '更改店家名稱為{}\n請傳送未壓縮照片( /hint ) 或重新輸入名稱'.format(
                        add_query_shopname[chat_id]))
                update.message.reply_text(
                    '店家無菜單或傳送完畢請輸入 /add 結束傳送。',
                    reply_markup=ForceReply(selective=True))
        else:
            print('ignore it')

        appendlog(getID(update), update.message.from_user.full_name,
                  update.message.text)
Beispiel #2
0
def run_command(update, context):
    try:
        sessions[update.message.from_user.id][0].stdin.write(
            literal_eval(repr(update.message.text).replace("\\\\", "\\")).encode()
        )
        sessions[update.message.from_user.id][0].stdin.flush()
        time.sleep(2)
        text = ansistrip.ansi_strip(
            sessions[update.message.from_user.id][2].replace(
                sessions[update.message.from_user.id][4], "", 1
            )
        )
        sessions[update.message.from_user.id][4] = sessions[
            update.message.from_user.id
        ][2]
        if sessions[update.message.from_user.id][0].poll() is None:
            update.message.reply_text(text, reply_markup=ForceReply())
            return 0
        else:
            update.message.reply_text(text)
            del sessions[update.message.from_user.id]
            return ConversationHandler.END
    except BaseException:
        if sessions[update.message.from_user.id][0].poll() is None:
            update.message.reply_text(empty_output, reply_markup=ForceReply())
            return 0
        else:
            update.message.reply_text(empty_output)
            del sessions[update.message.from_user.id]
            return ConversationHandler.END
Beispiel #3
0
def plan(update: Update, context: CallbackContext):
    logging.debug("/plan")
    if len(context.args) == 0:
        send_plan(str(update.message.from_user.id), update.effective_chat, new_plan=True)
    else:
        name = context.args[0]
        valid = True
        if not 1 < len(name) < 20:
            valid = False
        for char in name:
            if char not in "abcdefghijklmnopqrstuvwxyzöäü":
                valid = False

        if not valid:
            update.message.reply_text(f"Der Name darf nur Buchstaben enthalten.")
            update.message.reply_text("Bitte gib mir die Login-Daten für deinen Stundenplan (Nachname).",
                                      reply_markup=ForceReply())
            return
        check, check_dbidx = Stundenplan.check_name(name)
        if not check:
            update.message.reply_text(f"Der Name {name} ist nicht gültig.")
            update.message.reply_text("Bitte gib mir die Login-Daten für deinen Stundenplan (Nachname).",
                                      reply_markup=ForceReply())

        elif len(check) > 1:
            keyboard = []
            for i in range(len(check)):
                keyboard.append(
                    [InlineKeyboardButton(str(check[i]), callback_data=f"quickplan {name} {check_dbidx[i]}")])
            reply_markup = InlineKeyboardMarkup(keyboard)
            update.message.reply_text("Es wurden mehrere Einträge gefunden, bitte wähle.",
                                      reply_markup=reply_markup)
        else:
            send_plan(str(update.message.from_user.id), update.effective_chat, new_plan=True, custom_name=[name, 0])
Beispiel #4
0
    def start(self, update: Update, context: CallbackContext):
        try:
            if self.checkUpdateAgeExpired(update):
                return
            chat_type = update.effective_chat.type
            _ = self.gettext_translation(update.effective_user)
            if chat_type != "private":
                message = _('You must send me this in a private chat')
                self.reply_message(update=update, text=message)
                return
            user_id = update.effective_user.id
            user_username = update.effective_user.username

            this_participant = self.session.query(Participant).filter(
                Participant.telegram_id == user_id).first()
            if this_participant is None:
                logging.info(f"Start | New Participant | ID: {user_id} "
                             f"Username: {user_username}")
                this_participant = Participant(telegram_id=user_id,
                                               telegram_username=user_username)
                self.session.add(this_participant)
                self.session.commit()
                message = _('Hello! Lets get you setup!')
                self.send_message(
                    context=context,
                    chat_id=this_participant.telegram_id,
                    text=message,
                )
                message = _(
                    'What is your address? (Reply to this message to change it)'
                )  # noqa: E501
                self.send_message(
                    context=context,
                    chat_id=this_participant.telegram_id,
                    text=message,
                    reply_markup=ForceReply(),
                )
            elif this_participant.address is None:
                message = _(
                    'What is your address? (Reply to this message to change it)'
                )  # noqa: E501
                self.send_message(
                    context=context,
                    chat_id=this_participant.telegram_id,
                    text=message,
                    reply_markup=ForceReply(),
                )
            else:
                already_setup = _(
                    'You are already set up. I have your address as:'
                ) + '\n'  # noqa: E501
                message = already_setup + this_participant.address
                self.send_message(
                    context=context,
                    chat_id=this_participant.telegram_id,
                    text=message,
                )
            logging.info(f"start | This Participant ID: {this_participant.id}")
        except Exception as this_ex:
            logging.exception(this_ex)
Beispiel #5
0
def add_alert(bot, update, market_id=None, price=None):
    if market_id is None:
        return market_list(update, 'add_alert')
    chat = get_chat(update)
    if chat.market_id != market_id:
        chat.market_id = market_id
        session.commit()
    market = chat.market
    if price is None:
        text = "_Precio actual = {} {}_".format(market.ask, market.currency)
        update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN)
        return update.message.reply_text(ALERT_INPUT_TEXT,
                                         reply_markup=ForceReply())
    try:
        price = round(float(price), market.decimals)
        if price % 1 == 0:
            price = int(price)
        if price <= 0:
            raise ValueError
    except ValueError:
        update.message.reply_text("El precio debe ser un número mayor a 0.")
        return update.message.reply_text(ALERT_INPUT_TEXT,
                                         reply_markup=ForceReply())
    if chat.alert_count() == MAX_ALERT_NUMBER:
        text = "Lo siento, sólo puedes agregar un máximo de {} /alertas.".format(
            MAX_ALERT_NUMBER)
        return update.message.reply_text(text)
    market = chat.market
    alert = chat.get_alert(market, str(price))
    if alert is None:  # Create alert only if it doesn't exist
        alert_data = {
            'chat': chat,
            'market': market,
            'price': str(price),
            'trigger_on_lower': price <= float(market.ask)
        }
        alert = Alert(**alert_data)
        session.add(alert)
        session.commit()
    values = {
        'coin': market.coin,
        'sign': '<' if alert.trigger_on_lower else '>',
        'price': price,
        'currency': market.currency,
    }
    text = "Perfecto, te enviaré una alerta si\n*1 {coin} {sign} {price} {currency}*".format(
        **values)
    keyboard = [[
        InlineKeyboardButton("Añadir otra alerta",
                             callback_data='add_alert {}'.format(market.id)),
        InlineKeyboardButton("Ver alertas", callback_data='alert_list')
    ]]
    update.message.reply_text(text,
                              parse_mode=ParseMode.MARKDOWN,
                              reply_markup=InlineKeyboardMarkup(keyboard))
    def test_equality(self):
        a = ForceReply(True, False)
        b = ForceReply(False, False)
        c = ForceReply(True, True)
        d = ReplyKeyboardRemove()

        assert a == b
        assert hash(a) == hash(b)

        assert a != c
        assert hash(a) != hash(c)

        assert a != d
        assert hash(a) != hash(d)
Beispiel #7
0
def neue_erweiterung(update, context):
    if check_user(update.message.chat_id):
        if "group" in update.message.chat.type:
            try:
                context.bot.delete_message(update.message.chat_id,
                                           update.message.message_id)
            except BadRequest:
                handle_bot_not_admin(context.bot, update.message.chat_id)
            try:
                context.bot.send_message(update.message.from_user.id,
                                         'Hey, /neue_erweiterung kannst du im Gruppenchat '
                                         'nicht verwenden. Hier schon!')
            except Unauthorized:
                handle_bot_unauthorized(context.bot, update.message.chat_id,
                                        update.message.from_user.username,
                                        try_again='das Ganze im Privatchat')
        elif "private" in update.message.chat.type:
            msg = context.bot.send_message(update.message.chat_id,
                                           'Für welches Spiel hast du eine neue '
                                           'Erweiterung?\n'
                                           'Antworte mit /stop, um abzubrechen.',
                                           reply_markup=ForceReply())
            user_or_household_id = check_household(
                                    update.message.from_user.username)
            ForceReplyJobs().add_with_query(msg.message_id, "expansion_for",
                                            "new_expansion," +
                                            user_or_household_id)
    else:
        update.message.reply_text('Bitte authentifiziere dich zunächst '
                                  'mit /key.')
Beispiel #8
0
def expansion_for(update):
    if "/stop" in update.message.text:
        ForceReplyJobs().clear_query(
            update.message.reply_to_message.message_id)
        update.message.reply_text('Okay, hier ist nichts passiert.',
                                  reply_markup=ReplyKeyboardRemove())
    # find uuid, if owner does not have this game, return
    else:
        query = ForceReplyJobs().get_query(
            update.message.reply_to_message.message_id)
        uuid = dbf.search_uuid(update.message.from_user.username,
                               update.message.text)
        if uuid:
            msg = update.message.reply_text(
                'Wie heißt deine Erweiterung für ' + update.message.text +
                '?\n'
                'Antworte mit /stop, um abzubrechen.',
                reply_markup=ForceReply())
            query += "," + uuid  # query now has structure new_expansion, <owner>, <uuid>
            ForceReplyJobs().clear_query(
                update.message.reply_to_message.message_id)
            ForceReplyJobs().add_with_query(msg.message_id, "expansion_title",
                                            query)
        else:
            update.message.reply_text(
                'Mir ist nicht bekannt, dass du dieses '
                'Spiel hast. Du kannst es gerne mit '
                '/neues_spiel hinzufügen.',
                reply_markup=ReplyKeyboardRemove())
            ForceReplyJobs().clear_query(
                update.message.reply_to_message.message_id)
Beispiel #9
0
def start_command(update: Update, _: CallbackContext) -> None:
    """Send a message when the command /start is issued."""
    user = update.effective_user
    update.message.reply_markdown_v2(
        fr'Hi {user.mention_markdown_v2()}\!, use the /help command if you need to look at all the possible commands',
        reply_markup=ForceReply(selective=True),
    )
Beispiel #10
0
def add_edit_nick(update: Update, context: CallbackContext) -> int:  # SET_NICK
    """Adds or updates your nickname. Then goes back to main menu."""

    chat_id = update.effective_chat.id
    msg_id = update.message.message_id

    if 'nickname' not in context.user_data:
        context.user_data['nickname'] = []

    if any(bad_word in update.message.text.lower().split()
           for bad_word in prohibited):
        context.bot.send_message(
            chat_id=chat_id,
            reply_markup=ForceReply(selective=True),
            reply_to_message_id=msg_id,
            text=
            "See this language is embarrassing to me ok. I'm giving you one more chance "
            "that's it.")
        return SET_NICK

    else:
        context.user_data['nickname'].append(update.message.text)
        nicky = context.user_data['nickname'][-1]

        context.bot.send_message(chat_id=chat_id,
                                 text=f"Hi {nicky} what you're doing like",
                                 reply_to_message_id=msg_id,
                                 reply_markup=markup)

        logger(
            message=
            f"{update.effective_user.first_name} just changed their nickname to {nicky}."
        )

        return CHOICE
Beispiel #11
0
def add_points(update: Update, context):
    points = update.message.text
    try:
        int(points)
    except:
        # Telegram clients will display a reply interface to the user
        # (act as if the user has selected the bot’s message and tapped ‘Reply’)
        force_reply = ForceReply(force_reply=True, selective=True)
        update.message.reply_text(
            f'{points} is not a number. Please enter number 😊',
            reply_markup=force_reply)
        return POINTS
    else:

        context.user_data[POINTS] = points
        update.message.reply_text(
            f'Ok. Activity {context.user_data[ACTIVITY]} gives {context.user_data[POINTS]} points 😎',
            quote=False)

        # Saving activity to the database
        act = Activity(activity_name=context.user_data[ACTIVITY],
                       points=context.user_data[POINTS],
                       author_user_id=update.effective_user.id,
                       leaderboard_id=update.effective_chat.id)
        act.save_activity()

        # Get new user input
        return wait_for_input(update, context)
Beispiel #12
0
def menu(bot, update):
    query = update.callback_query
    chat_id = query.message.chat_id

    if format(query.data) == 'add':
        bot.send_message(chat_id, ADD_NAME_MESSAGE, reply_markup=ForceReply())
    elif format(query.data) == 'list':
        monitor_list = get_monitors(chat_id)

        if not monitor_list:
            bot.send_message(chat_id, 'You don\'t have any monitors active.')
        else:
            print_status(bot, chat_id, monitor_list)
    elif format(query.data) == 'stats':
        monitor_amount = bot_statistics['monitor_amount']
        user_amount = len(bot_statistics['users'])

        bot.send_message(chat_id, STATISTICS_MESSAGE_TEMPLATE.format(monitor_amount, user_amount))
    elif format(query.data) == 'delete':
        delete_confirmation_message(bot, chat_id)
    elif 'del_monitor_' in format(query.data):
        monitor_id = format(query.data).replace('del_monitor_', '')
        success, _ = db.find(monitoring_collection, {'_id': ObjectId(monitor_id)}, many=False)
        if success:
            db.delete(monitoring_collection, {'_id': ObjectId(monitor_id)})

            bot_statistics['monitor_amount'] -= 1
            decrease_or_delete_user_from_statistics(chat_id)
            bot.send_message(chat_id, 'Monitor deleted!')
        else:
            bot.send_message(chat_id, 'This monitor doesn\'t exist anymore.')

    query.answer()
Beispiel #13
0
    def send_reply(self,
                   message,
                   reply_markup=None,
                   dead_end=False,
                   expect_reply=False):
        """Sends a reply.  reply_markup can be used to append buttons; dead_end can be used instead of
        reply_markup to add just a '<< Main menu' button; expect_reply puts the user into reply mode (only
        has effect if reply_markup and dead_end are omitted)."""
        if not reply_markup:
            if dead_end:
                reply_markup = InlineKeyboardMarkup([[
                    InlineKeyboardButton('<< Main menu', callback_data='main')
                ]])
            elif expect_reply:
                reply_markup = ForceReply()

        if self.update.message:
            send = lambda msg, rmarkup: self.update.message.reply_markdown(
                msg, reply_markup=rmarkup, disable_web_page_preview=True)
        else:
            chat_id = self.update.callback_query.message.chat_id
            send = lambda msg, rmarkup: self.context.bot.send_message(
                chat_id=chat_id,
                text=msg,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=rmarkup,
                disable_web_page_preview=True)

        msgs = self.breakup_long_message(message, 4096)
        for msg in msgs[:-1]:
            send(msg, None)
        send(msgs[-1], reply_markup)
Beispiel #14
0
def subs_entry(update, context):

    update.effective_message.reply_text(
        st.TOSEARCHSUBS, reply_markup=ForceReply(selective=True),
    )

    return 1
Beispiel #15
0
def search(bot, update):
    global state
    state[update.message.chat_id] = (SEARCH, datetime.now())
    bot.sendMessage(update.message.chat_id,
                    text="Enter search query:",
                    reply_markup=ForceReply(selective=True),
                    reply_to_message_id=update.message.message_id)
Beispiel #16
0
    def start(self, bot, update):
        try:
            chat_type = update.message.chat.type
            if chat_type != "private":
                message = "You must send me this in a private chat"
                update.message.reply_text(message)
                return
            user_id = update.message.from_user.id
            user_username = update.message.from_user.username

            this_participant = self.session.query(Participant).filter(
                Participant.telegram_id == user_id).first()
            print("This Participant: " + str(this_participant))
            if this_participant is None:
                print("New Participant: " + str(user_id) + " " +
                      str(user_username))
                this_participant = Participant(telegram_id=user_id,
                                               telegram_username=user_username)
                self.session.add(this_participant)
                self.session.commit()
                message = "Hello! Lets get you setup!"
                bot.send_message(chat_id=this_participant.telegram_id,
                                 text=message)
                message = "What is your secret santa gift request? (Reply to this message to change it)"
                bot.send_message(chat_id=this_participant.telegram_id,
                                 text=message,
                                 reply_markup=ForceReply())
            else:
                message = "You are already setup. I have your gift request as: \n" + this_participant.gift_request
                bot.send_message(chat_id=this_participant.telegram_id,
                                 text=message)
        except Exception as this_ex:
            print(this_ex)
Beispiel #17
0
    def show_request(self, bot, update):
        try:
            chat_type = update.message.chat.type
            if chat_type != "private":
                message = "You must send me this in a private chat"
                update.message.reply_text(message)
                return
            user_id = update.message.from_user.id
            user_username = update.message.from_user.username

            this_participant = self.session.query(Participant).filter(
                Participant.telegram_id == user_id).first()
            print("This Participant: " + str(this_participant))
            if this_participant is None:
                message = "Send me a /start in a private message, then follow the instructions!"
                update.message.reply_text(message)
                return
            else:
                message = "I currently have your secret santa gift request as: \n" + this_participant.gift_request + "\n" \
                    "If that is correct, you can ignore the following message."
                bot.send_message(chat_id=this_participant.telegram_id,
                                 text=message)
                message = "What is your secret santa gift request? (Reply to this message to change it)"
                bot.send_message(chat_id=this_participant.telegram_id,
                                 text=message,
                                 reply_markup=ForceReply())
        except Exception as this_ex:
            print(this_ex)
Beispiel #18
0
def csv_import(update, context):
    if check_user(update.message.chat_id):
        if "group" in update.message.chat.type:
            try:
                context.bot.delete_message(update.message.chat_id,
                                           update.message.message_id)
            except BadRequest:
                handle_bot_not_admin(context.bot, update.message.chat_id)
            try:
                context.bot.send_message(update.message.from_user.id,
                                         'Hey, /csv_import kannst du im Gruppenchat '
                                         'nicht verwenden. Hier schon!')
            except Unauthorized:
                handle_bot_unauthorized(context.bot, update.message.chat_id,
                                        update.message.from_user.username,
                                        try_again='das Ganze im Privatchat')
        elif "private" in update.message.chat.type:
            msg = context.bot.send_message(update.message.chat_id,
                                           'Gib die Daten ein, die du im CSV-Format '
                                           'in die Spiele-Datenbank importieren '
                                           'möchtest.\n'
                                           'Format: Besitzer, Titel, Max. Spielerzahl, '
                                           'Kategorie_1, Kategorie_2, ... '
                                           'Pro Zeile ein Spiel',
                                           reply_markup=ForceReply())
            ForceReplyJobs().add(msg.message_id, "csv")
    else:
        update.message.reply_text('Bitte authentifiziere dich zunächst '
                                  'mit /key.')
Beispiel #19
0
def process_callback_query(update, context):
    _ = set_lang(update, context)
    query = update.callback_query
    data = query.data

    if CALLBACK_DATA not in context.user_data:
        context.user_data[CALLBACK_DATA] = set()

    if data not in context.user_data[CALLBACK_DATA]:
        context.user_data[CALLBACK_DATA].add(data)
        if data == SET_LANG:
            send_lang(update, context, query)
        elif data in LANGUAGES:
            store_lang(update, context, query)
        if data == PAYMENT:
            send_support_options_without_async(update, context, query)
        elif data in [THANKS, COFFEE, BEER, MEAL]:
            send_payment_invoice(update, context, query)
        elif data == CUSTOM:
            context.bot.send_message(
                query.from_user.id,
                _("Send me the amount that you'll like to support PDF Bot"),
                reply_markup=ForceReply(),
            )

        context.user_data[CALLBACK_DATA].remove(data)
Beispiel #20
0
def magic8ball(update: Update, context: CallbackContext) -> int:
    """Asks the user for the question."""

    chat_id = update.effective_chat.id
    name = get_nick(update, context)

    initiate = (
        "If you have a doubt, just type it here",
        f"{name}, are you confused? Ask me and I'll search for some sow...so..solutions"
        " okay?",
        "I can predict the future like you say . Just ask me. I'm just trying to find you option",
        "Fast fast no time ask me!", "See tell me what's the confusion",
        f"Yes {name}?")

    context.bot.send_chat_action(chat_id=chat_id, action='typing')
    sleep(1)
    # Sends message with a force reply
    context.bot.send_message(
        chat_id=chat_id,
        text=f"{r.choice(initiate)}🔮\nOr, type /cancel so I won't mind that\n"
        f"(Reply to this message for this to work!)",
        reply_markup=ForceReply(force_reply=True, selective=True),
        reply_to_message_id=update.message.message_id)

    logger(message=f"/8ball", command=True, update=update)

    del chat_id, name

    return PROCESSING  # Will go into first (and only) state in convo handler in main.py
Beispiel #21
0
def request_clock_out_description(update: Update, context: CallbackContext):
    chat_id = update.effective_chat.id
    try:
        user_info = get_user_info(chat_id)
        msg_id = int(user_info['msg_reply_id'])
        clock_out_date = user_info['clock_out_date']
    except KeyError:
        return

    if not update.effective_message.reply_to_message or update.effective_message.reply_to_message.message_id != msg_id:
        try:
            update.effective_message.bot.delete_message(chat_id=chat_id,
                                                        message_id=msg_id)
        except BadRequest:
            logger.warn(
                'The message to be replied has been deleted by the user, but we\'ll try again'
            )
        msg = send_markup_msg(update,
                              strings()['feedback:exit:insist_reply'],
                              ForceReply(), True)
        set_clock_out_msg_reply_id(chat_id, msg.message_id)
        raise DispatcherHandlerStop
    else:
        replied_entry_description(chat_id, update.effective_message.text,
                                  clock_out_date)
        send_markup_msg(update,
                        strings()['feedback:exit:acknowledgment'],
                        options_kbd(strings()))
        remove_msg_reply_id(chat_id)
        raise DispatcherHandlerStop
Beispiel #22
0
def archetype(update, context):
    """Search Cards in Archetype"""
    if context.args != None:
        if context.args == []:
            update.message.reply_text(
                "Send me the name of the archetype to search",
                reply_markup=ForceReply(selective=True))
            return ONE
        else:
            user_says = " ".join(context.args)

    else:
        user_says = update.message.text

    url = "https://db.ygoprodeck.com/api/v7/cardinfo.php?archetype=" + user_says + "&language=" + lang

    cards = jurl(url)
    if cards == 0:
        update.message.reply_text('Wrong Archetype Name!')
    else:
        list_matches = []
        for name in cards['data']:
            list_matches.append("[" + name['type'] + "]" + ": " + name['name'])
        update.message.reply_text('\n'.join(sorted(list_matches)))
    return ConversationHandler.END
Beispiel #23
0
def movie_entry(update, context):

    update.effective_message.reply_text(
        st.TOSEARCHMOVIE, reply_markup=ForceReply(selective=True),
    )

    return 1
Beispiel #24
0
def obtain(update, context):

    if context.args != None:
        if context.args == []:
            update.message.reply_text("Send me the name of the card to search",
                                      reply_markup=ForceReply(selective=True))
            return ONE
        else:
            user_says = " ".join(context.args)

    else:
        user_says = update.message.text

    url = "https://db.ygoprodeck.com/api/v7/cardinfo.php?name=" + user_says + "&language=" + lang

    page = requests.get(url)
    if page.status_code != 200:
        update.message.reply_text(
            "Can't find card, try with partial search /card")
    else:
        card_exact = json.loads(page.text)
        msg = ""
        for set in card_exact['data'][0]['card_sets']:
            msg += set['set_name'] + "\n"
        update.message.reply_text(
            "Card can be found in the following sets:\n" + msg)
    return ConversationHandler.END
Beispiel #25
0
def start(update: Update, context):

    update.message.reply_text('Ok, let\'s start')

    # Create Leaderboard if do not exists
    leaderboard = create_leaderboard(update, context)
    # Create/Update User
    user = create_user(update, context)
    # Add user to the Leaderboard
    add_participant(update, user, leaderboard)

    # Get leaderboard activities
    acitivity_exists = leaderboard_has_activities(
        leaderboard_id=leaderboard.id)

    if not acitivity_exists:
        # Telegram clients will display a reply interface to the user
        # (act as if the user has selected the bot’s message and tapped ‘Reply’)
        force_reply = ForceReply(force_reply=True)
        update.message.reply_text(
            'Seems there is no Activities. \nSend me the name of a first activity',
            reply_markup=force_reply,
            quote=False)
        return ACTIVITY
    else:
        return wait_for_input(update, context)
    def feed_back(self, update: Update, context: CallbackContext):

        text_private = 'Send your <b>feedback</b>.\n/feedbackme'
        update.effective_user.send_message(
            text=text_private, reply_markup=ForceReply(selective=True))
        logger.info("User /feedbackme")
        return REQUEST_FEEDBACK
Beispiel #27
0
def start(update: Update, _: CallbackContext) -> None:
    """Send a message when the command /start is issued."""
    user = update.effective_user
    update.message.reply_markdown_v2(
        fr'Hi {user.mention_markdown_v2()}\!',
        reply_markup=ForceReply(selective=True),
    )
Beispiel #28
0
def erweiterungen(update, context):
    if check_user(update.message.chat_id):
        if "group" in update.message.chat.type:
            try:
                context.bot.delete_message(update.message.chat_id,
                                           update.message.message_id)
            except BadRequest:
                handle_bot_not_admin(context.bot, update.message.chat_id)
            try:
                context.bot.send_message(update.message.from_user.id,
                                         'Hey, /erweiterungen kannst du im Gruppenchat '
                                         'nicht verwenden. Hier schon!')
            except Unauthorized:
                handle_bot_unauthorized(context.bot, update.message.chat_id,
                                        update.message.from_user.username,
                                        try_again='das Ganze im Privatchat')
        elif "private" in update.message.chat.type:
            msg = context.bot.send_message(update.message.chat_id,
                                           'Für welches Grundspiel fragst du?\n'
                                           'Antworte mit /stop, um abzubrechen.',
                                           reply_markup=ForceReply())
            ForceReplyJobs().add(msg.message_id, "expansions_list")
    else:
        update.message.reply_text('Bitte authentifiziere dich zunächst '
                                  'mit /key.')
Beispiel #29
0
def ask_feedback(bot: Bot, update: Update):
    update.message.reply_text(
        "Введите сообщение, которое будет отправлено создателю бота\n"
        "Бот принимает текст, изображения и документы\n"
        "Введите /cancel для отмены",
        reply_markup=ForceReply(selective=True))
    return 0
Beispiel #30
0
    def __init__(self,
                 session_name,
                 api_id,
                 api_hash,
                 phone_number,
                 updater=None):
        self.phone_number = phone_number
        self.client = TelegramClient(session_name,
                                     api_id,
                                     api_hash,
                                     update_workers=1,
                                     spawn_read_thread=True)
        self.client.connect()
        self._pinged_bots = []
        self._responses = {}
        self.botbuilders = []

        if not self.client.is_user_authorized():
            log.info("Sending code request...")
            self.client.send_code_request(phone_number)
            if updater:
                updater.bot.send_message(settings.ADMINS[0],
                                         CONFIRM_PHONE_CODE,
                                         reply_markup=ForceReply())
                updater.dispatcher.add_handler(MessageHandler(
                    Filters.reply & Filters.user(settings.ADMINS[0]),
                    lambda bot, update: authorization_handler(
                        bot, update, self)),
                                               group=3)
                self.pending_authorization = True
            else:
                self.client.send_code_request(phone_number)
                self.client.sign_in(phone_number, input('Enter code: '))
        else:
            self._initialize()