예제 #1
0
def answerBackQuery(update, context):
    query = update.callback_query
    CallbackQuery.answer(query)
    query.edit_message_text(
        text="*Available packages for your search query :*",
        parse_mode=ParseMode.MARKDOWN_V2,
        reply_markup=result_keyboard)
예제 #2
0
def draft_heart_button_click_handler(bot: telegram.Bot, _: telegram.Update,
                                     query: telegram.CallbackQuery,
                                     data) -> None:
    """
    Обработчик кнопки выбора сердечка
    """
    user_id = query.from_user.id

    draft: Optional[CardDraftSelectHeart] = cache.get(
        f'{CACHE_PREFIX}:draft:card:{user_id}')
    if draft is None or not isinstance(draft, CardDraftSelectHeart):
        query.answer(text='Черновик не найден')
        query.message.delete()
        return

    heart: str = data['heart']
    chat_names = {
        chat.chat_id: get_chat_title(bot, chat.chat_id)
        for chat in draft.from_user.chats
    }
    answer = draft.select_heart(heart, chat_names)
    answer.original_draft_message_id = draft.original_draft_message_id

    cache.set(f'{CACHE_PREFIX}:draft:card:{user_id}', answer, time=TWO_DAYS)
    query.edit_message_text(text=answer.get_message_text(), parse_mode=HTML)
    query.edit_message_reply_markup(
        reply_markup=get_reply_markup(answer.get_message_buttons()))
    query.answer()
예제 #3
0
def mig_button_click_handler(bot: telegram.Bot, _: telegram.Update,
                             query: telegram.CallbackQuery, __) -> None:
    """
    Обработчик кнопки подмигивания
    """
    store = Store(query)
    if not store.load():
        return
    store.card = cast(Card, store.card)

    button_name = 'mig_clicked'
    result = store.card.mig(store.user_id, store.is_already_clicked(button_name),
                            get_username_or_link(store.user_id))

    query.answer(result.text)
    if result.success:
        store.mark_as_already_clicked(button_name)
        with StatsRedis.lock:
            with StatsRedis() as stats:
                stats.add_mig(store.card, store.user_id)
        try:
            bot.send_message(store.card.from_user.user_id, result.notify_text, parse_mode=HTML,
                             reply_to_message_id=store.card.original_draft_message_id)
        except Exception:
            pass
        sleep(0.8)
        try:
            bot.edit_message_text(f'✅ Тебе подмигнули!', store.card.from_user.user_id, store.card.status_message_id)
        except Exception:
            pass
예제 #4
0
파일: bot.py 프로젝트: sunyi00/PlayTRPGBot
def timer_next_callback(job_queue: JobQueue, query: telegram.CallbackQuery,
                        data: str):
    [_, timer, comment] = data.rsplit(':', 2)
    try:
        timer = int(timer)
        comment = base64.b64decode(comment).decode()
        if len(comment) > 128:
            raise ValueError()
    except ValueError:
        query.answer("wrong timer callback arguments")
    timer_message(job_queue, query.message.chat_id, timer, comment)
    query.answer()
예제 #5
0
def cancel_roadblock(bot: Bot, query: CallbackQuery) -> None:
    if query.message.chat.id == mods_chat:
        nmaps_message = retrieve_roadblock(mods_id=query.message.message_id)
    else:
        if query.from_user.last_name not in roads_staff:
            query.answer(BOT_NOT_ROAD_STAFF)
            return
        nmaps_message = retrieve_roadblock(roads_id=query.message.message_id)
    bot.send_message(nmaps_message.chat_id,
                     BOT_REQUEST_CANCELLED_USR,
                     reply_to_message_id=nmaps_message.chat_message_id)
    query.edit_message_text(BOT_REQUEST_CANCELLED.format(
        query.from_user.name, query.from_user.id),
                            parse_mode='markdown')
예제 #6
0
def show_post_statistics(query: CallbackQuery, post_id: ObjectId) -> None:
    try:
        post = db.models.find_post(post_id)
    except:
        LOGGER.error(
            f"Could not find post {post_id} on statistics button click")
        query.answer(text="Post has not been found. "
                     "Approach the developer.",
                     show_alert=False)
        return

    clicks_count, correct_clicks_count = db.models.count_post_clicks(post)
    query.answer(
        text=f"Правильных ответов: {correct_clicks_count} / {clicks_count}",
        show_alert=True)
