Exemplo n.º 1
0
    def more_info(self, bot: Bot, update: Update, trainer: Trainer, database: Database):
        dexnum = int(update.callback_query.data.replace(str(ButtonId.POKEDEX_MOREINFO), ""))

        # TODO optimize code
        dexterraw = Pokedex.get_all(database,
                                    columns = "id, trainerid",
                                    where = "id = " + str(dexnum),
                                    order = "id")
        rows = len(dexterraw)
        if rows != 0:
            data = Data.all_species[dexnum-1]
        if rows != 0:
            if data.type1 is not None:
                type1 = data.type1.name
            else:
                type1 = " - "
            if data.type2 is not None:
                type2 = data.type2.name
            else:
                type2 = " - "
            name = data.name
            text = data.pokedextext
        else:
            type1 = '???'
            type2 = '???'
            name = '???'
            text = '???'
        bot.answerCallbackQuery(callback_query_id = update.callback_query.id,
                                text = "Name: %s \nType 1: %s Type 2: %s\n%s" %
                                       (name, type1, type2, text), parse_mode = ParseMode.MARKDOWN, show_alert = True)
Exemplo n.º 2
0
    def wild_pokemon_popup(self, bot: Bot, update: Update):
        """displays information in a pop up"""
        text = "A WILD POKéMON APPEARS"

        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text=text,
                                show_alert=True)
Exemplo n.º 3
0
    def pages(self, bot: Bot, update: Update, trainer: Trainer, database: Database):
        """Sends Pokedex Entries as Pages to User"""

        data = update.callback_query.data
        num = int(data.replace(str(ButtonId.POKEDEX_PAGES), ""))
        result = ""
        if num == 1:
            result = self.getallentries(database, trainer.id, 1, 30)
        elif num == 31:
            result = self.getallentries(database, trainer.id, 31, 60)
        elif num == 61:
            result = self.getallentries(database, trainer.id, 61, 90)
        elif num == 91:
            result = self.getallentries(database, trainer.id, 91, 120)
        elif num == 121:
            result = self.getallentries(database, trainer.id, 121, 151)

        dex_but = [[InlineKeyboardButton("1-30", callback_data = str(ButtonId.POKEDEX_PAGES)+"1"),
                    InlineKeyboardButton("31-60", callback_data = str(ButtonId.POKEDEX_PAGES)+"31")],
                   [InlineKeyboardButton("61-90", callback_data = str(ButtonId.POKEDEX_PAGES)+"61"),
                    InlineKeyboardButton("91-120", callback_data = str(ButtonId.POKEDEX_PAGES)+"91")],
                   [InlineKeyboardButton("121-151", callback_data = str(ButtonId.POKEDEX_PAGES)+"121")],
                   [InlineKeyboardButton("⏪ Pokedex", callback_data = str(ButtonId.PROFILE_POKEDEX))]]
        dex_keys = InlineKeyboardMarkup(dex_but)

        try:
            bot.edit_message_text(text = result,
                                  chat_id = update.callback_query.message.chat_id,
                                  message_id = update.callback_query.message.message_id,
                                  reply_markup = dex_keys)
        except TelegramError:
            bot.answerCallbackQuery(callback_query_id = update.callback_query.id,
                                    text = "You are already here...",
                                    show_alert = False)
        pass
Exemplo n.º 4
0
    def on_show_click(cls, bot: telegram.Bot, _: telegram.Update,
                      query: telegram.CallbackQuery, data) -> None:
        spoiler: Spoiler = cache.get(cls.__get_key(data['spoiler_id']))
        if not spoiler:
            bot.answer_callback_query(
                query.id,
                f"Ошибка. Не могу найти спойлер {data['spoiler_id']}",
                show_alert=True)
            return

        uid = query.from_user.id
        if len(spoiler.body) <= 200:
            bot.answer_callback_query(query.id, spoiler.body, show_alert=True)
            logger.info(
                f'[spoiler] {uid} show popup spoiler {spoiler.spoiler_id}')
            return

        bot.answerCallbackQuery(query.id,
                                url=f"t.me/{bot.username}?start={query.data}")
        if not spoiler.show(bot, uid):
            cls.__cant_send(bot, query.message.chat_id, uid,
                            spoiler.spoiler_id)
            return
        logger.info(
            f'[spoiler] {uid} show private spoiler {spoiler.spoiler_id}')
