Skip to content

Commit c9f7bfe

Browse files
author
Pietro Albini
committed
Add a new Chat.leave() method
This method allows the bot to kick itself out of a group, for example if the group members are spamming him with too much messages. Support for it was introduced in the Bot API 2.1 update.
1 parent 79a6142 commit c9f7bfe

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

botogram/objects/chats.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
Released under the MIT license
77
"""
88

9+
from .. import api
910
from .base import BaseObject, multiple
1011
from . import mixins
1112

@@ -104,6 +105,20 @@ def name(self):
104105

105106
return result
106107

108+
def leave(self):
109+
"""Leave this chat"""
110+
if self.type not in ("group", "supergroup"):
111+
raise TypeError("This method can only be called in groups and "
112+
"supergroups")
113+
114+
try:
115+
self._api.call("leaveChat", {"chat_id": self.id})
116+
except api.APIError as e:
117+
if e.error_code == 403 and "not a member" in e.description:
118+
exc = RuntimeError("The bot isn't a member of this group")
119+
raise exc from None
120+
raise
121+
107122

108123
class UserProfilePhotos(BaseObject):
109124
"""Telegram API representation of an user's profile photos

docs/api/telegram.rst

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,25 @@ about its business.
370370

371371
.. versionadded:: 0.2
372372

373+
.. py:method:: leave()
374+
375+
Kick the bot from this chat. This method is available only on groups and
376+
supergroups, and the bot must be a member of the chat.
377+
378+
This method might be handy if the other members of the group are abusing
379+
your bot, or spamming it with too much messages. Keep in mind though, an
380+
admin of the chat can re-add your bot at any time, so if you want to
381+
forget about it you need to store the chat ID somewhere and leave the
382+
group as soon as your bot joins it.
383+
384+
.. code-block:: python
385+
386+
@bot.command("bye")
387+
def bye_command(chat):
388+
chat.leave()
389+
390+
.. versionadded:: 0.3
391+
373392
.. py:method:: send(message, [preview=True, reply_to=None, syntax=None, extra=None, notify=True])
374393
375394
Send the textual *message* to the chat. You may optionally stop clients

docs/changelog.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ New features
4747

4848
* Added new attribute :py:attr:`botogram.Message.pinned_message`
4949
* Added new attribute :py:attr:`botogram.Sticker.emoji`
50+
* Added new method :py:meth:`botogram.Chat.leave`
5051
* Every method which sends something to a chat now returns the sent
5152
:py:class:`~botogram.Message`
5253
* Multiple instances of the same bot are now properly handled (as errors)

0 commit comments

Comments
 (0)