Skip to content

Commit 4a50a69

Browse files
author
Pietro Albini
committed
Add the Chat.members_count dynamic attribute
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
1 parent 7aef207 commit 4a50a69

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

botogram/objects/chats.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,20 @@ def creator(self):
165165

166166
return self._cache_creator
167167

168+
@property
169+
def members_count(self):
170+
"""Get the number of members of this chat"""
171+
# This isn't *really* needed, but avoids an HTTP request
172+
if self.type == "private":
173+
return 1
174+
175+
# Be sure to cache the number of members
176+
if not hasattr(self, "_cache_members_count"):
177+
self._cache_members_count = self._api.call("getChatMembersCount",
178+
{"chat_id": self.id},
179+
expect=int)
180+
return self._cache_members_count
181+
168182
def leave(self):
169183
"""Leave this chat"""
170184
if self.type not in ("group", "supergroup"):

docs/api/telegram.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,24 @@ about its business.
434434
435435
.. versionadded:: 0.3
436436

437+
.. py:attribute:: members_count
438+
439+
Return the number of members of this chat. This works across all the
440+
kinds of chat.
441+
442+
Please remember the content of this attribute is fetched from Telegram
443+
the first time you access it (so it might be slow), but it's cached right
444+
after, so the following accesses will involve no network communication.
445+
446+
.. code-block:: python
447+
448+
@bot.command("members")
449+
def members_command(chat, message, args):
450+
"""Get the number of members in this group"""
451+
chat.send(str(chat.members_count))
452+
453+
.. versionadded:: 0.3
454+
437455
.. py:method:: leave()
438456
439457
Kick the bot from this chat. This method is available only on groups and

docs/changelog.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ New features
4949
* Added new attribute :py:attr:`botogram.Sticker.emoji`
5050
* Added new attribute :py:attr:`botogram.Chat.admins`
5151
* Added new attribute :py:attr:`botogram.Chat.creator`
52+
* Added new attribute :py:attr:`botogram.Chat.members_count`
5253
* Added new method :py:meth:`botogram.Chat.leave`
5354
* Every method which sends something to a chat now returns the sent
5455
:py:class:`~botogram.Message`

0 commit comments

Comments
 (0)