Exemplo n.º 5
0
def callback_handler(bot: telegram.Bot, update: telegram.Update) -> None:
    query = update.callback_query
    data = cache.get(f'callback:{query.data}')
    if not data:
        return
    if data['name'] == '/off':
        bot.answerCallbackQuery(query.id)
        callback_off(bot, update, query, data)
        return
    if data['name'] == 'last_word':
        bot.answerCallbackQuery(query.id,
                                url=f"t.me/{bot.username}?start={query.data}")
        callback_last_word(bot, update, query, data)
        return
    if data['name'] == 'dayof':
        DayOfManager.callback_handler(bot, update, query, data)
        return
    if data['name'] == 'bayanometer_show_orig':
        Bayanometer.callback_handler(bot, update, query, data)
        return
    if data['name'] == 'spoiler':
        SpoilerHandlers.callback_handler(bot, update, query, data)
        return
    if data['name'] == 'matshowtime':
        MatshowtimeHandlers.callback_handler(bot, update, query, data)
        return
    if data['name'] == 'i_stat':
        istat_callback_handler(bot, update, query, data)
        return
Exemplo n.º 6
0
def delete_message(bot: Bot, update: Update):
    "deletes Message and Prints Error-Message if user Clicks to fast"
    try:
        update.callback_query.message.delete()
    except TelegramError:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Don't click that fast...",
                                show_alert=False)
Exemplo n.º 7
0
 def callback_handler(cls, bot: telegram.Bot, uid, cid, _, data, query: telegram.CallbackQuery) -> None:
     orig: URL = data['orig']
     try:
         bot.forward_message(uid, cid, message_id=orig.message_id)
         bot.answer_callback_query(query.id, url=f"t.me/{bot.username}?start={query.data}")
     except Exception:
         text = f'Не могу отправить сообщение. Нажми Start в личке бота @{bot.username} и попробуй вновь'
         bot.answerCallbackQuery(query.id, text, show_alert=True)
Exemplo n.º 8
0
 def heal_no(self, bot: Bot, update: Update, trainer: Trainer,
             database: Database):
     trainer.menu_id = MenuId.MAIN_MENU
     trainer.update_values(database, "menu_id")
     try:
         update.callback_query.message.delete()
     except TelegramError:
         bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                 text="Don't click that fast...",
                                 show_alert=False)
     bot.send_message(
         Trainer.id,
         "We hope to see you again! Write or click on /handler to show the handler"
     )
Exemplo n.º 9
0
    def information_popup(self, bot: Bot, update: Update, trainer: Trainer,
                          database: Database):
        """displays information in a pop up"""
        trainer.load_values(database,
                            "game_pos_x, game_pos_y, game_location_id")
        interact = False
        actual_location = get_map().get_location_by_id(
            trainer.game_location_id)


        text = "You're currently here: " + actual_location.name + "\n\n" + actual_location.description + "\n" + \
        "_________\n🆗: Interact\n🔄: Warp to next location"

        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                show_alert=True)
Exemplo n.º 10
0
 def callback_handler(cls, bot: telegram.Bot, uid, cid, button_msg_id, data, query: telegram.CallbackQuery) -> None:
     url = data['url']
     orig_photo: Photo = data['orig_photo']
     orig_msg_id = orig_photo.message_id
     try:
         cache_key = f'{KEY_PREFIX}:callback_answer:{button_msg_id}'
         cached = cache.get(cache_key)
         if cached:
             msg = cached
         else:
             compare_hashes = cls.__compare_hashes(url, cid, orig_msg_id)
             orig_time = f'Оригинал запощен {orig_photo.date.strftime("%Y-%m-%d %H:%M")}'
             msg = f'Хеши баянистого изображения:\n\n{compare_hashes}\n\n{orig_time}'
             cache.set(cache_key, msg, time=USER_CACHE_EXPIRE)
         bot.send_message(uid, msg, parse_mode=telegram.ParseMode.HTML)
         bot.forward_message(uid, cid, message_id=orig_msg_id)
         bot.answer_callback_query(query.id, url=f"t.me/{bot.username}?start={query.data}")
     except Exception:
         text = f'Не могу отправить сообщение. Нажми Start в личке бота @{bot.username} и попробуй вновь'
         bot.answerCallbackQuery(query.id, text, show_alert=True)
