Ejemplo n.º 1
0
def inline_achv(update, context):
    player_id = str(update.inline_query.from_user.id)
    player_username = update.inline_query.from_user.username

    player = game.load_player(response=[],
                              player_id=player_id,
                              player_username=player_username)

    if not player.lattest_chat:
        context.bot.send_message(
            chat_id=player_id,
            text=
            "Por favor, escolha um chat para mandar as mensagens com /set_chat.\nVocê poderá mudar o chat quando quiser"
        )
        return

    results = []
    achievements = get_achv(player.achievements)
    for counter, achievement in enumerate(achievements):
        if counter == 49:
            break

        if not achievement.is_completed:
            results.append(
                InlineQueryResultCachedSticker(
                    id=achievement.id, sticker_file_id=achievement.sticker_id))

    context.bot.answer_inline_query(update.inline_query.id,
                                    results,
                                    cache_time=0)
Ejemplo n.º 2
0
def inlinequery(_, update):
    global large_results

    inl_q = update.inline_query
    query = inl_q.query
    offset = int(inl_q.offset) if inl_q.offset else 0

    if offset == 0 or query not in large_results:
        if query == 'random':
            stickers = sticker_storage.random()
        elif query:
            stickers = sticker_storage.find(query)
        else:
            stickers = sticker_storage.get_most_popular()

        if len(stickers) > PAGE_SIZE:
            large_results = save_result(large_results, query, stickers)

    else:
        stickers = get_result(large_results, query)

    large_results = filter_old_results(large_results)

    have_next_page = bool(len(stickers) - offset > PAGE_SIZE)
    next_offset = str(offset + PAGE_SIZE) if have_next_page else ''
    logger.info(
        'Query: %s, stickers: %s, offset: %d, has next page: %s, next offset: %s',
        query, len(stickers), offset, have_next_page, next_offset)

    results = [
        InlineQueryResultCachedSticker(sticker.id, sticker.file_id)
        for sticker in stickers[offset:offset + PAGE_SIZE]
    ]
    update.inline_query.answer(results, cache_time=0, next_offset=next_offset)
Ejemplo n.º 3
0
def tg_webhook():
    update = Update.de_json(request.get_json(), tg.bot)
    if not update.inline_query:
        return ""

    query = update.inline_query.query
    images = None

    if query:
        nmsp = Namespace.get(Namespace.slug == query)
        if nmsp:
            images = [e.image for e in nmsp.emotes]
            print(images)
    else:
        images = Image.select().where(Image.emote_id == None)

    rszimgs = []
    for image in images:
        if image:
            if image.original.split(".")[-1] != "gif":
                rszimgs.append(image.size(256, 256, webp=1))

    results = [
        InlineQueryResultCachedSticker(id=uuid4(),
                                       sticker_file_id=rszimg.tg_file_id,
                                       title="z") for rszimg in rszimgs
    ]

    update.inline_query.answer(results)
    return ""
def inline_query_result_cached_sticker():
    return InlineQueryResultCachedSticker(
        TestInlineQueryResultCachedSticker.id,
        TestInlineQueryResultCachedSticker.sticker_file_id,
        input_message_content=TestInlineQueryResultCachedSticker.
        input_message_content,
        reply_markup=TestInlineQueryResultCachedSticker.reply_markup)
Ejemplo n.º 5
0
def on_query(bot: Bot, update: Update):
    # This constant is defined by the Bot API.
    MAX_RESULTS = 50

    inline_query = update.inline_query

    if not inline_query:
        return

    # If query is empty - return random stickers.
    return_random = not inline_query.query

    logger.info("Inline query received",
                from_id=inline_query.from_user.id,
                from_name=inline_query.from_user.first_name,
                text=inline_query.query)

    if return_random:
        stickers = random_stickers(MAX_RESULTS)
    else:
        stickers = search_stickers(inline_query.query)

    if len(stickers) > MAX_RESULTS:
        stickers = stickers[:MAX_RESULTS]

    results = [InlineQueryResultCachedSticker(fid, fid) for fid in stickers]

    cache_time = 600
    if return_random:
        # Do not cache random results.
        cache_time = 0

    bot.answer_inline_query(inline_query.id, results, cache_time=cache_time)
