Пример #1
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,
        )
Пример #2
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()
Пример #3
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()
Пример #4
0
def Build_Poll(options):
    i = 0
    poll = []
    for option in options:
        i = i + 1
        poll.append(PollAnswer(option, bytes(i)))
    return poll
 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.'
Пример #6
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()
Пример #7
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))
Пример #8
0
async def createPolls(survey_polls):
    finalPollsList = []
    for cpoll in survey_polls:
        cpoll = Box(cpoll)
        answers = []
        # print(cpoll)
        for ans in cpoll.answers:
            b_ans = ans.encode()
            answers.append(PollAnswer(ans, b_ans))
        poll = Poll(
            id=random.choice(range(10000000, 100000000000)),
            question=cpoll.question,
            answers=answers
            # public_voters=cpoll.properties.anon_voting,
            # multiple_choice=cpoll.properties.multiple_answers,
            # quiz=cpoll.properties.quiz_mode
        )
        finalPollsList.append(poll)
    return finalPollsList
Пример #9
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()
Пример #10
0
def Build_Poll(options):
    return [
        PollAnswer(option, bytes(i))
        for i, option in enumerate(options, start=1)
    ]
Пример #11
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)