2
0
mirror of https://github.com/pyrogram/pyrogram synced 2025-08-29 21:38:04 +00:00

Refactor Poll types and methods to reflect Bot API 4.2 docs

This commit is contained in:
Dan 2019-04-14 20:17:42 +02:00
parent 605b5f1b0f
commit 4661fb035b
8 changed files with 74 additions and 66 deletions

View File

@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from .close_poll import ClosePoll from .stop_poll import StopPoll
from .delete_messages import DeleteMessages from .delete_messages import DeleteMessages
from .download_media import DownloadMedia from .download_media import DownloadMedia
from .edit_message_caption import EditMessageCaption from .edit_message_caption import EditMessageCaption
@ -72,7 +72,7 @@ class Messages(
SendVoice, SendVoice,
SendPoll, SendPoll,
VotePoll, VotePoll,
ClosePoll, StopPoll,
RetractVote, RetractVote,
DownloadMedia, DownloadMedia,
IterHistory, IterHistory,

View File

@ -18,6 +18,7 @@
from typing import Union from typing import Union
import pyrogram
from pyrogram.api import functions from pyrogram.api import functions
from pyrogram.client.ext import BaseClient from pyrogram.client.ext import BaseClient
@ -26,8 +27,8 @@ class RetractVote(BaseClient):
def retract_vote( def retract_vote(
self, self,
chat_id: Union[int, str], chat_id: Union[int, str],
message_id: id message_id: int
) -> bool: ) -> "pyrogram.Poll":
"""Use this method to retract your vote in a poll. """Use this method to retract your vote in a poll.
Args: Args:
@ -37,15 +38,15 @@ class RetractVote(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str). For a contact that exists in your Telegram address book you can use his phone number (str).
message_id (``int``): message_id (``int``):
Unique poll message identifier inside this chat. Identifier of the original message with the poll.
Returns: Returns:
On success, True is returned. On success, the :obj:`Poll <pyrogram.Poll>` with the retracted vote is returned.
Raises: Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error. :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
""" """
self.send( r = self.send(
functions.messages.SendVote( functions.messages.SendVote(
peer=self.resolve_peer(chat_id), peer=self.resolve_peer(chat_id),
msg_id=message_id, msg_id=message_id,
@ -53,4 +54,4 @@ class RetractVote(BaseClient):
) )
) )
return True return pyrogram.Poll._parse(self, r.updates[0])

View File

@ -47,10 +47,10 @@ class SendPoll(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str). For a contact that exists in your Telegram address book you can use his phone number (str).
question (``str``): question (``str``):
The poll question, as string. Poll question, 1-255 characters.
options (List of ``str``): options (List of ``str``):
The poll options, as list of strings (2 to 10 options are allowed). List of answer options, 2-10 strings 1-100 characters each.
disable_notification (``bool``, *optional*): disable_notification (``bool``, *optional*):
Sends the message silently. Sends the message silently.

View File

@ -18,19 +18,21 @@
from typing import Union from typing import Union
import pyrogram
from pyrogram.api import functions, types from pyrogram.api import functions, types
from pyrogram.client.ext import BaseClient from pyrogram.client.ext import BaseClient
class ClosePoll(BaseClient): class StopPoll(BaseClient):
def close_poll( def stop_poll(
self, self,
chat_id: Union[int, str], chat_id: Union[int, str],
message_id: id message_id: int,
) -> bool: reply_markup: "pyrogram.InlineKeyboardMarkup" = None
"""Use this method to close (stop) a poll. ) -> "pyrogram.Poll":
"""Use this method to stop a poll which was sent by you.
Closed polls can't be reopened and nobody will be able to vote in it anymore. Stopped polls can't be reopened and nobody will be able to vote in it anymore.
Args: Args:
chat_id (``int`` | ``str``): chat_id (``int`` | ``str``):
@ -39,17 +41,20 @@ class ClosePoll(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str). For a contact that exists in your Telegram address book you can use his phone number (str).
message_id (``int``): message_id (``int``):
Unique poll message identifier inside this chat. Identifier of the original message with the poll.
reply_markup (:obj:`InlineKeyboardMarkup`, *optional*):
An InlineKeyboardMarkup object.
Returns: Returns:
On success, True is returned. On success, the stopped :obj:`Poll <pyrogram.Poll>` with the final results is returned.
Raises: Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error. :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
""" """
poll = self.get_messages(chat_id, message_id).poll poll = self.get_messages(chat_id, message_id).poll
self.send( r = self.send(
functions.messages.EditMessage( functions.messages.EditMessage(
peer=self.resolve_peer(chat_id), peer=self.resolve_peer(chat_id),
id=message_id, id=message_id,
@ -60,8 +65,9 @@ class ClosePoll(BaseClient):
question="", question="",
answers=[] answers=[]
) )
) ),
reply_markup=reply_markup.write() if reply_markup else None
) )
) )
return True return pyrogram.Poll._parse(self, r.updates[0])

View File