Ejemplo n.º 6
0
def get_list_items_by_type(nt_list: NotetonList,
                           user: NotetonUser) -> List[InlineQueryResult]:
    items = NotetonUsersManager.get_items_of_list(user.id, nt_list)
    answer_items = []
    for item in items:
        id_ = item.id
        item_ = None
        if nt_list.type == NotetonList.TYPE_ARTICLE:
            ans_text = InputTextMessageContent(item.text)
            item_ = InlineQueryResultArticle(id=id_,
                                             title=item.text,
                                             input_message_content=ans_text)
        elif nt_list.type == NotetonList.TYPE_IMAGE:
            item_ = InlineQueryResultCachedPhoto(id=id_,
                                                 photo_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_STICKER:
            item_ = InlineQueryResultCachedSticker(
                id=id_, sticker_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_GIF:
            item_ = InlineQueryResultCachedGif(id=id_,
                                               gif_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_AUDIO:
            item_ = InlineQueryResultCachedAudio(id=id_,
                                                 audio_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_DOCUMENT:
            item_ = InlineQueryResultCachedDocument(
                id=id_, title=item.title, document_file_id=item.file_id)
        if item_:
            answer_items.append(item_)
    return answer_items
Ejemplo n.º 7
0
def search_sticker_sets(session, update, context, inline_query_request):
    """Query sticker sets."""
    # Get all matching stickers
    matching_sets, duration = get_matching_sticker_sets(session, context)

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_set_offset(context, matching_sets)

    inline_query_request.duration = duration
    inline_query_request.next_offset = (next_offset.split(":", 1)[1] if
                                        next_offset != "done" else next_offset)

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint

        pprint.pprint("\n\nNext: ")
        pprint.pprint(context.offset)
        pprint.pprint(matching_sets)

    # Create a result list of max 50 cached sticker objects
    results = []
    for sticker_set in matching_sets:
        sticker_set = sticker_set[0]
        url = f"https://telegram.me/addstickers/{sticker_set.name}"
        input_message_content = InputTextMessageContent(url)

        # Hash the sticker set name, since they tend to be super long
        sticker_set_hash = hashlib.md5(sticker_set.name.encode()).hexdigest()
        results.append(
            InlineQueryResultArticle(
                f"{context.inline_query_id}:{sticker_set_hash}",
                title=sticker_set.title,
                description=sticker_set.name,
                url=url,
                input_message_content=input_message_content,
            ))

        for index in range(0, 5):
            if index < len(sticker_set.stickers):
                sticker_id = sticker_set.stickers[index].id
                file_id = sticker_set.stickers[index].file_id
                results.append(
                    InlineQueryResultCachedSticker(
                        f"{context.inline_query_id}:{sticker_id}",
                        sticker_file_id=file_id,
                    ))

    call_tg_func(
        update.inline_query,
        "answer",
        args=[results],
        kwargs={
            "next_offset": next_offset,
            "cache_time": 1,
            "is_personal": True,
        },
    )
Ejemplo n.º 8
0
def inline_query(update, context):
    user_id = update.inline_query.from_user.id
    query = update.inline_query.query
    sticker_list = sticker_list_by_query(user_id=user_id, query=query)
    results = [InlineQueryResultCachedSticker(
        id=uuid4(), sticker_file_id=sticker) for sticker in sticker_list]
    update.inline_query.answer(results, cache_time=15, is_personal=True)
    sticker_list.clear()
    results.clear()
Ejemplo n.º 9
0
    def test_equality(self):
        a = InlineQueryResultCachedSticker(self.id_, self.sticker_file_id)
        b = InlineQueryResultCachedSticker(self.id_, self.sticker_file_id)
        c = InlineQueryResultCachedSticker(self.id_, "")
        d = InlineQueryResultCachedSticker("", self.sticker_file_id)
        e = InlineQueryResultCachedVoice(self.id_, "", "")

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

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

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
Ejemplo n.º 10
0
    def _inlinequery(self, update, context):
        """Handle the inline query."""
        # Loading active chat info

        if TelegramBot.MEME_CHAT_ID not in self.active_chats.keys():
            # Loading history of MEME chat
            current_chat = Chat(chat_id=TelegramBot.MEME_CHAT_ID,
                                loader=self.loader)
            self.active_chats[current_chat.chat_id] = current_chat
            logger.info(f'Chat {current_chat.chat_id} activated.')

        current_chat = self.active_chats[TelegramBot.MEME_CHAT_ID]

        # Prediction
        results_emojis = self.model.predict(
            current_chat.messages_queue[0]['text'])
        results_stickers = []

        if str(update['_effective_user']['id']) in TelegramBot.STICKER_PACKS:
            pack = TelegramBot.STICKER_PACKS[str(
                update['_effective_user']['id'])]
            user_packs = []
            for i in range(len(pack)):
                user_packs.append(
                    self.updater.bot.get_sticker_set(pack[i]).stickers)
            self.stiker_set = list(
                set([item for sublist in user_packs for item in sublist]))
        else:
            TelegramBot.STICKER_PACKS[str(
                update['_effective_user']
                ['id'])] = TelegramBot.BASIC_STICKER_SET
            self.stiker_set = TelegramBot.BASIC_STICKER_SET

        # Inner join with stickerpack
        for emoji in results_emojis:
            stickers = []
            i = 0
            for sticker in self.stiker_set:
                if sticker.emoji == emoji and i < TelegramBot.MAX_EMOJIS:
                    stickers.append(sticker)
                    i += 1
            results_stickers.extend(stickers)
            #results_stickers.extend([sticker for sticker in self.stiker_set if sticker.emoji == emoji])
        logger.info(f'Recommending {len(results_stickers)} stickers.')

        results_stickers = results_stickers[:TelegramBot.MAX_NUMBER]
        # Sending recommendation
        results = [
            InlineQueryResultCachedSticker(id=uuid4(),
                                           type='sticker',
                                           sticker_file_id=sticker.file_id)
            for sticker in results_stickers
        ]

        update.inline_query.answer(results, cache_time=1)
Ejemplo n.º 11
0
def search_sticker_sets(session, update, context, inline_query_request):
    """Query sticker sets."""
    # Get all matching stickers
    matching_sets, duration = get_matching_sticker_sets(session, context)

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_set_offset(context, matching_sets)

    inline_query_request.duration = duration
    inline_query_request.next_offset = next_offset.split(
        ':', 1)[1] if next_offset != 'done' else next_offset

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint
        pprint.pprint('\n\nNext: ')
        pprint.pprint(context.offset)
        pprint.pprint(matching_sets)

    # Create a result list of max 50 cached sticker objects
    results = []
    for sticker_set in matching_sets:
        sticker_set = sticker_set[0]
        url = f'https://telegram.me/addstickers/{sticker_set.name}'
        input_message_content = InputTextMessageContent(url)

        # Hash the sticker set name, since they tend to be super long
        sticker_set_hash = hashlib.md5(sticker_set.name.encode()).hexdigest()
        results.append(
            InlineQueryResultArticle(
                f'{context.inline_query_id}:{sticker_set_hash}',
                title=sticker_set.title,
                description=sticker_set.name,
                url=url,
                input_message_content=input_message_content,
            ))

        for index in range(0, 5):
            if index < len(sticker_set.stickers):
                file_id = sticker_set.stickers[index].file_id
                results.append(
                    InlineQueryResultCachedSticker(
                        f'{context.inline_query_id}:{file_id}',
                        sticker_file_id=file_id))

    call_tg_func(update.inline_query,
                 'answer',
                 args=[results],
                 kwargs={
                     'next_offset': next_offset,
                     'cache_time': 1,
                     'is_personal': True,
                     'switch_pm_text': 'Maybe tag some stickers :)?',
                     'switch_pm_parameter': 'inline',
                 })
Ejemplo n.º 12
0
def inlinequery(update, context):
    query: str = update.inline_query.query
    # Results will be returned from the database insead of a hard coded answer.
    raw_results = db_editor.search_stickers(query)
    results = list(
        map(
            lambda x: InlineQueryResultCachedSticker(id=uuid4(),
                                                     sticker_file_id=x),
            raw_results))

    update.inline_query.answer(results)
Ejemplo n.º 13
0
def search(bot, update, session, user):
    """Handle inline queries for sticker search."""
    # We don't want banned users
    if user.banned:
        results = [
            InlineQueryResultCachedSticker(
                uuid4(), sticker_file_id="CAADAQADOQIAAjnUfAmQSUibakhEFgI")
        ]
        update.inline_query.answer(results, cache_time=300, is_personal=True)
        return

    offset_payload = update.inline_query.offset
    # If the offset is 'done' there are no more stickers for this query.
    if offset_payload == "done":
        update.inline_query.answer([], cache_time=0)
        return

    context = Context(update.inline_query.query, offset_payload, user)

    # Create a new inline query or get the respective existing one,
    # if we are working with an offset.
    inline_query = InlineQuery.get_or_create(session, context.inline_query_id,
                                             context.query, user)
    context.inline_query_id = inline_query.id

    if context.mode == Context.STICKER_SET_MODE:
        inline_query.mode = InlineQuery.SET_MODE

    # Save this specific InlineQueryRequest
    try:
        saved_offset = 0
        if context.offset != 0:
            saved_offset = offset_payload.split(":", 1)[1]
        inline_query_request = InlineQueryRequest(inline_query, saved_offset)
        session.add(inline_query_request)
        session.commit()
    except IntegrityError:
        # This needs some explaining:
        # Sometimes (probably due to slow sticker loading) the telegram clients
        # fire queries with the same offset.
        # To prevent this, we have an unique constraint on InlineQueryRequests.
        # If this constraint is violated, we assume that the scenario
        # above just happened and just don't answer.
        # This prevents duplicate sticker suggestions due to slow internet connections.
        session.rollback()
        return

    if context.mode == Context.STICKER_SET_MODE:
        # Remove keyword tags to prevent wrong results
        search_sticker_sets(session, update, context, inline_query_request)
    else:
        search_stickers(session, update, context, inline_query_request)
Ejemplo n.º 14
0
def search_stickers(session, update, context, inline_query_request):
    """Execute the normal sticker search."""
    # Get all matching stickers
    matching_stickers, fuzzy_matching_stickers, duration = get_matching_stickers(
        session, context)

    if context.fuzzy_offset is not None:
        inline_query_request.fuzzy = True

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_offset(context, matching_stickers,
                                  fuzzy_matching_stickers)

    inline_query_request.duration = duration
    inline_query_request.next_offset = (next_offset.split(":", 1)[1] if
                                        next_offset != "done" else next_offset)

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint

        pprint.pprint("\n\nNext: ")
        pprint.pprint({
            "offset": context.offset,
            "fuzzy_offset": context.fuzzy_offset
        })
        pprint.pprint(f"Normal matching (Count: {len(matching_stickers)})::")
        pprint.pprint(matching_stickers)
        pprint.pprint(
            f"Fuzzy matching (Count: {len(fuzzy_matching_stickers)}):")
        pprint.pprint(fuzzy_matching_stickers)

    matching_stickers = matching_stickers + fuzzy_matching_stickers

    # Create a result list of max 50 cached sticker objects
    results = []
    for file_id in matching_stickers:
        results.append(
            InlineQueryResultCachedSticker(
                f"{context.inline_query_id}:{file_id[0]}",
                sticker_file_id=file_id[1]))

    call_tg_func(
        update.inline_query,
        "answer",
        args=[results],
        kwargs={
            "next_offset": next_offset,
            "cache_time": 1,
            "is_personal": True,
        },
    )
Ejemplo n.º 15
0
def search_stickers(session, update, context, inline_query_request):
    """Execute the normal sticker search."""
    # Get all matching stickers
    matching_stickers, fuzzy_matching_stickers, duration = get_matching_stickers(
        session, context)

    if context.fuzzy_offset is not None:
        inline_query_request.fuzzy = True

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_offset(context, matching_stickers,
                                  fuzzy_matching_stickers)

    inline_query_request.duration = duration
    inline_query_request.next_offset = next_offset.split(
        ':', 1)[1] if next_offset != 'done' else next_offset

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint
        pprint.pprint('\n\nNext: ')
        pprint.pprint({
            "offset": context.offset,
            "fuzzy_offset": context.fuzzy_offset
        })
        pprint.pprint(f'Normal matching (Count: {len(matching_stickers)})::')
        pprint.pprint(matching_stickers)
        pprint.pprint(
            f'Fuzzy matching (Count: {len(fuzzy_matching_stickers)}):')
        pprint.pprint(fuzzy_matching_stickers)

    matching_stickers = matching_stickers + fuzzy_matching_stickers

    # Create a result list of max 50 cached sticker objects
    results = []
    for file_id in matching_stickers:
        results.append(
            InlineQueryResultCachedSticker(
                f'{context.inline_query_id}:{file_id[0]}',
                sticker_file_id=file_id[0]))

    call_tg_func(update.inline_query,
                 'answer',
                 args=[results],
                 kwargs={
                     'next_offset': next_offset,
                     'cache_time': 1,
                     'is_personal': True,
                     'switch_pm_text': 'Maybe tag some stickers :)?',
                     'switch_pm_parameter': 'inline',
                 })
Ejemplo n.º 16
0
def inlinequery(bot, update):
    """Handle inline queries"""
    # TODO: prevent duplicate query tags and results

    query = update.inline_query.query
    querytags = query.split(",")
    qList = []
    for tag in querytags:
        valid = re.sub(r"[^A-Za-z]+", '', tag)
        qList.append(valid)

    # remove duplicate tags
    querytags = list(set(qList))
    logger.info(querytags)

    results = []
    file_ids = []
    #if query == 'showall':
    #cur.execute("""SELECT id FROM sticker_ids""")
    #ids = cur.fetchall()
    #ids = [tup[0] for tup in ids]
    #for id in ids:
    #if id in file_ids:
    #    pass
    #else:
    #results.append(InlineQueryResultCachedSticker(type='sticker', id=uuid4(), sticker_file_id=id))
    #file_ids.append(id)"""

    #else:
    for tag in querytags:
        cur.execute(
            """SELECT id FROM sticker_ids WHERE tags='{0}'""".format(tag))
        ids = cur.fetchall()
        ids = [tup[0] for tup in ids]
        for id in ids:
            if id in file_ids:
                pass
            else:
                results.append(
                    InlineQueryResultCachedSticker(type='sticker',
                                                   id=uuid4(),
                                                   sticker_file_id=id))
                file_ids.append(id)
    else:
        pass

    logger.info(results)

    update.inline_query.answer(results)
Ejemplo n.º 17
0
    def inline_serve(self, update):
        query = update.inline_query.query
        offset = update.inline_query.offset
        results = list()

        module_logger.debug('query: %s, offset: %s' % (query, offset))

        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADXwADAtezAg6Zqq6f1-PwAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADbgADAtezAphXv-ADklTlAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADmAADAtezAkZHL3xkTt7eAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADawADAtezAmBkKARLVtZ4Ag'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADZwADAtezAh2pt-ijJtUvAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADZQADAtezAj8CoIX7oxoTAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADYwADAtezAi67ju8aavYZAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAAD2wADAtezAqLEJmEGiVUhAg'))
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(), sticker_file_id='BQADBAADYQADAtezAnyu634Jm1AVAg'))
        self.bot.answerInlineQuery(update.inline_query.id,
                                   results=results,
                                   cache_time=3600)
