Example #1
0
def handle(msg):
    if 'text' in msg:
        if '/spoti' in msg['text']:
            spoti(msg, bot)
        elif msg['text'] == '/start':
            teclado = InlineKeyboardMarkup(
                inline_keyboard=[[dict(text='Pesquisar letras', switch_inline_query_current_chat='')]])
            bot.sendMessage(msg['chat']['id'],
                            'Pesquise por letras de músicas direto do Telegram :D\n\n'
                            '   - _Para mais informaçoes, use_ /help\n\n'
                            'Vamos iniciar? Comece testando pelo botão abaixo:',
                            reply_to_message_id=msg['message_id'],
                            reply_markup=teclado,
                            parse_mode='markdown')
        elif msg['text'] == '/help':
            bot.sendMessage(msg['chat']['id'],
                            'Este bot exibe letra de músicas de acordo com sua pesquisa, utilizando o letras.mus.br.\n\n'
                            'Você pode pesquisar atravez do modo inline (@lyricspyrobot <música>), ou até mesmo ver a letra da música que está tocando em seu Spotify atravez do spoti (necessitalogin) :D\n\n'
                            'Os seguintes comandos estão disponiveis:\n'
                            '   • /letra <música> (pesquisa determinada letra)\n'
                            '   • /spoti (mostra a música atual tocando ~não necessita premium~)\n\n'
                            'Em caso de dúvida, entre em contato pelo @AmanoSupport ou por nosso chat @AmanoChat.\n'
                            '- Novidades e atualizações serão postadas no canal @AmanoTeam.',reply_to_message_id=msg['message_id'])
        elif msg['text'].split()[0] == '/letras':
            text = msg['text'].split()[1]
            if text == '':
                bot.sendMessage(msg['chat']['id'], '**Uso:** /letra <nome da música>',
                                reply_to_message_id=msg['message_id'],
                                parse_mode='markdown')
            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 not text:
                return bot.sendMessage(msg['chat']['id'], '**Uso:** /letra <nome da música>',
                                       reply_to_message_id=msg['message_id'],
                                       parse_mode='markdown')
            elif re.match(r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+', text):
                a = lyricspy.letra(text)
            else:
                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]
                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"]}')]])
                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:
                bot.sendMessage(msg['chat']['id'], "Letra não encontrada :(",
                                reply_to_message_id=msg['message_id'])
Example #2
0
async def spoti(msg):
    if msg['text'] == '/spoti':
        tk = db.get(msg['from']['id'])
        if not tk:
            kb = InlineKeyboardMarkup(inline_keyboard=[
                [dict(text='Login', url='https://xn--f77h6a.ml/1ec28a')]
            ])
            await bot.sendMessage(msg['chat']['id'],
                            'Use o botão abaixo e faça login. Em seguida, mande o link após o comando /spoti.\n\n'
                            '**Ex.:** ```/spoti https://lyricspy.ml/go?code=AQCan-Nd1Mk2qToUGsIopwV_yOm```',
                            parse_mode='markdown',
                            reply_to_message_id=msg['message_id'],
                            reply_markup=kb)
        else:
            a = get_current_playing(msg['from']['id'])
            if a is None:
                await bot.sendMessage(msg['chat']['id'], 'No momento não há nada tocando. Que tal dar um _play_ em seu Spotify?',
                                parse_mode='markdown',
                                reply_to_message_id=msg['message_id'])
            else:
                await bot.sendMessage(msg['chat']['id'],
                                       f"🎶 {a['item']['artists'][0]['name']} - {a['item']['name']}")
                text = f"{a['item']['artists'][0]['name']} {a['item']['name']}"
                print(text)
                a = await mux.auto(text, limit=1)
                if not a:
                    a = await let.auto(text, limit=1)
                    if not a:
                        await bot.sendMessage(msg['chat']['id'],
                                        'Letra não encontrada :(',reply_to_message_id=msg['message_id'])
                        return True
                a = a[0]
                hash = hashlib.md5(a['link'].encode()).hexdigest()
                db.add_hash(hash, a)
                user = msg['from']['id']
                if 'traducao' in a:
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}')]+[dict(text=a['tr_name']or'tradução', callback_data=f'-{hash}')]])
                else:
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}')]])
                await bot.sendMessage(msg['chat']['id'],
                                '[{} - {}]({})\n{}'.format(a["musica"], a["autor"], a['link'], a['letra'])[:4096]
                                ,reply_to_message_id=msg['message_id'], disable_web_page_preview=True, reply_markup=teclado, parse_mode='markdown')
    else:
        text = msg['text'].split(' ',1)[1]
        if 'lyricspy.ml' in text:
            access_code = text.split('code=')[1]
        else:
            access_code = text
        res = get_token(msg['from']['id'], access_code)
        if res[0]:
            await bot.sendMessage(msg['chat']['id'], 'ok')
        else:
            await bot.sendMessage(msg['chat']['id'], f'ocorreu um erro:\n{res[1]}')
Example #3
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)
Example #4
0
async def on_chat_message(msg):
    content_type, chat_type, chat_id = amanobot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)

    if content_type != 'text':
        return

    command = msg['text'][-1:].lower()

    if command == 'c':
        markup = ReplyKeyboardMarkup(keyboard=[
                     ['Plain text', KeyboardButton(text='Text only')],
                     [dict(text='Phone', request_contact=True), KeyboardButton(text='Location', request_location=True)],
                 ])
        await bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup)
    elif command == 'i':
        markup = InlineKeyboardMarkup(inline_keyboard=[
                     [dict(text='Telegram URL', url='https://core.telegram.org/')],
                     [InlineKeyboardButton(text='Callback - show notification', callback_data='notification')],
                     [dict(text='Callback - show alert', callback_data='alert')],
                     [InlineKeyboardButton(text='Callback - edit message', callback_data='edit')],
                     [dict(text='Switch to using bot inline', switch_inline_query='initial query')],
                 ])

        global message_with_inline_keyboard
        message_with_inline_keyboard = await bot.sendMessage(chat_id, 'Inline keyboard with various buttons', reply_markup=markup)
    elif command == 'h':
        markup = ReplyKeyboardRemove()
        await bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup)
    elif command == 'f':
        markup = ForceReply()
        await bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
Example #5
0
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
Example #6
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)
Example #7
0
async def pypi(msg):
    if msg.get('text'):
        if msg['text'].startswith('/pypi ') or msg['text'].startswith('!pypi '):
            text = msg['text'][6:]
            async with aiohttp.ClientSession() as session:
                r = await session.get(f"https://pypi.org/pypi/{text}/json",
                                      headers={"User-Agent": str(uuid4())})
            if r.status == 200:
                json = await r.json()
                pypi_info = escape_definition(json["info"])
                message = "<b>%s</b> by <i>%s</i> (%s)\n" \
                          "Platform: <b>%s</b>\n" \
                          "Version: <b>%s</b>\n" \
                          "License: <b>%s</b>\n" \
                          "Summary: <b>%s</b>\n" % (
                              pypi_info["name"], pypi_info["author"], pypi_info["author_email"], pypi_info["platform"],
                              pypi_info["version"], pypi_info["platform"], pypi_info["summary"])
                if pypi_info['home_page'] and pypi_info['home_page'] != "UNKNOWN":
                    kb = InlineKeyboardMarkup(inline_keyboard=[
                                              [dict(text='Package home page', url=pypi_info['home_page'])]])
                else:
                    kb = None
                await bot.sendMessage(msg['chat']['id'], message, reply_to_message_id=msg['message_id'],
                                      parse_mode="HTML", disable_web_page_preview=True, reply_markup=kb)
            else:
                await bot.sendMessage(msg['chat']['id'], f"Cant find *{text}* in pypi (Returned code was {r.status})",
                                      reply_to_message_id=msg['message_id'], parse_mode="Markdown",
                                      disable_web_page_preview=True)
            return True
