Skip to content

Commit

Permalink
Merge pull request eternnoir#1353 from coder2020official/master
Browse files Browse the repository at this point in the history
Bot API 5.4 features
  • Loading branch information
Badiboy authored Nov 6, 2021
2 parents 2623fa3 + bf96f13 commit 695c699
Show file tree
Hide file tree
Showing 10 changed files with 188 additions and 35 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
* [Poll Answer Handler](#poll-answer-handler)
* [My Chat Member Handler](#my-chat-member-handler)
* [Chat Member Handler](#chat-member-handler)
* [Chat Join request handler](#chat-join-request-handler)
* [Inline Mode](#inline-mode)
* [Inline handler](#inline-handler)
* [Chosen Inline handler](#chosen-inline-handler)
Expand Down Expand Up @@ -272,6 +273,10 @@ Handle updates of a chat member's status in a chat
`@bot.chat_member_handler() # <- passes a ChatMemberUpdated type object to your function`
*Note: "chat_member" updates are not requested by default. If you want to allow all update types, set `allowed_updates` in `bot.polling()` / `bot.infinity_polling()` to `util.update_types`*

#### Chat Join Request Handler
Handle chat join requests using:
`@bot.chat_join_request_handler() # <- passes ChatInviteLink type object to your function`

### Inline Mode

More information about [Inline mode](https://core.telegram.org/bots/inline).
Expand Down
11 changes: 11 additions & 0 deletions examples/chat_join_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import telebot


bot = telebot.TeleBot('TOKEN')

@bot.chat_join_request_handler()
def make_some(message: telebot.types.ChatJoinRequest):
bot.send_message(message.chat.id, 'I accepted a new user!')
bot.approve_chat_join_request(message.chat.id, message.from_user.id)

bot.infinity_polling(allowed_updates=telebot.util.update_types)
30 changes: 18 additions & 12 deletions examples/custom_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,19 @@
bot = telebot.TeleBot("")


class MyStates:
name = 1
surname = 2
age = 3



@bot.message_handler(commands=['start'])
def start_ex(message):
"""
Start command. Here we are starting state
"""
bot.set_state(message.chat.id, 1)
bot.set_state(message.from_user.id, MyStates.name)
bot.send_message(message.chat.id, 'Hi, write me a name')


Expand All @@ -22,38 +28,38 @@ def any_state(message):
Cancel state
"""
bot.send_message(message.chat.id, "Your state was cancelled.")
bot.delete_state(message.chat.id)
bot.delete_state(message.from_user.id)

@bot.message_handler(state=1)
@bot.message_handler(state=MyStates.name)
def name_get(message):
"""
State 1. Will process when user's state is 1.
"""
bot.send_message(message.chat.id, f'Now write me a surname')
bot.set_state(message.chat.id, 2)
with bot.retrieve_data(message.chat.id) as data:
bot.set_state(message.from_user.id, MyStates.surname)
with bot.retrieve_data(message.from_user.id) as data:
data['name'] = message.text


@bot.message_handler(state=2)
@bot.message_handler(state=MyStates.surname)
def ask_age(message):
"""
State 2. Will process when user's state is 2.
"""
bot.send_message(message.chat.id, "What is your age?")
bot.set_state(message.chat.id, 3)
with bot.retrieve_data(message.chat.id) as data:
bot.set_state(message.from_user.id, MyStates.age)
with bot.retrieve_data(message.from_user.id) as data:
data['surname'] = message.text

# result
@bot.message_handler(state=3, is_digit=True)
@bot.message_handler(state=MyStates.age, is_digit=True)
def ready_for_answer(message):
with bot.retrieve_data(message.chat.id) as data:
with bot.retrieve_data(message.from_user.id) as data:
bot.send_message(message.chat.id, "Ready, take a look:\n<b>Name: {name}\nSurname: {surname}\nAge: {age}</b>".format(name=data['name'], surname=data['surname'], age=message.text), parse_mode="html")
bot.delete_state(message.chat.id)
bot.delete_state(message.from_user.id)

#incorrect number
@bot.message_handler(state=3, is_digit=False)
@bot.message_handler(state=MyStates.age, is_digit=False)
def age_incorrect(message):
bot.send_message(message.chat.id, 'Looks like you are submitting a string in the field age. Please enter a number')

Expand Down
89 changes: 82 additions & 7 deletions telebot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ def __init__(
self.poll_answer_handlers = []
self.my_chat_member_handlers = []
self.chat_member_handlers = []
self.chat_join_request_handlers = []
self.custom_filters = {}
self.state_handlers = []

Expand All @@ -205,7 +206,8 @@ def __init__(
'poll': [],
'poll_answer': [],
'my_chat_member': [],
'chat_member': []
'chat_member': [],
'chat_join_request': []
}
self.default_middleware_handlers = []

Expand Down Expand Up @@ -426,6 +428,7 @@ def process_new_updates(self, updates):
new_poll_answers = None
new_my_chat_members = None
new_chat_members = None
chat_join_request = None

for update in updates:
if apihelper.ENABLE_MIDDLEWARE:
Expand Down Expand Up @@ -480,6 +483,9 @@ def process_new_updates(self, updates):
if update.chat_member:
if new_chat_members is None: new_chat_members = []
new_chat_members.append(update.chat_member)
if update.chat_join_request:
if chat_join_request is None: chat_join_request = []
chat_join_request.append(update.chat_join_request)

if new_messages:
self.process_new_messages(new_messages)
Expand Down Expand Up @@ -507,6 +513,9 @@ def process_new_updates(self, updates):
self.process_new_my_chat_member(new_my_chat_members)
if new_chat_members:
self.process_new_chat_member(new_chat_members)
if chat_join_request:
self.process_new_chat_join_request(chat_join_request)


def process_new_messages(self, new_messages):
self._notify_next_handlers(new_messages)
Expand Down Expand Up @@ -550,6 +559,9 @@ def process_new_my_chat_member(self, my_chat_members):
def process_new_chat_member(self, chat_members):
self._notify_command_handlers(self.chat_member_handlers, chat_members)

def process_new_chat_join_request(self, chat_join_request):
self._notify_command_handlers(self.chat_join_request_handlers, chat_join_request)

def process_middlewares(self, update):
for update_type, middlewares in self.typed_middleware_handlers.items():
if getattr(update, update_type) is not None:
Expand Down Expand Up @@ -1667,9 +1679,11 @@ def set_chat_permissions(
return apihelper.set_chat_permissions(self.token, chat_id, permissions)

def create_chat_invite_link(
self, chat_id: Union[int, str],
self, chat_id: Union[int, str],
name: Optional[str]=None,
expire_date: Optional[Union[int, datetime]]=None,
member_limit: Optional[int]=None) -> types.ChatInviteLink:
member_limit: Optional[int]=None,
creates_join_request: Optional[bool]=None) -> types.ChatInviteLink:
"""
Use this method to create an additional invite link for a chat.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Expand All @@ -1681,13 +1695,15 @@ def create_chat_invite_link(
:return:
"""
return types.ChatInviteLink.de_json(
apihelper.create_chat_invite_link(self.token, chat_id, expire_date, member_limit)
apihelper.create_chat_invite_link(self.token, chat_id, name, expire_date, member_limit, creates_join_request)
)

def edit_chat_invite_link(
self, chat_id: Union[int, str], invite_link: str,
self, chat_id: Union[int, str], name: Optional[str]=None,
invite_link: Optional[str] = None,
expire_date: Optional[Union[int, datetime]]=None,
member_limit: Optional[int]=None) -> types.ChatInviteLink:
member_limit: Optional[int]=None ,
creates_join_request: Optional[bool]=None) -> types.ChatInviteLink:
"""
Use this method to edit a non-primary invite link created by the bot.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Expand All @@ -1701,7 +1717,7 @@ def edit_chat_invite_link(
:return:
"""
return types.ChatInviteLink.de_json(
apihelper.edit_chat_invite_link(self.token, chat_id, invite_link, expire_date, member_limit)
apihelper.edit_chat_invite_link(self.token, chat_id, name, invite_link, expire_date, member_limit, creates_join_request)
)

def revoke_chat_invite_link(
Expand Down Expand Up @@ -1731,6 +1747,32 @@ def export_chat_invite_link(self, chat_id: Union[int, str]) -> str:
"""
return apihelper.export_chat_invite_link(self.token, chat_id)

def approve_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool:
"""
Use this method to approve a chat join request.
The bot must be an administrator in the chat for this to work and must have
the can_invite_users administrator right. Returns True on success.
:param chat_id: Unique identifier for the target chat or username of the target supergroup
(in the format @supergroupusername)
:param user_id: Unique identifier of the target user
:return: True on success.
"""
return apihelper.approve_chat_join_request(self.token, chat_id, user_id)

def decline_chat_join_request(self, chat_id: Union[str, int], user_id: Union[int, str]) -> bool:
"""
Use this method to decline a chat join request.
The bot must be an administrator in the chat for this to work and must have
the can_invite_users administrator right. Returns True on success.
:param chat_id: Unique identifier for the target chat or username of the target supergroup
(in the format @supergroupusername)
:param user_id: Unique identifier of the target user
:return: True on success.
"""
return apihelper.decline_chat_join_request(self.token, chat_id, user_id)

def set_chat_photo(self, chat_id: Union[int, str], photo: Any) -> bool:
"""
Use this method to set a new profile photo for the chat. Photos can't be changed for private chats.
Expand Down Expand Up @@ -3148,6 +3190,39 @@ def register_chat_member_handler(self, callback, func=None, **kwargs):
handler_dict = self._build_handler_dict(callback, func=func, **kwargs)
self.add_chat_member_handler(handler_dict)

def chat_join_request_handler(self, func=None, **kwargs):
"""
chat_join_request handler
:param func:
:param kwargs:
:return:
"""

def decorator(handler):
handler_dict = self._build_handler_dict(handler, func=func, **kwargs)
self.add_chat_join_request_handler(handler_dict)
return handler

return decorator

def add_chat_join_request_handler(self, handler_dict):
"""
Adds a chat_join_request handler
:param handler_dict:
:return:
"""
self.chat_join_request_handlers.append(handler_dict)

def register_chat_join_request_handler(self, callback, func=None, **kwargs):
"""
Registers chat join request handler.
:param callback: function to be called
:param func:
:return: decorated function
"""
handler_dict = self._build_handler_dict(callback, func=func, **kwargs)
self.add_chat_join_request_handler(handler_dict)

def _test_message_handler(self, message_handler, message):
"""
Test message handler
Expand Down
27 changes: 24 additions & 3 deletions telebot/apihelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,7 @@ def set_chat_permissions(token, chat_id, permissions):
return _make_request(token, method_url, params=payload, method='post')


def create_chat_invite_link(token, chat_id, expire_date, member_limit):
def create_chat_invite_link(token, chat_id, name, expire_date, member_limit, creates_join_request):
method_url = 'createChatInviteLink'
payload = {
'chat_id': chat_id
Expand All @@ -986,11 +986,15 @@ def create_chat_invite_link(token, chat_id, expire_date, member_limit):
payload['expire_date'] = expire_date
if member_limit:
payload['member_limit'] = member_limit
if creates_join_request is not None:
payload['creates_join_request'] = creates_join_request
if name:
payload['name'] = name

return _make_request(token, method_url, params=payload, method='post')


def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit):
def edit_chat_invite_link(token, chat_id, invite_link, name, expire_date, member_limit, creates_join_request):
method_url = 'editChatInviteLink'
payload = {
'chat_id': chat_id,
Expand All @@ -1005,6 +1009,10 @@ def edit_chat_invite_link(token, chat_id, invite_link, expire_date, member_limit

if member_limit is not None:
payload['member_limit'] = member_limit
if name:
payload['name'] = name
if creates_join_request:
payload['creates_join_request'] = creates_join_request

return _make_request(token, method_url, params=payload, method='post')

Expand All @@ -1023,7 +1031,20 @@ def export_chat_invite_link(token, chat_id):
payload = {'chat_id': chat_id}
return _make_request(token, method_url, params=payload, method='post')


def approve_chat_join_request(token, chat_id, user_id):
method_url = 'approveChatJoinRequest'
payload = {
'chat_id': chat_id,
'user_id': user_id
}
return _make_request(token, method_url, params=payload, method='post')
def decline_chat_join_request(token, chat_id, user_id):
method_url = 'declineChatJoinRequest'
payload = {
'chat_id': chat_id,
'user_id': user_id
}
return _make_request(token, method_url, params=payload, method='post')
def set_chat_photo(token, chat_id, photo):
method_url = 'setChatPhoto'
payload = {'chat_id': chat_id}
Expand Down
Loading

0 comments on commit 695c699

Please sign in to comment.