예제 #7
0
def round_inline_callback(bot: telegram.Bot, query: telegram.CallbackQuery,
                          gm: bool):
    game_round = Round.objects.filter(chat_id=query.message.chat_id).first()

    def _(t: Text):
        get_by_user(t, query.from_user)

    if not isinstance(game_round, Round):
        query.answer(show_alert=True, text=_(Text.GAME_NOT_IN_ROUND))
        return
    try:
        with transaction.atomic():
            round_inline_handle(bot, query, gm, game_round)
    except NotGm:
        query.answer(show_alert=True, text=_(Text.NOT_GM), cache_time=0)
예제 #8
0
def round_inline_handle(bot: telegram.Bot, query: telegram.CallbackQuery,
                        gm: bool, game_round: Round):
    _ = partial(get_by_user, user=query.from_user)

    method = str(query.data)
    actors = game_round.get_actors()
    if method == 'round:next':
        next_count = game_round.counter + 1
        if next_count >= len(actors):
            next_count = 0
            game_round.round_counter += 1
        game_round.counter = next_count
        game_round.save()
        query.answer()
        refresh_round_message(bot, game_round, _)
    elif method == 'round:prev':
        prev_count = game_round.counter - 1
        if prev_count < 0:
            if game_round.round_counter <= 1:
                query.answer(text=_(Text.ALREADY_FIRST_TURN))
                return
            else:
                prev_count = len(actors) - 1
                game_round.round_counter -= 1
        game_round.counter = prev_count
        query.answer()
        refresh_round_message(bot, game_round, _, refresh=True)
        game_round.save()
    elif method == 'round:remove':
        if not gm:
            raise NotGm()

        actors = game_round.get_actors()
        if len(actors) > 1:
            current = actors[game_round.counter % len(actors)]
            current.delete()
            query.answer()
            refresh_round_message(bot, game_round, _, refresh=True)
        else:
            query.answer(show_alert=True, text=_(Text.AT_LEAST_ONE_ACTOR))
    elif method == 'round:finish':
        if not gm:
            raise NotGm()
        query.edit_message_text(_(Text.ROUND_ALREADY_FINISHED))
        remove_round(bot, game_round.chat_id)
예제 #9
0
def answerCallback(update, context):
    query = update.callback_query
    finalQuery = str(query.data).replace("callback_", "")
    data = fetch_pkg(finalQuery)

    version = data['version']
    description = data['description'].rstrip()
    pubdev_url = "https://pub.dev/packages/" + data['name']
    github_url = data['homepage']

    msg_string = f"""*Package name :* `{finalQuery}`\n*Latest version :* `{version}`
                    \n*Description :* `{description}`\n\n*Pubspec :* `{finalQuery} ^{version}`
                """
    CallbackQuery.answer(query)
    keyboard = [[
        InlineKeyboardButton("Github", url=github_url),
        InlineKeyboardButton("Pub.dev", url=pubdev_url),
        InlineKeyboardButton("Back", callback_data="back"),
    ]]
    query.edit_message_text(text=msg_string,
                            parse_mode=ParseMode.MARKDOWN_V2,
                            reply_markup=InlineKeyboardMarkup(keyboard))
예제 #10
0
def revn_button_click_handler(_: telegram.Bot, __: telegram.Update,
                              query: telegram.CallbackQuery, ___) -> None:
    """
    Обработчик кнопки ревности
    """
    store = Store(query)
    if not store.load():
        return
    store.card = cast(Card, store.card)

    button_name = 'revn_clicked'
    old_emoji = store.card.revn_emoji
    result = store.card.revn(store.user_id, store.is_already_clicked(button_name))

    if result.success:
        store.mark_as_already_clicked(button_name)
        with StatsRedis.lock:
            with StatsRedis() as stats:
                stats.add_revn(store.card, store.user_id, old_emoji)
        store.save()
        store.update_buttons()
    query.answer(result.text)
예제 #11
0
def send_roadblock_resolution(bot: Bot, query: CallbackQuery) -> None:
    if query.from_user.last_name not in roads_staff:
        query.answer(BOT_NOT_ROAD_STAFF)
        return

    nmaps_message = retrieve_roadblock(roads_id=query.message.message_id)

    if query.data == 'road_closed':
        msg = BOT_ROADBLOCK_SET_USR
        btn_msg = BOT_ROADBLOCK_SET
    elif query.data == 'road_opened':
        msg = BOT_ROADBLOCK_DEL_USR
        btn_msg = BOT_ROADBLOCK_DEL
    else:
        msg = BOT_INFOPOINT_SET_USR
        btn_msg = BOT_INFOPOINT_SET

    bot.send_message(nmaps_message.chat_id,
                     msg,
                     reply_to_message_id=nmaps_message.chat_message_id)
    query.edit_message_text(btn_msg.format(query.from_user.name,
                                           query.from_user.id),
                            parse_mode='markdown')