Ejemplo n.º 18
0
def inlinequery(update: Update, context: CallbackContext):

    query = update.inline_query.query

    if (query == 'sticker'):
        #same as before, list constructor can be bottleneck. to review.
        stickers = random.choices(list(stickers_dict.values()), k=4)
        update.inline_query.answer([
            InlineQueryResultCachedSticker(id=uuid4(), sticker_file_id=sticker)
            for sticker in stickers
        ])
    else:
        quote = random.choice(p_list)
        update.inline_query.answer([
            InlineQueryResultArticle(
                id=uuid4(),
                title='Random quote:',
                description=quote,
                input_message_content=InputTextMessageContent(quote)),
        ])
Ejemplo n.º 19
0
def inlinequery(bot, update):
    """Handle the inline query."""
    query = update.inline_query.query
    if '/' not in query:
        return

    id_chat = update.effective_user.id
    message = bot.sendSticker(magic_chat_id,
                              generate_url(query, id_chat),
                              timeout=60)
    results = [
        InlineQueryResultCachedSticker(
            id=uuid4(),
            sticker_file_id=message.sticker.file_id,
        )
    ]

    bot.answerInlineQuery(update.inline_query.id, results=results)

    bot.delete_message(chat_id=magic_chat_id, message_id=message.message_id)
