コード例 #1
0
def button_parser(chat_id, texts, pm=False, aio=False, row_width=None):
    buttons = InlineKeyboardMarkup(row_width=row_width) if aio else []
    pattern = r'\[(.+?)\]\((button|btn)(.+?)(:.+?|)(:same|)\)(\n|)'
    raw_buttons = re.findall(pattern, texts)
    text = re.sub(pattern, '', texts)
    for raw_button in raw_buttons:
        name = raw_button[0]
        action = raw_button[2]
        argument = raw_button[3][1:].lower() if raw_button[3] else ''

        if action in BUTTONS:
            cb = BUTTONS[action]
            string = f'{cb}_{argument}_{chat_id}' if argument else f'{cb}_{chat_id}'
            if aio:
                start_btn = InlineKeyboardButton(
                    name, url=f'https://t.me/{BOT_USERNAME}?start=' + string)
                cb_btn = InlineKeyboardButton(name, callback_data=string)
            else:
                start_btn = Button.url(
                    name, f'https://t.me/{BOT_USERNAME}?start=' + string)
                cb_btn = Button.inline(name, string)

            if cb.endswith('sm'):
                btn = cb_btn if pm else start_btn
            elif cb.endswith('cb'):
                btn = cb_btn
            elif cb.endswith('start'):
                btn = start_btn
            elif cb.startswith('url'):
                btn = Button.url(name, argument)
        elif action == 'url':
            if argument[0] == '/' and argument[1] == '/':
                argument = argument[2:]
            btn = InlineKeyboardButton(
                name, url=argument) if aio else Button.url(name, argument)
        else:
            # If btn not registred
            btn = None
            if argument:
                text += f'\n[{name}].(btn{action}:{argument})'
            else:
                text += f'\n[{name}].(btn{action})'
                continue

        if aio:
            buttons.insert(btn) if raw_button[4] else buttons.add(btn)
        else:
            if len(buttons) < 1 and raw_button[4]:
                buttons.add(btn) if aio else buttons.append([btn])
            else:
                buttons[-1].append(btn) if raw_button[4] else buttons.append(
                    [btn])

    if not aio and len(buttons) == 0:
        buttons = None

    if not text or text == ' ':  # TODO: Sometimes we can return text == ' '
        text = None

    return text, buttons
コード例 #2
0
async def callquery(event):
    data = event.data.decode("utf-8")

    if data.startswith("nodelete"):
        filename = data.split("nodelete-")[1]
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.edit(
            f"**Here is the link of the old file: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url))
    elif data.startswith("remove"):
        filename = data.split("remove-")[1]
        await event.edit(
            f"**Are you sure for delete `{filename}` permanently?**",
            buttons=[
                Button.inline('✅ Yes', f"yes-{filename}"),
                Button.inline('❌ No', "no")
            ])
    elif data.startswith("yes"):
        filename = data.split("yes-")[1]
        await Yandex.remove(filename, permanently=True)
        return await event.edit(f"✅ **Deleted successfully!**")
    elif data == "no":
        return await event.edit("__OK! File will not be deleted.__")
    elif data.startswith("publish"):
        filename = data.split("publish-")[1]
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.edit(
            f"__✅ I made the file public.__ **Here is public link: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url))

        return remove(file)
    elif data == "nopublish":
        return await event.edit("__OK! Only you will access the file.__")
コード例 #3
0
async def img(event):
    j = await event.client(GetFullUserRequest(event.chat_id))
    mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.from_id})\nMesaj: {event.message.message}"
    await bot.send_message("By_Azade", mesaj)
    markup = bot.build_reply_markup([
        Button.url(text='📍 Kanal Linkleri', url="t.me/KanalLinkleri"),
        Button.url(text='👤 Yapımcı', url="t.me/By_Azade")
    ])
    url = event.pattern_match.group(1)
    if url:
        x = await event.reply("`İşlem yapılıyor lütfen bekleyiniz...`")
        get_url = get_download_url(url)
        j = download_image(get_url)

        if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(TMP_DOWNLOAD_DIRECTORY)
        c_time = time.time()
        await event.client.send_file(
            event.chat_id,
            j,
            caption="**Daha fazlası için**\n\n@KanalLinkleri",
            force_document=False,
            allow_cache=False,
            reply_to=event.message.id,
            buttons=markup,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(progress(d, t, event, c_time, "yükleniyor...")))
        await event.delete()
        await x.delete()
        os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
    else:
        await event.reply("**bana komutla beraber link gönder.**")
コード例 #4
0
async def img(event):
    markup = bot.build_reply_markup([
        Button.url(text='📍 My Channel', url="t.me/KanalLinkleri"),
        Button.url(text='👤 Developer', url="t.me/By_Azade")
    ])
    x = await event.reply("`Progressing...`")
    url = event.pattern_match.group(1)
    get_url = get_download_url(url)
    j = download_image(get_url)

    if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TMP_DOWNLOAD_DIRECTORY)
    c_time = time.time()
    await event.client.send_file(
        event.chat_id,
        j,
        caption="`For more` @KanalLinkleri",
        force_document=False,
        allow_cache=False,
        reply_to=event.message.id,
        buttons=markup,
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "trying to upload")))
    await event.delete()
    await x.delete()
    os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_iamge.jpg')
