在 telethon 电报机器人中发送投票

send a poll in telethon telegram bot

如何发送投票?我正在尝试以下代码,但它 returns 没有错误并且未发送轮询:

from typing import Optional
from telethon.sync import TelegramClient
from telethon.tl.types import *
from telethon.tl.functions.messages import *

def _build_poll(question: str, *answers: str, closed: Optional[bool] = None,
                id: int = 0) -> InputMediaPoll:
    """Build a poll object."""
    return InputMediaPoll(Poll(
        id=id, question=question, answers=[
            PollAnswer(text=i, option=bytes([idx]))
            for idx, i in enumerate(answers)
        ],
        closed=closed
    ))

poll = _build_poll(f"Question", "Answer 1", "Answer 2", "Answer 3")
message = client.send_message(-325188743, file=poll)

有什么更好的方法可以通过电视节目提交投票吗?

要发送民意调查,您需要使用 raw API types found in https://tl.telethon.dev/.

构造民意调查媒体对象

在您的情况下,您需要一个发送示例,如示例所示发送 InputMediaPoll

await client.send_message('@username',file=types.InputMediaPoll(
    poll=types.Poll(
        id=..., # type: long (random id)
        question=..., # type: string (the question)
        answers=... # type: list of PollAnswer (up to 10 answers)
    )
))

实际值:

from telethon.tl.types import InputMediaPoll, Poll, PollAnswer

await client.send_message("telethonofftopic",file=InputMediaPoll(
    poll=Poll(
        id=53453159,
        question="Is it 2020?",
        answers=[PollAnswer('Yes', b'1'), PollAnswer('No', b'2')]
    )
))

此函数在测验模式下创建投票,这意味着只有一个正确答案,函数获取以下参数:

group 是您要发送测验的组 ID 或频道 ID ()。为了获取组id/频道id,打开telegram web 并转到旧版本的telegram web 点击group/channel,在网页复制的url 例如在url -> "https://web.telegram.org/?legacy=1#/im?p=@IntiriorChannel" IntiriorChannel 部分, 如果是私人群组,请复制 url 中的号码,例如 https://web.telegram.org/?legacy=1#/im?p=s1504616337_1547258548617074964 id 为 1504616337。

answers 参数假定是可能答案的列表(您可以有 1 到 10 个答案),例如 [“10”、“20”、“30”、“40”、“50”]。

问题参数是你想在测验中被问到的问题

correct_answer 参数是答案列表中正确答案的索引+1,例如正确答案是“10”,那么 correct_answer 参数是 1,或者如果答案是“40” " 那么 correct_answer 参数就是 4。

from telethon.tl.types import Poll, PollAnswer, PollAnswerVoters,PollResults, MessageMediaPoll 
from telethon import TelegramClient 


client = TelegramClient("SessionBot", "api_id", "api_hash").start(bot_token="bot token")

async def build_quiz_poll(group: str, answers: list, question:str, correct_answer: int) -> None:
    """ Create poll in quiz mode """

    await client.send_message(group, file=MessageMediaPoll(
        poll=Poll(
            id=random.randint(0, 100_000),
            question=question,
            answers=[PollAnswer(text=option, option=bytes([i])) for i, option in
                     enumerate(answers, start=1)],
            quiz=True
        )
        results=PollResults(
            results=[PollAnswerVoters(option=bytes([correct_answer]), 
voters=200_000, correct=True)],
        )
    ))