Ejemplo n.º 1
0
async def pollcreator(lionpoll):
    reply_to_id = None
    if lionpoll.reply_to_msg_id:
        reply_to_id = lionpoll.reply_to_msg_id
    string = "".join(lionpoll.text.split(maxsplit=1)[1:])
    if not string:
        options = Build_Poll(["Yah sure 😊✌️", "Nah 😏😕", "Whatever die sur 🥱🙄"])
        try:
            await bot.send_message(
                lionpoll.chat_id,
                file=InputMediaPoll(
                    poll=Poll(
                        id=random.getrandbits(32),
                        question="👆👆So do you guys agree with this?",
                        answers=options,
                    )
                ),
                reply_to=reply_to_id,
            )
            await lionpoll.delete()
        except PollOptionInvalidError:
            await edit_or_reply(
                lionpoll, "`A poll option used invalid data (the data may be too long).`"
            )
        except ForbiddenError:
            await edit_or_reply(lionpoll, "`This chat has forbidden the polls`")
        except exception as e:
            await edit_or_reply(lionpoll, str(e))
    else:
        lioninput = string.split(";")
        if len(lioninput) > 2 and len(lioninput) < 12:
            options = Build_Poll(lioninput[1:])
            try:
                await bot.send_message(
                    lionpoll.chat_id,
                    file=InputMediaPoll(
                        poll=Poll(
                            id=random.getrandbits(32),
                            question=lioninput[0],
                            answers=options,
                        )
                    ),
                    reply_to=reply_to_id,
                )
                await lionpoll.delete()
            except PollOptionInvalidError:
                await edit_or_reply(
                    lionpoll,
                    "`A poll option used invalid data (the data may be too long).`",
                )
            except ForbiddenError:
                await edit_or_reply(lionpoll, "`This chat has forbidden the polls`")
            except Exception as e:
                await edit_or_reply(lionpoll, str(e))
        else:
            await edit_or_reply(
                lionpoll,
                "Make sure that you used Correct syntax `.poll question ; option1 ; option2`",
            )
Ejemplo n.º 2
0
async def pollcreator(icsspoll):
    reply_to_id = None
    if icsspoll.reply_to_msg_id:
        reply_to_id = icsspoll.reply_to_msg_id
    string = "".join(icsspoll.text.split(maxsplit=1)[1:])
    if not string:
        options = Build_Poll(["- ايي 😊✌️", "- لاع 😏😕", "- مادري 🥱🙄"])
        try:
            await bot.send_message(
                icsspoll.chat_id,
                file=InputMediaPoll(poll=Poll(
                    id=random.getrandbits(32),
                    question="تحبوني ؟",
                    answers=options,
                )),
                reply_to=reply_to_id,
            )
            await icsspoll.delete()
        except PollOptionInvalidError:
            await edit_or_reply(
                icsspoll,
                "⌔∮ الاستفتاء المستخدم غير صالح (قد تكون المعلومات طويلة جدا).",
            )
        except ForbiddenError:
            await edit_or_reply(icsspoll,
                                "⌔∮ هذه الدردشة تحظر استطلاعات الرأي. ")
        except exception as e:
            await edit_or_reply(icsspoll, str(e))
    else:
        icssinput = string.split("|")
        if len(icssinput) > 2 and len(icssinput) < 12:
            options = Build_Poll(icssinput[1:])
            try:
                await bot.send_message(
                    icsspoll.chat_id,
                    file=InputMediaPoll(poll=Poll(
                        id=random.getrandbits(32),
                        question=icssinput[0],
                        answers=options,
                    )),
                    reply_to=reply_to_id,
                )
                await icsspoll.delete()
            except PollOptionInvalidError:
                await edit_or_reply(
                    icsspoll,
                    "⌔∮ الاستفتاء المستخدم غير صالح (قد تكون المعلومات طويلة جدا).",
                )
            except ForbiddenError:
                await edit_or_reply(icsspoll,
                                    "⌔∮ هذه الدردشة تحظر استطلاعات الرأي. ")
            except Exception as e:
                await edit_or_reply(icsspoll, str(e))
        else:
            await edit_or_reply(
                icsspoll,
                "⌔∮ انت تكتب الامر بشكل خاطئ عليك كتابته بهذا الشكل `.استفتاء` السؤال ، الجواب الاول ، الجواب الثاني.",
            )