@ -18,6 +18,7 @@
from typing import Union from typing import Union
import pyrogram
from pyrogram.api import functions from pyrogram.api import functions
from pyrogram.client.ext import BaseClient from pyrogram.client.ext import BaseClient
@ -28,7 +29,7 @@ class VotePoll(BaseClient):
chat_id: Union[int, str], chat_id: Union[int, str],
message_id: id, message_id: id,
option: int option: int
) -> bool: ) -> "pyrogram.Poll":
"""Use this method to vote a poll. """Use this method to vote a poll.
Args: Args:
@ -38,25 +39,26 @@ class VotePoll(BaseClient):
For a contact that exists in your Telegram address book you can use his phone number (str). For a contact that exists in your Telegram address book you can use his phone number (str).
message_id (``int``): message_id (``int``):
Unique poll message identifier inside this chat. Identifier of the original message with the poll.
option (``int``): option (``int``):
Index of the poll option you want to vote for (0 to 9). Index of the poll option you want to vote for (0 to 9).
Returns: Returns:
On success, True is returned. On success, the :obj:`Poll <pyrogram.Poll>` with the chosen option is returned.
Raises: Raises:
:class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error. :class:`RPCError <pyrogram.RPCError>` in case of a Telegram RPC error.
""" """
poll = self.get_messages(chat_id, message_id).poll poll = self.get_messages(chat_id, message_id).poll
self.send( r = self.send(
functions.messages.SendVote( functions.messages.SendVote(
peer=self.resolve_peer(chat_id), peer=self.resolve_peer(chat_id),
msg_id=message_id, msg_id=message_id,
options=[poll.options[option].data] options=[poll.options[option]._data]
) )
) )
return True return pyrogram.Poll._parse(self, r.updates[0])

View File

@ -29,78 +29,80 @@ class Poll(PyrogramType):
Args: Args:
id (``int``): id (``int``):
The poll id in this chat. Unique poll identifier.
closed (``bool``):
Whether the poll is closed or not.
question (``str``): question (``str``):
Poll question. Poll question, 1-255 characters.
options (List of :obj:`PollOption`): options (List of :obj:`PollOption`):
The available poll options. List of poll options.
is_closed (``bool``):
True, if the poll is closed.
total_voters (``int``): total_voters (``int``):
Total amount of voters for this poll. Total count of voters for this poll.
option_chosen (``int``, *optional*): chosen_option (``int``, *optional*):
The index of your chosen option (in case you voted already), None otherwise. Index of your chosen option (0-9), None in case you haven't voted yet.
""" """
__slots__ = ["id", "closed", "question", "options", "total_voters", "option_chosen"] __slots__ = ["id", "question", "options", "is_closed", "total_voters", "chosen_option"]
def __init__( def __init__(
self, self,
*, *,
client: "pyrogram.client.ext.BaseClient", client: "pyrogram.client.ext.BaseClient",
id: int, id: int,
closed: bool,
question: str, question: str,
options: List[PollOption], options: List[PollOption],
is_closed: bool,
total_voters: int, total_voters: int,
option_chosen: int = None chosen_option: int = None
): ):
super().__init__(client) super().__init__(client)
self.id = id self.id = id
self.closed = closed
self.question = question self.question = question
self.options = options self.options = options
self.is_closed = is_closed
self.total_voters = total_voters self.total_voters = total_voters
self.option_chosen = option_chosen self.chosen_option = chosen_option
@staticmethod @staticmethod
def _parse(client, media_poll: types.MessageMediaPoll) -> "Poll": def _parse(client, media_poll: types.MessageMediaPoll) -> "Poll":
poll = media_poll.poll poll = media_poll.poll
results = media_poll.results.results results = media_poll.results.results
total_voters = media_poll.results.total_voters total_voters = media_poll.results.total_voters
option_chosen = None chosen_option = None
options = [] options = []
for i, answer in enumerate(poll.answers): for i, answer in enumerate(poll.answers):
voters = 0 voter_count = 0
if results: if results:
result = results[i] result = results[i]
voters = result.voters voter_count = result.voters
if result.chosen: if result.chosen:
option_chosen = i chosen_option = i
options.append(PollOption( options.append(
text=answer.text, PollOption(
voters=voters, text=answer.text,
data=answer.option, voter_count=voter_count,
client=client data=answer.option,
)) client=client
)
)
return Poll( return Poll(
id=poll.id, id=poll.id,
closed=poll.closed,
question=poll.question, question=poll.question,
options=options, options=options,
is_closed=poll.closed,
total_voters=total_voters, total_voters=total_voters,
option_chosen=option_chosen, chosen_option=chosen_option,
client=client client=client
) )

View File

@ -21,32 +21,29 @@ from ..pyrogram_type import PyrogramType
class PollOption(PyrogramType): class PollOption(PyrogramType):
"""This object represents a Poll Option. """This object contains information about one answer option in a poll.
Args: Args:
text (``str``): text (``str``):
Text of the poll option. Option text, 1-100 characters.
voters (``int``): voter_count (``int``):
The number of users who voted this option. Number of users that voted for this option.
It will be 0 until you vote for the poll. Equals to 0 until you vote.
data (``bytes``):
Unique data that identifies this option among all the other options in a poll.
""" """
__slots__ = ["text", "voters", "data"] __slots__ = ["text", "voter_count", "_data"]
def __init__( def __init__(
self, self,
*, *,
client: "pyrogram.client.ext.BaseClient", client: "pyrogram.client.ext.BaseClient",
text: str, text: str,
voters: int, voter_count: int,
data: bytes data: bytes
): ):
super().__init__(client) super().__init__(client)
self.text = text self.text = text
self.voters = voters self.voter_count = voter_count
self.data = data self._data = data # Hidden

View File

@ -51,7 +51,7 @@ def default(o: PyrogramType):
return remove_none( return remove_none(
OrderedDict( OrderedDict(
[("_", "pyrogram." + o.__class__.__name__)] [("_", "pyrogram." + o.__class__.__name__)]
+ [i for i in content.items()] + [i for i in content.items() if not i[0].startswith("_")]
) )
) )
except AttributeError: except AttributeError: