Ejemplo n.º 1
0
client = TelegramClient(config["session_name"], config["api_id"],
                        config["api_hash"])

# Default to another parse mode
client.parse_mode = 'html'


def get_regional_tz_buttons(region, df):
    rzones = df[df['region'] == region]['name']
    ul = rzones.values.tolist()
    buttons = get_common_buttons(ul)
    return buttons


@client.on(events.CallbackQuery())
async def callback(event):
    query_name = event.data.decode()
    #    print(f"callback: " + query_name)
    await event.edit('Thank you for clicking {}!'.format(query_name))
    df = get_commontz()
    timezone_regions = df.region.unique()

    msg = ""
    # print(state_list)
    if query_name in regions:
        msg = get_region_state_data(query_name)
        await client.send_message(event.sender_id, msg)
        state_buttons = get_state_buttons(query_name)
        note = "\nGet more data below:\n"
        await client.send_message(event.sender_id, note, buttons=state_buttons)
Ejemplo n.º 2
0
def press_event(user_id):
    return events.CallbackQuery(func=lambda e: e.sender_id == user_id)
Ejemplo n.º 3
0
                Button.inline(module_name.strip(), data=f"help_{module_name}"))

            if len(to_append) > 2:
                buttons.append(to_append)
                to_append = []

        if to_append:
            buttons.append(to_append)

        await e.client.send_message(e.chat_id,
                                    text,
                                    reply_to=e.id,
                                    buttons=buttons)


@register(events.CallbackQuery())
async def help_buttons(e):
    module = str(e.data.decode())[5:]
    if module in help_dict:
        await e.answer()
        await e.client.edit_message(
            e.chat_id,
            e.message_id,
            f"Help for **{module}** module:\n\n{help_dict[module]}",
            buttons=[[Button.inline('Back', data='help_back')]],
            parse_mode='md')
    if e.data == b'help_back':
        text = "Here are the help for all available modules\n\nClick on each button to get its help!"
        buttons = []
        to_append = []
        for module_name in sorted(help_dict):
Ejemplo n.º 4
0
        buttons=[
            [
                Button.inline(
                    "📤 Get Torrents from Sumanjay's API",
                    data=f"torrent-{sender}|{search}|{index}|{chatid}|{msgid}",
                )
            ],
            [
                Button.inline("❌ Cancel Search",
                              data=f"torrentstop-{sender}|{chatid}|{msgid}")
            ],
        ],
    )


@tbot.on(events.CallbackQuery(pattern=r"torrent(\-(.*))"))
async def paginate_news(event):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if event.is_group:
        if await is_register_admin(event.input_chat, event.sender_id):
            pass
        elif event.chat_id == iid and event.sender_id == userss:
            pass
        else:
            return
    tata = event.pattern_match.group(1)
    data = tata.decode()
    meta = data.split("-", 1)[1]
Ejemplo n.º 5
0
    try:
        rights = member.banned_rights
    except AttributeError:
        rights = ChatBannedRights(until_date=None)
    # if until_date - now < 30 seconds the restriction would be infinite,
    # so we kindly unban them slightly ahead of schedule
    # use 35 here for safety
    if rights.until_date and rights.until_date.timestamp() < time.time() + 35:
        rights = ChatBannedRights(until_date=None)
    try:
        await bot(EditBannedRequest(chat, target, rights))
    except errors.RPCError as e:
        raise e


@bot.on(events.CallbackQuery())
async def handle_challenge_response(event):
    global config, current_challenges

    user_ans = event.data.decode()

    chat = event.chat
    user = await event.get_sender()
    username = '******' + user.username if user.username else (
        user.first_name + (' ' + user.last_name if user.last_name else ''))
    bot_msg = event.message_id

    async with config_lock:
        group_config = config.get(str(chat.id), config['*'])

    # handle manual approval/refusal by group admins
Ejemplo n.º 6
0
class SearchPagingHandler(BaseCallbackQueryHandler):
    filter = events.CallbackQuery(
        pattern='^/search_([A-Za-z0-9]+)_([0-9]+)_([0-9]+)$')
    should_reset_last_widget = False

    def preprocess_query(self, query):
        return query.replace(
            f'@{self.application.config["telegram"]["bot_external_name"]}',
            '').strip()

    def parse_pattern(self, event: events.ChatAction):
        session_id = event.pattern_match.group(1).decode()
        message_id = int(event.pattern_match.group(2).decode())
        page = int(event.pattern_match.group(3).decode())

        return session_id, message_id, page

    async def handler(self, event: events.ChatAction,
                      request_context: RequestContext):
        session_id, message_id, page = self.parse_pattern(event)

        request_context.add_default_fields(mode='search_paging',
                                           session_id=session_id)
        start_time = time.time()

        message = await event.get_message()
        if not message:
            return await event.answer()

        reply_message = await message.get_reply_message()
        try:
            if not reply_message:
                raise MessageHasBeenDeletedError()
            query = self.preprocess_query(reply_message.raw_text)
            search_widget = await SearchWidget.create(
                application=self.application,
                chat=request_context.chat,
                session_id=session_id,
                message_id=message_id,
                request_id=request_context.request_id,
                query=query,
                page=page,
            )
        except MessageHasBeenDeletedError:
            return await event.respond(
                t('REPLY_MESSAGE_HAS_BEEN_DELETED',
                  language=request_context.chat.language), )
        except AioRpcError as e:
            if e.code() == StatusCode.INVALID_ARGUMENT or e.code(
            ) == StatusCode.CANCELLED:
                request_context.error_log(e)
                return await event.answer(
                    t('MAINTENANCE_WO_PIC',
                      language=request_context.chat.language), )
            raise e

        action = 'documents_found'
        if len(search_widget.scored_documents) == 0:
            action = 'documents_not_found'

        request_context.statbox(
            action=action,
            duration=time.time() - start_time,
            query=f'page:{page} query:{query}',
        )
        serp, buttons = await search_widget.render()
        return await asyncio.gather(
            event.answer(),
            message.edit(serp, buttons=buttons, link_preview=False))
Ejemplo n.º 7
0
                        "https://github.com/MissJuliaRobot/MissJuliaRobot"),
                ],
                [
                    Button.url("Channel 🗞️",
                               url="https://t.me/MissJuliaRobotNews/2"),
                    Button.url("Webiste 🌐", "missjuliarobot.unaux.com"),
                    Button.url("Donate 💲", "https://ko-fi.com/missjuliarobot"),
                ],
                [Button.inline("Close Menu 🔒", data="start_again")],
            ],
        )
    else:
        await event.reply("I am Alive ^_^")


@tbot.on(events.CallbackQuery(pattern=r"start_again"))
async def start_again(event):
    if not event.is_group:
        await event.edit(
            "The menu is closed 🔒",
            buttons=[[Button.inline("Reopen Menu 🔑", data="reopen_again")]],
        )
    else:
        await event.reply("I am Alive ^_^")


@tbot.on(events.CallbackQuery(pattern=r"reopen_again"))
async def reopen_again(event):
    if not event.is_group:
        await event.edit(
            PM_START_TEXT,
Ejemplo n.º 8
0
 def decorator(func):
     tbot.add_event_handler(func, events.CallbackQuery(**args))
     return func
Ejemplo n.º 9
0
                    title=title,
                    count=count,
                    first=first,
                    last=last,
                    fullname=fullname,
                    username=username,
                    userid=userid,
                ),
                file=cws.media_file_id,
            )
            #print (current_message)
            update_previous_goodbye(event.chat_id, current_message.id)

# -- @MissJulia_Robot (sassiet captcha ever) --#

@tbot.on(events.CallbackQuery(pattern=r"start-ruless-(\d+)"))
async def rules_st(event):
    rules = sql.get_rules(event.chat_id)
    # print(rules)
    user_id = int(event.pattern_match.group(1))        
    if not event.sender_id == user_id:
       await event.answer("You aren't a new user!")
       return
    text = f"The rules for **{event.chat.title}** are:\n\n{rules}"
    try:
        await tbot.send_message(
            user_id,
            text,
            parse_mode="markdown",
            link_preview=False)
    except Exception:
Ejemplo n.º 10
0
 def decorator(func):
     if compile is True:
         tbot.add_event_handler(func,
                                events.CallbackQuery(data=re.compile(data)))
     else:
         tbot.add_event_handler(func, events.CallbackQuery(data=data))
Ejemplo n.º 11
0
            buttons=[
                [
                    Button.inline("🧰 Tutorial", data="soon"),
                    Button.inline("📚 Perintah", data="help_menu"),
                ],
                  [
                    Button.url(
                        "📌 Tambahkan Saya Ke Grup Kamu!", "t.me/TheToniBot?startgroup=true"
                    ),
                ],
            ],
        )
    else:
        await event.reply("Yuhu Toni disini!,\nada yang bisa saya bantu?")