Ejemplo n.º 3
0
async def sugg(event):
    if await event.get_reply_message():
        msgid = (await event.get_reply_message()).id
        try:
            await ultroid.send_message(
                event.chat_id,
                file=InputMediaPoll(poll=Poll(
                    id=12345,
                    question="Do you agree to the replied suggestion?",
                    answers=[PollAnswer("Yes", b"1"),
                             PollAnswer("No", b"2")],
                ), ),
                reply_to=msgid,
            )
        except Exception as e:
            return await eod(
                event,
                f"`Oops, you can't send polls here!\n\n{str(e)}`",
                time=5,
            )
        await event.delete()
    else:
        return await eod(
            event,
            "`Please reply to a message to make a suggestion poll!`",
            time=5,
        )
Ejemplo n.º 4
0
async def sugg(event):
    sll = event.text.split(maxsplit=1)
    try:
        text = sll[1]
    except IndexError:
        text = None
    if not (event.is_reply or text):
        return await eod(
            event,
            "`Please reply to a message to make a suggestion poll!`",
        )
    if event.is_reply and not text:
        text = "Do you Agree to Replied Suggestion ?"
    reply_to = event.reply_to_msg_id if event.is_reply else event.id
    try:
        await event.client.send_file(
            event.chat_id,
            file=InputMediaPoll(poll=Poll(
                id=12345,
                question=text,
                answers=[PollAnswer("Yes", b"1"),
                         PollAnswer("No", b"2")],
            ), ),
            reply_to=reply_to,
        )
    except Exception as e:
        return await eod(event, f"`Oops, you can't send polls here!\n\n{e}`")
    await event.delete()
Ejemplo n.º 5
0
async def handler_new_message(event):
    """NewMessage event handler.
    """
    # skip if Album
    if hasattr(event, 'grouped_id') and event.grouped_id is not None:
        return
    try:
        logger.debug(f'New message from {event.chat_id}:\n{event.message}')
        targets = CHANNEL_MAPPING.get(event.chat_id)
        if targets is None or len(targets) < 1:
            logger.warning(
                f'NewMessage. No target channel for {event.chat_id}')
            return
        if REMOVE_URLS:
            event.message = remove_url_from_message(event.message)
        sent = 0
        for chat in targets:
            mirror_message = None
            if isinstance(event.message.media, MessageMediaPoll):
                mirror_message = await client.send_message(
                    chat, file=InputMediaPoll(poll=event.message.media.poll))
            else:
                mirror_message = await client.send_message(chat, event.message)

            sent += 1
            if sent > LIMIT_TO_WAIT:
                sent = 0
                time.sleep(TIMEOUT_MIRRORING)

    except Exception as e:
        logger.error(e, exc_info=True)
