コード例 #1
0
ファイル: spoti.py プロジェクト: imutk/LyricsPyRobot
def inline(msg, bot):
    db = dbc()
    a = get_current_playing(str(msg['from']['id']), db)
    if a is None:
        articles = [
            InlineQueryResultArticle(
                id='a',
                title='spoti: Você não está tocando nada',
                thumb_url='https://piics.ml/amn/lpy/spoti.png',
                input_message_content=InputTextMessageContent(
                    message_text="Você não está tocando nada"))
        ]
    else:
        a = lyricspy.auto(
            f"{a['item']['artists'][0]['name']} {a['item']['name']}",
            limit=1)[0]
        teclado = InlineKeyboardMarkup(
            inline_keyboard=[[dict(text='Aguarde...', callback_data='a')]])
        articles = [
            InlineQueryResultArticle(
                id=a['link'],
                thumb_url='https://piics.ml/amn/lpy/spoti.png',
                title=f'spoti: {a["musica"]} - {a["autor"]}',
                input_message_content=InputTextMessageContent(
                    message_text='Aguarde...',
                    parse_mode='markdown',
                    disable_web_page_preview=True),
                reply_markup=teclado)
        ]
    return articles
コード例 #2
0
def inline_query(msg):
    if msg['query'] == '':
        db = dbc()
        if str(msg['from']['id']) in db:
            articles = inline(msg, bot)
        else:
            articles = []
        bot.answerInlineQuery(msg['id'], results=articles, is_personal=True, cache_time=0)
    elif msg['query'] != '':
        db = dbc()
        if str(msg['from']['id']) in db:
            articles = inline(msg, bot)
        else:
            articles = []
        result = lyricspy.auto(msg['query'])
        for a in result:
            teclado = InlineKeyboardMarkup(inline_keyboard=[
                [dict(text='Aguarde...', callback_data='a')]
            ])
            articles.append(InlineQueryResultArticle(
                id=a['link'],
                title=f'{a["musica"]} - {a["autor"]}',
                thumb_url='https://piics.ml/i/010.png',
                input_message_content=InputTextMessageContent(
                    message_text='Aguarde...',
                    parse_mode='markdown', disable_web_page_preview=True),
                reply_markup=teclado)
            )
        if not articles:
            articles = [InlineQueryResultArticle(id='a', title=f'sem resultado',
                                                 input_message_content=InputTextMessageContent(
                                                     message_text=f"sem resultado para {msg['query']}"))]
        bot.answerInlineQuery(msg['id'], results=articles, is_personal=True, cache_time=0)
コード例 #3
0
ファイル: skeletona_route.py プロジェクト: n8wachT/amanobot
    def compute():
        query_id, from_id, query_string = amanobot.glance(msg, flavor='inline_query')
        print('Computing for: %s' % query_string)

        articles = [InlineQueryResultArticle(
                        id='abcde', title='Telegram', input_message_content=InputTextMessageContent(message_text='Telegram is a messaging app')),
                    dict(type='article',
                        id='fghij', title='Google', input_message_content=dict(message_text='Google is a search engine'))]

        photo1_url = 'https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'
        photo2_url = 'https://www.telegram.org/img/t_logo.png'
        photos = [InlineQueryResultPhoto(
                      id='12345', photo_url=photo1_url, thumb_url=photo1_url),
                  dict(type='photo',
                      id='67890', photo_url=photo2_url, thumb_url=photo2_url)]

        result_type = query_string[-1:].lower()

        if result_type == 'a':
            return articles
        elif result_type == 'p':
            return photos
        else:
            results = articles if random.randint(0,1) else photos
            if result_type == 'b':
                return dict(results=results, switch_pm_text='Back to Bot', switch_pm_parameter='Optional_start_parameter')
            else:
                return dict(results=results)
コード例 #4
0
async def inline(msg):
    print(msg['query'])
    tk = db.get(msg['from']['id'])
    if tk[0]:
        r, articles = await ainline(msg)
    else:
        r, articles = {}, []
    if msg['query'] != '':
        a = await mux.auto(msg['query'])
        for i in a:
            hash = hashlib.md5(i['link'].encode()).hexdigest()
            r.update({hash: i['link']})
            teclado = InlineKeyboardMarkup(
                inline_keyboard=[[dict(text='Aguarde...', callback_data='a')]])
            articles.append(
                InlineQueryResultArticle(
                    id=hash,
                    title=f'{i["musica"]} - {i["autor"]}',
                    thumb_url='https://piics.ml/i/010.png',
                    reply_markup=teclado,
                    input_message_content=InputTextMessageContent(
                        message_text='Aguarde...',
                        parse_mode='markdown',
                        disable_web_page_preview=True)))
        db.tem(msg['from']['id'], r)
    print(r)
    await bot.answerInlineQuery(msg['id'],
                                results=articles,
                                is_personal=True,
                                cache_time=0)
コード例 #5
0
ファイル: spoti.py プロジェクト: ankit-sinha-18/LyricsPyRobot
async def ainline(msg):
    r = {}
    a = get_current_playing(msg['from']['id'])
    if a is None:
        articles = [InlineQueryResultArticle(
            id='spoti',
            title='spoti: Você não está tocando nada',
            thumb_url='https://piics.ml/amn/lpy/spoti.png',
            input_message_content=InputTextMessageContent(
                message_text="Você não está tocando nada"))]
    else:
        text = f"{a['item']['artists'][0]['name']} {a['item']['name']}"
        print(text)
        a = await mux.auto(text, limit=1)
        print(a)
        if not a:
            print(a)
            a = await let.auto(text, limit=1)
            if not a:
                articles = [InlineQueryResultArticle(
                    id='spoti',
                    title='spoti: Letra não encontrada',
                    thumb_url='https://piics.ml/amn/lpy/spoti.png',
                    input_message_content=InputTextMessageContent(
                        message_text="Não foi possivel achar letra"))]
                return r, articles
        a = a[0]
        hash = hashlib.md5(a['link'].encode()).hexdigest()
        r.update({hash:a['link']})
        teclado = InlineKeyboardMarkup(inline_keyboard=[
            [dict(text='Aguarde...', callback_data='a')]
        ])
        articles = [InlineQueryResultArticle(
            id=hash,
            title=f'spoti: {a["musica"]} - {a["autor"]}',
            thumb_url='https://piics.ml/i/010.png',
            reply_markup=teclado,
            input_message_content=InputTextMessageContent(
                message_text='Aguarde...',
                parse_mode='markdown', disable_web_page_preview=True))]
        db.tem(msg['from']['id'], r)
    return r, articles
コード例 #6
0
def on_inline_query(msg):
    query_id, from_id, query_string = amanobot.glance(msg,
                                                      flavor='inline_query')
    print('Inline Query:', query_id, from_id, query_string)

    articles = [
        InlineQueryResultArticle(id='abc',
                                 title='ABC',
                                 input_message_content=InputTextMessageContent(
                                     message_text='Hello'))
    ]

    bot.answerInlineQuery(query_id, articles)
コード例 #7
0
    def compute():
        query_id, from_id, query_string = amanobot.glance(
            msg, flavor='inline_query')
        print('Inline Query:', query_id, from_id, query_string)

        articles = [
            InlineQueryResultArticle(
                id='abc',
                title=query_string,
                input_message_content=InputTextMessageContent(
                    message_text=query_string))
        ]

        return articles
コード例 #8
0
    def compute():
        articles = [InlineQueryResultArticle(
                       id='abc', title='HK', input_message_content=InputTextMessageContent(message_text='Hong Kong'), url='https://www.google.com', hide_url=True),
                   {'type': 'article',
                       'id': 'def', 'title': 'SZ', 'input_message_content': {'message_text': 'Shenzhen'}, 'url': 'https://www.yahoo.com'}]

        photos = [InlineQueryResultPhoto(
                      id='123', photo_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf', thumb_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'),
                  {'type': 'photo',
                      'id': '345', 'photo_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'thumb_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'caption': 'Caption', 'title': 'Title', 'input_message_content': {'message_text': 'Shenzhen'}}]

        games = [InlineQueryResultGame(
                    id='abc', game_short_name='sunchaser')]

        results = random.choice([articles, photos, games])
        return results
コード例 #9
0
ファイル: datecalca.py プロジェクト: LordRimuru/amanobot
            def make_result(today, week_delta, day_delta):
                future = today + week_delta + day_delta

                n = 0 if future.weekday() > today.weekday() else 1
                n += int(week_delta.days / 7)

                return InlineQueryResultArticle(
                    id=future.strftime('%Y-%m-%d'),
                    title=('next ' * n if n > 0 else 'this ') +
                    weekdays[future.weekday()].capitalize(),
                    input_message_content=InputTextMessageContent(
                        message_text=future.strftime('%A, %Y-%m-%d')),
                    reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                        InlineKeyboardButton(text='Yes', callback_data='yes'),
                        InlineKeyboardButton(text='No', callback_data='no'),
                    ]]))
コード例 #10
0
ファイル: inline_per_user.py プロジェクト: n8wachT/amanobot
        def compute():
            query_id, from_id, query_string = amanobot.glance(
                msg, flavor='inline_query')
            print(self.id, ':', 'Inline Query:', query_id, from_id,
                  query_string)

            self._count += 1
            text = '%d. %s' % (self._count, query_string)

            articles = [
                InlineQueryResultArticle(
                    id='abc',
                    title=text,
                    input_message_content=InputTextMessageContent(
                        message_text=text))
            ]

            return articles
コード例 #11
0
async def inlines(msg):
    if 'query' in msg:
        first_name = msg['from']['first_name']
        user_id = msg['from']['id']
        if 'username' in msg['from']:
            username = '******' + msg['from']['username']
        else:
            username = '******'
        msg["query"] = msg["query"] or "0"
        if msg['query'].split()[0].lower() == 'ip' and len(msg['query']) > 6:
            async with aiohttp.ClientSession() as session:
                r = await session.get(geo_ip + msg['query'][3:])
                rjson = await r.json()
            res = "\n".join(["*{}*: `{}`".format(i, rjson[i]) for i in rjson])

            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title='Informações de ' + msg['query'][3:],
                    input_message_content=InputTextMessageContent(
                        message_text='*Consulta*: `' + msg['query'][3:] +
                        '`\n\n' + res,
                        parse_mode="Markdown"))
            ]

            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)

        elif msg['query'].split()[0].lower() == 'echo' and len(
                msg['query'].split()) >= 2:
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title=msg['query'][5:],
                    input_message_content=InputTextMessageContent(
                        message_text=msg['query'][5:]))
            ]

            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)

        elif msg['query'].split()[0].lower() == 'duck' and len(
                msg['query'].split()) >= 2:
            count = 50
            number = 1
            search = msg['query'][5:]
            duc = await ddg_client.search(str(search))
            articles = []
            if duc:
                if count + number > len(duc):
                    maxdef = len(duc)
                else:
                    maxdef = count + number
                for i in range(number - 1, maxdef - 1):
                    deftxt = duc[i]
                    deftxt = escape_definition(deftxt)
                    articles.append(
                        InlineQueryResultArticle(
                            id=str(uuid4()),
                            title=deftxt['title'],
                            thumb_url='https://piics.ml/i/002.png',
                            description=deftxt['url'],
                            input_message_content=InputTextMessageContent(
                                message_text=
                                f"<b>{deftxt['title']}</b>\n{deftxt['url']}",
                                parse_mode='HTML')))
            else:
                articles.append(
                    InlineQueryResultArticle(
                        id=str(uuid4()),
                        title="Sem resultados.",
                        input_message_content=InputTextMessageContent(
                            message_text=f"Sem resultados para '{search}'.")))

            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)

        elif msg['query'].split()[0].lower() == 'img':
            query = msg['query'][4:]
            async with aiohttp.ClientSession() as session:
                r = await session.get(googl_img_api, params=dict(cari=query))
                img = await r.json()
            resp = []
            for k, result in enumerate(img):
                if k == 50:
                    break
                resp.append(
                    InlineQueryResultPhoto(id=str(uuid4()),
                                           photo_url=result["Isi"],
                                           thumb_url=result["Tumbnil"],
                                           caption=html.unescape(
                                               result["Deskripsi"])))
            await bot.answerInlineQuery(msg['id'],
                                        results=resp,
                                        cache_time=60,
                                        is_personal=True)

        elif msg['query'].split()[0].lower() == 'invert' and len(
                msg['query'].split()) >= 2:
            query = msg['query'][7:]
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title=query[::-1],
                    input_message_content=InputTextMessageContent(
                        message_text=query[::-1]))
            ]

            await bot.answerInlineQuery(msg['id'], results=articles)

        elif msg['query'].split()[0].lower() == 'markdown' and len(
                msg['query'].split()) >= 2:
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title=msg['query'][9:],
                    input_message_content=InputTextMessageContent(
                        message_text=msg['query'][9:], parse_mode='Markdown'))
            ]

            await bot.answerInlineQuery(msg['id'], results=articles)

        elif msg['query'].split()[0].lower() == 'html' and len(
                msg['query'].split()) >= 2:
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title=msg['query'][5:],
                    input_message_content=InputTextMessageContent(
                        message_text=msg['query'][5:], parse_mode='html'))
            ]
            try:
                await bot.answerInlineQuery(msg['id'], results=articles)
            except TelegramError:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='Texto com erros de formatação.',
                        input_message_content=InputTextMessageContent(
                            message_text=
                            'Ocorreu um erro. provavelmente porque você usou uma tag não suportada, ou porque você esqueceu de fechar alguma tag. As tags suportadas são estas: <b>, <i>, <code>, <a> e <pre>.'
                        ))
                ]
                await bot.answerInlineQuery(msg['id'], results=articles)

        elif msg['query'].split()[0].lower() == 'yt' and len(
                msg['query'].split()) >= 2:
            articles = []
            search = await search_yt(msg['query'][3:])
            for i in search:
                articles.append(
                    InlineQueryResultArticle(
                        id=str(uuid4()),
                        title=i['title'],
                        thumb_url=
                        f"https://i.ytimg.com/vi/{i['url'].split('v=')[1]}/default.jpg",
                        input_message_content=InputTextMessageContent(
                            message_text=i['url'])))
            if not articles:
                articles.append(
                    InlineQueryResultArticle(
                        id=str(uuid4()),
                        title=
                        f'Nenhum resultado encontrado para "{msg["query"][3:]}".',
                        input_message_content=InputTextMessageContent(
                            message_text='.')))

            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)

        elif msg['query'].split()[0].lower() == 'print' and len(
                msg['query'].split()) >= 2:
            url = msg['query'][6:]
            requests.get("https://image.thum.io/get/width/1000/" + url)
            if re.match(r'^https?://', msg['query'][6:]):
                url = msg['query'][6:]
            else:
                url = 'http://' + msg['query'][6:]
            try:
                res = [
                    InlineQueryResultPhoto(
                        id='a',
                        photo_url="https://image.thum.io/get/width/1000/" +
                        url,
                        thumb_url="https://image.thum.io/get/width/320/" + url,
                        caption=url)
                ]
                await bot.answerInlineQuery(msg['id'],
                                            results=res,
                                            cache_time=60,
                                            is_personal=True)
            except Exception as e:
                res = [
                    InlineQueryResultArticle(
                        id='a',
                        title='Error',
                        input_message_content=InputTextMessageContent(str(e)))
                ]
                await bot.answerInlineQuery(msg['id'],
                                            results=res,
                                            cache_time=60,
                                            is_personal=True)

        elif msg['query'].lower() == 'faces' or msg['query'].lower() == 'f':
            faces = [
                '¯\\_(ツ)_/¯', '( ͡° ͜ʖ ͡°)', '( ͡~ ͜ʖ ͡°)', '( ͡◐ ͜ʖ ͡◑))',
                '( ͡◔ ͜ʖ ͡◔)', '( ͡⚆ ͜ʖ ͡⚆)', '( ͡ʘ ͜ʖ ͡ʘ)', 'ヽ༼ຈل͜ຈ༽ノ',
                '༼ʘ̚ل͜ʘ̚༽', '(╯°□°)╯', '(ノ◕ヮ◕)ノ', '(ノ◕ヮ◕)ノ*:・゚✧', '(◕‿◕)',
                '(。◕‿‿◕。)', '(っ◕‿◕)っ', '(づ。◕‿‿◕。)づ', '༼ つ ◕_◕ ༽つ',
                '(ง ͠° ͟ل͜ ͡°)ง', '(ง\'̀-\'́)ง', 'ᕙ(⇀‸↼‶)ᕗ', '(҂⌣̀_⌣́)',
                'ᕦ(ò_óˇ)ᕤ', '╚(ಠ_ಠ)=┐', 'ლ(ಠ益ಠლ)', '\\_(ʘ_ʘ)_/', '( ⚆ _ ⚆ )',
                '(ಥ﹏ಥ)', '﴾͡๏̯͡๏﴿', '(◔̯◔)', '(ಠ_ಠ)', '(ಠ‿ಠ)', '(¬_¬)',
                '(¬‿¬)', '\\ (•◡•) /', '(◕‿◕✿)',
                '( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)'
            ]
            articles = [
                InlineQueryResultArticle(
                    id=str(uuid4()),
                    title=face,
                    input_message_content=dict(message_text=face))
                for face in faces
            ]

            await bot.answerInlineQuery(msg['id'], results=articles)

        elif msg['query'].split()[0].lower() == 'hidemsg':
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title='Resultado: ' + msg['query'][8:],
                    input_message_content=InputTextMessageContent(
                        message_text='\u2060' * 3600 + msg['query'][8:]))
            ]
            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)

        else:
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title='Informações',
                    thumb_url='https://piics.ml/amn/eduu/info.png',
                    description='Exibe informações sobre você',
                    input_message_content=dict(
                        message_text=
                        '<b>Suas informações:</b>\n\n<b>Nome:</b> <code>' +
                        html.escape(first_name) +
                        '</code>\n<b>ID:</b> <code>' + str(user_id) +
                        '</code>\n<b>Username:</b> <code>' + username +
                        '</code>',
                        parse_mode="HTML")),
                InlineQueryResultArticle(
                    id='b',
                    title='duck',
                    thumb_url='https://piics.ml/amn/eduu/duck.png',
                    description='Pesquise no DuckDuckGo via inline.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} duck</code> - Pesquise no DuckDuckGo via inline.'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='c',
                    title='faces (f)',
                    thumb_url='https://piics.ml/amn/eduu/faces.png',
                    description='Mostra uma lista de carinhas ¯\\_(ツ)_/¯',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} faces</code> - exibe uma lista de carinhas :D'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='d',
                    title='hidemsg',
                    thumb_url='https://piics.ml/amn/eduu/hidemsg.png',
                    description=
                    'Envia uma mensagem que não aparece nas ações recentes ao ser apagada em até 1 minuto.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} hidemsg</code> - Envie uma mensagem que se for apagada em até 1 minuto não aparece nas <i>ações recentes</i> do grupo.'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='f',
                    title='img',
                    thumb_url='https://piics.ml/amn/eduu/img.png',
                    description='Buscador de imagens via inline.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} img</code> - Buscador de imagens via inline.'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='g',
                    title='ip',
                    thumb_url='https://piics.ml/amn/eduu/ip.png',
                    description='Exibe informações de determinado IP/URL.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} ip</code> - Exibe informações de determinado IP/URL.'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='h',
                    title='print',
                    thumb_url='https://piics.ml/amn/eduu/print.png',
                    description='Faz uma screenshot de uma página.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} print</code> - Faz uma screenshot de uma página.'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='i',
                    title='run',
                    thumb_url='https://piics.ml/amn/eduu/html.png',
                    description='Execute códigos via inline.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{0} run &lt;lang&gt; &lt;code&gt;</code> - Execute códigos via inline.\n\nEx.: <code>@{0} run python3 print("Olá mundo")</code>'
                        .format(bot_username),
                        parse_mode='HTML')),
                InlineQueryResultArticle(
                    id='j',
                    title='yt',
                    thumb_url='https://piics.ml/amn/eduu/yt.png',
                    description='Pesquise vídeos no YouTube via inline.',
                    input_message_content=dict(
                        message_text=
                        '<b>Uso:</b> <code>@{} yt</code> - Pesquise vídeos no YouTube via inline.'
                        .format(bot_username),
                        parse_mode='HTML'))
            ]

            await bot.answerInlineQuery(msg['id'],
                                        results=articles,
                                        cache_time=60,
                                        is_personal=True)
コード例 #12
0
ファイル: inlines.py プロジェクト: LordRimuru/EduuRobot
def inlines(msg):
    if 'query' in msg:
        first_name = msg['from']['first_name']
        user_id = msg['from']['id']
        if 'username' in msg['from']:
            username = '******' + msg['from']['username']
        else:
            username = '******'
        if msg['query'].startswith('ip') and len(msg['query']) > 6:
            r = requests.get(geo_ip + msg['query'][3:])
            x = ''
            for i in r.json():
                x += "*{}*: `{}`\n".format(i, r.json()[i])
            articles = [InlineQueryResultArticle(
                id='a', title='Informações de ' + msg['query'][3:], input_message_content=InputTextMessageContent(
                    message_text='*Consulta*: `' + msg['query'][3:] + '`\n\n' + x, parse_mode="Markdown"))]

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)


        elif msg['query'].startswith('echo'):
            articles = [InlineQueryResultArticle(
                id='a', title=msg['query'][5:],
                input_message_content=InputTextMessageContent(message_text=msg['query'][5:]))]

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)


        elif msg['query'].startswith('proxy'):
            count = 50
            number = 1
            prox = get(proxs, params={
                "max": count,
                "key": config.keys['grab_proxy']
            }).json()["result"]
            if len(prox) > 0:
                articles = []
                if count + number > len(prox):
                    maxdef = len(prox)
                else:
                    maxdef = count + number
                for i in range(number - 1, maxdef - 1):
                    deftxt = prox[i]
                    deftxt = escape_definition(deftxt)
                    articles.append(InlineQueryResultArticle(
                        id=str(uuid4()), title=deftxt["country"] + ' - ' + deftxt["ip"] + ':' + deftxt['port'],
                        thumb_url='http://piics.ml/i/003.png', description='Last checked: ' + deftxt["last_checked"],
                        input_message_content=InputTextMessageContent(
                            message_text=f'<b>Proxy:</b>\nPaís: {deftxt["country"]}\nIP: <code>{deftxt["ip"]}</code>\nPorta: <code>{deftxt["port"]}</code>\nChecado há: <i>{deftxt["last_checked"]}</i>',
                            parse_mode='HTML')))

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)


        elif msg['query'].startswith('duck'):
            count = 50
            number = 1
            search = msg['query'][5:]
            duc = duckpy.search(str(search))['results']
            articles = []
            if duc:
                if count + number > len(duc):
                    maxdef = len(duc)
                else:
                    maxdef = count + number
                for i in range(number - 1, maxdef - 1):
                    deftxt = duc[i]
                    deftxt = escape_definition(deftxt)
                    articles.append(InlineQueryResultArticle(
                        id=str(uuid4()),
                        title=deftxt['title'],
                        thumb_url='http://piics.ml/i/003.png',
                        description=deftxt['url'],
                        input_message_content=InputTextMessageContent(
                            message_text=f"<b>{deftxt['title']}</b>\n{deftxt['url']}",
                            parse_mode='HTML')))
            else:
                articles.append(InlineQueryResultArticle(
                    id=str(uuid4()),
                    title="Sem resultados.",
                    input_message_content=InputTextMessageContent(
                        message_text=f"Sem resultados para '{search}'."
                    )))

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)


        elif msg['query'].startswith('img'):
            query = msg['query'][4:]
            img = get(googl_img_api,
                  params={
                      "cari": query
                  },
                  headers=HEADERS).json()
            resp = []
            for k, result in enumerate(img):
                    if k == 50:
                        break
                    resp.append(InlineQueryResultPhoto(
                        id=str(uuid4()),
                        photo_url=result["Isi"],
                        thumb_url=result["Tumbnil"],
                        caption=f'{result["Deskripsi"]}'
                    ))
            bot.answerInlineQuery(msg['id'], results=resp, cache_time=60, is_personal=True)


        elif msg['query'].startswith('invert'):
            query = msg['query'][7:]
            articles = [InlineQueryResultArticle(id='abcde', title=query[::-1],
                                                 input_message_content=InputTextMessageContent(
                                                     message_text=query[::-1]))]

            bot.answerInlineQuery(msg['id'], results=articles)


        elif msg['query'].startswith('markdown'):
            articles = [InlineQueryResultArticle(
                id='a', title=msg['query'][9:],
                input_message_content=InputTextMessageContent(message_text=kk, parse_mode='Markdown'))]

            bot.answerInlineQuery(msg['id'], results=articles)


        elif msg['query'].startswith('html'):
            articles = [InlineQueryResultArticle(
                id='a', title=msg['query'][5:],
                input_message_content=InputTextMessageContent(message_text=msg['query'][6:], parse_mode='html'))]
            try:
                bot.answerInlineQuery(msg['id'], results=articles)
            except TelegramError:
                articles = [InlineQueryResultArticle(
                    id='a', title='Texto com erros de formatação.', input_message_content=InputTextMessageContent(
                        message_text='Ocorreu um erro. provavelmente porque você usou uma tag não suportada, ou porque você esqueceu de fechar alguma tag. As tags suportadas são estas: <b>, <i>, <code>, <a> e <pre>.'))]
                bot.answerInlineQuery(msg['id'], results=articles)


        elif msg['query'].startswith('yt '):
            articles = []
            search = search_yt(msg['query'][3:])
            for i in search:
                articles.append(InlineQueryResultArticle(
                    id=str(uuid4()), title=i['title'],
                    thumb_url=f"https://i.ytimg.com/vi/{i['url'].split('v=')[1]}/default.jpg",
                    input_message_content=InputTextMessageContent(message_text=i['url'])))
            if not articles:
                articles.append(InlineQueryResultArticle(
                    id=str(uuid4()), title=f'Nenhum resultado encontrado para "{msg["query"][3:]}".',
                    input_message_content=InputTextMessageContent(message_text='.')))

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)


        elif msg['query'].startswith('faces'):
            articles = [
                InlineQueryResultArticle(
                    id='a', title='¯\\_(ツ)_/¯',
                    input_message_content=InputTextMessageContent(message_text='¯\\_(ツ)_/¯')),
                InlineQueryResultArticle(
                    id='b', title='( ͡° ͜ʖ ͡°)', input_message_content=dict(message_text='( ͡° ͜ʖ ͡°)')),
                InlineQueryResultArticle(
                    id='c', title='( ͡~ ͜ʖ ͡°)', input_message_content=dict(message_text='( ͡~ ͜ʖ ͡°)')),
                InlineQueryResultArticle(
                    id='d', title='( ͡◐ ͜ʖ ͡◑))', input_message_content=dict(message_text='( ͡◐ ͜ʖ ͡◑))')),
                InlineQueryResultArticle(
                    id='e', title='( ͡◔ ͜ʖ ͡◔)', input_message_content=dict(message_text='( ͡◔ ͜ʖ ͡◔)')),
                InlineQueryResultArticle(
                    id='f', title='( ͡⚆ ͜ʖ ͡⚆)', input_message_content=dict(message_text='( ͡⚆ ͜ʖ ͡⚆)')),
                InlineQueryResultArticle(
                    id='g', title='( ͡ʘ ͜ʖ ͡ʘ)', input_message_content=dict(message_text='( ͡ʘ ͜ʖ ͡ʘ)')),
                InlineQueryResultArticle(
                    id='h', title='ヽ༼ຈل͜ຈ༽ノ', input_message_content=dict(message_text='ヽ༼ຈل͜ຈ༽ノ')),
                InlineQueryResultArticle(
                    id='i', title='༼ʘ̚ل͜ʘ̚༽', input_message_content=dict(message_text='༼ʘ̚ل͜ʘ̚༽')),
                InlineQueryResultArticle(
                    id='j', title='(╯°□°)╯', input_message_content=dict(message_text='(╯°□°)╯')),
                InlineQueryResultArticle(
                    id='k', title='(ノ◕ヮ◕)ノ', input_message_content=dict(message_text='(ノ◕ヮ◕)ノ')),
                InlineQueryResultArticle(
                    id='l', title='(ノ◕ヮ◕)ノ*:・゚✧', input_message_content=dict(message_text='(ノ◕ヮ◕)ノ*:・゚✧')),
                InlineQueryResultArticle(
                    id='m', title='(◕‿◕)', input_message_content=dict(message_text='(◕‿◕)')),
                InlineQueryResultArticle(
                    id='n', title='(。◕‿‿◕。)', input_message_content=dict(message_text='(。◕‿‿◕。)')),
                InlineQueryResultArticle(
                    id='o', title='(っ◕‿◕)っ', input_message_content=dict(message_text='(っ◕‿◕)っ')),
                InlineQueryResultArticle(
                    id='p', title='(づ。◕‿‿◕。)づ', input_message_content=dict(message_text='(づ。◕‿‿◕。)づ')),
                InlineQueryResultArticle(
                    id='q', title='༼ つ ◕_◕ ༽つ', input_message_content=dict(message_text='༼ つ ◕_◕ ༽つ')),
                InlineQueryResultArticle(
                    id='r', title='(ง ͠° ͟ل͜ ͡°)ง', input_message_content=dict(message_text='(ง ͠° ͟ل͜ ͡°)ง')),
                InlineQueryResultArticle(
                    id='s', title='(ง\'̀-\'́)ง', input_message_content=dict(message_text='(ง\'̀-\'́)ง')),
                InlineQueryResultArticle(
                    id='t', title='ᕙ(⇀‸↼‶)ᕗ', input_message_content=dict(message_text='ᕙ(⇀‸↼‶)ᕗ')),
                InlineQueryResultArticle(
                    id='u', title='(҂⌣̀_⌣́)', input_message_content=dict(message_text='(҂⌣̀_⌣́)')),
                InlineQueryResultArticle(
                    id='v', title='ᕦ(ò_óˇ)ᕤ', input_message_content=dict(message_text='ᕦ(ò_óˇ)ᕤ')),
                InlineQueryResultArticle(
                    id='w', title='╚(ಠ_ಠ)=┐', input_message_content=dict(message_text='╚(ಠ_ಠ)=┐')),
                InlineQueryResultArticle(
                    id='x', title='ლ(ಠ益ಠლ)', input_message_content=dict(message_text='ლ(ಠ益ಠლ)')),
                InlineQueryResultArticle(
                    id='y', title='\\_(ʘ_ʘ)_/', input_message_content=dict(message_text='\\_(ʘ_ʘ)_/')),
                InlineQueryResultArticle(
                    id='z', title='( ⚆ _ ⚆ )', input_message_content=dict(message_text='( ⚆ _ ⚆ )')),
                InlineQueryResultArticle(
                    id='aa', title='(ಥ﹏ಥ)', input_message_content=dict(message_text='(ಥ﹏ಥ)')),
                InlineQueryResultArticle(
                    id='ab', title='﴾͡๏̯͡๏﴿', input_message_content=dict(message_text='﴾͡๏̯͡๏﴿')),
                InlineQueryResultArticle(
                    id='ac', title='(◔̯◔)', input_message_content=dict(message_text='(◔̯◔)')),
                InlineQueryResultArticle(
                    id='ad', title='(ಠ_ಠ)', input_message_content=dict(message_text='(ಠ_ಠ)')),
                InlineQueryResultArticle(
                    id='ae', title='(ಠ‿ಠ)', input_message_content=dict(message_text='(ಠ‿ಠ)')),
                InlineQueryResultArticle(
                    id='af', title='(¬_¬)', input_message_content=dict(message_text='(¬_¬)')),
                InlineQueryResultArticle(
                    id='ag', title='(¬‿¬)', input_message_content=dict(message_text='(¬‿¬)')),
                InlineQueryResultArticle(
                    id='ah', title='\\ (•◡•) /', input_message_content=dict(message_text='\\ (•◡•) /')),
                InlineQueryResultArticle(
                    id='ai', title='(◕‿◕✿)', input_message_content=dict(message_text='(◕‿◕✿)')),
                InlineQueryResultArticle(
                    id='aj', title='( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)',
                    input_message_content=dict(message_text='( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)'))]

            bot.answerInlineQuery(msg['id'], results=articles)


        elif msg['query'].startswith('hidemsg'):
            articles = [InlineQueryResultArticle(
                id='a', title='Resultado: ' + msg['query'][8:],
                input_message_content=InputTextMessageContent(message_text='\u2060' * 3600 + msg['query'][8:]))]
            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)

        else:
            articles = [
                InlineQueryResultArticle(
                    id='a', title='Informações', description='Exibe informações sobre você', input_message_content=dict(
                        message_text='<b>Suas informações:</b>\n\n<b>Nome:</b> <code>' + html.escape(
                            first_name) + '</code>\n<b>ID:</b> <code>' + str(
                            user_id) + '</code>\n<b>Username:</b> <code>' + username + '</code>', parse_mode="HTML")),
                InlineQueryResultArticle(
                    id='b', title='duck', description='searching with ddg engine',
                    input_message_content=dict(message_text='Uso: duck')),
                InlineQueryResultArticle(
                    id='c', title='faces', description='Mostra uma lista de carinhas ¯\\_(ツ)_/¯',
                    input_message_content=dict(
                        message_text='Uso: @{} faces - exibe uma lista de carinhas ¯\\_(ツ)_/¯'.format(bot_username))),
                InlineQueryResultArticle(
                    id='d', title='hidemsg',
                    description='Envia uma mensagem que não aparece nas ações recentes ao ser apagada em até 1 minuto.',
                    input_message_content=dict(
                        message_text='Uso: @{} hidemsg texto para a mensagem\n\nEnvia uma mensagem que se for apagada em até 1 minuto não aparece nas ações recentes do grupo'.format(
                            bot_username))),
                InlineQueryResultArticle(
                    id='e', title='html', description='Formata um texto usando HTML',
                    input_message_content=dict(message_text='Uso: @{} html <b>texto</b>'.format(bot_username))),
                InlineQueryResultArticle(
                    id='f', title='ip', description='Exibe informações de um IP informado',
                    input_message_content=dict(message_text='Uso: @{} ip google.com'.format(bot_username))),
                InlineQueryResultArticle(
                    id='g', title='proxy', description='searching proxy', input_message_content=dict(
                        message_text='Uso: @{} proxy - Exibe uma lista de proxys de vários países.'.format(
                            bot_username))),
                InlineQueryResultArticle(
                    id='h', title='google image', description='searching image using google image', input_message_content=dict(
                        message_text='Uso: @{} image - Exibe uma image de image de vários países.'.format(
                            bot_username))),
                InlineQueryResultArticle(
                    id='i', title='yt', description='Pesquisar vídeos no YouTube', input_message_content=dict(
                        message_text='Uso: @{} yt - Pesquisar vídeos no YouTube.'.format(bot_username)))
            ]

            bot.answerInlineQuery(msg['id'], results=articles, cache_time=60, is_personal=True)
コード例 #13
0
async def rextester(msg):
    if msg.get('text'):
        if msg['text'].startswith('/rextester'):
            text = msg['text'][10:]
            rex = re.split('[ |\n]+', text, 2)
            code = rex[2:]
            reply_id = msg['message_id']
            if not text:
                await bot.sendMessage(
                    msg['chat']['id'],
                    """💻Bem vindo ao meu interpretador de codigos, digite meu comando seguido de uma linguagem de programação seguido de seu codigo, ex: /rextester python seu_codigo!
                    
 💻Linguagens Suportadas: -ada -bash -brainfuck -c_clang -c_gcc -c_vc -c# -c++_clang -c++_gcc -c++_vc++ -d -elixir -erlang -f#  -fortran -go -haskell -java -javascript -kotlin -lisp -lua -mysql -nasm -node.js -objective-c -ocaml -octave -oracle -pascal -perl -php -postgresql -prolog -python -python2 -python3 -py3 -py2 -r -ruby  -scala -scheme -sql server -swift -tcl -vb.net """,
                    reply_to_message_id=reply_id)
            elif len(code) == 0:
                await bot.sendMessage(
                    msg['chat']['id'],
                    '💻me de uma linguagem ex /rextester python seu_codigo',
                    reply_to_message_id=reply_id)
            elif msg['text'].split()[1] not in languages:
                await bot.sendMessage(msg['chat']['id'],
                                      '💻linguagem errada.',
                                      reply_to_message_id=reply_id)
            else:
                langs = rex[1]
                program = ' '.join(code).strip()
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                elif warning:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                elif result and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n*Errors:*\n`{errors}`"
                elif errors:
                    resp = f"*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                else:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                if len(resp) > 4096:
                    await bot.sendMessage(msg['chat']['id'],
                                          'muito longo!',
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
                else:
                    await bot.sendMessage(msg['chat']['id'],
                                          resp,
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
            return True

    elif msg.get('query'):
        if msg['query'].split()[0].lower() == 'run' and len(
                msg['query'].split()) >= 2:
            rex = re.split('[ |\n]+', msg['query'], 2)
            if len(rex) == 2:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='give me code',
                        input_message_content=InputTextMessageContent(
                            message_text='give me code'))
                ]
            elif rex[1].lower() not in languages:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='unknown Lang',
                        input_message_content=InputTextMessageContent(
                            message_text='unknown lang'))
                ]
            else:
                langs = rex[1]
                program = rex[2]
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                elif warning:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                    desc = result or 'NULL'
                elif result and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Errors:*\n`{errors}`"
                    desc = result or 'NULL'
                elif errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                else:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                    desc = result or 'NULL'
                print(shorten_stats(stats))
                print(len(shorten_stats(stats)))
                print(stats)
                print(len(stats))
                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text='Stats',
                                             callback_data='rstats ' +
                                             shorten_stats(stats))
                    ],
                ])
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title=langs,
                        description=desc,
                        input_message_content=InputTextMessageContent(
                            message_text=resp, parse_mode='markdown'),
                        reply_markup=keyboard)
                ]

            return await bot.answerInlineQuery(msg['id'],
                                               results=articles,
                                               cache_time=60,
                                               is_personal=True)

    elif msg.get('data'):
        if msg['data'].startswith('rstats '):
            await bot.answerCallbackQuery(msg['id'],
                                          unshorten_stats(msg['data'][7:]),
                                          show_alert=True)
コード例 #14
0
def handle(msg):
    if 'text' in msg:
        if msg['text'] == '/start':
            teclado = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='Pesquisar letras',
                     switch_inline_query_current_chat='')
            ]])
            bot.sendMessage(
                msg['chat']['id'],
                f'Pesquise por letras de músicas direto do telegram\n\nTeste apertando o botão abaixo:',
                reply_to_message_id=msg['message_id'],
                reply_markup=teclado)
        elif msg['text'].split()[0] == '/letras':
            text = msg['text'].split()[1]
            if text == '':
                bot.sendMessage(msg['chat']['id'],
                                'uso:\n/letras nome da musica',
                                reply_to_message_id=msg['message_id'])
            else:
                res = [
                    '{}: <a href="{}">{} - {}</a>'.format(
                        num + 1, i['link'], i["musica"], i["autor"])
                    for num, i in enumerate(lyricspy.auto(text, 30))
                ] or "Nenhum resultado foi encontrado"
                bot.sendMessage(msg['chat']['id'],
                                '\n'.join(res),
                                'HTML',
                                reply_to_message_id=msg['message_id'],
                                disable_web_page_preview=True)
        elif msg['text'].split()[0] == '/letra':
            text = msg['text'][7:]
            if text == '':
                bot.sendMessage(msg['chat']['id'],
                                'uso:\n/letra nome ou url da letra',
                                reply_to_message_id=msg['message_id'])
            elif re.match(
                    r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+',
                    text):
                print('tem')
                a = lyricspy.letra(text)
                if a:
                    mik = re.split(
                        r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br)',
                        a["link"])[-1]
                    print(mik)
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Telegra.ph',
                             callback_data=f'tell-{mik}|{msg["from"]["id"]}')
                    ]])
                    if a.get('traducao'):
                        teclado = InlineKeyboardMarkup(inline_keyboard=[[
                            dict(
                                text='Telegra.ph',
                                callback_data=f'tell-{mik}|{msg["from"]["id"]}'
                            )
                        ] + [
                            dict(text='Tradução',
                                 callback_data=f'tr_{mik}|{msg["from"]["id"]}')
                        ]])
                    print(teclado)
                    bot.sendMessage(msg['chat']['id'],
                                    '[{} - {}]({})\n{}'.format(
                                        a["musica"], a["autor"], a['link'],
                                        a['letra']),
                                    reply_to_message_id=msg['message_id'],
                                    parse_mode='markdown',
                                    disable_web_page_preview=True,
                                    reply_markup=teclado)
            else:
                print('não tem')
                a = lyricspy.auto(text)[0]
                if a.get('letra'):
                    mik = re.split(
                        r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br)',
                        a["link"])[-1]
                    print(mik)
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Telegra.ph',
                             callback_data=f'tell-{mik}|{msg["from"]["id"]}')
                    ]])
                    if a.get('traducao'):
                        teclado = InlineKeyboardMarkup(inline_keyboard=[[
                            dict(
                                text='Telegra.ph',
                                callback_data=f'tell-{mik}|{msg["from"]["id"]}'
                            )
                        ] + [
                            dict(text='Tradução',
                                 callback_data=f'tr_{mik}|{msg["from"]["id"]}')
                        ]])
                    print(teclado)
                    bot.sendMessage(msg['chat']['id'],
                                    '[{} - {}]({})\n{}'.format(
                                        a["musica"], a["autor"], a['link'],
                                        a['letra']),
                                    reply_to_message_id=msg['message_id'],
                                    parse_mode='markdown',
                                    disable_web_page_preview=True,
                                    reply_markup=teclado)

    elif 'data' in msg:
        if 'tr_' in msg['data']:
            if msg["from"]["id"] == int(msg['data'].split('|')[1]):
                link = msg['data'][3:].split("|")[0]
                a = lyricspy.letra('https://m.letras.mus.br' + link)
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Telegra.ph',
                         callback_data=f'tell_{link}|{msg["from"]["id"]}')
                ]])
                if a.get('traducao'):
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Telegra.ph',
                             callback_data=f'tell_{link}|{msg["from"]["id"]}')
                    ] + [
                        dict(text='Original',
                             callback_data=
                             f"tr-{link}|{int(msg['data'].split('|')[1])}")
                    ]])
                if 'inline_message_id' in msg:
                    bot.editMessageText(msg['inline_message_id'],
                                        '[{} - {}]({})\n{}'.format(
                                            a['musica'], a['autor'], a['link'],
                                            a['traducao']),
                                        parse_mode='markdown',
                                        disable_web_page_preview=True,
                                        reply_markup=teclado)
                else:
                    bot.editMessageText(
                        (msg['message']['chat']['id'],
                         msg['message']['message_id']),
                        '[{} - {}]({})\n{}'.format(a['musica'], a['autor'],
                                                   a['link'], a['traducao']),
                        parse_mode='markdown',
                        disable_web_page_preview=True,
                        reply_markup=teclado)
            else:
                bot.answerCallbackQuery(
                    msg['id'],
                    text='Você não pode editar esta mensagem',
                    show_alert=True)
        if 'tell-' in msg['data']:
            if msg["from"]["id"] == int(msg['data'].split('|')[1]):
                link = msg['data'][5:].split("|")[0]
                a = lyricspy.letra('https://m.letras.mus.br' + link)
                response = send_te(a, a['letra'])
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Texto',
                         callback_data=
                         f"tr-{link}|{int(msg['data'].split('|')[1])}")
                ]])
                if a.get('traducao'):
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Texto',
                             callback_data=
                             f"tr-{link}|{int(msg['data'].split('|')[1])}")
                    ] + [
                        dict(text='Traducão',
                             callback_data=
                             f"tell_{link}|{int(msg['data'].split('|')[1])}")
                    ]])
                if 'inline_message_id' in msg:
                    bot.editMessageText(
                        msg['inline_message_id'],
                        f'https://telegra.ph/{response["path"]}',
                        reply_markup=teclado)
                else:
                    bot.editMessageText(
                        (msg['message']['chat']['id'],
                         msg['message']['message_id']),
                        f'https://telegra.ph/{response["path"]}',
                        reply_markup=teclado)
            else:
                bot.answerCallbackQuery(
                    msg['id'],
                    text='Você não pode editar esta mensagem',
                    show_alert=True)
        if 'tell_' in msg['data']:
            if msg["from"]["id"] == int(msg['data'].split('|')[1]):
                link = msg['data'][5:].split("|")[0]
                a = lyricspy.letra('https://m.letras.mus.br' + link)
                response = send_te(a, a['traducao'])
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Texto',
                         callback_data=
                         f"tr_{link}|{int(msg['data'].split('|')[1])}")
                ]])
                if a.get('traducao'):
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Texto',
                             callback_data=
                             f"tr_{link}|{int(msg['data'].split('|')[1])}")
                    ] + [
                        dict(text='Original',
                             callback_data=
                             f"tell-{link}|{int(msg['data'].split('|')[1])}")
                    ]])
                if 'inline_message_id' in msg:
                    bot.editMessageText(
                        msg['inline_message_id'],
                        f'https://telegra.ph/{response["path"]}',
                        reply_markup=teclado)
                else:
                    bot.editMessageText(
                        (msg['message']['chat']['id'],
                         msg['message']['message_id']),
                        f'https://telegra.ph/{response["path"]}',
                        reply_markup=teclado)
            else:
                bot.answerCallbackQuery(
                    msg['id'],
                    text='Você não pode editar esta mensagem',
                    show_alert=True)
        if 'tr-' in msg['data']:
            if msg["from"]["id"] == int(msg['data'].split('|')[1]):
                link = msg['data'][3:].split("|")[0]
                a = lyricspy.letra('https://m.letras.mus.br' + link)
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Telegra.ph',
                         callback_data=f'tell-{link}|{msg["from"]["id"]}')
                ]])
                if a.get('traducao'):
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Telegra.ph',
                             callback_data=f'tell-{link}|{msg["from"]["id"]}')
                    ] + [
                        dict(text='Tradução',
                             callback_data=f'tr_{link}|{msg["from"]["id"]}')
                    ]])
                if 'inline_message_id' in msg:
                    bot.editMessageText(msg['inline_message_id'],
                                        '[{} - {}]({})\n{}'.format(
                                            a['musica'], a['autor'], a['link'],
                                            a['letra']),
                                        parse_mode='markdown',
                                        disable_web_page_preview=True,
                                        reply_markup=teclado)
                else:
                    bot.editMessageText(
                        (msg['message']['chat']['id'],
                         msg['message']['message_id']),
                        '[{} - {}]({})\n{}'.format(a['musica'], a['autor'],
                                                   a['link'], a['letra']),
                        parse_mode='markdown',
                        disable_web_page_preview=True,
                        reply_markup=teclado)
            else:
                bot.answerCallbackQuery(
                    msg['id'],
                    text='Você não pode editar esta mensagem',
                    show_alert=True)
    elif 'query' in msg:
        if msg.get('inline_message_id'):
            teclado = None
            try:
                a = lyricspy.letra(msg['result_id'])
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Telegra.ph',
                         callback_data=f'tell-{a["link"]}|{msg["from"]["id"]}')
                ]])
                if a.get('traducao'):
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Telegra.ph',
                             callback_data=
                             f'tell-{a["link"]}|{msg["from"]["id"]}')
                    ] + [
                        dict(
                            text='Tradução',
                            callback_data=f'tr_{a["link"]}|{msg["from"]["id"]}'
                        )
                    ]])
                bot.editMessageText(msg['inline_message_id'],
                                    '[{} - {}]({})\n{}'.format(
                                        a['musica'], a['autor'], a['link'],
                                        a['letra']),
                                    parse_mode='markdown',
                                    disable_web_page_preview=True,
                                    reply_markup=teclado)
            except Exception as e:
                print(e)
                bot.editMessageText(msg['inline_message_id'],
                                    'ocorreu um erro ao exibir a letra')
        elif msg['query'] != '':
            articles = []
            result = lyricspy.auto(msg['query'])
            for a in result:
                teclado = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='Aguarde...', callback_data='a')
                ]])
                articles.append(
                    InlineQueryResultArticle(
                        id=a['link'],
                        title=f'{a["musica"]} - {a["autor"]}',
                        input_message_content=InputTextMessageContent(
                            message_text='Aguarde...',
                            parse_mode='markdown',
                            disable_web_page_preview=True),
                        reply_markup=teclado))
            if not articles:
                articles = [
                    InlineQueryResultArticle(
                        id='abcde',
                        title=f'sem resultado',
                        input_message_content=InputTextMessageContent(
                            message_text=f"sem resultado para {msg['query']}"))
                ]
            bot.answerInlineQuery(msg['id'],
                                  results=articles,
                                  is_personal=True)
コード例 #15
0
ファイル: rextester.py プロジェクト: PerU-MoNsteR/EduRobot
async def rextester(msg):
    if msg.get('text'):
        if msg['text'].startswith('/rextester') or msg['text'].startswith(
                '!rextester'):
            text = msg['text'][10:]
            rex = re.split('[ |\n]+', text, 2)
            code = rex[2:]
            reply_id = msg['message_id']
            if not text:
                await bot.sendMessage(msg['chat']['id'],
                                      'give me lang',
                                      reply_to_message_id=reply_id)
            elif len(code) == 0:
                await bot.sendMessage(msg['chat']['id'],
                                      'give me code',
                                      reply_to_message_id=reply_id)
            elif msg['text'].split()[1] not in languages:
                await bot.sendMessage(msg['chat']['id'],
                                      'wrong langs',
                                      reply_to_message_id=reply_id)
            else:
                langs = rex[1]
                program = ' '.join(code).strip()
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                elif warning:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                elif result and errors:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n*Errors:*\n`{errors}`"
                elif errors:
                    resp = f"*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                else:
                    resp = f"*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                if len(resp) > 4096:
                    await bot.sendMessage(msg['chat']['id'],
                                          'msgs are too long!',
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
                else:
                    await bot.sendMessage(msg['chat']['id'],
                                          resp,
                                          reply_to_message_id=reply_id,
                                          parse_mode='markdown')
            return True

    elif msg.get('query'):
        if msg['query'].split()[0].lower() == 'run' and len(
                msg['query'].split()) >= 2:
            rex = re.split('[ |\n]+', msg['query'], 2)
            if len(rex) == 2:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='give me code',
                        input_message_content=InputTextMessageContent(
                            message_text='give me code'))
                ]
            elif rex[1].lower() not in languages:
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title='unknown Lang',
                        input_message_content=InputTextMessageContent(
                            message_text='unknown lang'))
                ]
            else:
                langs = rex[1]
                program = rex[2]
                source = await rexec_aio(langs, program)
                result = source.results
                warning = source.warnings
                errors = source.errors
                stats = source.stats
                if warning and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Warning:*\n`{warning}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                elif warning:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Warning:*\n`{warning}`"
                    desc = result or 'NULL'
                elif result and errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`\n\n*Errors:*\n`{errors}`"
                    desc = result or 'NULL'
                elif errors:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Errors:*\n`{errors}`"
                    desc = errors
                else:
                    resp = f"*Language:*\n`{langs}`\n\n*Source:*\n`{program}`\n\n*Results:*\n`{result}`"
                    desc = result or 'NULL'
                print(shorten_stats(stats))
                print(len(shorten_stats(stats)))
                print(stats)
                print(len(stats))
                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text='Stats',
                                             callback_data='rstats ' +
                                             shorten_stats(stats))
                    ],
                ])
                articles = [
                    InlineQueryResultArticle(
                        id='a',
                        title=langs,
                        description=desc,
                        input_message_content=InputTextMessageContent(
                            message_text=resp, parse_mode='markdown'),
                        reply_markup=keyboard)
                ]

            return await bot.answerInlineQuery(msg['id'],
                                               results=articles,
                                               cache_time=60,
                                               is_personal=True)

    elif msg.get('data'):
        if msg['data'].startswith('rstats '):
            await bot.answerCallbackQuery(msg['id'],
                                          unshorten_stats(msg['data'][7:]),
                                          show_alert=True)