コード例 #5
0
async def vid(event):
    j = await event.client(GetFullUserRequest(event.chat_id))
    mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.from_id})\nMesaj: {event.message.message}"
    await bot.send_message("By_Azade", mesaj)
    markup = bot.build_reply_markup([
        Button.url(text='📍 Kanal Linkleri', url="t.me/KanalLinkleri"),
        Button.url(text='👤 Yapımcı', url="t.me/By_Azade")
    ])
    url = event.pattern_match.group(1)
    if url:
        x = await event.reply("`işlem yapılıyor bekleyiniz...`")

        get_url = get_download_url(url)
        j = download_video(get_url)
        thumb_image_path = TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg"

        if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
            os.makedirs(TMP_DOWNLOAD_DIRECTORY)

        metadata = extractMetadata(createParser(j))
        duration = 0

        if metadata.has("duration"):
            duration = metadata.get('duration').seconds
            width = 0
            height = 0
            thumb = None

        if os.path.exists(thumb_image_path):
            thumb = thumb_image_path
        else:
            thumb = await take_screen_shot(j,
                                           os.path.dirname(os.path.abspath(j)),
                                           (duration / 2))

        c_time = time.time()
        await event.client.send_file(
            event.chat_id,
            j,
            thumb=thumb,
            caption="**Daha fazlası için**\n\n@KanalLinkleri",
            force_document=False,
            allow_cache=False,
            reply_to=event.message.id,
            buttons=markup,
            attributes=[
                DocumentAttributeVideo(duration=duration,
                                       w=width,
                                       h=height,
                                       round_message=False,
                                       supports_streaming=True)
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(progress(d, t, event, c_time, "yükleniyor...")))
        await event.delete()
        await x.delete()
        os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4')
        os.remove(thumb_image_path)
    else:
        await event.reply("**bana komutla beraber link gönder.**")
コード例 #6
0
async def start(event):
    if event:
        markup = bot.build_reply_markup([
            Button.url(text='📍 My Channel', url="t.me/KanalLinkleri"),
            Button.url(text='👤 Developer', url="t.me/By_Azade")
        ])
        await bot.send_message(event.chat_id,
                               mesaj,
                               buttons=markup,
                               link_preview=False)
コード例 #7
0
async def vid(event):
    markup = bot.build_reply_markup([
        Button.url(text='📍 My Channel', url="t.me/KanalLinkleri"),
        Button.url(text='👤 Developer', url="t.me/By_Azade")
    ])
    x = await event.reply("`progressing...`")
    url = event.pattern_match.group(1)
    get_url = get_download_url(url)
    j = download_video(get_url)
    thumb_image_path = TMP_DOWNLOAD_DIRECTORY + "thumb_image.jpg"

    if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(TMP_DOWNLOAD_DIRECTORY)

    metadata = extractMetadata(createParser(j))
    duration = 0

    if metadata.has("duration"):
        duration = metadata.get('duration').seconds
        width = 0
        height = 0
        thumb = None

    if os.path.exists(thumb_image_path):
        thumb = thumb_image_path
    else:
        thumb = await take_screen_shot(j, os.path.dirname(os.path.abspath(j)),
                                       (duration / 2))

    c_time = time.time()
    await event.client.send_file(
        event.chat_id,
        j,
        thumb=thumb,
        caption="`For more` @KanalLinkleri",
        force_document=False,
        allow_cache=False,
        reply_to=event.message.id,
        buttons=markup,
        attributes=[
            DocumentAttributeVideo(duration=duration,
                                   w=width,
                                   h=height,
                                   round_message=False,
                                   supports_streaming=True)
        ],
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "trying to upload")))
    await event.delete()
    await x.delete()
    os.remove(TMP_DOWNLOAD_DIRECTORY + 'pinterest_video.mp4')
    os.remove(thumb_image_path)
コード例 #8
0
async def start(event):
    j = await event.client(GetFullUserRequest(event.chat_id))
    mesaj = f"Gönderen [{j.user.first_name}](tg://user?id={event.from_id})\nMesaj: {event.message.message}"
    await bot.send_message("By_Azade", mesaj)
    if event:
        markup = bot.build_reply_markup([
            Button.url(text='📍 Kanal Linkleri', url="t.me/KanalLinkleri"),
            Button.url(text='👤 Yapımcı', url="t.me/By_Azade")
        ])
        await bot.send_message(event.chat_id,
                               mesaj,
                               buttons=markup,
                               link_preview=False)
コード例 #9
0
async def help(event):
    await event.delete()
    if event.query.user_id is not bot.uid:
        await tgbot.send_message(
            event.chat_id,
            message=
            "You Can Deploy Friday In Heroku By Following Steps Bellow, You Can See Some Quick Guides On Support Channel Or On Your Own Assistant Bot. \nThank You For Contacting Me.",
            buttons=[
                [
                    Button.url("Deploy Tutorial 📺",
                               "https://youtu.be/xfHcm_e92eQ")
                ],
                [Button.url("Need Help ❓", "t.me/FridaySupportOfficial")],
            ],
        )
