Пример #1
0
def button_parser(chat_id, texts):
    buttons = []
    raw_buttons = re.findall(r'\[(.+?)\]\(button(.+?):(.+?)(:same|)\)', texts)
    text = re.sub(r'\[(.+?)\]\(button(.+?):(.+?)(:same|)\)', '', texts)
    for raw_button in raw_buttons:
        if raw_button[1] == 'url':
            url = raw_button[2]
            if url[0] == '/' and url[0] == '/':
                url = url[2:]
            t = [custom.Button.url(raw_button[0], url)]
        elif raw_button[1] == 'note':
            t = [
                Button.inline(raw_button[0],
                              'get_note_{}_{}'.format(chat_id, raw_button[2]))
            ]
        elif raw_button[1] == 'alert':
            t = [
                Button.inline(raw_button[0],
                              'get_alert_{}_{}'.format(chat_id, raw_button[2]))
            ]
        elif raw_button[1] == 'deletemsg':
            t = [
                Button.inline(
                    raw_button[0],
                    'get_delete_msg_{}_{}'.format(chat_id, raw_button[2]))
            ]

        if raw_button[3]:
            new = buttons[-1] + t
            buttons = buttons[:-1]
            buttons.append(new)
        else:
            buttons.append(t)

    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 do_welcomesecurity(event, strings, from_id, chat_id):
    welcome_security = mongodb.welcome_security.find_one({'chat_id': chat_id})
    if welcome_security and welcome_security['security'] == 'soft':
        buttons = [[
            Button.inline(strings['clik2tlk_btn'],
                          'wlcm_{}_{}'.format(from_id, chat_id))
        ]]
        time_val = int(time.time() + 60 * 60)  # Mute 1 hour
        try:
            await mute_user(event, int(from_id), chat_id, time_val)
        except Exception as err:
            await event.reply(err)

        text = strings['wlcm_sec'].format(mention=await user_link(from_id))
        await event.reply(text, buttons=buttons)

    elif welcome_security and welcome_security['security'] == 'hard':
        buttons = [[
            Button.inline(strings['clik2tlk_btn'],
                          'wlcm_{}_{}'.format(from_id, chat_id))
        ]]
        try:
            await mute_user(event, int(from_id), chat_id, None)
        except Exception as err:
            await event.reply(err)

        text = strings['wlcm_sec'].format(mention=await user_link(from_id))
        await event.reply(text, buttons=buttons)
Пример #4
0
    async def _locked_start_poll(
            event: Union[events.NewMessage.Event, Message]) -> None:
        global current_vote

        if current_vote:
            await event.reply('There\'s already an ongoing sticker poll.')
            return
        elif last_accepted + ADD_COOLDOWN > int(time()):
            await event.reply('Less than 24 hours have passed since the '
                              'previous sticker was added.')
            return

        emoji = event.pattern_match.group(1)
        try:
            _, sender_name = WEIGHTS[event.sender_id]
        except KeyError:
            await event.reply('Please upgrade to a Telethon OffTopic Premium '
                              'Membership to start sticker polls.')
            return
        orig_evt: Message = await event.get_reply_message()
        # TODO add support for animated stickers
        if not orig_evt.photo and (not orig_evt.sticker
                                   or orig_evt.sticker.mime_type
                                   == 'application/x-tgsticker'):
            return

        filename = Path(DATA_FILE_FORMAT.format(ts=int(time())))
        await orig_evt.download_media(filename)

        delete_task = asyncio.ensure_future(event.delete(), loop=bot.loop)
        current_vote_status.clear()
        current_vote = {
            'chat':
            event.chat_id,
            'started_at':
            int(time()),
            'sender_id':
            event.sender_id,
            'sender_name':
            sender_name,
            'score':
            0,
            'emoji':
            emoji,
            'votes': {},
            'filepath':
            str(filename),
            'animated':
            orig_evt.sticker
            and orig_evt.sticker.mime_type == 'application/x-tgsticker'
        }
        reply_evt: Message = await orig_evt.reply(
            POLL_TEMPLATE.format_map(get_template_data()),
            buttons=[Button.inline(UP, UP_DAT),
                     Button.inline(DOWN, DOWN_DAT)],
            parse_mode='html')
        pin_task = asyncio.ensure_future(reply_evt.pin(), loop=bot.loop)
        current_vote['poll'] = reply_evt.id
        asyncio.ensure_future(wait_for_poll(), loop=bot.loop)
        await asyncio.gather(delete_task, pin_task, loop=bot.loop)