コード例 #16
0
def inlines(msg):
    if 'query' in msg:
        first_name = msg['from']['first_name']
        user_id = msg['from']['id']
        if 'username' in msg['from']:
            username = '******' + msg['from']['username']
        else:
            username = '******'
        if msg['query'].startswith('/ip') and len(msg['query']) > 7:
            r = requests.get(geo_ip + msg['query'][4:])
            x = ''
            for i in r.json():
                x += "*{}*: `{}`\n".format(i, r.json()[i])
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title='Informações de ' + msg['query'][4:],
                    input_message_content=InputTextMessageContent(
                        message_text='*Consulta*: `' + msg['query'][4:] +
                        '`\n\n' + x,
                        parse_mode="Markdown"))
            ]

        elif msg['query'].startswith('/echo'):
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title=msg['query'][6:],
                    input_message_content=InputTextMessageContent(
                        message_text=msg['query'][6:]))
            ]

        elif msg['query'].startswith('/invert'):
            query = msg['query'][8:]
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title=query[::-1],
                    input_message_content=InputTextMessageContent(
                        message_text=query[::-1]))
            ]

        elif msg['query'].startswith('/markdown'):
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title=msg['query'][10:],
                    input_message_content=InputTextMessageContent(
                        message_text=kk, parse_mode='Markdown'))
            ]

        elif msg['query'].startswith('/html'):
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title=msg['query'][6:],
                    input_message_content=InputTextMessageContent(
                        message_text=msg['query'][6:], parse_mode='html'))
            ]

        elif msg['query'].startswith('/faces'):
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title='¯\\_(ツ)_/¯',
                    input_message_content=InputTextMessageContent(
                        message_text='¯\\_(ツ)_/¯')),
                dict(type='article',
                     id='b',
                     title='( ͡° ͜ʖ ͡°)',
                     input_message_content=dict(message_text='( ͡° ͜ʖ ͡°)')),
                dict(type='article',
                     id='c',
                     title='( ͡~ ͜ʖ ͡°)',
                     input_message_content=dict(message_text='( ͡~ ͜ʖ ͡°)')),
                dict(type='article',
                     id='d',
                     title='( ͡◐ ͜ʖ ͡◑))',
                     input_message_content=dict(message_text='( ͡◐ ͜ʖ ͡◑))')),
                dict(type='article',
                     id='e',
                     title='( ͡◔ ͜ʖ ͡◔)',
                     input_message_content=dict(message_text='( ͡◔ ͜ʖ ͡◔)')),
                dict(type='article',
                     id='f',
                     title='( ͡⚆ ͜ʖ ͡⚆)',
                     input_message_content=dict(message_text='( ͡⚆ ͜ʖ ͡⚆)')),
                dict(type='article',
                     id='g',
                     title='( ͡ʘ ͜ʖ ͡ʘ)',
                     input_message_content=dict(message_text='( ͡ʘ ͜ʖ ͡ʘ)')),
                dict(type='article',
                     id='h',
                     title='ヽ༼ຈل͜ຈ༽ノ',
                     input_message_content=dict(message_text='ヽ༼ຈل͜ຈ༽ノ')),
                dict(type='article',
                     id='i',
                     title='༼ʘ̚ل͜ʘ̚༽',
                     input_message_content=dict(message_text='༼ʘ̚ل͜ʘ̚༽')),
                dict(type='article',
                     id='j',
                     title='(╯°□°)╯',
                     input_message_content=dict(message_text='(╯°□°)╯')),
                dict(type='article',
                     id='k',
                     title='(ノ◕ヮ◕)ノ',
                     input_message_content=dict(message_text='(ノ◕ヮ◕)ノ')),
                dict(type='article',
                     id='l',
                     title='(ノ◕ヮ◕)ノ*:・゚✧',
                     input_message_content=dict(message_text='(ノ◕ヮ◕)ノ*:・゚✧')),
                dict(type='article',
                     id='m',
                     title='(◕‿◕)',
                     input_message_content=dict(message_text='(◕‿◕)')),
                dict(type='article',
                     id='n',
                     title='(。◕‿‿◕。)',
                     input_message_content=dict(message_text='(。◕‿‿◕。)')),
                dict(type='article',
                     id='o',
                     title='(っ◕‿◕)っ',
                     input_message_content=dict(message_text='(っ◕‿◕)っ')),
                dict(type='article',
                     id='p',
                     title='(づ。◕‿‿◕。)づ',
                     input_message_content=dict(message_text='(づ。◕‿‿◕。)づ')),
                dict(type='article',
                     id='q',
                     title='༼ つ ◕_◕ ༽つ',
                     input_message_content=dict(message_text='༼ つ ◕_◕ ༽つ')),
                dict(
                    type='article',
                    id='r',
                    title='(ง ͠° ͟ل͜ ͡°)ง',
                    input_message_content=dict(message_text='(ง ͠° ͟ل͜ ͡°)ง')),
                dict(type='article',
                     id='s',
                     title='(ง\'̀-\'́)ง',
                     input_message_content=dict(message_text='(ง\'̀-\'́)ง')),
                dict(type='article',
                     id='t',
                     title='ᕙ(⇀‸↼‶)ᕗ',
                     input_message_content=dict(message_text='ᕙ(⇀‸↼‶)ᕗ')),
                dict(type='article',
                     id='u',
                     title='(҂⌣̀_⌣́)',
                     input_message_content=dict(message_text='(҂⌣̀_⌣́)')),
                dict(type='article',
                     id='v',
                     title='ᕦ(ò_óˇ)ᕤ',
                     input_message_content=dict(message_text='ᕦ(ò_óˇ)ᕤ')),
                dict(type='article',
                     id='w',
                     title='╚(ಠ_ಠ)=┐',
                     input_message_content=dict(message_text='╚(ಠ_ಠ)=┐')),
                dict(type='article',
                     id='x',
                     title='ლ(ಠ益ಠლ)',
                     input_message_content=dict(message_text='ლ(ಠ益ಠლ)')),
                dict(type='article',
                     id='y',
                     title='\\_(ʘ_ʘ)_/',
                     input_message_content=dict(message_text='\\_(ʘ_ʘ)_/')),
                dict(type='article',
                     id='z',
                     title='( ⚆ _ ⚆ )',
                     input_message_content=dict(message_text='( ⚆ _ ⚆ )')),
                dict(type='article',
                     id='aa',
                     title='(ಥ﹏ಥ)',
                     input_message_content=dict(message_text='(ಥ﹏ಥ)')),
                dict(type='article',
                     id='ab',
                     title='﴾͡๏̯͡๏﴿',
                     input_message_content=dict(message_text='﴾͡๏̯͡๏﴿')),
                dict(type='article',
                     id='ac',
                     title='(◔̯◔)',
                     input_message_content=dict(message_text='(◔̯◔)')),
                dict(type='article',
                     id='ad',
                     title='(ಠ_ಠ)',
                     input_message_content=dict(message_text='(ಠ_ಠ)')),
                dict(type='article',
                     id='ae',
                     title='(ಠ‿ಠ)',
                     input_message_content=dict(message_text='(ಠ‿ಠ)')),
                dict(type='article',
                     id='af',
                     title='(¬_¬)',
                     input_message_content=dict(message_text='(¬_¬)')),
                dict(type='article',
                     id='ag',
                     title='(¬‿¬)',
                     input_message_content=dict(message_text='(¬‿¬)')),
                dict(type='article',
                     id='ah',
                     title='\\ (•◡•) /',
                     input_message_content=dict(message_text='\\ (•◡•) /')),
                dict(type='article',
                     id='ai',
                     title='(◕‿◕✿)',
                     input_message_content=dict(message_text='(◕‿◕✿)')),
                dict(type='article',
                     id='aj',
                     title='( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)',
                     input_message_content=dict(
                         message_text='( ͡°( ͡° ͜ʖ( ͡° ͜ʖ ͡°)ʖ ͡°) ͡°)'))
            ]

        elif msg['query'].startswith('/hidemsg'):
            articles = [
                InlineQueryResultArticle(
                    id='abcde',
                    title='Resultado: ' + msg['query'][9:],
                    input_message_content=InputTextMessageContent(
                        message_text='\u2060' * 3600 + msg['query'][9:]))
            ]

        else:
            articles = [
                InlineQueryResultArticle(
                    id='a',
                    title='/echo',
                    description='Repete o texto informado',
                    input_message_content=InputTextMessageContent(
                        message_text='Uso: @{} /echo texto'.format(
                            bot_username))),
                dict(
                    type='article',
                    id='b',
                    title='/faces',
                    description='Mostra uma lista de carinhas ¯\\_(ツ)_/¯',
                    input_message_content=dict(
                        message_text=
                        'Uso: @{} /faces - exibe uma lista de carinhas ¯\\_(ツ)_/¯'
                        .format(bot_username))),
                dict(
                    type='article',
                    id='c',
                    title='/hidemsg',
                    description=
                    'Envia uma mensagem que não aparece nas ações recentes ao ser apagada em até 1 minuto.',
                    input_message_content=dict(
                        message_text=
                        'Uso: @{} /hidemsg texto para a mensagem\n\nEnvia uma mensagem que se for apagada em até 1 minuto não aparece nas ações recentes do grupo'
                        .format(bot_username))),
                dict(type='article',
                     id='d',
                     title='/html',
                     description='Formata um texto usando HTML',
                     input_message_content=dict(
                         message_text='Uso: @{} /html <b>texto</b>'.format(
                             bot_username))),
                dict(type='article',
                     id='e',
                     title='/id',
                     description='Exibe informações sobre você',
                     input_message_content=dict(
                         message_text='Suas informações:\n\nNome: ' +
                         first_name + '\nID: ' + str(user_id) +
                         '\nUsername: '******'article',
                     id='f',
                     title='/ip',
                     description='Exibe informações de um IP informado',
                     input_message_content=dict(
                         message_text='Uso: @{} /ip google.com'.format(
                             bot_username))),
                dict(type='article',
                     id='g',
                     title='/markdown',
                     description='Formata um texto usando Markdown',
                     input_message_content=dict(
                         message_text='Uso: @{} /markdown *texto*'.format(
                             bot_username)))
            ]

        bot.answerInlineQuery(msg['id'], results=articles, is_personal=True)