Skip to content

Commit

Permalink
Add the Chat.members_count dynamic attribute
Browse files Browse the repository at this point in the history
This new attribute returns the number of members in a chat. This works
for all kinds of chats (private, groups/supergroups and channels).
This is possible thanks to a new API introduced in the Bot API 2.1
update.

Issue: GH-64
  • Loading branch information
Pietro Albini committed May 31, 2016
1 parent 7aef207 commit 4a50a69
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions botogram/objects/chats.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,20 @@ def creator(self):

return self._cache_creator

@property
def members_count(self):
"""Get the number of members of this chat"""
# This isn't *really* needed, but avoids an HTTP request
if self.type == "private":
return 1

# Be sure to cache the number of members
if not hasattr(self, "_cache_members_count"):
self._cache_members_count = self._api.call("getChatMembersCount",
{"chat_id": self.id},
expect=int)
return self._cache_members_count

def leave(self):
"""Leave this chat"""
if self.type not in ("group", "supergroup"):
Expand Down
18 changes: 18 additions & 0 deletions docs/api/telegram.rst
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,24 @@ about its business.
.. versionadded:: 0.3

.. py:attribute:: members_count
Return the number of members of this chat. This works across all the
kinds of chat.

Please remember the content of this attribute is fetched from Telegram
the first time you access it (so it might be slow), but it's cached right
after, so the following accesses will involve no network communication.

.. code-block:: python
@bot.command("members")
def members_command(chat, message, args):
"""Get the number of members in this group"""
chat.send(str(chat.members_count))
.. versionadded:: 0.3

.. py:method:: leave()
Kick the bot from this chat. This method is available only on groups and
Expand Down
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ New features
* Added new attribute :py:attr:`botogram.Sticker.emoji`
* Added new attribute :py:attr:`botogram.Chat.admins`
* Added new attribute :py:attr:`botogram.Chat.creator`
* Added new attribute :py:attr:`botogram.Chat.members_count`
* Added new method :py:meth:`botogram.Chat.leave`
* Every method which sends something to a chat now returns the sent
:py:class:`~botogram.Message`
Expand Down

0 comments on commit 4a50a69

Please sign in to comment.