Ejemplo n.º 20
0
def search_stickers(session, update, user, query, tags, nsfw, furry, offset,
                    fuzzy_offset, inline_query, inline_query_request):
    """Execute the normal sticker search."""
    # Get all matching stickers
    matching_stickers, fuzzy_matching_stickers, duration = get_matching_stickers(
        session, user, query, tags, nsfw, furry, offset, fuzzy_offset)

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_offset(inline_query, matching_stickers, offset,
                                  fuzzy_matching_stickers, fuzzy_offset)

    inline_query_request.duration = duration
    inline_query_request.next_offset = next_offset.split(
        ':', 1)[1] if next_offset != 'done' else next_offset

    matching_stickers = matching_stickers + fuzzy_matching_stickers

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint
        pprint.pprint('\n\nNext: ')  # noqa
        pprint.pprint(offset_incoming)  # noqa
        pprint.pprint(matching_stickers)  # noqa

    # Create a result list of max 50 cached sticker objects
    results = []
    for file_id in matching_stickers:
        results.append(
            InlineQueryResultCachedSticker(f'{inline_query.id}:{file_id[0]}',
                                           sticker_file_id=file_id[0]))

    call_tg_func(update.inline_query,
                 'answer',
                 args=[results],
                 kwargs={
                     'next_offset': next_offset,
                     'cache_time': 1,
                     'is_personal': True,
                     'switch_pm_text': 'Maybe tag some stickers :)?',
                     'switch_pm_parameter': 'inline',
                 })