Exemplo n.º 11
0
    def on_mig_click(cls, bot: telegram.Bot, _: telegram.Message,
                     query: telegram.CallbackQuery, data):
        uid = query.from_user.id
        card: Card = cache.get(cls.__get_key(data['card_id']))
        if not card:
            bot.answer_callback_query(
                query.id,
                f"Ошибка. Не могу найти открытку #{data['card_id']}",
                show_alert=True)
            return

        if uid != card.to_uid:
            bot.answerCallbackQuery(
                query.id, 'Только адресат валентинки может подмигнуть 💔')
            return

        if uid in card.mig_uids:
            if User.get(uid).female:
                text = 'Подруга, ты уже подмигивала 💆'
            else:
                text = 'Дружище, ты уже подмигивал 💆‍♂️'
            bot.answerCallbackQuery(query.id, text)
            return

        card.mig_uids.append(uid)
        cache.set(cls.__get_key(card.card_id), card, time=USER_CACHE_EXPIRE)
        bot.answerCallbackQuery(query.id, 'Подмигивание прошло успешно')
        Stats.total_migs.incr()
        Stats.migs_users.add(uid)
        user = User.get(uid)
        username = user.get_username_or_link()
        ReactionNotification.send(bot, card.from_uid,
                                  f"{username} подмигивает тебе ❤", card)
        cls.__set_card_preview_as_done(bot, card)
Exemplo n.º 12
0
 def pickuppkmn(self, bot: Bot, update: Update, trainer: Trainer,
                database: Database):
     trainer.get_values(database, "blocktimer")
     blocktime = trainer.blocktimer
     if blocktime <= dt.datetime.now():
         bot.send_message(
             Trainer.id,
             text=
             """Thank you! Your Pokémon are fighting fit! We hope to see you again! Hehe... What? I'm not a s****t... Click or write /handler to show the handler!"""
         )
         # d.cmd("UPDATE trainer SET blocktimer = NULL WHERE id = %s;", (cid,))
         trainer.blocktime = None
         trainer.menu_id = 3
         trainer.update_values(database, "menu_id, blocktimer")
         pass
     else:
         waitfor = blocktime - dt.datetime.now()
         minutes = (waitfor.days * 1440) + (waitfor.seconds /
                                            60) + 1  # + waitfor.minute
         bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                 text="Wait for %d min..." % minutes,
                                 show_alert=False)
Exemplo n.º 13
0
    def on_revn_click(cls, bot: telegram.Bot, _: telegram.Message,
                      query: telegram.CallbackQuery, data) -> None:
        uid = query.from_user.id
        card: Card = cache.get(cls.__get_key(data['card_id']))
        if not card:
            bot.answer_callback_query(
                query.id,
                f"Ошибка. Не могу найти открытку #{data['card_id']}",
                show_alert=True)
            return

        # уже ревновали?
        if uid in card.revn_uids:
            if User.get(uid).female:
                text = 'Подруга, да забудь ты про эту сучку 🍸'
            else:
                text = 'Дружище, да забей ты на эту сучку 🍺'
            bot.answerCallbackQuery(query.id, text)
            return

        card.revn_uids.append(uid)
        cache.set(cls.__get_key(card.card_id), card, time=USER_CACHE_EXPIRE)
        Stats.total_revn.incr()
        Stats.revn_users.add(uid)
        user = User.get(uid)
        if uid == card.to_uid:
            bot.answerCallbackQuery(query.id, 'Саша, ты? 👸')
        else:
            if user.female:
                text = 'Вот она сучка, да? Уж мы-то ей покажем 👗'
            else:
                text = 'Ха! Мы-то с тобой знаем, кто тут круче всех 👑'
            bot.answerCallbackQuery(query.id, text)

        username = user.get_username_or_link()
        to_username = '' if not User.get(card.to_uid) else User.get(
            card.to_uid).get_username_or_link()
        ReactionNotification.send(bot, card.to_uid,
                                  f"{username} ревнует к валентинке для тебя",
                                  card)
        ReactionNotification.send(bot, card.from_uid,
                                  f"{username} ревнует к {to_username}", card)
        cls.__update_buttons(bot, card)