Example #8
0
File: pypi.py Project: hanslett12/a
def pypi(msg):
    if msg.get('text'):
        if msg['text'].startswith('/pypi ') or msg['text'].startswith(
                '!pypi '):
            text = msg['text'][6:]
            r = requests.get(f"https://pypi.python.org/pypi/{text}/json",
                             headers={"User-Agent": "Eduu/v1.0_Beta"})
            if r.ok:
                pypi = escape_definition(r.json()["info"])
                MESSAGE = "<b>%s</b> by <i>%s</i> (%s)\n" \
                          "Platform: <b>%s</b>\n" \
                          "Version: <b>%s</b>\n" \
                          "License: <b>%s</b>\n" \
                          "Summary: <b>%s</b>\n" % (pypi["name"], pypi["author"], pypi["author_email"], pypi["platform"],
                                                    pypi["version"], pypi["platform"], pypi["summary"])
                return bot.sendMessage(
                    msg['chat']['id'],
                    MESSAGE,
                    reply_to_message_id=msg['message_id'],
                    parse_mode="HTML",
                    disable_web_page_preview=True,
                    reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Package home page',
                             url='{}'.format(pypi['home_page']))
                    ]]))
            else:
                return bot.sendMessage(msg['chat']['id'],
                                       f"Cant find *{text}* in pypi",
                                       reply_to_message_id=msg['message_id'],
                                       parse_mode="Markdown",
                                       disable_web_page_preview=True)
Example #9
0
def chosen_inline_result(msg):
    try:
        a = lyricspy.letra(msg['result_id'])
        mik = re.split(r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br)', a["link"])[-1]
        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.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'], f'ocorreu um erro ao exibir a letra\nErro:{e}')
Example #10
0
 async def on_chat_message(self, msg):
     content_type, chat_type, chat_id = glance(msg)
     await self.sender.sendMessage(
         'Press START to do some math ...',
         reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
             InlineKeyboardButton(text='START', callback_data='start'),
         ]]))
     self.close()  # let Quizzer take over
Example #11
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = amanobot.glance(msg)

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                   [InlineKeyboardButton(text='Press me', callback_data='press')],
               ])

    bot.sendMessage(chat_id, 'Use inline keyboard', reply_markup=keyboard)
Example #12
0
def botao2():
    menu = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Link do grupo', callback_data='L'),
         InlineKeyboardButton(text='Help', callback_data='SOS')],
        [InlineKeyboardButton(text='Sites + usados', callback_data='url')],
        [InlineKeyboardButton(text='Conteúdo', callback_data='co')],
    ])
    return menu
Example #13
0
def botao4():
    conte = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Cursos', callback_data='curs'),
         InlineKeyboardButton(text='Livros', callback_data='li')],
        [InlineKeyboardButton(text='Musicas', callback_data='mu')],
        [InlineKeyboardButton(text='Radios', callback_data='ha')],
    ])
    return conte
Example #14
0
def welcome(msg):
    if msg.get('text'):
        if msg['text'].split()[0] == '/welcome' or msg['text'].split()[0] == '/welcome@'+bot_username or msg['text'].split()[0] == '!welcome':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(msg['chat']['id'], 'Este comando só funciona em grupos ¯\\_(ツ)_/¯')

            elif is_admin(msg['chat']['id'], msg['from']['id']):
                text = msg['text'].split(' ', 1)
                if len(text) == 1:
                    bot.sendMessage(msg['chat']['id'], 'Uso: /welcome on/off/reset/mensagem de boas-vindas do grupo (suporta Markdown e as tags $name, $title, $id e $rules)',
                                    reply_to_message_id=msg['message_id'])
                elif text[1] == 'on':
                    enable_welcome(msg['chat']['id'])
                    bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi ativada.',
                                    reply_to_message_id=msg['message_id'])
                elif text[1] == 'off':
                    disable_welcome(msg['chat']['id'])
                    bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi desativada.',
                                    reply_to_message_id=msg['message_id'])
                elif text[1] == 'reset':
                    set_welcome(msg['chat']['id'], None)
                    bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi redefinida.',
                                    reply_to_message_id=msg['message_id'])
                else:
                    set_welcome(msg['chat']['id'], text[1])
                    bot.sendMessage(msg['chat']['id'], 'A mensagem de boas-vindas foi definida.',
                                    reply_to_message_id=msg['message_id'])


    elif msg.get('new_chat_member'):
        chat_title = msg['chat']['title']
        chat_id = msg['chat']['id']
        first_name = msg['new_chat_member']['first_name']
        user_id = msg['new_chat_member']['id']
        if msg['new_chat_member']['id'] == bot_id:
            pass
        else:
            welcome = get_welcome(chat_id)
            if welcome[1]:
                if welcome[0] != None:
                    welcome = welcome[0].replace('$name', escape(first_name)).replace('$title', escape(chat_title)).replace('$id', str(user_id))
                else:
                    welcome = 'Olá {}, seja bem-vindo(a) ao {}!'.format(first_name, escape(chat_title))
                if '$rules' in welcome:
                    welcome = welcome.replace('$rules', '')
                    rules_markup = InlineKeyboardMarkup(inline_keyboard=[
                        [dict(text='Leia as regras',
                                  url='https://t.me/{}?start=rules_{}'.format(bot_username, chat_id))]
                    ])
                else:
                    rules_markup = None
                bot.sendMessage(chat_id, welcome, 'Markdown',
                                reply_to_message_id=msg['message_id'],
                                reply_markup=rules_markup,
                                disable_web_page_preview=True)
                
Example #15
0
async def lastfm(msg):
    if msg['text'] == '/lfm':
        tk = db.get(msg['from']['id'])
        if not tk[2]:
            await bot.sendMessage(msg['chat']['id'],
                            'Mande seu user do last.fm após o /lfm.\n\n'
                            '**Ex.:** ```/lfm alisson```',
                            parse_mode='markdown',
                            reply_to_message_id=msg['message_id'])
        else:
            a = get_current(tk[2])
            if not a:
                await bot.sendMessage(msg['chat']['id'], 'No momento não há nada tocando. Que tal dar um _play_ em sua playlist?',
                                parse_mode='markdown',
                                reply_to_message_id=msg['message_id'])
            else:
                await bot.sendMessage(msg['chat']['id'],
                                      f"🎶 {a[0]['artist']['#text']} - {a[0]['name']}")
                text = f"{a[0]['artist']['#text']} {a[0]['name']}"
                print(text)
                a = await mux.auto(text, limit=1)
                if not a:
                    a = await let.auto(text, limit=1)
                    if not a:
                        await bot.sendMessage(msg['chat']['id'],
                                        'Letra não encontrada :(',reply_to_message_id=msg['message_id'])
                        return True
                a = a[0]
                hash = hashlib.md5(a['link'].encode()).hexdigest()
                db.add_hash(hash, a)
                user = msg['from']['id']
                if 'traducao' in a:
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}')]+[dict(text=a['tr_name']or'tradução', callback_data=f'-{hash}')]])
                else:
                    teclado = InlineKeyboardMarkup(inline_keyboard=[[dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}')]])
                await bot.sendMessage(msg['chat']['id'],
                                '[{} - {}]({})\n{}'.format(a["musica"], a["autor"], a['link'], a['letra'])[:4096]
                                ,reply_to_message_id=msg['message_id'], disable_web_page_preview=True, reply_markup=teclado, parse_mode='markdown')
    else:
        text = msg['text'].split(' ',1)[1]
        db.add_user_last(msg['from']['id'], text)
        await bot.sendMessage(msg['chat']['id'], 'ok')
Example #16
0
class Lover(amanobot.helper.ChatHandler):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                   InlineKeyboardButton(text='Yes', callback_data='yes'),
                   InlineKeyboardButton(text='um ...', callback_data='no'),
               ]])

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._count, self._edit_msg_ident = propose_records[self.id]
            self._editor = amanobot.helper.Editor(self.bot, self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._count = 0
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        self._count += 1
        sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self.keyboard)
        self._editor = amanobot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = amanobot.message_identifier(sent)

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        self._propose()

    def on_callback_query(self, msg):
        query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')

        if query_data == 'yes':
            self._cancel_last()
            self.sender.sendMessage('Thank you!')
            self.close()
        else:
            self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
            self._cancel_last()
            self._propose()

    def on__idle(self, event):
        self.sender.sendMessage('I know you may need a little time. I will always be here for you.')
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._count, self._edit_msg_ident)
Example #17
0
            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'),
                    ]]))