Пример #5
0
async def get_mod_help_callback(event):
    chat_id = event.chat_id
    module = re.search('mod_help_(.*)', str(event.data)).group(1)[:-1]
    text = get_string(module, "title", chat_id, dir="HELPS")
    text += '\n'
    lang = get_chat_lang(chat_id)
    buttons = []
    for string in get_string(module, "text", chat_id, dir="HELPS"):
        if "HELPS" in LANGUAGES[lang]:
            text += LANGUAGES[lang]["HELPS"][module]['text'][string]
        else:
            text += LANGUAGES["en"]["HELPS"][module]['text'][string]
        text += '\n'
    if 'buttons' in LANGUAGES[lang]["HELPS"][module]:
        counter = 0
        for btn in LANGUAGES[lang]["HELPS"][module]['buttons']:
            counter += 1
            btn_name = LANGUAGES[lang]["HELPS"][module]['buttons'][btn]
            t = [Button.inline(btn_name, btn)]
            if counter % 2 == 0:
                new = buttons[-1] + t
                buttons = buttons[:-1]
                buttons.append(new)
            else:
                buttons.append(t)
    buttons += [[Button.inline("Back", 'get_help')]]
    await event.edit(text, buttons=buttons)
Пример #6
0
    def commit(cls, **kwargs):
        # Stop
        # Note
        # Request Review
        print("HEYDIHOE")
        event = kwargs['event']
        print(event)
        data = event.query.data.decode("utf-8").lower()
        pid = data.split(":")[1]

        from .models import Workpackage

        workpackage = Workpackage.objects.get(pid=pid)
        return (
            f'`{workpackage.name}`',
            [
                [
                    Button.inline(
                        'Stop',
                        data=(f"wp_commit_handler:{pid}:waiting").encode()),
                    #Button.inline('Note', data=(f"wp_note:{pid}").encode())
                ],
                [
                    Button.inline(
                        'Request Review',
                        data=(f"wp_commit_handler:{pid}:review").encode())
                ],
                [Button.inline('Back')]
            ])
Пример #7
0
 def help(cls, **kwargs):
     return ("useable commands and arguments are", [
         [
             Button.inline('Workpackages', data=b'workpackages'),
             Button.inline('Start')
         ],
     ])
Пример #8
0
async def upload(event):
    if event.media is None:
        return

    mesaj = await event.reply("`Your file downloading! Please Wait...`")
    baslangic = time.time()
    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")))
    await mesaj.edit("`Uploading to YaDisk! Please Wait...`")

    try:
        await Yandex.upload(filename, 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'remove-{filename}'),
                Button.inline('❌ No', f'nodelete-{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))

    await mesaj.edit(
        "**✅ File has been successfully uploaded to Yandex. Do you want to make it public?**",
        buttons=[
            Button.inline('✅ Yes', f'publish-{filename}'),
            Button.inline('❌ No', f'nopublish')
        ])
Пример #9
0
async def handleAddChannel(event):
    await event.delete()
    async with bot.conversation(event.query.peer) as conv:
        btns = [Button.inline(text='Cancel', data=b'mainpage')]
        q = await conv.send_message('Enter channel link.', buttons=btns)
        try:
            resp = await conv.get_response()
        except asyncio.TimeoutError:
            await q.delete()
            conv.send_message('Timeout\nPlease try again...')
            conv.cancel()
            return
        channelLink = resp.message
        await resp.delete()
        await q.delete()
        valid, entity = await getEntity(channelLink)
        if valid:
            newChannel = {
                'id': entity.id,
                'title': entity.title,
                'link': channelLink
            }
            await addChannel(newChannel)
            btns = [
                Button.inline(text='Back', data=b'mainpage')
            ]
            await conv.send_message('Channel added to the list of channels.', buttons=btns)
        else:
            btns = [Button.inline(text='Back', data=b'mainpage')]
            await conv.send_message('The entered link is not a valid telegram channel link.', buttons=btns)
Пример #10
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)
    await event.edit("`Uploading to YaDisk! Please Wait...`")

    try:
        await Yandex.upload(filename, filename)
    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))

    await event.edit(
        "**✅ File has been successfully uploaded to Yandex. Do you want to make it public?**",
        buttons=[
            Button.inline('✅ Yes', f'publish-{filename}'),
            Button.inline('❌ No', f'nopublish')
        ])
Пример #11
0
async def connect(event):
    user_id = event.from_id
    if not event.chat_id == user_id:
        return
    history = mongodb.connections.find_one({'user_id': user_id})
    if not history:
        await event.reply(
            get_string("connections", "history_empty", event.chat_id))
        return
    buttons = []
    chat_title = mongodb.chat_list.find_one({'chat_id': history['btn1']})
    buttons += [[
        Button.inline("{}".format(chat_title['chat_title']),
                      'connect_{}'.format(history['btn1']))
    ]]
    if history['btn2']:
        chat_title = mongodb.chat_list.find_one({'chat_id': history['btn2']})
        buttons += [[
            Button.inline("{}".format(chat_title['chat_title']),
                          'connect_{}'.format(history['btn2']))
        ]]
    if history['btn3']:
        chat_title = mongodb.chat_list.find_one({'chat_id': history['btn3']})
        buttons += [[
            Button.inline("{}".format(chat_title['chat_title']),
                          'connect_{}'.format(history['btn3']))
        ]]
    chat_title = mongodb.chat_list.find_one(
        {'chat_id': int(history['chat_id'])})
    text = get_string("connections", "connected_chat", event.chat_id)
    text += chat_title['chat_title']
    text += get_string("connections", "select_chat_to_connect", event.chat_id)
    await event.reply(text, buttons=buttons)
Пример #12
0
    async def on_click_game(self, event: events.CallbackQuery.Event):
        mes = await event.get_message()
        logger.info(
            f'{get_member(event.sender_id)} clicked game button (mes_id={mes.id}, chat_id={event.chat_id})'
        )

        lvl, cur, sel = [int(x) for x in event.pattern_match.groups()]
        buttons = (await mes.get_buttons())[0]  # first row
        complexity = 4 * len(buttons)**3
        chance = lvl / (lvl + complexity)

        if sel != cur and random.random() < chance:
            buttons[cur] = Button.inline(self.empty_ch)
            buttons[sel] = Button.inline(self.dead_ch)
            await mes.edit('🎉 Победа! 🎉', buttons=buttons)
            await asyncio.sleep(1)
            await mes.edit(
                buttons=Button.inline("Получить награду", self.game_butt_id +
                                      'f'))
        else:
            new_cur = random.randrange(len(buttons) - 1)
            if new_cur >= cur:
                new_cur = new_cur + 1
            lvl += 1
            game_state = self.game_butt_id + str(lvl) + ' ' + str(new_cur)
            buttons = [
                Button.inline(self.empty_ch if i != new_cur else self.alive_ch,
                              game_state + ' ' + str(i))
                for i in range(len(buttons))
            ]
            await mes.edit(buttons=buttons)

        raise events.StopPropagation
Пример #13
0
def get_showmore_buttons(search: str, start: int, total: int):
    """start: begin with 0
    """
    digest = hashlib.md5(search.encode()).hexdigest()
    previous_start = max((start - constants.MessagesEachSearch), 0)
    next_start = min((start + constants.MessagesEachSearch), total)
    # print(previous_start, next_start)
    fsm = constants.CQ.FindShowMore
    button_left = Button.inline('⇦',
                                data=fsm.format(digest=digest,
                                                start=previous_start))
    button_right = Button.inline('⇨',
                                 data=fsm.format(digest=digest,
                                                 start=next_start))
    button_shown = Button.inline(
        f'{start + constants.MessagesEachSearch} / {total}')
    # MessagesEachSearch/total ⇨
    if start == 0:
        return [button_shown, button_right]
    # ⇦ total/total
    if start + constants.MessagesEachSearch >= total:
        button_shown = Button.inline(f'{total} / {total}')
        return [button_left, button_shown]
    # ⇦ start+MessagesEachSearch/total ⇨
    return [button_left, button_shown, button_right]
Пример #14
0
 async def handler(event):
     try:
         me = await client.get_me()
         if not event.query.user_id == me.id:
             return await event.answer(
                 "Sorry, You dont have permission to  Access me!",
                 alert=True)
         et = event.data.decode("UTF-8")
         if et == "back":
             sad = sad2 = sad3 = sad4 = None
             lol = 0
             tbu = [[
                 Button.inline('❌ Close menu', b'close'),
             ]]
             for i in CMD_HELP:
                 if lol == 0:
                     sad = str(i)
                     lol = 1
                 elif lol == 1:
                     sad2 = str(i)
                     lol = 2
                 elif lol == 2:
                     sad3 = str(i)
                     lol = 3
                 elif lol == 3:
                     sad4 = str(i)
                     lol = 0
                 if sad and sad2 and sad3 and sad4:
                     tbu += [[
                         Button.inline(f"{sad}", f"{sad}"),
                         Button.inline(f"{sad2}", f"{sad2}"),
                         Button.inline(f"{sad3}", f"{sad3}"),
                         Button.inline(f"{sad4}", f"{sad4}")
                     ]]
                     sad = sad2 = sad3 = sad4 = None
             if sad:
                 tbu += [[Button.inline(f"{sad}", f"{sad}")]]
             if sad2:
                 tbu += [[Button.inline(f"{sad2}", f"{sad2}")]]
             if sad3:
                 tbu += [[Button.inline(f"{sad3}", f"{sad3}")]]
             return await event.edit(
                 "For Support, Report bugs & help @errorsender_bot",
                 buttons=tbu,
                 link_preview=False)
         if et == "close":
             return await event.edit(" Help Menu Closed")
         if et in CMD_HELP:
             fci = [[
                 Button.inline('Go back', 'back'),
                 Button.inline('❌ Close menu', b'close')
             ]]
             await event.edit(str(CMD_HELP[et]), buttons=fci)
         else:
             await event.answer("Please Wait Sir", alert=True)
     except Exception as e:
         return await event.edit(str(e))
Пример #15
0
    async def _locked_vote_poll(event: events.CallbackQuery.Event) -> None:
        global current_vote

        if not current_vote or current_vote['poll'] != event.message_id:
            await event.answer('That poll is closed.')
            return

        try:
            await bot(
                GetParticipantRequest(channel=current_vote["chat"],
                                      user_id=event.input_sender))
        except UserNotParticipantError:
            await event.answer('You\'re not participating in the chat.')
            return

        weight, displayname = WEIGHTS.get(event.sender_id,
                                          (DEFAULT_WEIGHT, None))
        if weight == 0:
            await event.answer('You don\'t have the permission to vote.')
            return
        if event.data == b'addsticker/-':
            weight = -weight

        displayname = displayname or utils.get_display(await
                                                       event.get_sender())
        try:
            existing = current_vote['votes'][event.sender_id]
            if existing.weight == weight:
                await event.answer(f'You already voted {weight}')
                return
        except KeyError:
            pass

        current_vote['votes'][event.sender_id] = VoteData(
            weight=weight, displayname=displayname)

        scores = calculate_scores()
        current_vote['score'] = scores.sum

        if abs(scores.sum) >= VOTES_REQUIRED:
            current_vote_status.set()
            accepted = await _locked_finish_poll()
            res = 'accepted' if accepted else 'rejected'
            await event.answer(f'Successfully voted {fancy_round(weight)},'
                               f' which made the sticker be {res} \U0001f389')
        else:
            await bot.edit_message(
                current_vote['chat'],
                current_vote['poll'],
                POLL_TEMPLATE.format_map(get_template_data()),
                buttons=[
                    Button.inline(f'{UP} ({scores.yes_count})', UP_DAT),
                    Button.inline(f'{DOWN} ({scores.no_count})', DOWN_DAT)
                ],
                parse_mode='html')
            await event.answer(f'Successfully voted {weight}')
Пример #16
0
async def lang_command_handler(event: NewMessage.Event, strings):
    user = await event.get_chat()
    buttons = [[Button.inline(strings.lang_follow_telegram, data='follow')]]
    for i in range(0, len(i18n.languages), 3):
        buttons.append([
            Button.inline(i18n.languages[langcode], data=langcode)
            for langcode in list(i18n.languages.keys())[i:i + 3]
        ])
    db.set_user_state(user, states.SettingLang)
    await event.respond(strings.lang_select_lang, buttons=buttons)
Пример #17
0
def get_start(event):
    text = get_string("pm_menu", "start_hi", event.chat_id)
    buttons = [[Button.inline(get_string("pm_menu", "btn_help", event.chat_id), 'get_help')]]
    buttons += [[Button.inline(get_string("pm_menu", "btn_lang", event.chat_id), 'set_lang')]]
    buttons += [[custom.Button.url(get_string("pm_menu", "btn_chat", event.chat_id),
                'https://t.me/YanaBotGroup'),
                 custom.Button.url(get_string("pm_menu", "btn_channel", event.chat_id),
                 'https://t.me/SophieNEWS')]]

    return text, buttons
Пример #18
0
async def echo(event):
    # Echo the user message.
    chat = await event.get_input_chat()
    sender = await event.get_sender()
    buttons = await event.get_buttons()
    print(sender.id)
    print(event.raw_text)
    # отправка сообщения со встроенными кнопками
    await event.respond(event.text, buttons=[[Button.inline('Left'), 
        Button.inline("MyLoc")]])
Пример #19
0
async def lang_command_handler(event: NewMessage.Event, _):
    user = await event.get_chat()
    buttons = [
        Button.inline(i18n.languages[code], data=code)
        for code in i18n.langcodes
    ]
    buttons = three_buttons_each_line(buttons)
    buttons.insert(
        0, [Button.inline(_('Follow Telegram settings'), data='follow')])
    db.set_user_state(user, states.SettingLang)
    await event.respond(_('Select your language:'), buttons=buttons)
Пример #20
0
async def add_bug(event):
    if not event.is_reply and len(event.text.split()) == 1:
        return await event.delete()
    await bot.send_message(
        event.chat_id,
        'Thanks for your bug report. Please await admin\'s approval',
        buttons=[
            Button.inline("Approve", b'bug'),
            Button.inline("Reject", b"no" + b'bug')
        ],
        reply_to=event.reply_to_msg_id or event)
Пример #21
0
def gen_int_btns(ansrw):
    buttons = []

    for a in [random.randint(1, 20) for _ in range(3)]:
        while a == ansrw:
            a = random.randint(1, 20)
        buttons.append(Button.inline(str(a), data='wc_int_btn:' + str(a)))

    buttons.insert(random.randint(0, 3), Button.inline(str(ansrw), data='wc_int_btn:' + str(ansrw)))

    return buttons
Пример #22
0
async def test(event):
    channel = -1001477006210
    global data
    global data_1
    global data_2
    # name = get_display_name(event.original_update.user_id)
    name = await bot.get_entity(PeerUser(event.original_update.user_id))
    msg = f"[{name.first_name}](tg://user?id={name.id})"
    # message_link = f"tg://openmessage?chat_id={event.original_update.peer.channel_id}&message_id={event.original_update.msg_id}"
    message_link = f"https://t.me/c/{event.original_update.peer.channel_id}/{event.original_update.msg_id}"
    if event.data.decode('utf-8') == "up":
        data += 1
        buton = tgbot.build_reply_markup([
            Button.inline(f"👍🏻 {data}", data="up"),
            Button.inline(f"❤️ {data_1}", data="kalp"),
            Button.inline(f"😢 {data_2}", data="agla")
        ])
        await tgbot.edit_message(channel,
                                 event.original_update.msg_id,
                                 buttons=buton)
        await bot.send_message(
            -443785781,
            f"Tıklayan: {msg}, 👍 e tıkladı.\n\nMesaja git: {message_link}")
        reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder."
        await event.answer(reply_pop_up_alert, cache_time=0, alert=True)
        # data += 1

    if event.data.decode('utf-8') == "kalp":
        data_1 += 1
        buton = tgbot.build_reply_markup([
            Button.inline(f"👍🏻 {data}", data="up"),
            Button.inline(f"❤️ {data_1}", data="kalp"),
            Button.inline(f"😢 {data_2}", data="agla")
        ])
        await tgbot.edit_message(channel,
                                 event.original_update.msg_id,
                                 buttons=buton)
        await bot.send_message(
            -443785781,
            f"Tıklayan: {msg}, ❤️ e tıkladı.\n\nMesaja git: {message_link}")
        reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder."
        await event.answer(reply_pop_up_alert, cache_time=0, alert=True)
        # data_1 += 1

    if event.data.decode('utf-8') == "agla":
        data_2 += 1
        buton = tgbot.build_reply_markup([
            Button.inline(f"👍🏻 {data}", data="up"),
            Button.inline(f"❤️ {data_1}", data="kalp"),
            Button.inline(f"😢 {data_2}", data="agla")
        ])
        await tgbot.edit_message(channel,
                                 event.original_update.msg_id,
                                 buttons=buton)
        await bot.send_message(
            -443785781,
            f"Tıklayan: {msg}, 😢 e tıkladı.\n\nMesaja git: {message_link}")
        reply_pop_up_alert = "@RetroTurk Katılımınız İçin Teşekkür Eder."
        await event.answer(reply_pop_up_alert, cache_time=0, alert=True)
Пример #23
0
async def all_messages_catcher(event):
    channel = -1001477006210
    if channel:
        buton = tgbot.build_reply_markup([
            Button.inline(f"👍🏻 {data}", data="up"),
            Button.inline(f"❤️ {data_1}", data="kalp"),
            Button.inline(f"😢 {data_2}", data="agla")
        ])
        chat = await event.get_chat()
        admin = chat.admin_rights
        if admin:
            await tgbot.edit_message(channel, event.message.id, buttons=buton)
Пример #24
0
async def convert_image_to_sticker(event):
    """if sender is not None:
    Receive image then convert it to png format and resize into suitable size for telegram sticker
    """
    logger.debug("Request received")
    await get_sender_info(event)
    sender = await event.get_sender()
    f = 2 if sender.username == 'Pandaaaa906' else 1
    await event.reply(
        'Pick resize method:',
        buttons=[
            [Button.inline('Normal(Fast)', NORMAL)],
            [Button.inline('Seam Carving(Very Slow)', SEAM_CARVING)],
        ][:f])
Пример #25
0
async def welcome_trigger(event, strings):
    if event.user_joined is True or event.user_added is True:
        chat = event.chat_id
        chat = mongodb.chat_list.find_one({'chat_id': int(chat)})

        user_id = event.action_message.from_id
        bot_id = await bot.get_me()
        if bot_id.id == user_id:
            return  # Do not welcome yourselve
        chat_id = event.action_message.chat_id
        welcome = mongodb.welcomes.find_one({'chat_id': chat_id})
        cleaner = mongodb.clean_service.find_one({'chat_id': chat})
        if cleaner and cleaner['service'] is True:
            await event.delete()
        if not welcome:
            await event.reply(get_string("greetings", "welcome_hay", chat))
        elif welcome['enabled'] is False:
            return
        else:
            if hasattr(event.action_message.action, 'users'):
                from_id = event.action_message.action.users[0]
            else:
                from_id = event.action_message.from_id
            await send_note(event.chat_id,
                            chat_id,
                            event.action_message.id,
                            welcome['note'],
                            show_none=True,
                            from_id=from_id)
        welcome_security = mongodb.welcome_security.find_one(
            {'chat_id': chat_id})
        if welcome_security['security'] == 'soft':
            buttons = [[
                Button.inline(strings['clik2tlk_btn'],
                              'wlcm_{}_{}'.format(user_id, chat_id))
            ]]
            time_val = int(time.time() + 60 * 60)  # Mute 1 hour
            await mute_user(event, user_id, chat_id, time_val)
            text = strings['wlcm_sec'].format(mention=await user_link(user_id))
            await event.reply(text, buttons=buttons)
        elif welcome_security['security'] == 'hard':
            buttons = [[
                Button.inline(strings['clik2tlk_btn'],
                              'wlcm_{}_{}'.format(user_id, chat_id))
            ]]
            await mute_user(event, user_id, chat_id, None)
            text = strings['wlcm_sec'].format(mention=await user_link(user_id))
            await event.reply(text, buttons=buttons)