Ejemplo n.º 21
0
def inlinequery(bot, update):
    tag_name = update.inline_query.query.lower()
    user_id = update.inline_query.from_user.id

    results = list()

    # get tag id by user and tag name
    tagResult = database.get_tag_by_userid_and_tagname(user_id, tag_name)
    tagObjects = tagResult.all()
    stickerObjects = []
    # get stickers by user uuid and tag id
    if tagObjects is not None:
        for tagObject in tagObjects:
            objects = database.get_sticker_by_userid_and_tagid(user_id, tagObject.id)

            for obj in objects:
                stickerObjects.append(obj)

        for stickerObject in stickerObjects:
            results.append(InlineQueryResultCachedSticker(id=stickerObject.id, sticker_file_id=stickerObject.sticker_uuid))
    
    update.inline_query.answer(results, is_personal=True, cache_time=0)
Ejemplo n.º 22
0
def inlinequery(bot, update):  # pylint: disable=unused-argument
    """The inline query handler.
       Finds and returns all the sticker that match the query string, all if no
       string is given.
    """
    inline_query = update.inline_query.query.strip()
    inline_results = list()

    cursor = conn.cursor()
    if inline_query == "":
        cursor.execute("SELECT * "
                       "FROM USER_STICKER, STICKER_TAG, USER, STICKER, TAG "
                       "WHERE USER.id = ? AND "
                       "USER_STICKER.user_rowid = USER.rowid AND "
                       "STICKER_TAG.tag_rowid = TAG.rowid AND "
                       "STICKER_TAG.user_sticker_rowid = USER_STICKER.rowid AND "
                       "USER_STICKER.sticker_rowid = sticker.rowid "
                       "group by USER_STICKER.sticker_rowid",
                       (str(update.inline_query.from_user.id),))
    else:
        cursor.execute("SELECT * "
                       "FROM USER_STICKER, STICKER_TAG, USER, STICKER, TAG "
                       "WHERE USER.id = ? AND "
                       "TAG.tag LIKE ? AND "
                       "USER_STICKER.user_rowid = USER.rowid AND "
                       "STICKER_TAG.tag_rowid = TAG.rowid AND "
                       "STICKER_TAG.user_sticker_rowid = USER_STICKER.rowid AND "
                       "USER_STICKER.sticker_rowid = sticker.rowid "
                       "group by USER_STICKER.sticker_rowid",
                       (str(update.inline_query.from_user.id), "%{}%".format(inline_query)))

    bd_query = cursor.fetchall()
    for sticker in bd_query:
        inline_results.append(InlineQueryResultCachedSticker(uuid4(),
                                                             sticker_file_id=sticker["file_id"]))

    update.inline_query.answer(inline_results, cache_time=0,
                               is_personal=True, switch_pm_text="Tag a sticker",
                               switch_pm_parameter="inline")