예제 #12
0
파일: bot.py 프로젝트: zeteticl/PlayTRPGBot
def handle_delete_callback(_bot: telegram.Bot, query: telegram.CallbackQuery):
    def _(t: Text):
        return get_by_user(t, user=query.from_user)
    message = query.message
    assert isinstance(message, telegram.Message)
    deletion = Deletion.get(message.chat_id, message.message_id)
    if not deletion:
        query.answer(_(Text.INTERNAL_ERROR), alert=True)
        delete_message(message.chat_id, message.message_id)
        return
    if deletion.user_id != query.from_user.id:
        query.answer(_(Text.MUST_SAME_USER))
        return
    delete_message(message.chat_id, message.message_id)
    if query.data == 'delete:cancel':
        query.answer(_(Text.CANCELED))
    elif query.data == 'delete:confirm':
        deletion.do()
        query.answer(_(Text.DELETED))
예제 #13
0
def draft_chat_button_click_handler(bot: telegram.Bot, _: telegram.Update,
                                    query: telegram.CallbackQuery,
                                    data) -> None:
    """
    Обработчик кнопки выбора чата
    """
    user_id = query.from_user.id

    draft: Optional[CardDraftSelectChat] = cache.get(
        f'{CACHE_PREFIX}:draft:card:{user_id}')
    if draft is None or not isinstance(draft, CardDraftSelectChat):
        query.answer(text='Черновик не найден')
        query.message.delete()
        return

    key_delayed = f'{CACHE_PREFIX}:delayed:{user_id}'
    if cache.get(key_delayed):
        query.answer(text='Отправляй раз в минуту. Жди 👆')
        return
    cache.set(key_delayed, True, time=60)

    chat_id: int = data['chat_id']
    card = draft.select_chat(chat_id)

    card_in_chat_msg = bot.send_message(chat_id,
                                        card.get_message_text(),
                                        reply_markup=get_reply_markup(
                                            card.get_message_buttons()),
                                        parse_mode=HTML,
                                        disable_web_page_preview=True)
    card.message_id = card_in_chat_msg.message_id

    with StatsRedis.lock:
        with StatsRedis() as stats:
            stats.add_card(card)

    query.message.delete()

    status_message: telegram.Message = bot.send_message(
        user_id,
        'Валентинка отправлена!',
        reply_to_message_id=draft.original_draft_message_id)
    card.original_draft_message_id = draft.original_draft_message_id
    card.status_message_id = status_message.message_id
    cache.set(f'{CACHE_PREFIX}:card:{chat_id}:{card.message_id}',
              card,
              time=TWO_DAYS)

    clear_random_hearts(user_id)
    query.answer()
예제 #14
0
def round_inline_callback(query: telegram.CallbackQuery, gm: bool):
    game_round = Round.objects.filter(chat_id=query.message.chat_id).first()
    if not isinstance(game_round, Round):
        query.answer(show_alert=True, text='现在游戏没在回合状态之中')
        return
    method = str(query.data)
    if method == 'round:next':
        game_round.counter += 1
        game_round.save()
        refresh_round_message(game_round, query=query)
    elif method == 'round:prev':
        if game_round.counter > 0:
            game_round.counter -= 1
            refresh_round_message(game_round, query=query)
            game_round.save()
        else:
            query.answer(text='已经是第一回合了')
    elif method == 'round:remove':
        if not gm:
            raise NotGm()

        actors = game_round.get_actors()
        if len(actors) > 1:
            current = actors[game_round.counter % len(actors)]
            current.delete()
            refresh_round_message(game_round, query=query)
        else:
            query.answer(show_alert=True, text='至少要有一位角色在回合中')
    elif method == 'round:finish':
        if not gm:
            raise NotGm()
        remove_round(game_round.chat_id)
        query.edit_message_text('回合轮已结束')
        if isinstance(query.bot, telegram.Bot):
            try:
                query.bot.unpin_chat_message(chat_id=game_round.chat_id)
            except TelegramError:
                pass
    return
예제 #15
0
 def _(self, query: CallbackQuery, **dialog):
     query.answer()
     query.edit_message_text(**dialog)