コード例 #10
0
ファイル: cobra.py プロジェクト: Friends-Zone/D--C
 async def inline_handler(event):
     builder = event.builder
     result = None
     query = event.text
     DEFAULTUSER = os.environ.get("ALIVE_NAME", None)
     if event.query.user_id == bot.uid and query.startswith("help"):
         rev_text = query[::-1]
         dc = paginate_help(0, CMD_LIST, "helpme")
         result = builder.article(
             "© Dark Cobra Userbot Help",
             text=
             "Userbot Helper.. Provided by ✨{}✨ \n `Userbot Helper to reveal all the commands`\n__Do .help plugin_name for commands, in case popup doesn't appear.\n{}\nCurrently Loaded Plugins: {}"
             .format(DEFAULTUSER, query, len(CMD_LIST)),
             buttons=dc,
             link_preview=False,
         )
         await event.answer([result] if result else None)
     elif not event.query.user_id == bot.uid:
         s = builder.article(
             title="I am Not your Servant",
             description=
             "Do your Own work sir don't interfere in Others Work",
             text="Hey You Must Use DARK COBRA USERBOT",
             buttons=[
                 [
                     Button.url(
                         "Dark Cobra Modified",
                         "https://github.com/The-Terminal/DARKCOBRA",
                     )
                 ],
             ],
         )
         await event.answer([s])
     else:
         return
コード例 #11
0
ファイル: login.py プロジェクト: muhammedfurkan/YandexUpDown
async def login(event):
    global token
    if token is not None:
        return await event.edit("`You are already logged!`")

    async with event.client.conversation(event.chat_id) as conv:
        url = Yandex.get_code_url()
        await conv.send_message(
            f"To login;\nFirst go to [this link]({url}), then allow the app. It will give you a number, write it.",
            buttons=Button.url("🔗 Link", url),
        )
        response = await conv.wait_event(
            NewMessage(incoming=True, from_users=event.chat_id))

        try:
            token2 = await Yandex.get_token(response.message.raw_text)
        except BadRequestError:
            return await event.reply(
                "**You entered an invalid code! Token process canceled.**")

        Yandex.token = token2.access_token
        if await Yandex.check_token():
            token = Yandex.token
            open("token.txt", "a+").write(token)
            await event.reply(
                "**✅ Your token has been successfully added. Now you can use this bot.**"
            )
        else:
            await event.reply(
                "**❌ Something went wrong. Not sure how though...**")
コード例 #12
0
ファイル: misc.py プロジェクト: NotFoundError/SophieBot
async def help(event, strings):
    if event.chat_id != event.from_id:
        buttons = [[
            Button.url(strings['help_btn'],
                       url='https://t.me/{}?start=help'.format(BOT_USERNAME))
        ]]
        text = strings['help_txt']
        await event.reply(text, buttons=buttons)
コード例 #13
0
async def send_json(borg: TelegramClient, json_pl: str, chat=None):
    print(f"JSON: {json_pl}")
    try:
        out_j = json.loads(json_pl)
        if out_j and not isinstance(out_j, str) and isinstance(out_j, Iterable):
            for item in out_j:
                if isinstance(item, dict):
                    chat = item.get("receiver", chat)
                    caption = item.get("tlg_content", item.get("caption", ""))
                    buttons_inline = item.get("buttons_inline", [])
                    buttons_zsh = item.get("buttons_zsh", [])

                    buttons_inline_tl = []
                    buttons_tl = None
                    for btn in buttons_inline:
                        # Note that the given `data` must be less or equal to 64 bytes. If more than 64 bytes are passed as data, ``ValueError`` is raised.
                        if len(btn) == 1:
                            buttons_inline_tl.append(Button.inline(btn[0]))
                        else:
                            buttons_inline_tl.append(Button.inline(btn[0], btn[1]))
                    for btn in buttons_zsh:
                        btn_json = json.dumps(btn)
                        cmd = btn.get("cmd", "echo Empty command was inlined")
                        btn_caption = btn.get("caption", cmd)
                        jdata = btn.get("jdata", "")
                        jaction = btn.get("jaction", "reply")

                        uid = uuid4()
                        pl = f"zsh_{uid}"
                        key = create_key(pl)
                        zp(
                            "reval-ec jtokey {key} {cmd} {json_pl} {btn_json} {jdata} {jaction}"
                        )
                        buttons_inline_tl.append(Button.inline(btn_caption, pl))
                    if len(buttons_inline_tl) >= 1:
                        buttons_tl = [buttons_inline_tl]
                    await borg.send_message(chat, caption, buttons=buttons_tl)
    except:
        exc = "Julia encountered an exception. :(\n" + traceback.format_exc()
        await borg.send_message(chat, exc)

    return
    await borg.send_message(
        chat,
        'A single button, with "clk1" as data',
        buttons=Button.inline("Click me", b"clk1"),
    )

    await borg.send_message(
        chat,
        "Pick one from this grid",
        buttons=[
            [Button.inline("Left"), Button.inline("Right")],
            [Button.url("Check this site!", "https://lonamiwebs.github.io")],
        ],
    )