Example #18
0
    def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
            InlineKeyboardButton(text='Yes', callback_data='yes'),
            InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
        ]])
        sent = self.sender.sendMessage("Let's Vote ...", reply_markup=keyboard)

        self._ballot_box = {}
        self._keyboard_msg_ident = amanobot.message_identifier(sent)
        self._editor = amanobot.helper.Editor(self.bot,
                                              self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(
            30, ('_vote_expired', {
                'seconds': 30
            }))
Example #19
0
    def _show_next_question(self):
        x = random.randint(1,50)
        y = random.randint(1,50)
        sign, op = random.choice([('+', lambda a,b: a+b),
                                  ('-', lambda a,b: a-b),
                                  ('x', lambda a,b: a*b)])
        answer = op(x,y)
        question = '%d %s %d = ?' % (x, sign, y)
        choices = sorted(list(map(random.randint, [-49]*4, [2500]*4)) + [answer])

        self.editor.editMessageText(question,
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[
                    list(map(lambda c: InlineKeyboardButton(text=str(c), callback_data=str(c)), choices))
                ]
            )
        )
        return answer
Example #20
0
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
Example #21
0
def EnviaPerguntas(chat_id):
	data = datetime.now(timezone('Brazil/East')).strftime('%Y%m%d')

	keybVoto = InlineKeyboardMarkup(inline_keyboard=[[
			InlineKeyboardButton(text="Sim", callback_data=data+'|sim'),
			InlineKeyboardButton(text="Não", callback_data=data+'|nao'),
	]])

	stamps = getTimes(chat_id)
	send_question = True if (len(stamps) == 0) else True if (str(data) not in stamps[0]) else False
	if (send_question):
		enviada = bot.sendMessage(chat_id,"Você dormiu mais de 6 horas por noite a cada dia nessa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você praticou alguma atividade física em ao menos 1 dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você fez algo que te dá muito prazer, fora trabalho, em ao menos um dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
		enviada = bot.sendMessage(chat_id,"Você teve algum momento de autocuidado (relacionado à auto estima, beleza etc) em ao menos um dia essa semana?",reply_markup=keybVoto)
		insertQuestion(enviada['message_id'],enviada['text'],data,chat_id)
	else:
		bot.sendMessage(chat_id,"Já foi enviada uma enquete hoje")
Example #22
0
    async def _init_ballot(self):
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
            InlineKeyboardButton(text='Yes', callback_data='yes'),
            InlineKeyboardButton(text='Nah!!!!', callback_data='no'),
        ]])
        sent = await self.sender.sendMessage("Let's Vote ...",
                                             reply_markup=keyboard)

        self._member_count = await self.administrator.getChatMembersCount(
        ) - 1  # exclude myself, the bot

        self._ballot_box = {}
        self._keyboard_msg_ident = message_identifier(sent)
        self._editor = amanobot.aio.helper.Editor(self.bot,
                                                  self._keyboard_msg_ident)

        # Generate an expiry event 30 seconds later
        self._expired_event = self.scheduler.event_later(
            30, ('_vote_expired', {
                'seconds': 30
            }))
Example #23
0
def callback(msg):
	query_id, from_id, query_data = amanobot.glance(msg, flavor='callback_query')
	#print(msg)
	message_id = msg['message']['message_id']
	chat_id = msg['message']['chat']['id']

	refreshButton = False
	data = query_data.split('|')
	timestamp = data[0]

	if data[1] == 'sim' or data[1] == 'nao':
		if data[1] == 'sim':
			if count('sim',from_id, chat_id,message_id) == 0:
				delete('nao',from_id, chat_id,message_id,timestamp)
				insert('sim',from_id, chat_id,message_id,timestamp)
				bot.answerCallbackQuery(query_id,"Votado!")
				refreshButton = True
			else:
				bot.answerCallbackQuery(query_id,"Você já votou nessa opção!")

		if data[1] == 'nao':
			if count('nao',from_id, chat_id,message_id) == 0:
				delete('sim',from_id, chat_id,message_id,timestamp)
				insert('nao',from_id, chat_id,message_id,timestamp)
				bot.answerCallbackQuery(query_id,"Votado!")
				refreshButton = True
			else:
				bot.answerCallbackQuery(query_id,"Você já votou nessa opção!")
		
		count_sim = count('sim',None, chat_id,message_id)
		count_nao = count('nao',None, chat_id,message_id)

		keybVoto = InlineKeyboardMarkup(inline_keyboard=[[
						InlineKeyboardButton(text='Sim' +' '+ str(count_sim), callback_data=timestamp+'|sim'),
						InlineKeyboardButton(text='Não' + ' ' + str(count_nao), callback_data=timestamp+'|nao'),
		]])
		ident_mensagem = (chat_id,message_id)
		if(refreshButton):
			bot.editMessageReplyMarkup(ident_mensagem, reply_markup=keybVoto)