Ejemplo n.º 6
0
async def sugg(event):
    sll = event.text.split(" ", maxsplit=1)
    try:
        text = sll[1]
    except IndexError:
        text = None
    if event.is_reply:
        text = "Do you Agree to Replied Suggestion ?"
        cevent = await event.get_reply_message()
    elif text:
        cevent = event
    else:
        return await eod(
            event,
            "`Please reply to a message to make a suggestion poll!`",
        )
    try:
        await cevent.reply(file=InputMediaPoll(poll=Poll(
            id=12345,
            question=text,
            answers=[PollAnswer("Yes", b"1"),
                     PollAnswer("No", b"2")],
        ), ), )
    except Exception as e:
        return await eod(
            event,
            f"`Oops, you can't send polls here!\n\n{str(e)}`",
        )
    await event.delete()
 async def schedule_poll(self, channel_id, **kwargs):
     schedule_time = datetime.utcnow()
     year = kwargs.get('year', None)
     if year:
         schedule_time = schedule_time.replace(year=year)
     month = kwargs.get('month', None)
     if month:
         schedule_time = schedule_time.replace(month=month)
     day = kwargs.get('day', None)
     if day:
         schedule_time = schedule_time.replace(day=day)
     hour = kwargs.get('hour')
     if hour:
         schedule_time = schedule_time.replace(hour=hour)
     minute = kwargs.get('minute', None)
     if minute:
         schedule_time = schedule_time.replace(minute=minute)
     schedule_time = schedule_time - timedelta(hours=5, minutes=30)
     channel = await self.client.get_entity(int(channel_id))
     if isinstance(channel, Channel):
         return 302, "You should not schedule quiz in the channels.. Use groups instead!"
     subject = kwargs.get('subject', None)
     poll_question = kwargs.get('question')
     poll_answers = kwargs.get('answers')
     questionNumber = kwargs.get('questionNumber')
     answers = []
     for an in poll_answers:
         a = PollAnswer(an, str(poll_answers.index(an)).encode())
         answers.append(a)
     try:
         shuffle(answers)
         message = await self.client.send_message(
             channel,
             file=InputMediaPoll(poll=Poll(id=53453159,
                                           question=poll_question,
                                           answers=answers,
                                           quiz=True,
                                           public_voters=True),
                                 correct_answers=[b'0']),
             schedule=schedule_time)
         await self.dbUtils.createPoll(poll_question,
                                       poll_answers,
                                       message.poll,
                                       0,
                                       channel.title,
                                       channel.id,
                                       message.id,
                                       subject,
                                       questionNumber=questionNumber)
         return 0, 'Quiz scheduled successfully!'
     except errors.rpcerrorlist.PollAnswersInvalidError:
         return 1, 'Message scheduler failed!\nYou did not provide enough answers or you provided too many answers for the poll.'
     except errors.rpcerrorlist.ScheduleTooMuchError:
         return 2, "Schedule limit reached! \nYou cannot schedule more than 100 messages on telegram servers!"
     except errors.rpcerrorlist.PollOptionDuplicateError:
         return 3, 'A duplicate option was sent in the same poll.'
Ejemplo n.º 8
0
    async def newMessageHandler(msg):
        pollsList = polls
        for poll in pollsList:
            sent_msg = await client.send_message(user_chat_id, file=InputMediaPoll(poll=poll))
            sent_msg = Box(sent_msg.to_dict())
            chat_id = sent_msg.to_id.chat_id
            msg_id = sent_msg.id
            # print(f'{chat_id} : {msg_id}')
            answer = await getPollAnswer(chat_id, msg_id)
            print(f'{answer}')
            # TODO: Store Answer in database

        await client.send_message(user_chat_id, 'Thank you for the survey!')
        return
Ejemplo n.º 9
0
async def uri_poll(e):
    if not e.client._bot and e.is_private:
        return await eor(e, "`Use this in Group/Channel.`", time=15)
    match = e.pattern_match.group(1)
    if not match:
        return await eor(e, "`Give Proper Input...`", time=5)
    if ";" not in match:
        return await eor(e, "`Unable to Determine Options.`.", time=5)
    ques = match.split(";")[0]
    option = match.split(";")[1::]
    publ = None
    quizo = None
    karzo = None
    mpp = None
    if "|" in match:
        ptype = match.split(" | ")[1]
        option = match.split("|")[0].split(";")[1::]
        if "_" in ptype:
            karzo = [str(int(ptype.split("_")[1]) - 1).encode()]
            ptype = ptype.split("_")[0]
        if ptype not in ["public", "quiz", "multiple"]:
            return await eor(e, "`Invalid Poll Type...`", time=5)
        if ptype == "multiple":
            mpp = True
        elif ptype == "public":
            publ = True
        elif ptype == "quiz":
            quizo = True
    if len(option) <= 1:
        return await eor(e, "`Options Should be More than 1..`", time=5)
    m = await eor(e, get_string("com_1"))
    OUT = [
        PollAnswer(option[on],
                   str(on).encode()) for on in range(len(option))
    ]
    await e.client.send_file(
        e.chat_id,
        InputMediaPoll(
            Poll(20,
                 ques,
                 OUT,
                 multiple_choice=mpp,
                 public_voters=publ,
                 quiz=quizo),
            correct_answers=karzo,
        ),
    )
    await m.delete()