@tbot.on(events.CallbackQuery(pattern=r"reopen_again"))
async def reopen_again(event):
    if not event.is_group:
        await event.edit(
            pm_caption,
            buttons=[
                [
                    Button.inline("🧰 Tutorial", data="soon"),
                    Button.inline("📚 Perintah", data="help_menu"),
                ],
                  [
                    Button.url(
                        "📌 Tambahkan Saya Ke Grup Kamu!", "t.me/TheToniBot$?startgroup=true"
                    ),
                ],
            ],
Ejemplo n.º 12
0
    permissions = await tbot.get_permissions(event.chat_id, event.sender_id)
    if not permissions.is_creator:
        return await event.reply(
            f"You need to be the chat owner of {event.chat.title} to do this.")
    TEXT = f"Are you sure you would like to clear **ALL** filters in {event.chat.title}? This action cannot be undone."
    await tbot.send_message(
        event.chat_id,
        TEXT,
        buttons=[
            [Button.inline("Delete all filters", data="fuk")],
            [Button.inline("Cancel", data="suk")],
        ],
        reply_to=event.id)


@tbot.on(events.CallbackQuery(pattern=r"suk"))
async def start_again(event):
    permissions = await tbot.get_permissions(event.chat_id, event.sender_id)
    if not permissions.is_creator:
        return await event.answer("Yeah suck my dick")
    await event.edit("Stopping of all filters has been cancelled.")


@tbot.on(events.CallbackQuery(pattern=r"fuk"))
async def start_again(event):
    permissions = await tbot.get_permissions(event.chat_id, event.sender_id)
    if not permissions.is_creator:
        return await event.answer("Yeah suck my dick")
    remove_all_filters(event.chat_id)
    await event.edit("Deleted all chat filters.")
Ejemplo n.º 13
0
                await tbot(
                    EditBannedRequest(event.chat_id, event.sender_id,
                                      MUTE_RIGHTS))
                await tbot.send_message(event.chat_id,
                                        text,
                                        buttons=buttons,
                                        link_preview=False)
        except:
            if not await rights(event):
                await tbot.send_message(
                    event.chat_id,
                    "❗**I am not an admin here.**\nMake me admin with ban user permission"
                )


@tbot.on(events.CallbackQuery(pattern=r"fs(\_(.*))"))
async def start_again(event):
    tata = event.pattern_match.group(1)
    data = tata.decode()
    user = data.split("_", 1)[1]
    if not event.sender_id == int(user):
        return await event.answer("You are not the muted user!")
    chat_id = event.chat_id
    chat_db = sql.fs_settings(chat_id)
    if chat_db:
        channel = chat_db.channel
        rip = await check_him(channel, event.sender_id)
        if rip is True:
            try:
                await event.delete()
                await tbot(
Ejemplo n.º 14
0
        name = f["fed"]["fname"]
    await xbot.send_message(
        event.chat_id,
        "Are you sure you want to delete your federation? This action cannot be undone - you will lose your entire ban list, and '{}' will be permanently gone."
        .format(name),
        buttons=[
            [
                Button.inline("Delete Federation",
                              data="rmfed_{}".format(fed_id))
            ],
            [Button.inline("Cancel", data="nada")],
        ],
    )


@xbot.on(events.CallbackQuery(pattern=r"rmfed(\_(.*))"))
async def delete_fed(event):
    tata = event.pattern_match.group(1)
    data = tata.decode()
    fed_id = data.split("_", 1)[1]
    delete = sql.del_fed(fed_id)
    await event.edit(
        "You have deleted your federation! All chats linked to it are now federation-less."
    )


@xbot.on(events.CallbackQuery(pattern=r"nada"))
async def delete_fed(event):
    await event.edit("Federation deletion canceled")

Ejemplo n.º 15
0
@System.bot.on(events.NewMessage(pattern="[/?]start"))
async def sup(event):
    await event.reply("sup?")


@System.bot.on(events.NewMessage(pattern="[/?]help"))
async def help(event):
    await event.reply("""
This bot is a inline bot, You can use it by typing `@SibylSystemRobot`
If a user is gbanned -
    Getting reason for gban, message the user was gbanned for - `@SibylSystemRobot proof <user_id|proof_id>`
    """)


@System.bot.on(events.CallbackQuery(pattern=r"(approve|reject)_(\d*)"))
async def callback_handler(event):
    split = event.data.decode().split("_", 1)
    index = int(split[1])
    message = await event.get_message()
    async with DATA_LOCK:
        try:
            dict_ = data[index]
        except IndexError:
            dict_ = None
    if not dict_:
        await event.answer(
            "Message is too old (Bot was restarted after message was sent), Use /approve on it instead",
            alert=True,
        )
        return
Ejemplo n.º 16
0
async def pre():
    logger.info(
        f"RSS-to-Telegram-Bot ({', '.join(env.VERSION.split())}) started!\n"
        f"MANAGER: {env.MANAGER}\n"
        f"T_PROXY (for Telegram): {env.TELEGRAM_PROXY if env.TELEGRAM_PROXY else 'not set'}\n"
        f"R_PROXY (for RSS): {env.REQUESTS_PROXIES['all'] if env.REQUESTS_PROXIES else 'not set'}\n"
        f"DATABASE: {env.DATABASE_URL.split('://', 1)[0]}\n"
        f"TELEGRAPH: {f'Enable ({tgraph.apis.count} accounts)' if tgraph.apis else 'Disable'}\n"
        f"UVLOOP: {f'Enable' if uvloop is not None else 'Disable'}\n"
        f"MULTIUSER: {f'Enable' if env.MULTIUSER else 'Disable'}")

    await db.init()

    # noinspection PyTypeChecker
    manager_lang: Optional[str] = await db.User.get_or_none(id=env.MANAGER
                                                            ).values_list(
                                                                'lang',
                                                                flat=True)

    try:  # set bot command
        await asyncio.gather(
            command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code='',
                commands=command.utils.get_commands_list()),
            *(command.utils.set_bot_commands(
                scope=types.BotCommandScopeDefault(),
                lang_code=i18n[lang]['iso_639_code'],
                commands=command.utils.get_commands_list(lang=lang))
              for lang in ALL_LANGUAGES
              if len(i18n[lang]['iso_639_code']) == 2),
            command.utils.set_bot_commands(
                scope=types.BotCommandScopePeer(
                    types.InputPeerUser(env.MANAGER, 0)),
                lang_code='',
                commands=command.utils.get_commands_list(lang=manager_lang,
                                                         manager=True)),
        )
    except Exception as e:
        logger.warning('Set command error: ', exc_info=e)

    # command handler
    bot.add_event_handler(command.sub.cmd_sub,
                          events.NewMessage(pattern='/add|/sub'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.PrivateMessage(pattern=r'https?://'))
    bot.add_event_handler(command.sub.cmd_sub,
                          command.utils.ReplyMessage(pattern=r'https?://'))
    bot.add_event_handler(
        command.sub.cmd_unsub,
        events.NewMessage(pattern='(/remove|/unsub)([^_]|$)'))
    bot.add_event_handler(command.sub.cmd_unsub_all,
                          events.NewMessage(pattern='/remove_all|/unsub_all'))
    bot.add_event_handler(command.sub.cmd_list_or_callback_get_list_page,
                          events.NewMessage(pattern='/list'))
    bot.add_event_handler(command.opml.cmd_import,
                          events.NewMessage(pattern='/import'))
    bot.add_event_handler(command.opml.cmd_export,
                          events.NewMessage(pattern='/export'))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.NewMessage(pattern='/set([^_]|$)'))
    bot.add_event_handler(
        command.opml.opml_import,
        command.utils.NewFileMessage(filename_pattern=r'^.*\.opml$'))
    bot.add_event_handler(command.management.cmd_start,
                          events.NewMessage(pattern='/start'))
    bot.add_event_handler(command.management.cmd_or_callback_help,
                          events.NewMessage(pattern='/help'))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=True), events.NewMessage(pattern='/activate_subs'))
    bot.add_event_handler(
        partial(command.customization.cmd_activate_or_deactivate_subs,
                activate=False), events.NewMessage(pattern='/deactivate_subs'))
    bot.add_event_handler(command.management.cmd_version,
                          events.NewMessage(pattern='/version'))
    bot.add_event_handler(command.management.cmd_lang,
                          events.NewMessage(pattern='/lang'))
    bot.add_event_handler(command.administration.cmd_test,
                          events.NewMessage(pattern='/test'))
    bot.add_event_handler(command.administration.cmd_set_option,
                          events.NewMessage(pattern='/set_option'))
    # callback query handler
    bot.add_event_handler(
        command.utils.answer_callback_query_null,  # null callback query
        events.CallbackQuery(data='null'))
    bot.add_event_handler(command.sub.cmd_list_or_callback_get_list_page,
                          events.CallbackQuery(pattern=r'^get_list_page_\d+$'))
    bot.add_event_handler(command.sub.callback_unsub,
                          events.CallbackQuery(pattern=r'^unsub_\d+(\|\d+)$'))
    bot.add_event_handler(
        command.sub.callback_get_unsub_page,
        events.CallbackQuery(pattern=r'^get_unsub_page_\d+$'))
    bot.add_event_handler(command.management.callback_set_lang,
                          events.CallbackQuery(pattern=r'^set_lang_[\w_\-]+$'))
    bot.add_event_handler(command.management.cmd_or_callback_help,
                          events.CallbackQuery(pattern=r'^help$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=True),
        events.CallbackQuery(pattern=r'^activate_all_subs$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_all_subs,
                activate=False),
        events.CallbackQuery(pattern=r'^deactivate_all_subs$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=True),
        events.CallbackQuery(pattern=r'^activate_sub_\d+(\|\d+)$'))
    bot.add_event_handler(
        partial(command.customization.callback_activate_or_deactivate_sub,
                activate=False),
        events.CallbackQuery(pattern=r'^deactivate_sub_\d+(\|\d+)$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=True),
        events.CallbackQuery(pattern=r'^get_activate_page_\d+$'))
    bot.add_event_handler(
        partial(command.customization.callback_get_activate_or_deactivate_page,
                activate=False),
        events.CallbackQuery(pattern=r'^get_deactivate_page_\d+$'))
    bot.add_event_handler(
        command.customization.callback_set,
        events.CallbackQuery(pattern=r'^set(_\d+(_\w+(_\w+)?)?)?(\|\d+)?$'))
    bot.add_event_handler(
        command.customization.cmd_set_or_callback_get_set_page,
        events.CallbackQuery(pattern=r'^get_set_page_\d+$'))
    # being added to a group handler
    bot.add_event_handler(command.management.cmd_start,
                          command.utils.AddedToGroupAction())
    bot.add_event_handler(command.management.cmd_start,
                          command.utils.GroupMigratedAction())
Ejemplo n.º 17
0
        if (await is_register_admin(event.chat_id, event.sender_id)):
            pass
        elif event.chat_id == iid and event.sender_id == userss:
            pass
        else:
            return
    sender = event.sender_id
    country = event.pattern_match.group(1)
    lang = event.pattern_match.group(2)
    index = 0
    chatid = event.chat_id
    msg = await tbot.send_message(chatid, "Loading ...")
    msgid = msg.id
    await tbot.edit_message(chatid, msgid, "Click on the below button to read the latest news headlines 👇", buttons=[[Button.inline('▶️', data=f'news-{sender}|{country}|{lang}|{index}|{chatid}|{msgid}')], [Button.inline('❌', data=f'newsstop-{sender}|{chatid}|{msgid}')]])

@tbot.on(events.CallbackQuery(pattern=r"news(\-(.*))"))
async def paginate_news(event):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch['id']
        userss = ch['user']
    if event.is_group:
        if (await is_register_admin(event.chat_id, event.sender_id)):
            pass
        elif event.chat_id == iid and event.sender_id == userss:
            pass
        else:
            return
    tata = event.pattern_match.group(1)
    data = tata.decode()
    meta = data.split('-', 1)[1]
Ejemplo n.º 18
0
            else:
                self.calls[-1] += 1
        await self.func(event)


async def nothing(event):
    pass


messages = Store(nothing)
inline_queries = Store(nothing)
callback_queries = Store(nothing)

telethn.add_event_handler(messages, events.NewMessage())
telethn.add_event_handler(inline_queries, events.InlineQuery())
telethn.add_event_handler(callback_queries, events.CallbackQuery())


@telethn.on(events.NewMessage(pattern=r"/getstats", from_users=OWNER_ID))
async def getstats(event):
    await event.reply(
        f"**__KIGYO EVENT STATISTICS__**\n**Average messages:** {messages.average()}/s\n**Average Callback Queries:** {callback_queries.average()}/s\n**Average Inline Queries:** {inline_queries.average()}/s",
        parse_mode='md')


@dev_plus
def pip_install(update: Update, context: CallbackContext):
    message = update.effective_message
    args = context.args
    if not args:
        message.reply_text("Enter a package name.")
Ejemplo n.º 19
0
                    gmj.started(match)
                    await event.reply(
                        'Match Started!\n\n' +
                        '__Total round__: `{}`, __Round timeout__: `{}`'.
                        format(round_count, round_duration))
                else:
                    await event.reply('Match already started!!')
            else:
                gmj.remove_match(match)
                await event.reply(
                    'No match found\n__Start a new match with /newmatch.__')
                return
        else:
            await event.reply(
                'No match found\n__Start a new match with /newmatch.__')


@events.register(events.CallbackQuery(pattern="^choisCard_"))
async def card_choosed(event):
    global match_contexts

    splited = str(event.data).split('_')
    match_id = splited[1]
    card = splited[2].replace("'", "")

    match_context = [x for x in match_contexts if x.match_id == match_id][0]
    if match_context:
        if match_context.card_selected(event.sender.id, card):
            await event.answer("Selected!")
            await event.edit(f"__{card}__ Selected!")