Example #24
0
def admins(msg):
    if msg.get('text'):
        if msg['text'].split()[0] == '/ban' or msg['text'].split(
        )[0] == '!ban':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            else:
                if msg.get('reply_to_message'):
                    reply_id = msg['reply_to_message']['from']['id']
                    reply_name = msg['reply_to_message']['from']['first_name']
                elif len(msg['text'].split()) > 1:
                    u_id = msg['text'].split()[1]
                    try:
                        get = bot.getChat(u_id)
                        reply_id = get['id']
                        reply_name = get['first_name']
                    except:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'ID inválida ou desconhecida. use nesse formato: /ban ID do usuário',
                            reply_to_message_id=msg['message_id'])
                        return
                else:
                    reply_id = None

                adm = isAdmin(msg['chat']['id'], msg['from']['id'], reply_id)

                if adm['user']:
                    try:
                        int(reply_id)
                    except:
                        return bot.sendMessage(
                            msg['chat']['id'],
                            'Responda alguém ou informe sua ID',
                            reply_to_message_id=msg['message_id'])
                    if adm['bot']:
                        if adm['reply']:
                            bot.sendMessage(
                                msg['chat']['id'],
                                'Esse aí tem admin',
                                reply_to_message_id=msg['message_id'])
                        else:
                            bot.kickChatMember(msg['chat']['id'], reply_id)
                            bot.sendMessage(
                                msg['chat']['id'],
                                '{} baniu {}!'.format(
                                    msg['from']['first_name'], reply_name),
                                reply_to_message_id=msg['message_id'])
                    else:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ei, eu nao tenho admin aqui',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/kick' or msg['text'].split(
        )[0] == '!kick':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            else:
                if msg.get('reply_to_message'):
                    reply_id = msg['reply_to_message']['from']['id']
                    reply_name = msg['reply_to_message']['from']['first_name']
                elif len(msg['text'].split()) > 1:
                    u_id = msg['text'].split()[1]
                    try:
                        get = bot.getChat(u_id)
                        reply_id = get['id']
                        reply_name = get['first_name']
                    except:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'ID inválida ou desconhecida. use nesse formato: /kick ID do usuário',
                            reply_to_message_id=msg['message_id'])
                        return
                else:
                    reply_id = None

                adm = isAdmin(msg['chat']['id'], msg['from']['id'], reply_id)

                if adm['user']:
                    try:
                        int(reply_id)
                    except:
                        return bot.sendMessage(
                            msg['chat']['id'],
                            'Responda alguém ou informe sua ID',
                            reply_to_message_id=msg['message_id'])
                    if adm['bot']:
                        if adm['reply']:
                            bot.sendMessage(
                                msg['chat']['id'],
                                'Esse aí tem admin',
                                reply_to_message_id=msg['message_id'])
                        else:
                            bot.unbanChatMember(msg['chat']['id'], reply_id)
                            bot.sendMessage(
                                msg['chat']['id'],
                                '{} kickou {}!'.format(
                                    msg['from']['first_name'], reply_name),
                                reply_to_message_id=msg['message_id'])
                    else:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ei, eu nao tenho admin aqui',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/mute' or msg['text'].split(
        )[0] == '!mute':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            else:
                if msg.get('reply_to_message'):
                    reply_id = msg['reply_to_message']['from']['id']
                    reply_name = msg['reply_to_message']['from']['first_name']
                elif len(msg['text'].split()) > 1:
                    u_id = msg['text'].split()[1]
                    try:
                        get = bot.getChat(u_id)
                        reply_id = get['id']
                        reply_name = get['first_name']
                    except:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'ID inválida ou desconhecida. use nesse formato: /mute ID do usuário',
                            reply_to_message_id=msg['message_id'])
                        return
                else:
                    reply_id = None

                adm = isAdmin(msg['chat']['id'], msg['from']['id'], reply_id)

                if adm['user']:
                    try:
                        int(reply_id)
                    except:
                        return bot.sendMessage(
                            msg['chat']['id'],
                            'Responda alguém ou informe sua ID',
                            reply_to_message_id=msg['message_id'])
                    if adm['bot']:
                        if adm['reply']:
                            bot.sendMessage(
                                msg['chat']['id'],
                                'Esse aí tem admin',
                                reply_to_message_id=msg['message_id'])
                        else:
                            bot.unbanChatMember(msg['chat']['id'], reply_id)
                            bot.sendMessage(
                                msg['chat']['id'],
                                '{} restringiu {}!'.format(
                                    msg['from']['first_name'], reply_name),
                                reply_to_message_id=msg['message_id'])
                    else:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ei, eu nao tenho admin aqui',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/unmute' or msg['text'].split(
        )[0] == '!unmute':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            else:
                if msg.get('reply_to_message'):
                    reply_id = msg['reply_to_message']['from']['id']
                    reply_name = msg['reply_to_message']['from']['first_name']
                elif len(msg['text'].split()) > 1:
                    u_id = msg['text'].split()[1]
                    try:
                        get = bot.getChat(u_id)
                        reply_id = get['id']
                        reply_name = get['first_name']
                    except Exception as e:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'ID inválida ou desconhecida. use nesse formato: /unban ID do usuário',
                            reply_to_message_id=msg['message_id'])
                        return
                else:
                    reply_id = None

                adm = isAdmin(msg['chat']['id'], msg['from']['id'], reply_id)

                if adm['user']:
                    try:
                        int(reply_id)
                    except:
                        return bot.sendMessage(
                            msg['chat']['id'],
                            'Responda alguém ou informe sua ID',
                            reply_to_message_id=msg['message_id'])
                    if adm['bot']:
                        if adm['reply']:
                            bot.sendMessage(
                                msg['chat']['id'],
                                'Esse aí tem admin',
                                reply_to_message_id=msg['message_id'])
                        else:
                            bot.restrictChatMember(
                                chat_id,
                                reply_id,
                                can_send_messages=True,
                                can_send_media_messages=True,
                                can_send_other_messages=True,
                                can_add_web_page_previews=True)
                            bot.sendMessage(
                                msg['chat']['id'],
                                '{} agora pode falar aqui!'.format(reply_name),
                                reply_to_message_id=msg['message_id'])
                    else:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ei, eu nao tenho admin aqui',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/unban' or msg['text'].split(
        )[0] == '!unban':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            else:
                if msg.get('reply_to_message'):
                    reply_id = msg['reply_to_message']['from']['id']
                    reply_name = msg['reply_to_message']['from']['first_name']
                elif len(msg['text'].split()) > 1:
                    u_id = msg['text'].split()[1]
                    try:
                        get = bot.getChat(u_id)
                        reply_id = get['id']
                        reply_name = get['first_name']
                    except Exception as e:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'ID inválida ou desconhecida. use nesse formato: /unban ID do usuário',
                            reply_to_message_id=msg['message_id'])
                        return
                else:
                    reply_id = None

                adm = isAdmin(msg['chat']['id'], msg['from']['id'], reply_id)

                if adm['user']:
                    try:
                        int(reply_id)
                    except:
                        return bot.sendMessage(
                            msg['chat']['id'],
                            'Responda alguém ou informe sua ID',
                            reply_to_message_id=msg['message_id'])
                    if adm['bot']:
                        if adm['reply']:
                            bot.sendMessage(
                                msg['chat']['id'],
                                'Esse aí tem admin',
                                reply_to_message_id=msg['message_id'])
                        else:
                            bot.unbanChatMember(msg['chat']['id'], reply_id)
                            bot.sendMessage(
                                msg['chat']['id'],
                                '{} desbaniu {}!'.format(
                                    msg['from']['first_name'], reply_name),
                                reply_to_message_id=msg['message_id'])
                    else:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ei, eu nao tenho admin aqui',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/pin' or msg['text'].split(
        )[0] == '!pin':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            elif isAdmin(msg['chat']['id'], msg['from']['id'])['user']:
                if msg.get('reply_to_message'):
                    bot.pinChatMessage(msg['chat']['id'],
                                       msg['reply_to_message']['message_id'])
                    bot.sendMessage(msg['chat']['id'],
                                    'Mensagem fixada',
                                    reply_to_message_id=msg['message_id'])
                else:
                    bot.sendMessage(msg['chat']['id'],
                                    'Responda a uma mensagem para eu fixar.',
                                    reply_to_message_id=msg['message_id'])

        elif msg['text'].split()[0] == '/unpin' or msg['text'].split(
        )[0] == '!unpin':
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            elif isAdmin(msg['chat']['id'], msg['from']['id'])['user']:
                bot.unpinChatMessage(msg['chat']['id'])
                bot.sendMessage(msg['chat']['id'],
                                'Mensagem desfixada',
                                reply_to_message_id=msg['message_id'])

        elif msg['text'].startswith('/title') or msg['text'].startswith(
                '!title'):
            text = msg['text'][7:]
            if msg['chat']['type'] == 'private':
                bot.sendMessage(
                    chat_id, 'Este comando só funciona em grupos ¯\\_(ツ)_/¯')
            elif isAdmin(msg['chat']['id'], msg['from']['id'])['user']:
                if text == '':
                    bot.sendMessage(msg['chat']['id'],
                                    'Uso: /title titulo do grupo',
                                    reply_to_message_id=msg['message_id'])
                else:
                    try:
                        bot.setChatTitle(msg['chat']['id'], text)
                        bot.sendMessage(
                            msg['chat']['id'],
                            'O novo título do grupo foi definido com sucesso!',
                            reply_to_message_id=msg['message_id'])
                    except NotEnoughRightsError:
                        bot.sendMessage(
                            msg['chat']['id'],
                            'Eu nao tenho tenho permissão para alterar as informações do grupo',
                            reply_to_message_id=msg['message_id'])
                    except:
                        bot.sendMessage(msg['chat']['id'],
                                        'Ocorreu um erro.',
                                        reply_to_message_id=msg['message_id'])

        elif msg['text'] == '/config':
            if isAdmin(msg['chat']['id'], msg['from']['id'])['user']:
                kb = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text='⚙️ Opções do chat',
                         callback_data='options {}'.format(msg['chat']['id']))
                ], [dict(text='🗑 Deletar mensagem', callback_data='del_msg')]])
                bot.sendMessage(msg['from']['id'],
                                'Menu de configuração do chat {}'.format(
                                    msg['chat']['title']),
                                reply_markup=kb)
                bot.sendMessage(msg['chat']['id'],
                                'Enviei um menu de configurações no seu pv.',
                                reply_to_message_id=msg['message_id'])
            return True

    elif msg.get('data'):

        if msg['data'].startswith('options'):
            bot.answerCallbackQuery(msg['id'], 'Abrindo...')
            if isAdmin(msg['data'].split()[1], msg['from']['id'])['user']:
                info = bot.getChat(msg['data'].split()[1])
                kb = InlineKeyboardMarkup(
                    inline_keyboard=[[
                        dict(text='IA',
                             callback_data='.'.format(msg['data'].split()[1]))
                    ] + [
                        dict(text='None',
                             callback_data='IA {}'.format(msg['data'].split()
                                                          [1]))
                    ],
                                     [
                                         dict(text='Voltar',
                                              callback_data='back {}'.format(
                                                  msg['data'].split()[1]))
                                     ]])
                bot.editMessageText(
                    (msg['from']['id'], msg['message']['message_id']),
                    'Opções do chat {}'.format(info['title']),
                    reply_markup=kb)

        elif msg['data'].startswith('back'):
            info = bot.getChat(msg['data'].split()[1])
            kb = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='⚙️ Opções do chat',
                     callback_data='options {}'.format(msg['data'].split()[1]))
            ], [dict(text='🗑 Deletar mensagem', callback_data='del_msg')]])
            bot.editMessageText(
                (msg['from']['id'], msg['message']['message_id']),
                'Menu de configuração do chat {}'.format(info['title']),
                reply_markup=kb)

        elif msg['data'] == 'del_msg':
            bot.deleteMessage(
                (msg['from']['id'], msg['message']['message_id']))