Ejemplo n.º 10
0
def _build_poll(question: str,
                *answers: str,
                closed: Optional[bool] = None,
                id: int = 0) -> InputMediaPoll:
    """Build a poll object.
    Message construction adapted from Pyrogram.
    https://github.com/pyrogram/pyrogram/blob/develop/pyrogram/client/methods/messages/send_poll.py
    https://github.com/pyrogram/pyrogram/blob/develop/pyrogram/client/methods/messages/stop_poll.py"""
    return InputMediaPoll(
        Poll(id=id,
             question=question,
             answers=[
                 PollAnswer(text=i, option=bytes([idx]))
                 for idx, i in enumerate(answers)
             ],
             closed=closed))
Ejemplo n.º 11
0
async def handler_new_message(event):
    try:
        logger.debug(f'New message:\n{event.message}')
        if REMOVE_URLS:
            event.message.message = remove_urls(event.message.message)
        mirror_id = None
        if (isinstance(event.message.media, MessageMediaPoll)):
            mirror_id = await client.send_message(
                TARGET_CHAT,
                file=InputMediaPoll(poll=event.message.media.poll))
        else:
            mirror_id = await client.send_message(TARGET_CHAT, event.message)
        database.insert({
            'original_id': event.message.id,
            'mirror_id': mirror_id.id,
            'original_channel': event.chat_id
        })
    except Exception as e:
        logger.error(e, exc_info=True)
Ejemplo n.º 12
0
async def uri_poll(e):
    match = e.pattern_match.group(1)
    if not match:
        return await eod(e, "`Give Proper Input...`")
    if ";" not in match:
        return await eod(e, "`Unable to Determine Options.`.")
    ques = match.split(";")[0]
    option = match.split(";")[1::]
    publ = None
    quizo = None
    karzo = None
    mpp = None
    if "|" in match:
        ptype = match.split(" | ")[1]
        option = match.split("|")[0].split(";")[1::]
        if "_" in ptype:
            karzo = [str(int(ptype.split("_")[1]) - 1).encode()]
            ptype = ptype.split("_")[0]
        if ptype not in ["public", "quiz", "multiple"]:
            return await eod(e, "`Invalid Poll Type...`")
        if ptype == "public":
            publ = True
        if ptype == "quiz":
            quizo = True
        if ptype == "multiple":
            mpp = True
    if len(option) <= 1:
        return await eod(e, "`Options Should be More than 1..`")
    m = await eor(e, "`Processing... `")
    OUT = []
    for on in range(len(option)):
        OUT.append(PollAnswer(option[on], str(on).encode()))
    await ultroid_bot.send_file(
        e.chat_id,
        InputMediaPoll(
            Poll(20, ques, OUT, multiple_choice=mpp, public_voters=publ, quiz=quizo),
            correct_answers=karzo,
        ),
    )
    await m.delete()