Ejemplo n.º 23
0
def inlinequery(update: Update, context: CallbackContext) -> None:
    """Handle the inline query."""
    query = update.inline_query.query

    results = []

    # This constant is defined by the Bot API.
    MAX_RESULTS = 50

    inline_query = update.inline_query
    query = update.inline_query.query
    offset = update.inline_query.offset

    if not inline_query:
        return

    # If query is empty - return random stickers.
    return_random = not inline_query.query

    if return_random:
        stickers = random_stickers(MAX_RESULTS)
    elif query == "":
        stickers = random_stickers(MAX_RESULTS)
    else:
        stickers = search_stickers(inline_query.query)

    stickers = list(dict.fromkeys(stickers))

    if len(stickers) > MAX_RESULTS:
        stickers = stickers[:MAX_RESULTS]

    for sticker_file_id in stickers:
        results.append(
            InlineQueryResultCachedSticker(
                id=uuid4(),
                sticker_file_id=sticker_file_id,
            ), )
    if len(results) > 0:
        update.inline_query.answer(results)
Ejemplo n.º 24
0
def inlinequery(update, context):
	query = update.inline_query.query
	if len(query) == 0:
		update.inline_query.answer([])
		return

	sign_text = query
	sign_text = auto_line_break(sign_text)

	# Create a temporary buffer to hold the sticker
	fp = BytesIO()

	create_sign_sticker(sign_text, fp)

	# Seek to the beginning to be ready for reading
	fp.seek(0)

	msg = None
	try:
		msg = context.bot.send_sticker(CHAT_ID, fp)
	except Exception as e:
		logging.exception(e, exc_info=True)

	if not msg:
		update.inline_query.answer([])

	file_id = msg.sticker.file_id

	if file_id:
		update.inline_query.answer([
			InlineQueryResultCachedSticker(
				id=uuid4(), sticker_file_id=file_id
			)
		])
	else:
		update.inline_query.answer([])