コード例 #14
0
async def start(event):
    msg = ("**Welcome to Yandisk!**\n\n" +
           "**This bot is made by @By_Azade.**\n" +
           "**You can use this bot to upload files to Yandisk.**\n" +
           "**You can use this bot to download files from Yandisk.**\n" +
           "**You can use this bot to get info about files on Yandisk.**\n" +
           "**You can use this bot to delete files on Yandisk.**\n" +
           "**You can use this bot to make files public.**\n" +
           "**You can use this bot to make files private.**\n" +
           "**You can use this bot to get public link of files.**\n" +
           "**You can use this bot to get private link of files.**\n" +
           "**ALL COMMANDS:**\n\n" + "`/info` get information disk usage\n")
    await log_yolla(event)
    markup = event.client.build_reply_markup([
        Button.url(text="📍 Our Channels & Groups", url="t.me/KanalLinkleri"),
        Button.url(text="👤 Developer", url="t.me/By_Azade"),
    ])

    await event.reply(msg, buttons=markup)
コード例 #15
0
async def welcome_security_handler(message, strings):
    chat_id = message.chat.id

    if not check_admin_rights(chat_id, BOT_ID, ['can_restrict_members']):
        await message.reply(strings['not_admin_ws'])
        return

    user_id = message.from_user.id
    db_item = await db.greetings.find_one({'chat_id': chat_id})

    if not db_item or 'welcome_security' not in db_item:
        return

    user = await message.chat.get_member(user_id)

    # Check if user was muted before
    if 'can_send_messages' in user and user['can_send_messages'] is False:
        return

    # Check on OPs and chat owner
    if await is_user_admin(chat_id, user_id):
        return

    # Mute user
    await mute_user(chat_id, user_id)

    if 'security_note' not in db_item:
        db_item = {'security_note': {}}
        db_item['security_note']['text'] = strings['default_security_note']
        db_item['security_note']['parse_mode'] = 'md'

    text, kwargs = await t_unparse_note_item(message, db_item['security_note'], chat_id)

    kwargs['reply_to'] = message.message_id

    kwargs['buttons'] = None if not kwargs['buttons'] else kwargs['buttons']
    msg = await tbot.send_message(chat_id, text, **kwargs)

    # Edit msg to apply button
    kwargs['buttons'] = [] if not kwargs['buttons'] else kwargs['buttons']
    kwargs['buttons'] += [Button.url(strings['click_here'], f'https://t.me/{BOT_USERNAME}?start=welcome_security_{chat_id}_{user_id}_{msg.id}')]

    del kwargs['reply_to']
    await msg.edit(text, **kwargs)

    redis.set(f'welcomesecurity_users_{user_id}', chat_id)

    scheduler.add_job(
        join_expired,
        "date",
        id=f"wc_expire:{chat_id}:{user_id}",
        run_date=datetime.utcnow() + convert_time(get_str_key('JOIN_CONFIRM_DURATION')),
        kwargs={'chat_id': chat_id, 'user_id': user_id, 'message_id': msg.id, 'wlkm_msg_id': message.message_id},
        replace_existing=True
    )
コード例 #16
0
ファイル: misc.py プロジェクト: Haise-Kakashi/SophieBot
async def rules(event, strings):
    rule = mongodb.rules.find_one({'chat': event.chat_id})
    if rule:
        buttons = [[
            Button.url(strings['rules_btn'],
                       url='https://t.me/{}?start=rules{}'.format(
                           BOT_USERNAME, event.chat_id))
        ]]
        text = strings['rules_text']
        await event.reply(text, buttons=buttons)
    else:
        await event.reply(strings['no_rules'])  # thank paul for dis string :/
コード例 #17
0
async def start_hndlr( event ) :
	await event.reply("""
🧹 I will get you the clear urls without any tracking data using Unalix library.

You can send multiple urls in one message/one inline query as well with newline or space as separator.

❔ How to use?
1. Forward me any message with links, I will reply you with clean URLs
2. Add me to your group, I will reply the messages with clean URLs
3. Use me in inline as well (but limited to 255 chars)
""",
	                  buttons = [Button.url("📝 Source", "https://github.com/GauthamramRavichandran/clearurls")])
	raise events.StopPropagation
コード例 #18
0
async def start(event):
    starkbot = await tgbot.get_me()
    bot_id = starkbot.first_name
    bot_username = starkbot.username
    replied_user = await event.client(GetFullUserRequest(event.sender_id))
    firstname = replied_user.user.first_name
    vent = event.chat_id
    starttext = f"Hello, {firstname} ! Nice To Meet You, Well I Am {bot_id}, An Powerfull Assistant Bot. \n\nMy [➤ Master](tg://user?id={bot.uid}) \nYou Can Talk/Contact My Master Using This Bot. \n\nIf You Want Your Own Assistant You Can Deploy From Button Below. \n\nPowered By [Thunder Userbot](t.me/blackthundersupport)"
    if event.sender_id == bot.uid:
        await tgbot.send_message(
            vent,
            message=
            f"Hi Master, It's Me {bot_id}, Your Assistant ! \nWhat You Wanna Do today ?",
            buttons=[
                [custom.Button.inline("Show Users 🔥", data="users")],
                [
                    custom.Button.inline("Commands For Assistant",
                                         data="gibcmd")
                ],
                [
                    Button.url("Add Me to Group 👥",
                               f"t.me/{bot_username}?startgroup=true")
                ],
            ],
        )
    else:
        if already_added(event.sender_id):
            pass
        elif not already_added(event.sender_id):
            add_usersid_in_db(event.sender_id)
        await tgbot.send_message(
            event.chat_id,
            message=starttext,
            link_preview=False,
            buttons=[
                [custom.Button.inline("Deploy your Friday 🇮🇳", data="deploy")],
                [Button.url("Help Me ❓", "t.me/Fridayot")],
            ],
        )