Example #25
0
File: kibe.py Project: hanslett12/a
def kibe(msg):
    if msg.get('text'):
        if msg['text'].startswith('/kibe_stickerid') or msg['text'].startswith(
                '!stickerid'):
            if msg.get('reply_to_message') and msg['reply_to_message'].get(
                    'sticker'):
                bot.sendMessage(msg['chat']['id'],
                                "Sticker ID:\n```" +
                                msg['reply_to_message']['sticker']['file_id'] +
                                "```",
                                parse_mode='markdown',
                                reply_to_message_id=msg['message_id'])
            else:
                bot.sendMessage(msg['chat']['id'],
                                "Please reply to a sticker to get its ID.")

        elif msg['text'].startswith(
                '/kibe_getsticker') or msg['text'].startswith('!getsticker'):
            if msg.get('reply_to_message') and msg['reply_to_message'].get(
                    'sticker'):
                chat_id = msg['chat']['id']
                file_id = msg['reply_to_message']['sticker']['file_id']
                bot.download_file(file_id, 'sticker.png')
                bot.sendDocument(chat_id, document=open('sticker.png', 'rb'))
                os.remove("sticker.png")
            else:
                bot.sendMessage(
                    msg['chat']['id'],
                    "Please reply to a sticker for me to upload its PNG.",
                    reply_to_message_id=msg['message_id'])

        elif msg['text'].startswith('/kibe') or msg['text'].startswith(
                '!kibe'):
            if msg.get('reply_to_message') and msg['reply_to_message'].get(
                    'sticker'):
                user = msg['from']
                file_id = msg['reply_to_message']['sticker']['file_id']
                bot.download_file(file_id,
                                  str(msg['from']['id']) + '_kibe_sticker.png')
                packname = "a" + str(
                    user['id']) + "_by_" + config.me['username']
                if len(msg['text'][5:]) > 0:
                    sticker_emoji = msg['text'].split()[1]
                else:
                    sticker_emoji = msg['reply_to_message']['sticker']['emoji']
                success = False
                try:
                    bot.addStickerToSet(user_id=user['id'],
                                        name=packname,
                                        png_sticker=open(
                                            str(msg['from']['id']) +
                                            '_kibe_sticker.png', 'rb'),
                                        emojis=sticker_emoji)
                    success = True
                except TelegramError as e:
                    if e.description == "Bad Request: STICKERSET_INVALID":
                        bot.sendMessage(
                            msg['chat']['id'],
                            "Use /make_kibe to create a pack first.",
                            reply_to_message_id=msg['message_id'])
                        return
                    elif e.description == "Internal Server Error: sticker set not found":
                        success = True
                finally:
                    os.remove(str(msg['from']['id']) + "_kibe_sticker.png")

                if success:
                    bot.sendMessage(
                        msg['chat']['id'],
                        "Sticker successfully added to [pack](t.me/addstickers/%s)"
                        % packname,
                        parse_mode='markdown',
                        reply_to_message_id=msg['message_id'])

            else:
                bot.sendMessage(
                    msg['chat']['id'],
                    "Please reply to a sticker for me to kibe it.")
        elif msg['text'].startswith('/make_kibe') or msg['text'].startswith(
                '!make_kibe'):
            user = msg['from']
            name = user['first_name']
            name = name[:50]
            packname = "a" + str(user['id']) + "_by_" + config.me['username']
            success = False
            try:
                success = bot.createNewStickerSet(
                    user['id'],
                    packname,
                    name + "'s Kibe @AmanoTeam",
                    png_sticker="https://i.imgur.com/wB1iZFI.png",
                    emojis='©')
            except TelegramError as e:
                if e.description == "Bad Request: sticker set name is already occupied":
                    bot.sendMessage(
                        msg['chat']['id'],
                        "Your pack can be found [here](t.me/addstickers/%s)" %
                        packname,
                        parse_mode='markdown',
                        reply_to_message_id=msg['message_id'])
                elif e.description == "Bad Request: PEER_ID_INVALID":
                    bot.sendMessage(
                        msg['chat']['id'],
                        "Contact me in PM first.",
                        reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
                            dict(text='Start',
                                 url="t.me/{}".format(config.me['username']))
                        ]]),
                        reply_to_message_id=msg['message_id'])
                else:
                    bot.sendMessage(
                        msg['chat']['id'],
                        "Failed to create sticker pack. Possibly due to blek mejik.",
                        reply_to_message_id=msg['message_id'])

            if success:
                bot.sendMessage(
                    msg['chat']['id'],
                    "Sticker pack successfully created. Get it [here](t.me/addstickers/%s)"
                    % packname,
                    parse_mode='markdown',
                    reply_to_message_id=msg['message_id'])