Exemplo n.º 14
0
def inlinekeyboard(bot: Bot, update):
    """Seleziona un preset dalla tastiera."""
    game = findgamebyid(update.callback_query.message.chat.id)
    if game is None:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text=s.error_no_games_found,
                                show_alert=True)
        return
    if game.phase is 'Preset':
        if update.callback_query.from_user.id != game.admin.tid:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text=s.error_not_admin,
                                    show_alert=True)
            return
        game.loadpreset(update.callback_query.data)
        bot.answerCallbackQuery(
            callback_query_id=update.callback_query.id,
            text=s.preset_selected.format(selected=update.callback_query.data))
    elif game.phase is 'Voting':
        # Controlla che non sia il primo giorno
        if game.day <= 1:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text=s.error_no_votes_on_first_day,
                                    show_alert=True)
            return
        # Trova il giocatore
        player = game.findplayerbyid(update.callback_query.from_user.id)
        if player is None:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text=s.error_not_in_game,
                                    show_alert=True)
            return
        # Controlla che sia vivo
        if not player.alive:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text=s.error_dead,
                                    show_alert=True)
            return
        if update.callback_query.data == "-":
            # Annulla il voto
            player.votingfor = None
            game.message(s.vote_none.format(player=player))
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text=s.vote_none_fp)
        else:
            # Cambia il voto
            target = game.findplayerbyusername(update.callback_query.data)
            player.votingfor = target
            game.message(
                s.vote.format(voting=player.tusername, voted=target.tusername))
            bot.answerCallbackQuery(
                callback_query_id=update.callback_query.id,
                text=s.vote_fp.format(voted=target.tusername))
        # Aggiorna i voti
        game.updatevotes()
        mostvoted = game.mostvotedplayers()
        # Aggiorna la tastiera
        table = list()
        for player in game.players:
            if not player.alive:
                continue
            if player in mostvoted:
                status_icon = s.status_most_voted
            else:
                status_icon = s.status_normal_voted
            row = list()
            row.append(
                InlineKeyboardButton(s.vote_keyboard_line.format(
                    status=status_icon, player=player, votes=player.votes),
                                     callback_data=player.tusername))
            table.append(row)
        row = list()
        row.append(
            InlineKeyboardButton(s.vote_keyboard_nobody, callback_data="-"))
        table.append(row)
        keyboard = InlineKeyboardMarkup(table)
        # Manda la tastiera
        bot.editMessageReplyMarkup(game.groupid,
                                   game.votemsg.message_id,
                                   reply_markup=keyboard)
Exemplo n.º 15
0
def inlinekeyboard(bot: Bot, update):
    """Seleziona un preset dalla tastiera."""
    game = findgamebyid(update.callback_query.message.chat.id)
    if game is None:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.error_no_games_found, show_alert=True)
        return
    if game.phase is 'Preset':
        if update.callback_query.from_user.id != game.admin.tid:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.error_not_admin, show_alert=True)
            return
        game.loadpreset(update.callback_query.data)
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.preset_selected.format(selected=update.callback_query.data))
    elif game.phase is 'Voting':
        # Controlla che non sia il primo giorno
        if game.day <= 1:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.error_no_votes_on_first_day, show_alert=True)
            return
        # Trova il giocatore
        player = game.findplayerbyid(update.callback_query.from_user.id)
        if player is None:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.error_not_in_game, show_alert=True)
            return
        # Controlla che sia vivo
        if not player.alive:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.error_dead, show_alert=True)
            return
        if update.callback_query.data == "-":
            # Annulla il voto
            player.votingfor = None
            game.message(s.vote_none.format(player=player))
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.vote_none_fp)
        else:
            # Cambia il voto
            target = game.findplayerbyusername(update.callback_query.data)
            player.votingfor = target
            game.message(s.vote.format(voting=player.tusername, voted=target.tusername))
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text=s.vote_fp.format(voted=target.tusername))
        # Aggiorna i voti
        game.updatevotes()
        mostvoted = game.mostvotedplayers()
        # Aggiorna la tastiera
        table = list()
        for player in game.players:
            if not player.alive:
                continue
            if player in mostvoted:
                status_icon = s.status_most_voted
            else:
                status_icon = s.status_normal_voted
            row = list()
            row.append(InlineKeyboardButton(s.vote_keyboard_line.format(status=status_icon, player=player, votes=player.votes),
                                            callback_data=player.tusername))
            table.append(row)
        row = list()
        row.append(InlineKeyboardButton(s.vote_keyboard_nobody, callback_data="-"))
        table.append(row)
        keyboard = InlineKeyboardMarkup(table)
        # Manda la tastiera
        bot.editMessageReplyMarkup(game.groupid, game.votemsg.message_id, reply_markup=keyboard)