コード例 #19
0
async def callquery(event):
    data = event.data.decode("utf-8")

    if data.startswith("ndlt"):
        filename = data.split("ndlt-")[1]
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.edit(
            f"**Here is the link of the old file: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url))
    elif data.startswith("rm"):
        filename = data.split("rm-")[1]
        await event.edit(
            f"**Are you sure for delete `{filename}` permanently?**",
            buttons=[
                Button.inline('✅ Yes', f"yes-{filename}"),
                Button.inline('❌ No', "no")
            ])
    elif data.startswith("yes"):
        msg = await event.client.get_messages(entity=event.query.peer,
                                              ids=event.query.msg_id)
        print(msg)
        filename = data.split("yes-")[1]
        await Yandex.remove(filename, permanently=True)
        return await event.edit('✅ **Deleted successfully!**')
    elif data == "no":
        return await event.edit("__OK! File will not be deleted.__")
    elif data.startswith("ph"):
        filename = data.split("ph-")[1]
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.edit(
            f"__✅ I made the file public.__ **Here is public link: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url))
        remove(filename)
        return "file removed"
    elif data == "npb":
        return await event.edit("__OK! Only you will access the file.__")
コード例 #20
0
async def on_new_mssg(event):
    who = event.sender_id
    # doesn't reply to that user anymore
    if event.text.startswith("/") or who == OWNER_ID:
        return
    if FSUB:
        MSG = ""
        BTTS = []
        for chat in FSUB:
            try:
                await event.client.get_permissions(chat, event.sender_id)
            except UserNotParticipantError:
                if not MSG:
                    MSG += get_string("pmbot_1")
                try:
                    TAHC_ = await event.client.get_entity(chat)
                    if hasattr(TAHC_, "username") and TAHC_.username:
                        uri = "t.me/" + TAHC_.username
                    elif CACHE.get(chat):
                        uri = CACHE[chat]
                    else:
                        if isinstance(TAHC_, Channel):
                            FUGB = await event.client(
                                GetFullChannelRequest(chat))
                        elif isinstance(TAHC_, Chat):
                            FUGB = await event.client(GetFullChatRequest(chat))
                        else:
                            return
                        if FUGB.full_chat.exported_invite:
                            CACHE[chat] = FUGB.full_chat.exported_invite.link
                            uri = CACHE[chat]
                    BTTS.append(Button.url(get_display_name(TAHC_), uri))
                except Exception as er:
                    LOGS.exception(
                        f"Error On PmBot Force Sub!\n - {chat} \n{er}")
        if MSG and BTTS:
            return await event.reply(MSG, buttons=BTTS)
    xx = await event.forward_to(OWNER_ID)
    if event.fwd_from:
        await xx.reply(
            f"From {inline_mention(event.sender)} [`{event.sender_id}`]")
    add_stuff(xx.id, who)
コード例 #21
0
ファイル: forcesubscribe.py プロジェクト: nryadav7412/Ultroid
async def fcall(e):
    match = e.pattern_match.group(1).strip()
    spli = match.split("_")
    user = await ultroid_bot.get_entity(int(spli[0]))
    cl = await ultroid_bot.get_entity(int(spli[1]))
    text = f"Hi {inline_mention(user)}, You Need to Join"
    text += f" {cl.title} in order to Chat in this Group."
    if not cl.username:
        el = (await ultroid_bot(ExportChatInviteRequest(cl))).link
    else:
        el = "https://t.me/" + cl.username
    res = [
        await e.builder.article(
            title="forcesub",
            text=text,
            buttons=[
                [Button.url(text=get_string("fsub_4"), url=el)],
                [Button.inline(get_string("fsub_5"), data=f"unm_{match}")],
            ],
        )
    ]
    await e.answer(res)
コード例 #22
0
async def fcall(e):
    match = e.pattern_match.group(1)
    spli = match.split("_")
    user = await ultroid_bot.get_entity(int(spli[0]))
    cl = await ultroid_bot.get_entity(int(spli[1]))
    text = f"Hi [{user.first_name}](tg://user?id={user.id}), You Need to Join"
    text += f" {cl.title} in order to Chat in this Group."
    if not cl.username:
        el = (await ultroid_bot(ExportChatInviteRequest(cl))).link
    else:
        el = "https://t.me/" + cl.username
    res = [
        await e.builder.article(
            title="forcesub",
            text=text,
            buttons=[
                [Button.url(text="Join Channel", url=el)],
                [Button.inline("Unmute Me", data=f"unm_{match}")],
            ],
        )
    ]
    await e.answer(res)
コード例 #23
0
    async def welcome(event):
        """
        Detecta quando usuário entra no grupo (via link ou adicionado
        por outro usuário. Postando, portanto, a mensagem de boas vindas,
        seguida das regras do grupo.
        """
        last_welcome = {}

        bot_user = await bot.get_entity("me")

        conditions = [
            event.user_joined or event.user_added,
            event.user.id != bot_user.id,
        ]

        if all(conditions):
            if event.chat_id in last_welcome:
                try:
                    await last_welcome[event.chat_id].delete()
                except errors.MessageDeleteForbiddenError as error:
                    logging.error(error)

            user_id = event.user.id
            user = await bot.get_entity(user_id)

            welcome_user = (
                f'Olá <a href="tg://user?id={user_id}">{get_display_name(user)}</a>!'
            )

            await bot.send_message(
                event.chat_id,
                welcome_user + " " + WELCOME["pugma"],
                buttons=Button.url(
                    text=f"Leia as Regras do Grupo!",
                    url=f"https://t.me/{bot_user.username}?start=start",
                ),
                parse_mode="html",
            )
コード例 #24
0
async def upload(event):
    if event.media is None:
        return

    mesaj = await event.reply("`Your file downloading! Please Wait...`")
    baslangic = time.time()
    # if not os.path.isdir(TMP_DOWNLOAD_DIRECTORY):
    #     os.makedirs(TMP_DOWNLOAD_DIRECTORY)
    filename = await event.download_media(
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, mesaj, baslangic, "Trying to Download Your File")))
    x = await mesaj.edit("`Uploading to YaDisk! Please Wait...`")

    try:
        await Yandex.upload(filename, filename)
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.reply(
            f"__✅ I made the file public.__ **Here is public link: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url),
            link_preview=False)
        await x.delete()

        os.remove(filename)
    except exceptions.PathExistsError:
        await mesaj.edit(
            "**You have already uploaded a file with this name.**\n__Do you want remove old file?__",
            buttons=[
                Button.inline('✅ Yes', f'rm-{filename}'),
                Button.inline('❌ No', f'ndlt-{filename}')
            ])
    except exceptions.UnauthorizedError:
        await mesaj.edit(
            "You are not logged to Yandex. Please use /login then try upload file."
        )
    except Exception as e:
        print(str(e))