Example #26
0
async def welcome(msg):
    if msg.get('text'):
        if msg['text'].split()[0] == '/welcome' or msg['text'].split()[0] == '/welcome@' + bot_username or \
                msg['text'].split()[0] == '!welcome':
            if msg['chat']['type'] == 'private':
                await bot.sendMessage(
                    msg['chat']['id'],
                    'Este comando só funciona em grupos ¯\\_(ツ)_/¯')

            elif (await is_admin(msg['chat']['id'],
                                 msg['from']['id']))['user']:
                text = msg['text'].split(' ', 1)
                if len(text) == 1:
                    await bot.sendMessage(
                        msg['chat']['id'],
                        'Uso: /welcome on/off/reset/mensagem de boas-vindas do grupo (suporta Markdown e as tags $name, $title, $id e $rules)',
                        reply_to_message_id=msg['message_id'])
                elif text[1] == 'on':
                    enable_welcome(msg['chat']['id'])
                    await bot.sendMessage(
                        msg['chat']['id'],
                        'A mensagem de boas-vindas foi ativada.',
                        reply_to_message_id=msg['message_id'])
                elif text[1] == 'off':
                    disable_welcome(msg['chat']['id'])
                    await bot.sendMessage(
                        msg['chat']['id'],
                        'A mensagem de boas-vindas foi desativada.',
                        reply_to_message_id=msg['message_id'])
                elif text[1] == 'reset':
                    set_welcome(msg['chat']['id'], None)
                    await bot.sendMessage(
                        msg['chat']['id'],
                        'A mensagem de boas-vindas foi redefinida.',
                        reply_to_message_id=msg['message_id'])
                else:
                    try:
                        sent = await bot.sendMessage(
                            msg['chat']['id'],
                            text[1],
                            parse_mode='Markdown',
                            reply_to_message_id=msg['message_id'])
                        set_welcome(msg['chat']['id'], text[1])
                        await bot.editMessageText(
                            (msg['chat']['id'], sent['message_id']),
                            'A mensagem de boas-vindas foi definida.')
                    except TelegramError as e:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '''Ocorreu um erro ao definir a mensagem de boas-vindas:
{}

Se esse erro persistir entre em contato com @AmanoSupport.'''.format(
                                e.description),
                            reply_to_message_id=msg['message_id'])

            return True

    elif msg.get('new_chat_member'):
        chat_title = msg['chat']['title']
        chat_id = msg['chat']['id']
        first_name = msg['new_chat_member']['first_name']
        user_id = msg['new_chat_member']['id']
        if msg['new_chat_member']['id'] == bot_id:
            pass
        else:
            welcome = get_welcome(chat_id)
            if welcome[1]:
                if welcome[0] is not None:
                    welcome = welcome[0].replace('$id', str(user_id))
                    welcome = welcome.replace('$title',
                                              escape_markdown(chat_title))
                    welcome = welcome.replace('$name',
                                              escape_markdown(first_name))
                else:
                    welcome = 'Olá {}, seja bem-vindo(a) ao {}!'.format(
                        escape_markdown(first_name),
                        escape_markdown(chat_title))
                if '$rules' in welcome:
                    welcome = welcome.replace('$rules', '')
                    rules_markup = InlineKeyboardMarkup(inline_keyboard=[[
                        dict(text='Leia as regras',
                             url='https://t.me/{}?start=rules_{}'.format(
                                 bot_username, chat_id))
                    ]])
                else:
                    rules_markup = None
                await bot.sendMessage(chat_id,
                                      welcome,
                                      'markdown',
                                      reply_to_message_id=msg['message_id'],
                                      reply_markup=rules_markup,
                                      disable_web_page_preview=True)
        return True
Example #27
0
async def start(msg):
    if msg.get('text'):
        strs = Strings(msg['chat']['id'])

        if msg['text'] == '/start' or msg['text'] == '!start' or msg[
                'text'].split()[0] == '/start@' + bot_username or msg[
                    'text'] == '/start start':

            if msg['chat']['type'] == 'private':
                kb = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        dict(text=strs.get('commands_button'),
                             callback_data='all_cmds')
                    ] + [
                        dict(text=strs.get('infos_button'),
                             callback_data='infos')
                    ],
                    [
                        dict(text=strs.get('lang_button'),
                             callback_data='change_lang')
                    ] + [
                        dict(text=strs.get('add_button'),
                             url='https://t.me/{}?startgroup=new'.format(
                                 bot_username))
                    ]
                ])
                smsg = strs.get('pm_start_msg')
            else:
                kb = InlineKeyboardMarkup(inline_keyboard=[[
                    dict(text=strs.get('start_pm_button'),
                         url='https://t.me/{}?start=start'.format(
                             bot_username))
                ]])
                smsg = strs.get('start_msg')

            await bot.sendMessage(msg['chat']['id'],
                                  smsg,
                                  reply_to_message_id=msg['message_id'],
                                  reply_markup=kb)
            return True

    elif msg.get('data') and msg.get('message'):
        strs = Strings(msg['message']['chat']['id'])

        cmds_back = InlineKeyboardMarkup(inline_keyboard=[[
            dict(text=strs.get('back_button'), callback_data='all_cmds')
        ]])

        start_back = InlineKeyboardMarkup(inline_keyboard=[[
            dict(text=strs.get('back_button'), callback_data='start_back')
        ]])

        if msg['data'] == 'tools_cmds':
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                text='''*Ferramentas:*

/clima - Exibe informações de clima.
/coub - Pesquisa de pequenas animações.
/echo - Repete o texto informado.
/gif - Pesquisa de GIFs.
/git - Envia informações de um user do GitHub.
/html - Repete o texto informado usando HTML.
/ip - Exibe informações sobre um IP/domínio.
/jsondump - Envia o json da mensagem.
/mark - Repete o texto informado usando Markdown.
/print - Envia uma print de um site.
/pypi - Pesquisa de módulos no PyPI.
/r - Pesquisa de tópicos no Reddit
/request - Faz uma requisição a um site.
/shorten - Encurta uma URL.
/token - Exibe informações de um token de bot.
/tr - Traduz um texto.
/yt - Pesquisa vídeos no YouTube.
/ytdl - Baixa o áudio de um vídeo no YouTube.''',
                parse_mode='Markdown',
                reply_markup=cmds_back)
            return True

        elif msg['data'] == 'admin_cmds':
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                '''*Comandos administrativos:*

/ban - Bane um usuário.
/config - Envia um menu de configurações.
/defregras - Define as regras do grupo.
/kick - Kicka um usuário.
/mute - Restringe um usuário.
/pin - Fixa uma mensagem no grupo.
/title - Define o título do grupo.
/unban - Desbane um usuário.
/unmute - Desrestringe um usuário.
/unpin - Desfixa a mensagem fixada no grupo.
/unwarn - Remove as advertências do usuário.
/warn - Adverte um usuário.
/welcome - Define a mensagem de welcome.''',
                parse_mode='Markdown',
                reply_markup=cmds_back)
            return True

        elif msg['data'] == 'user_cmds':
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                '''*Comandos para usuários normais:*

/admins - Mostra a lista de admins do chat.
/dados - Envia um número aleatório de 1 a 6.
/bug - Reporta um bug ao meu desenvolvedor.
/id - Exibe suas informações ou de um usuário.
/ping - Responde com uma mensagem de ping.
/regras - Exibe as regras do grupo.
/roleta - Para jogar a Roleta Russa.''',
                parse_mode='Markdown',
                reply_markup=cmds_back)
            return True

        elif msg['data'] == 'start_back':
            kb = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text=strs.get('commands_button'),
                     callback_data='all_cmds')
            ] + [
                dict(text=strs.get('infos_button'), callback_data='infos')
            ], [
                dict(text=strs.get('lang_button'), callback_data='change_lang')
            ] + [
                dict(text=strs.get('add_button'),
                     url='https://t.me/{}?startgroup=new'.format(bot_username))
            ]])
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                strs.get('pm_start_msg'),
                reply_markup=kb)
            return True

        elif msg['data'] == 'change_lang':
            langs_kb = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text='{lang_flag} {lang_name}'.format(**strings[x]),
                     callback_data='set_lang ' + x)
            ] for x in strings] + [[
                dict(text=strs.get('back_button'), callback_data='start_back')
            ]])
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                "Select your prefered lang below:",
                reply_markup=langs_kb)
            return True

        elif msg['data'].split()[0] == 'set_lang':
            cursor.execute(
                'UPDATE users SET chat_lang = ? WHERE user_id = ?',
                (msg['data'].split()[1], msg['message']['chat']['id']))
            usr_lang = Strings(msg['message']['chat']['id'])
            start_back = InlineKeyboardMarkup(inline_keyboard=[[
                dict(text=usr_lang.get('back_button'),
                     callback_data='start_back')
            ]])
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                usr_lang.get('lang_changed'),
                reply_markup=start_back)
            return True

        elif msg['data'] == 'all_cmds':
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                'Selecione uma categoria de comando para visualizar.\n\nCaso precise de ajuda com o bot ou tem alguma sugestão entre no @AmanoChat',
                reply_markup=keyboard.all_cmds)
            return True

        elif msg['data'] == 'infos':
            await bot.editMessageText(
                (msg['message']['chat']['id'], msg['message']['message_id']),
                '''• EduuRobot

Version: {version}
Source Code: <a href="{sourcelink}">Here</a>
Developers: <a href="https://github.com/AmanoTeam">Amano Team</>
Owner: <a href="tg://user?id=123892996">Edu :3</>

Partnerships:
 » <a href="https://t.me/hpxlist">HPXList - by usernein</>

©2019 - <a href="https://amanoteam.ml">AmanoTeam™</>'''.format(
                    version=version, sourcelink=git_repo[0]),
                parse_mode='html',
                reply_markup=start_back,
                disable_web_page_preview=True)
            return True