Ejemplo n.º 13
0
async def choose_cata(event):
    match = event.data_match.group(1).decode("utf-8")
    if not match:
        if TR_BTS.get("category"):
            buttons = TR_BTS["category"]
        else:
            req = (await async_searcher("https://opentdb.com/api_category.php",
                                        re_json=True))["trivia_categories"]
            btt = []
            for i in req:
                name = i["name"]
                if ":" in name:
                    name = name.split(":")[1]
                btt.append(Button.inline(name, f"trziad_{i['id']}"))
            buttons = list(zip(btt[::2], btt[1::2]))
            if len(btt) % 2 == 1:
                buttons.append((btt[-1], ))
            buttons.append([Button.inline("Cancel ❌", "delit")])
            TR_BTS.update({"category": buttons})
        text = get_string("games_2")
    elif match[0] == "d":
        cat = match[1:]
        buttons = [[Button.inline(i, f"trziac{cat}_{i}") for i in DIFI_KEYS]]
        buttons.append(get_back_button("trzia"))
        text = get_string("games_3")
    elif match[0] == "c":
        m = match[1:]
        buttons = [[
            Button.inline(str(i), f"trziat{m}_{i}") for i in range(10, 70, 20)
        ]]
        text = get_string("games_4")
    elif match[0] == "t":
        m_ = match[1:]
        buttons = [[
            Button.inline(str(i), f"trzias{m_}_{i}")
            for i in [10, 30, 60, 120]
        ]]
        text = get_string("games_5")
    elif match[0] == "s":
        chat = event.chat_id
        cat, le, nu, in_ = match[2:].split("_")
        msg = await event.edit(get_string("games_6").format(le, nu))
        for i in reversed(range(5)):
            msg = await msg.edit(buttons=Button.inline(f"{i} ⏰", f"ctdown{i}"))
            await asyncio.sleep(1)
        await msg.edit(msg.text + "\n\n• Send /cancel to stop the Quiz...",
                       buttons=None)
        qsss = await async_searcher(
            f"https://opentdb.com/api.php?amount={nu}&category={cat}&difficulty={le.lower()}",
            re_json=True,
        )
        qs = qsss["results"]
        if not qs:
            await event.respond(
                "Sorry, No Question Found for the given Criteria..")
            await event.delete()
            return
        TRIVIA_CHATS.update({chat: {}})
        for copper, q in enumerate(qs):
            if TRIVIA_CHATS[chat].get("cancel") is not None:
                break
            ansi = str(uuid.uuid1()).split("-")[0].encode()
            opts = [PollAnswer(unescape(q["correct_answer"]), ansi)]
            [
                opts.append(
                    PollAnswer(unescape(a),
                               str(uuid.uuid1()).split("-")[0].encode()))
                for a in q["incorrect_answers"]
            ]
            shuffle(opts)
            poll = InputMediaPoll(
                Poll(
                    0,
                    f"[{copper+1}].  " + unescape(q["question"]),
                    answers=opts,
                    public_voters=True,
                    quiz=True,
                    close_period=int(in_),
                ),
                correct_answers=[ansi],
                solution="Join @TheUltroid",
                solution_entities=[],
            )
            m_ = await event.client.send_message(chat, file=poll)
            POLLS.update(
                {m_.poll.poll.id: {
                    "chat": m_.chat_id,
                    "answer": ansi
                }})
            await asyncio.sleep(int(in_))
        if not TRIVIA_CHATS[chat]:
            await event.respond(
                "No-One Got Any Score in the Quiz!\nBetter Luck Next Time!")
        else:
            try:
                await event.respond(file=choice(CONGO_STICKER))
            except ChatSendStickersForbiddenError:
                pass
            LBD = "🎯 **Scoreboard of the Quiz.**\n\n"
            TRC = TRIVIA_CHATS[chat]
            if "cancel" in TRC.keys():
                del TRC["cancel"]
            for userid, user_score in dict(
                    sorted(TRC.items(),
                           key=operator.itemgetter(1),
                           reverse=True)).items():
                user = inline_mention(await event.client.get_entity(userid))
                LBD += f"••• {user} - {user_score}\n"
            await event.respond(LBD)
        del TRIVIA_CHATS[chat]
        list_ = list(POLLS.copy().keys())
        for key in list_:
            if POLLS[key]["chat"] == chat:
                del POLLS[key]
        return
    await event.edit(text, buttons=buttons)