Exemplo n.º 16
0
def FLOOD_EDITBTN(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    print("User {} clicked button FLOOD EDIT".format(user.id))
    qdata = query.data.split("=")[1].split("|")[0]
    chat_id = query.data.split("|")[1]
    if qdata == "?":
        bot.answerCallbackQuery(
            query.id,
            "Batas dari pesan beruntun. Jika pengguna mengirim pesan lebih dari batas, maka akan langsung di banned.",
            show_alert=True)
    if qdata == "-":
        button = []
        limit = sql.get_flood_limit(chat_id)
        limit = int(limit) - 1
        if limit == 0:
            status = "❎ Tidak Aktif"
        else:
            status = "✅ Aktif"
        if limit <= 2:
            bot.answerCallbackQuery(query.id,
                                    "Batas limit Tidak boleh kurang dari 3",
                                    show_alert=True)
            return
        sql.set_flood(chat_id, int(limit))
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Anti Pesan Beruntun*:\n\n".format(
            escape_markdown(chat.title))
        text += "Batas maksimal pesan beruntun telah di setel menjadi `{}`.".format(
            limit)
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_flim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_flim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_flim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format(status),
                callback_data="set_flim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)
    if qdata == "+":
        button = []
        limit = sql.get_flood_limit(chat_id)
        limit = int(limit) + 1
        if limit == 0:
            status = "❎ Tidak Aktif"
        else:
            status = "✅ Aktif"
        if limit <= 0:
            bot.answerCallbackQuery(query.id,
                                    "Batas limit Tidak boleh kurang dari 0",
                                    show_alert=True)
            return
        sql.set_flood(chat_id, int(limit))
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Anti Pesan Beruntun*:\n\n".format(
            escape_markdown(chat.title))
        text += "Batas maksimal pesan beruntun telah di setel menjadi `{}`.".format(
            limit)
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_flim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_flim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_flim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format(status),
                callback_data="set_flim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)
    if qdata == "exec":
        button = []
        limit = sql.get_flood_limit(chat_id)
        if limit == 0:
            sql.set_flood(chat_id, 3)
            limit = 3
            status = "✅ Aktif ({})".format(limit)
        else:
            sql.set_flood(chat_id, 0)
            limit = 0
            status = "❎ Tidak Aktif"
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Anti Pesan Beruntun*:\n\n".format(
            escape_markdown(chat.title))
        text += "Batas maksimal pesan beruntun telah di setel menjadi `{}`.".format(
            status)
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_flim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_flim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_flim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format(status),
                callback_data="set_flim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)
