【问题标题】:send a poll in telethon telegram bot在 Telethon 电报机器人中发送投票
【发布时间】:2020-04-16 22:31:36
【问题描述】:

如何发送投票?我正在尝试以下代码,但它没有返回错误,也没有发送投票:

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)

有没有更好的方法来通过 Telethon 提交投票?

【问题讨论】:

    标签: python telegram telegram-bot telethon


    【解决方案1】:

    要发送投票,您需要使用https://tl.telethon.dev/ 中的raw API types 构造投票媒体对象。

    在您的情况下,您需要一个发送示例,如示例所示发送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')]
        )
    ))
    

    【讨论】:

    • BadRequestError: RPCError 400: POLL_OPTION_INVALID(由 SendMediaRequest 引起)
    • 您发布的代码引发了该错误。看起来b'random_data_1' 无效。我已经编辑了答案以使其正常工作。
    猜你喜欢
    • 1970-01-01
    • 2016-03-11
    • 2017-03-19
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多