Пример #26
0
async def set_lang_callback(event):
    text, buttons = lang_info(event.chat_id, pm=True)
    buttons.append([Button.inline("Back", 'get_start')])
    try:
        await event.edit(text, buttons=buttons)
    except Exception:
        await event.reply(text, buttons=buttons)
Пример #27
0
    async def kick_user(delay, *, warn):
        with open(TARGET_FILE, 'w') as fd:
            fd.write('{}\n{}\n'.format(chosen.id, int(time.time() + delay)))

        if warn:
            event = await bot.send_message(
                GROUP,
                '<a href="tg://user?id={}">{}: you have 1 day to click this button or'
                ' you will be automatically kicked</a>'.format(
                    chosen.id, chosen.name),
                buttons=Button.inline('click me to stay', b'alive'),
                parse_mode='html')

        if chosen.id == self_id:
            await asyncio.sleep(random.randint(10, 20))
            await edit_save(event)
            async with bot.action(GROUP, 'typing'):
                await asyncio.sleep(random.randint(7, 10))
            await bot.send_message(GROUP, 'Oh darn! That was close 😅')

        try:
            await asyncio.wait_for(clicked.wait(), delay)
        except asyncio.TimeoutError:
            await bot.send_message(
                GROUP, f'<a href="tg://user?id={chosen.id}">{chosen.name} '
                f'was kicked for being inactive</a>',
                parse_mode='html')

            await bot.kick_participant(GROUP, chosen.id)
Пример #28
0
async def update_receiver(event):
    if event.raw_text.lower() == 'photos':
        ex = []
        for item in os.scandir():
            if '.jpeg' in item.name:
                ex.extend([[Button.inline(item.name,f'{event.sender_id}|1')]])
        await event.reply('ok',buttons = ex)
Пример #29
0
async def welcome_mute(event):
    if event.user_added or event.user_joined:
        try:
            user = await event.get_user()
        except TypeError:
            raise
            return

        participant = await bot(GetParticipantRequest(event.chat_id, user.id))
        if isinstance(participant.participant,
                      (ChannelParticipantAdmin, ChannelParticipantCreator)):
            return

        await bot(
            EditBannedRequest(
                event.input_chat, user.id,
                ChatBannedRights(until_date=None,
                                 view_messages=None,
                                 send_messages=True,
                                 send_media=True,
                                 send_stickers=True,
                                 send_gifs=True,
                                 send_games=True,
                                 send_inline=True,
                                 embed_links=True)))
        await bot.send_message(
            event.input_chat,
            "Hi {}! Please confirm you are not a bot !".format(
                user.username or user.first_name),
            buttons=[
                Button.inline("Click here to confirm",
                              bytes(str(user.id).encode('utf8')))
            ])
Пример #30
0
async def welcome_security_handler(message: Message, strings):
    if len(message.new_chat_members) > 1:
        # FIXME: Hitsuki doesnt support adding multiple users currently
        return

    new_user = message.new_chat_members[0]
    chat_id = message.chat.id
    user_id = new_user.id

    if user_id == BOT_ID:
        await message.reply(strings['thank_for_add'])
        await channel_log(
            f"I was added to the group <b>{html.escape(message.chat.title)}</b> (<code>{message.chat.id}</code>)",
            info_log=False)
        return

    db_item = await get_greetings_data(message.chat.id)
    if not db_item or 'welcome_security' not in db_item:
        return

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

    user = await message.chat.get_member(user_id)
    # Check if user was muted before
    if user['status'] == 'restricted':
        if user['can_send_messages'] is False:
            return

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

    # check if user added is a bot
    if new_user.is_bot and await is_user_admin(chat_id, message.from_user.id):
        return

    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'] = (None if 'clean_service' in db_item
                          and db_item['clean_service']['enabled'] is True else
                          message.message_id)

    kwargs['buttons'] = [] if not kwargs['buttons'] else kwargs['buttons']
    kwargs['buttons'] += [
        Button.inline(strings['click_here'], f'ws_{chat_id}_{user_id}')
    ]

    # FIXME: Better workaround
    if not (msg := await send_note(chat_id, text, **kwargs)):
        # Wasn't able to sent message
        return