コード例 #25
0
async def upload_url(event):
    filename = event.pattern_match.group(1)
    url = event.pattern_match.group(2)

    if url is None or filename is None:
        return await event.edit(
            "**You must provide url & filename!**\nExample: `/upload test.gif https://www.gmail.com/mail/help/images/logonew.gif`"
        )

    event = await event.reply("`Your URL downloading! Please Wait...`")
    await download_file(url, filename, event, time.time(), event.client)
    x = await event.edit("`Uploading to YaDisk! Please Wait...`")

    try:
        await Yandex.upload(filename, filename)
        await Yandex.publish(filename)
        file = await Yandex.get_meta(filename)
        await event.reply(
            f"__✅ I made the file public.__ **Here is public link: ** [Link]({file.public_url})",
            buttons=Button.url('🔗 Public Link', file.public_url),
            link_preview=False)
        await x.delete()

    except exceptions.PathExistsError:
        await event.edit(
            "**You have already uploaded a file with this name.**\n__Do you want remove old file?__",
            buttons=[
                Button.inline('✅ Yes', f'remove-{filename}'),
                Button.inline('❌ No', f'nodelete-{filename}')
            ])
    except exceptions.UnauthorizedError:
        await event.edit(
            "You are not logged to Yandex. Please use /login then try upload file."
        )
    except Exception as e:
        print(str(e))
コード例 #26
0
async def sendScheduledMessage(message):
    text = message.message.message
    payload = eval(text.replace('/sendMessage ', ''))
    question = payload['question']
    groupId = int(payload['groupId'])
    questionNumber = payload['questionNumber']
    questionDate = payload['questionDate']
    day = questionDate[0]
    month = questionDate[1]
    year = questionDate[2]
    targetGroup = await bot.get_entity(groupId)
    await message.delete()
    queryId = randrange(000000000000000, 99999999999999999)
    await dbUtils.addQuery(queryId, question, [day, month, year])
    await bot.send_message(
        targetGroup,
        question,
        buttons=[[
            Button.url(
                'Click here to submit your answer!',
                f'https://t.me/{botObject.username}?start=oer_{groupId}_{questionNumber}_{queryId}'
            )
        ]])
    raise StopPropagation