Exemplo n.º 17
0
class CryptoCoinBot(object):
    def __init__(self, token):

        # Creating the Updater and the dispatcher:
        self.logger = logging.getLogger(__name__)
        self.bot = Bot(token)
        self.updater = Updater(token)
        dp = self.updater.dispatcher

        # Adding some CommandHandlers:
        dp.add_handler(CommandHandler("start", self.start))
        dp.add_handler(CommandHandler("help", self.help))

        # This CommandHandler will receive arguments from the user:
        dp.add_handler(CommandHandler("search", self.search, pass_args=True))
        dp.add_handler(CommandHandler("list", self.get_list))

        # These will handler callback queries and inline queries:
        dp.add_handler(CallbackQueryHandler(self.callback_query_handler))
        dp.add_handler(InlineQueryHandler(self.inline_query_handler))

        # Log all errors:
        dp.add_error_handler(self.error)

    def start_polling(self):
        """starts the polling to run the bot."""

        self.updater.start_polling()
        self.updater.idle()

    def error(self, bot, update, err):
        """Logs all errors."""

        self.logger.warning("update {0} caused error {1}" % (update, err))

    def start(self, bot, update):
        """Handlers the 'start' command."""

        chat_id = update.message.chat_id
        self.send_message(chat_id,
                          templates.Texts.START,
                          parse_mode=ParseMode.HTML)

    def help(self, bot, update):
        """Handlers the 'help' command."""

        chat_id = update.message.chat_id
        self.send_message(chat_id,
                          templates.Texts.HELP,
                          parse_mode=ParseMode.HTML)

    def search(self, bot, update, args=None):
        """Handlers the 'price' command.""

        This command is meant to get the data about the cryptocurrency that
        the user specifies with arguments. If the user doesn't specify a
        cryptocurrency, the function will sent a menu of buttons in order to
        choose a cryptocurrency"""

        chat_id = update.message.chat_id

        # Requesting the price for the given cryptocurrency ID:
        try:
            results = CryptoCoinMarket().ticker()

        except CryptoCoinMarket.ERROR:
            self.send_message(chat_id, templates.Texts.ERROR)
            return

        # Checking if the user specified a cryptocurrency:
        if not args:
            l = len(results)
            n = l / 50 if l % 50 == 0 else l / 50 + 1
            rows = [
                InlineKeyboardButton(
                    text="%s %s" % (templates.LabelButtons.PAG, i + 1),
                    switch_inline_query_current_chat="+p %s" % (i + 1))
                for i in range(n)
            ]
            grid = [rows]
            reply_markup = InlineKeyboardMarkup(grid)
            self.send_message(chat_id,
                              templates.Texts.PRESS_BUTTON,
                              reply_markup=reply_markup,
                              parse_mode=ParseMode.HTML)
            return

        # Joining all of the arguments to create an unique ID:
        data = "-".join(args).lower()

        # Searching:
        found = None
        for result in results:
            if data == result.id or data == result.symbol.lower():
                found = result
                break

        if not found:
            self.send_message(chat_id, templates.Texts.NO_SUPPORTED)
            return

        # Preparing and sending the answer:
        text = templates.create_summary(found)
        button = InlineKeyboardButton(text=templates.LabelButtons.REFRESH,
                                      callback_data="refresh;%s" %
                                      found.symbol)
        grid = [[button]]
        reply_markup = InlineKeyboardMarkup(grid)

        self.send_message(chat_id,
                          text,
                          reply_markup=reply_markup,
                          parse_mode=ParseMode.HTML)

    def get_list(self, bot, update):
        """Handlers for the 'list' command.

        This command is meant to send a top list about the capitalization
        of cryptocurrencies. By default, the top value is set to 10, but the
        user is also allowed to choose among top 30, top 50 and top 100"""

        chat_id = update.message.chat_id
        try:
            results = CryptoCoinMarket().ticker()

        except CryptoCoinMarket.ERROR:
            self.send_message(chat_id, templates.Texts.ERROR)
            return

        text = templates.create_top_list(results, top=10)
        b1 = InlineKeyboardButton(text=templates.LabelButtons.TOP_10,
                                  callback_data="top;10")
        b2 = InlineKeyboardButton(text=templates.LabelButtons.TOP_30,
                                  callback_data="top;30")
        b3 = InlineKeyboardButton(text=templates.LabelButtons.TOP_50,
                                  callback_data="top;50")
        b4 = InlineKeyboardButton(text=templates.LabelButtons.TOP_100,
                                  callback_data="top;100")
        grid = [[b1, b2], [b3, b4]]
        reply_markup = InlineKeyboardMarkup(grid)

        self.send_message(chat_id,
                          text,
                          reply_markup=reply_markup,
                          parse_mode=ParseMode.HTML)

    def callback_query_handler(self, bot, update):
        """Handlers the callback_queries through an imported function."""

        components.callback_query_handler(self, bot, update)

    def inline_query_handler(self, bot, update):
        """Handlers the inline_queries through an imported function."""

        components.inline_query_handler(self, bot, update)

    @run_async
    def send_message(self, *args, **kwargs):
        """Runs this TelegramBot method in a separated thread."""

        self.bot.sendMessage(*args, **kwargs)

    @run_async
    def edit_message_text(self, *args, **kwargs):
        """Runs this TelegramBot method in a separated thread."""

        self.bot.editMessageText(*args, **kwargs)

    @run_async
    def answer_inline_query(self, *args, **kwargs):
        """Runs this TelegramBot method in a separated thread."""

        self.bot.answerInlineQuery(*args, **kwargs)

    @run_async
    def answer_callback_query(self, *args, **kwargs):
        """Runs this TelegramBot method in a separated thread."""

        self.bot.answerCallbackQuery(*args, **kwargs)