Ejemplo n.º 25
0
def inline(bot, update):
    global resId
    delta_ukr = ZNO_DATE_UKR - datetime.today()
    delta_math = ZNO_DATE_MATH - datetime.today()
    delta_eng = ZNO_DATE_ENG - datetime.today()
    delta_physics = ZNO_DATE_PHYSICS - datetime.today()
    days_ukr = delta_ukr.days
    days_math = delta_math.days
    days_eng = delta_eng.days
    days_physics = delta_physics.days

    day_rus = list(['дней', 'день', 'дня', 'дня', 'дня', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней', 'дней'])
    # soon
    # day_eng = list()
    day_ukr = list(['днів', 'день', 'дні', 'дні', 'дні', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів', 'днів'])

    warn_rus = list(['Берегись', 'Осторожнее', 'Спасайся', 'Беги', 'Учись', 'Пора', 'А мама говорила'])
    warn_ukr = list(['Тікай у село', 'Обережніше', 'Рятуйся', 'Ну ЗНУ це теж ЗВО', 'Починай готуватися', 'Готуй бабки',
                     'Солдат. Звучить не так і погано', 'Батько тебе породив, він тебе і вб\'є'])

    text = update.inline_query.query

    result = 'До ЗНО осталось {} {}, а ты {}.'.format(days_ukr, day_rus[days_ukr % 20], text)

    if text == '':
        warn_num = randint(0, warn_rus.__len__())
        result = 'До ЗНО осталось {} {}. {}.'.format(days_ukr, day_rus[days_ukr % 20], warn_rus[warn_num])

    query_result_rus = InlineQueryResultArticle(
        id='{}'.format(resId),
        title='Countdown Russian',
        input_message_content=InputTextMessageContent(
            message_text=result
        )
    )
    resId += 1

    result = 'До ЗНО з математики залишилось {} {}, а ти {}.'.format(days_math, day_ukr[days_math % 20], text)
    if text == '':
        warn_num = randint(0, warn_ukr.__len__())
        result = 'До ЗНО з математики залишилось {} {}. {}.'.format(days_math, day_ukr[days_math % 20], warn_ukr[warn_num])

    query_result_ukr_math = InlineQueryResultArticle(
        id='{}'.format(resId),
        title='Зворотній відлік математика',
        input_message_content=InputTextMessageContent(
            message_text=result
        )
    )
    resId += 1

    id_math = get_sticker_id_with_text(bot, result)
    query_result_sticker_math = InlineQueryResultCachedSticker(type='sticker', id=resId, sticker_file_id=id_math)
    resId += 1

    result = 'До ЗНО з української залишилось {} {}, а ти {}.'.format(days_ukr, day_ukr[days_ukr % 20], text)
    if text == '':
        warn_num = randint(0, warn_ukr.__len__())
        result = 'До ЗНО з української залишилось {} {}. {}.'.format(days_ukr, day_ukr[days_ukr % 20],
                                                                     warn_ukr[warn_num])
    query_result_ukr_ukr = InlineQueryResultArticle(
        id='{}'.format(resId),
        title='Зворотній відлік українська',
        input_message_content=InputTextMessageContent(
            message_text=result
        )
    )
    resId += 1

    id_ukr = get_sticker_id_with_text(bot, result)
    query_result_sticker_ukr = InlineQueryResultCachedSticker(type='sticker', id=resId, sticker_file_id=id_ukr)
    resId += 1

    #
    # English
    #
    result = 'До ЗНО з англійської залишилось {} {}, а ти {}.'.format(days_eng, day_ukr[days_eng % 20], text)
    if text == '':
        warn_num = randint(0, warn_ukr.__len__())
        result = 'До ЗНО з англійської залишилось {} {}. {}.'.format(days_eng, day_ukr[days_eng % 20],
                                                                     warn_ukr[warn_num])
    query_result_ukr_eng = InlineQueryResultArticle(
        id='{}'.format(resId),
        title='Зворотній відлік англійська',
        input_message_content=InputTextMessageContent(
            message_text=result
        )
    )
    resId += 1

    id_ukr = get_sticker_id_with_text(bot, result)
    query_result_sticker_eng = InlineQueryResultCachedSticker(type='sticker', id=resId, sticker_file_id=id_ukr)
    resId += 1

    #
    # Physics
    #
    result = 'До ЗНО з фізики залишилось {} {}, а ти {}.'.format(days_physics, day_ukr[days_physics % 20], text)
    if text == '':
        warn_num = randint(0, warn_ukr.__len__())
        result = 'До ЗНО з фізики залишилось {} {}. {}.'.format(days_physics, day_ukr[days_physics % 20],
                                                                     warn_ukr[warn_num])
    query_result_ukr_physics = InlineQueryResultArticle(
        id='{}'.format(resId),
        title='Зворотній відлік фізика',
        input_message_content=InputTextMessageContent(
            message_text=result
        )
    )
    resId += 1

    id_ukr = get_sticker_id_with_text(bot, result)
    query_result_sticker_physics = InlineQueryResultCachedSticker(type='sticker', id=resId, sticker_file_id=id_ukr)
    resId += 1

    update.inline_query.answer(results=list([query_result_rus,
                                             query_result_ukr_math,
                                             query_result_ukr_ukr,
                                             query_result_ukr_eng,
                                             query_result_ukr_physics,
                                             query_result_sticker_math,
                                             query_result_sticker_ukr,
                                             query_result_sticker_eng,
                                             query_result_sticker_physics]),
                               cache_time=0,
                               is_personal=True)

    f = open('ids.cnf', 'w')
    f.write(str(resId))
    f.close()
Ejemplo n.º 26
0
def sticker_inline_result(doc: Document) -> InlineQueryResultCachedSticker:
    content = doc.content
    return InlineQueryResultCachedSticker(
        id=doc.internal_id,
        sticker_file_id=content['file_id'],
    )
Ejemplo n.º 27
0
def _inline_query_result_from_entry(entry_type, entry):
    if entry_type == EntryType.STICKER:
        return InlineQueryResultCachedSticker(id=entry, sticker_file_id=entry)
    elif entry_type == EntryType.GIF:
        return InlineQueryResultCachedGif(id=entry, gif_file_id=entry)
Ejemplo n.º 28
0
# Enable logging
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO)

logger = logging.getLogger(__name__)

token = config.token

core = telegram.Bot(token)
stickers = core.get_sticker_set('animals').stickers
all_sticker_list = []
for i in range(10):
    all_sticker_list.append(
        InlineQueryResultCachedSticker(id=uuid4(),
                                       sticker_file_id=stickers[i].file_id))
sticker_dict = {
    'test1': all_sticker_list[0],
    'test2': all_sticker_list[1],
    'test3': all_sticker_list[2],
    'test4': all_sticker_list[3],
    'test5': all_sticker_list[4],
    'test6': all_sticker_list[5],
    'test7': all_sticker_list[6],
    'test8': all_sticker_list[7],
    'test9': all_sticker_list[8],
    'test10': all_sticker_list[9],
}

# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
Ejemplo n.º 29
0
def search(bot, update, session, user):
    """Handle inline queries for sticker search."""
    # We don't want banned users
    if user.banned:
        results = [
            InlineQueryResultCachedSticker(
                uuid4(), sticker_file_id='CAADAQADOQIAAjnUfAmQSUibakhEFgI')
        ]
        update.inline_query.answer(results,
                                   cache_time=300,
                                   is_personal=True,
                                   switch_pm_text="Maybe don't be a dick :)?",
                                   switch_pm_parameter='inline')
        return

    # Get tags
    query = update.inline_query.query
    tags = get_tags_from_text(update.inline_query.query, limit=5)

    # Return early, if we have no tags
    if len(tags) == 0:
        update.inline_query.answer(
            [],
            cache_time=300,
            is_personal=True,
            switch_pm_text="Just type what you're looking for :)",
            switch_pm_parameter='inline')
        return

    offset_incoming = update.inline_query.offset
    # If the offset is 'done' there are no more stickers for this query.
    if offset_incoming == 'done':
        update.inline_query.answer([], cache_time=0)
        return

    # Extract the current offsets from the incoming offset payload
    offset, fuzzy_offset, query_id = extract_info_from_offset(offset_incoming)

    # Handle special tags
    nsfw = 'nsfw' in tags
    furry = 'fur' in tags or 'furry' in tags

    # Create a new inline query or get the respective existing one, if we are working with an offset.
    inline_query = InlineQuery.get_or_create(session, query_id, query, user)
    if 'set' in tags or 'pack' in tags:
        inline_query.mode = InlineQuery.SET_MODE

    # Save this specific InlineQueryRequest
    try:
        saved_offset = offset_incoming.split(':', 1)[1] if offset != 0 else 0
        inline_query_request = InlineQueryRequest(inline_query, saved_offset)
        session.add(inline_query_request)
        session.commit()
    except IntegrityError:
        # This needs some explaining:
        # Sometimes (probably due to slow sticker loading) the telegram clients fire queries with the same offset.
        # To prevent this, we have an unique constraint on InlineQueryRequests.
        # If this constraint is violated, we assume that the scenario above just happened and just don't answer.
        # This prevents duplicate sticker suggestions due to slow internet connections.
        session.rollback()
        return

    if 'pack' in tags or 'set' in tags:
        # Remove keyword tags to prevent wrong results
        for tag in ['pack', 'set']:
            if tag in tags:
                tags.remove(tag)
        search_sticker_sets(session, update, user, query, tags, nsfw, furry,
                            offset, inline_query, inline_query_request)
    else:
        search_stickers(session, update, user, query, tags, nsfw, furry,
                        offset, fuzzy_offset, inline_query,
                        inline_query_request)