コード例 #27
0
async def ult(ult):
    plug = ult.pattern_match.group(1)
    tgbot = asst.me.username
    if plug:
        try:
            if plug in HELP:
                output = f"**Plugin** - `{plug}`\n"
                for i in HELP[plug]:
                    output += i
                output += "\n© @TeamUltroid"
                await eor(ult, output)
            elif plug in CMD_HELP:
                kk = f"Plugin Name-{plug}\n\n✘ Commands Available -\n\n"
                kk += str(CMD_HELP[plug])
                await eor(ult, kk)
            else:
                try:
                    x = f"Plugin Name-{plug}\n\n✘ Commands Available -\n\n"
                    for d in LIST[plug]:
                        x += HNDLR + d
                        x += "\n"
                    x += "\n© @TeamUltroid"
                    await eor(ult, x)
                except BaseException:
                    await eod(ult, get_string("help_1").format(plug), time=5)
        except BaseException:
            await eor(ult, "Error 🤔 occured.")
    else:
        try:
            results = await ultroid_bot.inline_query(tgbot, "ultd")
        except BotMethodInvalidError:
            z = []
            for x in LIST.values():
                for y in x:
                    z.append(y)
            cmd = len(z) + 10
            bnn = asst.me.username
            return await ultroid_bot.send_message(
                ult.chat_id,
                get_string("inline_4").format(
                    OWNER_NAME,
                    len(PLUGINS) - 5,
                    len(ADDONS),
                    cmd,
                ),
                buttons=[
                    [
                        Button.inline("• Pʟᴜɢɪɴs", data="hrrrr"),
                        Button.inline("• Aᴅᴅᴏɴs", data="frrr"),
                    ],
                    [
                        Button.inline("Oᴡɴᴇʀ•ᴛᴏᴏʟꜱ", data="ownr"),
                        Button.inline("Iɴʟɪɴᴇ•Pʟᴜɢɪɴs", data="inlone"),
                    ],
                    [Button.url("⚙️Sᴇᴛᴛɪɴɢs⚙️", url=f"https://t.me/{bnn}?start=set")],
                    [Button.inline("••Cʟᴏꜱᴇ••", data="close")],
                ],
            )
        except rep:
            return await eor(
                ult,
                get_string("help_2").format(HNDLR),
            )
        except dis:
            return await eor(ult, get_string("help_3"))
        await results[0].click(ult.chat_id, reply_to=ult.reply_to_msg_id, hide_via=True)
        await ult.delete()
コード例 #28
0
ファイル: script.py プロジェクト: phenom2514/YanDiskBot
async def handler(update):
    if update.message.media is not None:
        userid = update.message.from_id

        if str(userid) == user_id:

            if os.path.isfile(str(userid)):
                tokenfile = open(str(userid), 'r')
                token2 = tokenfile.read()
                start = time.time()
                message = await update.reply('Download process is starting...')

                async def progress(current, total):
                    sonuc = (current / total) * 100
                    await message.edit("Status: %" + str(round(sonuc, 2)) +
                                       " Downloaded.\nTotal Size: " +
                                       str(size(total, system=si)) +
                                       "\nDownloaded Sizze: " +
                                       str(size(current, system=si)))

                dosyaismi = await client.download_media(
                    update.message, progress_callback=progress)
                await message.delete()
                message2 = await update.reply(
                    "Succesfully downloaded... Uploadinh to Yandex...")
                y = yadisk.YaDisk(token=token2)
                y.upload(dosyaismi, dosyaismi)
                y.publish(dosyaismi)
                await message2.edit(
                    "Succesfully uploaded! Getting public-link...")
                link = y.get_meta(dosyaismi).public_url
                finish = time.time() - start
                await message2.delete()
                await client.send_message(
                    userid,
                    "File is uploaded in " + str(round(finish)) + " seconds!",
                    buttons=[[Button.url('Public Link', link)]])
                os.unlink(dosyaismi)
            else:
                y = yadisk.YaDisk(yandex_app_id, yandex_app_secret)
                url2 = y.get_code_url()
                async with client.conversation(userid) as conv:
                    try:
                        await conv.send_message(
                            'Aşağıdaki butona tıklayıp yandexin websitesine gideceksiniz, ardından uygulamaya izin veriniz, izin verdikten sonra bir kod alacaksınız. O kodu yazınız.',
                            buttons=[[
                                Button.url('Bu uygulamaya izin ver', url2)
                            ]])
                        code = await conv.get_response()
                    except asyncio.TimeoutError as e:
                        await conv.send_message(
                            "Timeout error. Please resend media and try again."
                        )
                    try:
                        response = y.get_token(code.raw_text)
                    except yadisk.exceptions.BadRequestError:
                        await conv.send_message(
                            "Bad code. Please resend media and try again.")

                    except yadisk.exceptions.ForbiddenError:
                        await conv.send_message(
                            "Please, First create YandexDisk user with this link. https://disk.yandex.com/client/disk"
                        )

                    if update.message.out == "false":
                        while not any(x.isdigit() for x in code.raw_text):
                            await conv.send_message(
                                "Your name didn't have any number! Try again")
                y.token = response.access_token
                if y.check_token():
                    await conv.send_message(
                        "Token başarılı bir şekilde kaydedildi!")
                    dosya = open(str(userid), "w", encoding="utf-8")
                    dosya.write(y.token)
                else:
                    await conv.send_message(
                        "Something went wrong. Not sure how though...")
        else:
            await update.reply(
                'Sorry, you are not premium user. If do you want be premium user contact with @'
                + admin)

    elif update.message.message == "/start":
        userid = update.message.from_id
        if str(userid) == user_id:
            await update.reply('Nice, You are premium user!')
        else:
            await update.reply(
                'Sorry, you are not premium user. If do you want be premium user contact with @'
                + admin)

    elif update.message.message == "/settings":
        await update.reply('Settings:',
                           buttons=[Button.inline('Delete token', b'token')])