Exemplo n.º 18
0
def not_implemented_yet(bot: Bot, update: Update, trainer: Trainer):
    bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                            text="Not implemented yet",
                            parse_mode=ParseMode.MARKDOWN,
                            show_alert=True)
Exemplo n.º 19
0
def WARN_EDITBTN(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    print("User {} clicked button WARN EDIT".format(user.id))
    qdata = query.data.split("=")[1].split("|")[0]
    chat_id = query.data.split("|")[1]
    if qdata == "?":
        bot.answerCallbackQuery(
            query.id,
            "Batas dari peringatan. Jika peringatan melewati batas maka akan di eksekusi.",
            show_alert=True)
    if qdata == "-":
        button = []
        limit, soft_warn = sql.get_warn_setting(chat_id)
        limit = int(limit) - 1
        if limit <= 2:
            bot.answerCallbackQuery(query.id,
                                    "Batas limit Tidak boleh kurang dari 3",
                                    show_alert=True)
            return
        sql.set_warn_limit(chat_id, int(limit))
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Peringatan*:\n\n".format(
            escape_markdown(chat.title))
        text += "Batas maksimal peringatan telah di setel menjadi `{}`. Dibutuhkan `{}` peringatan " \
           "sebelum pengguna akan mendapatkan *{}*.".format(limit, limit, "tendangan" if soft_warn else "pemblokiran")
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_wlim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_wlim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_wlim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format("❎ Tendang" if soft_warn else "⛔️ Blokir"),
                callback_data="set_wlim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)
    if qdata == "+":
        button = []
        limit, soft_warn = sql.get_warn_setting(chat_id)
        limit = int(limit) + 1
        if limit <= 0:
            bot.answerCallbackQuery(query.id,
                                    "Batas limit Tidak boleh kurang dari 0",
                                    show_alert=True)
            return
        sql.set_warn_limit(chat_id, int(limit))
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Peringatan*:\n\n".format(
            escape_markdown(chat.title))
        text += "Batas maksimal peringatan telah di setel menjadi `{}`. Dibutuhkan `{}` peringatan " \
           "sebelum pengguna akan mendapatkan *{}*.".format(limit, limit, "tendangan" if soft_warn else "pemblokiran")
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_wlim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_wlim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_wlim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format("❎ Tendang" if soft_warn else "⛔️ Blokir"),
                callback_data="set_wlim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)
    if qdata == "exec":
        button = []
        limit, soft_warn = sql.get_warn_setting(chat_id)
        if soft_warn:
            exc = "Blokir"
            sql.set_warn_strength(chat_id, False)
            soft_warn = False
        else:
            exc = "Tendang"
            sql.set_warn_strength(chat_id, True)
            soft_warn = True
        chat = bot.get_chat(chat_id)
        text = "*{}* memiliki pengaturan berikut untuk modul *Peringatan*:\n\n".format(
            escape_markdown(chat.title))
        text += "Pengguna akan di `{}` jika sudah diluar batas peringatan. Dibutuhkan `{}` peringatan " \
           "sebelum pengguna akan mendapatkan *{}*.".format(exc, limit, "tendangan" if soft_warn else "pemblokiran")
        button.append([
            InlineKeyboardButton(
                text="➖", callback_data="set_wlim=-|{}".format(chat_id)),
            InlineKeyboardButton(
                text="Limit {}".format(limit),
                callback_data="set_wlim=?|{}".format(chat_id)),
            InlineKeyboardButton(text="➕",
                                 callback_data="set_wlim=+|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="{}".format("❎ Tendang" if soft_warn else "⛔️ Blokir"),
                callback_data="set_wlim=exec|{}".format(chat_id))
        ])
        button.append([
            InlineKeyboardButton(
                text="Kembali", callback_data="stngs_back({})".format(chat_id))
        ])
        query.message.edit_text(text=text,
                                parse_mode=ParseMode.MARKDOWN,
                                reply_markup=InlineKeyboardMarkup(button))
        bot.answer_callback_query(query.id)