Example #28
0
async def tcxs(msg):
    if msg.get('text'):

        if msg['text'] == 'tcxs' or msg['text'] == 'tcxs project' or msg[
                'text'] == 'TCXS' or msg['text'] == 'TCXS Project':
            print('Usuario {} solicitou tcxs'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou tcxs --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '`{} O nome TCXS foi criado com base nos botoes do PlayStation3, TRIANGLE - CIRCLE - X - SQUARE, ou seja, triangulo, bolinha, x e quadrado, kkk. Como nosso dev era publicitario e odiava a cena vendo alguns imbecis AUTO PROMOVER seu nome criando lojas e projetos, ele decidiu entrar na cena com uma nomenclatura que lembrasse a cena hacker, ou seja, siglas! Siglas esyão no cotidiano de todo mundo e é facil sua absorção bem como dentro da parte web e publicitaria a sigla tem um forte papel facilitando a digitacao e pesquisa, entao com este intuito nos denominados de TCXS Project, a palavra Project veio da vontade de que nunca morra, sendo assim um projeto qualquer um que tiver habilidade e capacidade pode entrar na equipe e ajudar a coordenar bem como tocar o projeto, ja vimos na cena varios adms passarem pela TCXS, ela e um projeto feito a varias maos e cada um doa de forma gratuita seu tempo e conhecimento para disponibilizar tudo que temos em nossas redes e arquivos. Ficamos gratos a todos que passaram por esta equipe seja dos adms aos users e seria impossivel enumerar todos, voces que sao a TCXS Project e formam este projeto que ja esta indo para seu terceiro ano!  OBRIGADO COMUNIDADE GAMER, HACKER, EXPLOITER, DEVS, USUARIOS E SIMPATIZANTES, SEM VOCES NAO EXISTIRIAMOS!`'
                .format(msg['from']['first_name']),
                'markdown',
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'proxy' or msg['text'] == 'Proxy':
            await bot.sendMessage(
                msg['chat']['id'],
                '{} quer aumentar a velocidade dos downloads no seu PS3? Primeiro quero que saiba que o PS3 é de 2006 e sua placa de rede trabalha com um protocolo bem lento, logo nao adianta vc ter 100mb de net fibra full, pois sua placa de rede nao le neste tempo, bem como a gravaçao no HD do PS3 tambem é lenta, lembre que ele usa HDD e nao SSD assim eu te digo que  NAO ADIANTA TUA NET SER 100MB e de fibra se seu hd antigo e ja capenga grava no maximo a 30mb/s, porem vc sabia que antes de gravar no hd tudo fica na ram e so depois passa para o HD, tendo isto como afirmaçao entenda que o ps3 tem 256mb de ram e mtos slots desta ram estao ocupados, entao nao espere que o PS3 seja uma super maquina de download, ele era do tempo do final da Internet Discada e inicio da internet a Radio e ADLS na epoca da esturura dele em 2006 a maior velocidade de internet vigente como estavel era em torno de 1mb! Tendo isto em mente siga nosso tutorial de proxy para melhorar sua conexao, o serviço proxy é utilizar de outra maquina para que sua conexao esteja com o IP mais proximo do servidor e um cache seja armazenado neste -proxy- fazendo assim seu download melhorar significativamente, segue tutorial: https://youtu.be/l4o8ySk1Do4'
                .format(msg['from']['first_name']),
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'fix' or msg['text'] == 'Fix':
            await bot.sendMessage(
                msg['chat']['id'],
                '`{} vejo que esta precisando do fix para sua loja aparecer, instale este pkg em seu console e a loja começara aparecer.`'
                .format(msg['from']['first_name']),
                'markdown',
                reply_to_message_id=msg['message_id'])
            await bot.sendDocument(
                msg['chat']['id'],
                document=
                'BQACAgEAAx0CWJNTSQACC7FeXTrapHT8zx-Yz6Rm85I7s6BU2gACxQADxKN4RV4960o0M9ruGAQ',
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'torrent' or msg['text'] == 'Torrent' or msg[
                'text'] == 'torrents' or msg['text'] == 'Torrents':
            print('Usuario {} solicitou tcxs'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou tcxs --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '{} aqui nosso canal de torrents com pkg para download: https://t.me/tcxsp'
                .format(msg['from']['first_name']),
                'markdown',
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'codigo de erro' or msg[
                'text'] == 'lista de erros' or msg['text'] == 'erro psn' or msg[
                    'text'] == 'estou com erro' or msg[
                        'text'] == 'ta dando erro' or msg[
                            'text'] == 'deu erro' or msg[
                                'text'] == 'meu videogame ta com problema':
            print('Usuario {} solicitou tcxs'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou tcxs --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '`Querido usúario do sistema PlayStation3 e praticamente impossivel decorar ou trazer a minha base de dados todos os erros, imagina entao se um humano saberia o erro por um codigo, entao vou te fornecer aqui o site oficial da sony e na lista voce podera encontrar seu erro e solucao, caso seu erro persista seu erro esta ocorrendo com o exploit, ai aconselho que voce refaca todo o seu exploit novamente, nao e dificil mas antes veja aqui se seu erro tem solucao:` https://www.playstation.com/pt-pt/get-help/#!/error-code/ ',
                'markdown',
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'rap' or msg['text'] == 'raps' or msg[
                'text'] == 'licenca' or msg['text'] == '14.000' or msg[
                    'text'] == 'assinatura':
            print('Usuario {} solicitou raps'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou raps --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                'Agora precisamos apenas do PKG das licenças, no HEN as mesmas licenças servem para todos! Tutorial:https://www.youtube.com/watch?v=EYr_MKaL1Tg    Download: https://www.mediafire.com/file/23nzljx8w83dbl0/14Mil-raps-.pkg/file',
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'desbloqueio' or msg['text'] == 'o meu ps3' or msg[
                'text'] == 'Desbloqueio' or msg['text'] == 'desbloquear o ps3' or msg[
                    'text'] == 'desbloquear' or msg[
                        'text'] == 'desbloquear meu videogame' or msg[
                            'text'] == 'desbloquear o meu ps3' or msg[
                                'text'] == 'desbloquear o playstation' or msg[
                                    'text'] == 'desbloquear o meu console' or msg[
                                        'text'] == 'desbloqueei meu videogame' or msg[
                                            'text'] == 'desbloqueei meu console':
            print('Usuario {} solicitou desbloqueio'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou desbloqueio --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '`{} Tem certeza que ele foi feito de forma correta? O Joao PSX alem de fornecer arquivos bugados e ate mesmo mostrar bugs de mais ao vivo acaba nao fornecendo um material confiavel bem como ele nao tem total dominio doque faz como podemos ver nos videos a quantidade de erros ( ele podia editar os videos), enfim aconselho que veja, reveja e se possivel faça o exploit em cima deste tutorial:` https://www.youtube.com/watch?v=XUUieW4bv_Y'
                .format(msg['from']['first_name']),
                'markdown',
                reply_to_message_id=msg['message_id'])

        if 'mercado pago' in msg['text'] or msg[
                'text'] == 'Mercado Pago' or msg['text'] == 'Mercado pago':
            print('Usuario {} solicitou MERCADO PAGO'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou MERCADO PAGO --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                'Olá que bom que você quer doar, {} aqui esta o link de pagamento  ----->   https://www.mercadopago.com.br/checkout/v1/redirect?pref_id=354396246-315fce8c-d8f9-4aa0-8583-95d678936375'
                .format(msg['from']['first_name']),
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'tutorial segundo plano' or msg[
                'text'] == 'download segundo plano' or msg[
                    'text'] == 'downloads em segundo plano' or msg[
                        'text'] == 'Tutorial' or msg[
                            'text'] == 'Download em segundo plano' or msg[
                                'text'] == 'Downloads em segundo plano' or msg[
                                    'text'] == 'download em segundo plano':
            print('Usuario {} solicitou tutorial segundo plano'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou tutorial segundo plano --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '{} O nosso admin @MsT3Dz  criou um tutorial exclusivo de como fazer os downloads na TCXS Project, bem como os downloads em segundo plano. Confira o tutorial completo: https://youtu.be/_21a5REKhBc'
                .format(msg['from']['first_name']),
                reply_to_message_id=msg['message_id'])

        if msg['text'] == 'tutorial' or msg['text'] == 'instalar' or msg[
                'text'] == 'instalar a loja' or msg['text'] == 'instalar  loja' or msg[
                    'text'] == 'como instalar a loja' or msg[
                        'text'] == 'Como instalar a loja' or msg[
                            'text'] == 'Como instalo a loja' or msg[
                                'text'] == 'Instalação' or msg[
                                    'text'] == 'Tutorial de instalação' or msg[
                                        'text'] == 'Instalação da tcxs' or msg[
                                            'text'] == 'instalar a tcxs' or msg[
                                                'text'] == 'Instalação':
            print('Usuario {} solicitou tutorial instalar loja'.format(
                msg['from']['first_name']))
            log = '\nUsuario {} solicitou tutorial instalar loja --> Grupo: {} --> Data/hora:{}'.format(
                msg['from']['first_name'], msg['chat']['title'], time.ctime())
            arquivo = open('logs/grupos.txt', 'a')
            arquivo.write(log)
            arquivo.close()
            await bot.sendMessage(
                msg['chat']['id'],
                '{} O nosso admin @MsT3Dz  criou um tutorial exclusivo de como instalar a loja: https://www.youtube.com/watch?v=aG1jLj8QuBY'
                .format(msg['from']['first_name']),
                reply_to_message_id=msg['message_id'])

#--------------------------------------------------------------------------------------------------

        strs = Strings(msg['chat']['id'])
        if msg['text'] == 'lista jogos' or msg[
                'text'] == 'lista de jogos' or msg[
                    'text'] == 'Lista jogos' or msg[
                        'text'] == 'Lista jogos' or msg[
                            'text'] == 'Lista de jogos' or msg[
                                'text'] == 'PSN' or msg[
                                    'text'] == 'PSN Stuff' or msg[
                                        'text'] == 'PSN stuff' or msg[
                                            'text'] == 'psn' or msg[
                                                'text'] == 'psn stuff':
            if msg['chat']['type'] == 'private':
                kb = InlineKeyboardMarkup(inline_keyboard=[])
                smsg = strs.get('pm_start_msg')
            else:
                kb = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        dict(text=strs.get('🎮 Jogos de A a B'),
                             callback_data='AaB')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de B a D'),
                             callback_data='BaD')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de E a G'),
                             callback_data='EaG')
                    ],
                    [
                        dict(text=strs.get('🎮 Jogos de G a K'),
                             callback_data='GaK')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de K a M'),
                             callback_data='KaM')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de M a P'),
                             callback_data='MaP')
                    ],
                    [
                        dict(text=strs.get('🎮 Jogos de R a S'),
                             callback_data='RaS')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de S a T'),
                             callback_data='SaT')
                    ] + [
                        dict(text=strs.get('🎮 Jogos de T a Z'),
                             callback_data='TaZ')
                    ]
                ])
                smsg = strs.get(
                    '''🎮 Temos jogos para download com link direto 🎮
Basta clicar no botão que te trarei a lista com link direto para download, pedimos sua contribuição para que este projeto se mantenha vivo, Obrigado a todos da TCXS!'''
                )
            await bot.sendMessage(msg['chat']['id'],
                                  smsg,
                                  reply_to_message_id=msg['message_id'],
                                  reply_markup=kb)
            return True
Example #29
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)
Example #30
0
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from amanobot.namedtuple import InlineKeyboardMarkup

all_cmds = InlineKeyboardMarkup(inline_keyboard=[
    [dict(text='👮 Admins', callback_data='admin_cmds')] +
    [dict(text='👤 Usuários', callback_data='user_cmds')],
    [dict(text='🔧 Ferramentas', callback_data='tools_cmds')] +
    [dict(text='🔎 Modo inline', switch_inline_query_current_chat='')],
    [dict(text='« Voltar', callback_data='start_back')]
])

cmds_back = InlineKeyboardMarkup(
    inline_keyboard=[[dict(text='« Voltar', callback_data='all_cmds')]])

del_msg = InlineKeyboardMarkup(inline_keyboard=[[
    dict(text='🗑 Deletar mensagem', callback_data='del_msg')
]])

ia_question = InlineKeyboardMarkup(
    inline_keyboard=[[dict(text='✅ Aceitar', callback_data='ia_yes')] +
                     [dict(text='❌ Recusar', callback_data='ia_no')]])