コード例 #29
0
def button_parser(chat_id, texts, pm=False, aio=False, row_width=None):
    buttons = InlineKeyboardMarkup(row_width=row_width) if aio else []
    pattern = r"\[(.+?)\]\((button|btn|#)(.+?)(:.+?|)(:same|)\)(\n|)"
    raw_buttons = re.findall(pattern, texts)
    text = re.sub(pattern, "", texts)
    btn = None
    for raw_button in raw_buttons:
        name = raw_button[0]
        action = (raw_button[1]
                  if raw_button[1] not in ("button", "btn") else raw_button[2])

        if raw_button[3]:
            argument = raw_button[3][1:].lower().replace("`", "")
        elif action in ("#"):
            argument = raw_button[2]
            print(raw_button[2])
        else:
            argument = ""

        if action in BUTTONS.keys():
            cb = BUTTONS[action]
            string = f"{cb}_{argument}_{chat_id}" if argument else f"{cb}_{chat_id}"
            if aio:
                start_btn = InlineKeyboardButton(
                    name, url=f"https://t.me/{BOT_USERNAME}?start=" + string)
                cb_btn = InlineKeyboardButton(name, callback_data=string)
            else:
                start_btn = Button.url(
                    name, f"https://t.me/{BOT_USERNAME}?start=" + string)
                cb_btn = Button.inline(name, string)

            if cb.endswith("sm"):
                btn = cb_btn if pm else start_btn
            elif cb.endswith("cb"):
                btn = cb_btn
            elif cb.endswith("start"):
                btn = start_btn
            elif cb.startswith("url"):
                # Workaround to make URLs case-sensitive TODO: make better
                argument = raw_button[3][1:].replace(
                    "`", "") if raw_button[3] else ""
                btn = Button.url(name, argument)
            elif cb.endswith("rules"):
                btn = start_btn
        elif action == "url":
            argument = raw_button[3][1:].replace("`",
                                                 "") if raw_button[3] else ""
            if argument[0] == "/" and argument[1] == "/":
                argument = argument[2:]
            btn = (InlineKeyboardButton(name, url=argument)
                   if aio else Button.url(name, argument))
        else:
            # If btn not registred
            btn = None
            if argument:
                text += f"\n[{name}].(btn{action}:{argument})"
            else:
                text += f"\n[{name}].(btn{action})"
                continue

        if btn:
            if aio:
                buttons.insert(btn) if raw_button[4] else buttons.add(btn)
            else:
                if len(buttons) < 1 and raw_button[4]:
                    buttons.add(btn) if aio else buttons.append([btn])
                else:
                    buttons[-1].append(
                        btn) if raw_button[4] else buttons.append([btn])

    if not aio and len(buttons) == 0:
        buttons = None

    if not text or text.isspace():  # TODO: Sometimes we can return text == ' '
        text = None

    return text, buttons
コード例 #30
0
ファイル: spotify.py プロジェクト: Ger7u7/catuserbot
async def spotify_now(event):
    "Send spotify song"
    chat = "@DeezerMusicBot"
    msg_id = await reply_id(event)
    cmd = event.pattern_match.group(1).lower()
    link = event.pattern_match.group(2)
    catevent = await edit_or_reply(event, "🎶 `Fetching...`")
    if link:
        cap = f"<b>Spotify :- <a href = {link}>Link</a></b>"
        if not url(link) and "spotify" not in link:
            return await edit_delete(catevent, "**Give me a correct link...**")
    elif not link:
        if not await sp_var_check(event):
            return
        r = sp_data("https://api.spotify.com/v1/me/player/currently-playing")
        if r.status_code == 204:
            return await edit_delete(
                catevent, "\n**I'm not listening anything right now  ;)**")
        try:
            received = r.json()
            if received["currently_playing_type"] == "track":
                title = received["item"]["name"]
                link = received["item"]["external_urls"]["spotify"]
                cap = f"<b>Spotify :- <a href = {link}>{title}</a></b>"
        except KeyError:
            return await edit_delete(
                catevent,
                "\n**Strange!! Try after restaring Spotify once ;)**")
    async with event.client.conversation(chat) as conv:
        try:
            purgeflag = await conv.send_message("/start")
        except YouBlockedUserError:
            await catub(unblock("DeezerMusicBot"))
            purgeflag = await conv.send_message("/start")
        await conv.get_response()
        await event.client.send_read_acknowledge(conv.chat_id)
        await conv.send_message(link)
        song = await conv.get_response()
        await event.client.send_read_acknowledge(conv.chat_id)
        await catevent.delete()
        if cmd == "i":
            songg = await catub.send_file(BOTLOG_CHATID, song)
            fetch_songg = await catub.tgbot.get_messages(BOTLOG_CHATID,
                                                         ids=songg.id)
            btn_song = await catub.tgbot.send_file(BOTLOG_CHATID,
                                                   fetch_songg,
                                                   buttons=Button.url(
                                                       "🎧 Spotify", link))
            fetch_btn_song = await catub.get_messages(BOTLOG_CHATID,
                                                      ids=btn_song.id)
            await event.client.forward_messages(event.chat_id, fetch_btn_song)
            await songg.delete()
            await btn_song.delete()
        else:
            await event.client.send_file(
                event.chat_id,
                song,
                caption=cap,
                parse_mode="html",
                reply_to=msg_id,
            )
        await delete_conv(event, chat, purgeflag)