Skip to content

Commit

Permalink
Merge pull request #1409 from Badiboy/master
Browse files Browse the repository at this point in the history
Bugfix in send_data
  • Loading branch information
Badiboy authored Jan 10, 2022
2 parents ae2dbd0 + 9140044 commit 9050f4a
Show file tree
Hide file tree
Showing 9 changed files with 106 additions and 82 deletions.
17 changes: 11 additions & 6 deletions telebot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def enable_saving_states(self, filename="./.state-save/states.pkl"):
"""

self.current_states = StateFile(filename=filename)
self.current_states._create_dir()
self.current_states.create_dir()

def enable_save_reply_handlers(self, delay=120, filename="./.handler-saves/reply.save"):
"""
Expand Down Expand Up @@ -1221,11 +1221,13 @@ def send_document(
reply_to_message_id = reply_to_message_id, reply_markup = reply_markup, parse_mode = parse_mode,
disable_notification = disable_notification, timeout = timeout, caption = caption, thumb = thumb,
caption_entities = caption_entities, allow_sending_without_reply = allow_sending_without_reply,
disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name, protect_content = protect_content))
disable_content_type_detection = disable_content_type_detection, visible_file_name = visible_file_name,
protect_content = protect_content))

# TODO: Rewrite this method like in API.
def send_sticker(
self, chat_id: Union[int, str], sticker: Union[Any, str],
self, chat_id: Union[int, str],
sticker: Union[Any, str],
reply_to_message_id: Optional[int]=None,
reply_markup: Optional[REPLY_MARKUP_TYPES]=None,
disable_notification: Optional[bool]=None,
Expand All @@ -1236,6 +1238,7 @@ def send_sticker(
"""
Use this method to send .webp stickers.
:param chat_id:
:param sticker:
:param data:
:param reply_to_message_id:
:param reply_markup:
Expand All @@ -1254,7 +1257,8 @@ def send_sticker(
self.token, chat_id, sticker, 'sticker',
reply_to_message_id=reply_to_message_id, reply_markup=reply_markup,
disable_notification=disable_notification, timeout=timeout,
allow_sending_without_reply=allow_sending_without_reply, protect_content=protect_content))
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content))

def send_video(
self, chat_id: Union[int, str], video: Union[Any, str],
Expand Down Expand Up @@ -1330,6 +1334,7 @@ def send_animation(
:param thumb: InputFile or String : Thumbnail of the file sent
:param caption: String : Animation caption (may also be used when resending animation by file_id).
:param parse_mode:
:param protect_content:
:param reply_to_message_id:
:param reply_markup:
:param disable_notification:
Expand Down Expand Up @@ -1924,7 +1929,7 @@ def set_my_commands(self, commands: List[types.BotCommand],
return apihelper.set_my_commands(self.token, commands, scope, language_code)

def delete_my_commands(self, scope: Optional[types.BotCommandScope]=None,
language_code: Optional[int]=None) -> bool:
language_code: Optional[str]=None) -> bool:
"""
Use this method to delete the list of the bot's commands for the given scope and user language.
After deletion, higher level commands will be shown to affected users.
Expand Down Expand Up @@ -2559,7 +2564,7 @@ def add_data(self, chat_id: int, **kwargs):
:param chat_id:
"""
for key, value in kwargs.items():
self.current_states._add_data(chat_id, key, value)
self.current_states.add_data(chat_id, key, value)

def register_next_step_handler_by_chat_id(
self, chat_id: Union[int, str], callback: Callable, *args, **kwargs) -> None:
Expand Down
8 changes: 7 additions & 1 deletion telebot/apihelper.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def _make_request(token, method_name, method='get', params=None, files=None):
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
elif CUSTOM_REQUEST_SENDER:
# noinspection PyCallingNonCallable
result = CUSTOM_REQUEST_SENDER(
method, request_url, params=params, files=files,
timeout=(connect_timeout, read_timeout), proxies=proxy)
Expand Down Expand Up @@ -246,6 +247,7 @@ def send_message(
:param timeout:
:param entities:
:param allow_sending_without_reply:
:param protect_content:
:return:
"""
method_url = r'sendMessage'
Expand Down Expand Up @@ -861,7 +863,8 @@ def send_audio(token, chat_id, audio, caption=None, duration=None, performer=Non

def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_markup=None, parse_mode=None,
disable_notification=None, timeout=None, caption=None, thumb=None, caption_entities=None,
allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None):
allow_sending_without_reply=None, disable_content_type_detection=None, visible_file_name=None,
protect_content = None):
method_url = get_method_by_type(data_type)
payload = {'chat_id': chat_id}
files = None
Expand Down Expand Up @@ -896,6 +899,8 @@ def send_data(token, chat_id, data, data_type, reply_to_message_id=None, reply_m
payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities))
if allow_sending_without_reply is not None:
payload['allow_sending_without_reply'] = allow_sending_without_reply
if protect_content is not None:
payload['protect_content'] = protect_content
if method_url == 'sendDocument' and disable_content_type_detection is not None:
payload['disable_content_type_detection'] = disable_content_type_detection
return _make_request(token, method_url, params=payload, files=files, method='post')
Expand Down Expand Up @@ -1382,6 +1387,7 @@ def send_invoice(
:param max_tip_amount: The maximum accepted amount for tips in the smallest units of the currency
:param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the smallest units of the currency.
At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount.
:param protect_content:
:return:
"""
method_url = r'sendInvoice'
Expand Down
13 changes: 9 additions & 4 deletions telebot/async_telebot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1335,7 +1335,7 @@ def enable_saving_states(self, filename="./.state-save/states.pkl"):
"""

self.current_states = asyncio_handler_backends.StateFile(filename=filename)
self.current_states._create_dir()
self.current_states.create_dir()

async def set_webhook(self, url=None, certificate=None, max_connections=None, allowed_updates=None, ip_address=None,
drop_pending_updates = None, timeout=None):
Expand Down Expand Up @@ -1790,6 +1790,7 @@ async def send_sticker(
:param timeout: timeout
:param allow_sending_without_reply:
:param protect_content:
:param data: deprecated, for backward compatibility
:return: API reply.
"""
if data and not(sticker):
Expand Down Expand Up @@ -1837,13 +1838,16 @@ async def send_video(
:param allow_sending_without_reply:
:param reply_markup:
:param timeout:
:param data: function typo miss compatibility: do not use it
:param data: deprecated, for backward compatibility
"""
parse_mode = self.parse_mode if (parse_mode is None) else parse_mode
if data and not(video):
# function typo miss compatibility
video = data

return types.Message.de_json(
await asyncio_helper.send_video(
self.token, chat_id, data, duration, caption, reply_to_message_id, reply_markup,
self.token, chat_id, video, duration, caption, reply_to_message_id, reply_markup,
parse_mode, supports_streaming, disable_notification, timeout, thumb, width, height,
caption_entities, allow_sending_without_reply, protect_content))

Expand Down Expand Up @@ -1873,6 +1877,7 @@ async def send_animation(
:param thumb: InputFile or String : Thumbnail of the file sent
:param caption: String : Animation caption (may also be used when resending animation by file_id).
:param parse_mode:
:param protect_content:
:param reply_to_message_id:
:param reply_markup:
:param disable_notification:
Expand Down Expand Up @@ -3057,4 +3062,4 @@ async def add_data(self, chat_id, **kwargs):
:param chat_id:
"""
for key, value in kwargs.items():
await self.current_states._add_data(chat_id, key, value)
await self.current_states.add_data(chat_id, key, value)
42 changes: 21 additions & 21 deletions telebot/asyncio_handler_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def delete_state(self, chat_id):
"""Delete a state"""
self._states.pop(chat_id)

def _get_data(self, chat_id):
def get_data(self, chat_id):
return self._states[chat_id]['data']

async def set(self, chat_id, new_state):
Expand All @@ -39,7 +39,7 @@ async def set(self, chat_id, new_state):
"""
await self.add_state(chat_id,new_state)

async def _add_data(self, chat_id, key, value):
async def add_data(self, chat_id, key, value):
result = self._states[chat_id]['data'][key] = value
return result

Expand Down Expand Up @@ -77,28 +77,28 @@ async def add_state(self, chat_id, state):
:param chat_id:
:param state: new state
"""
states_data = self._read_data()
states_data = self.read_data()
if chat_id in states_data:
states_data[chat_id]['state'] = state
return await self._save_data(states_data)
return await self.save_data(states_data)
else:
new_data = states_data[chat_id] = {'state': state,'data': {}}
return await self._save_data(states_data)
states_data[chat_id] = {'state': state,'data': {}}
return await self.save_data(states_data)


async def current_state(self, chat_id):
"""Current state."""
states_data = self._read_data()
states_data = self.read_data()
if chat_id in states_data: return states_data[chat_id]['state']
else: return False

async def delete_state(self, chat_id):
"""Delete a state"""
states_data = self._read_data()
states_data = self.read_data()
states_data.pop(chat_id)
await self._save_data(states_data)
await self.save_data(states_data)

def _read_data(self):
def read_data(self):
"""
Read the data from file.
"""
Expand All @@ -107,7 +107,7 @@ def _read_data(self):
file.close()
return states_data

def _create_dir(self):
def create_dir(self):
"""
Create directory .save-handlers.
"""
Expand All @@ -117,7 +117,7 @@ def _create_dir(self):
with open(self.file_path,'wb') as file:
pickle.dump({}, file)

async def _save_data(self, new_data):
async def save_data(self, new_data):
"""
Save data after editing.
:param new_data:
Expand All @@ -126,8 +126,8 @@ async def _save_data(self, new_data):
pickle.dump(new_data, state_file, protocol=pickle.HIGHEST_PROTOCOL)
return True

def _get_data(self, chat_id):
return self._read_data()[chat_id]['data']
def get_data(self, chat_id):
return self.read_data()[chat_id]['data']

async def set(self, chat_id, new_state):
"""
Expand All @@ -138,10 +138,10 @@ async def set(self, chat_id, new_state):
"""
await self.add_state(chat_id,new_state)

async def _add_data(self, chat_id, key, value):
states_data = self._read_data()
async def add_data(self, chat_id, key, value):
states_data = self.read_data()
result = states_data[chat_id]['data'][key] = value
await self._save_data(result)
await self.save_data(result)

return result

Expand Down Expand Up @@ -173,7 +173,7 @@ class StateContext:
def __init__(self , obj: StateMemory, chat_id) -> None:
self.obj = obj
self.chat_id = chat_id
self.data = obj._get_data(chat_id)
self.data = obj.get_data(chat_id)

async def __aenter__(self):
return self.data
Expand All @@ -191,14 +191,14 @@ def __init__(self , obj: StateFile, chat_id) -> None:
self.data = None

async def __aenter__(self):
self.data = self.obj._get_data(self.chat_id)
self.data = self.obj.get_data(self.chat_id)
return self.data

async def __aexit__(self, exc_type, exc_val, exc_tb):
old_data = self.obj._read_data()
old_data = self.obj.read_data()
for i in self.data:
old_data[self.chat_id]['data'][i] = self.data.get(i)
await self.obj._save_data(old_data)
await self.obj.save_data(old_data)

return

Expand Down
4 changes: 2 additions & 2 deletions telebot/asyncio_helper.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import asyncio # for future uses
from time import time
import aiohttp
from telebot import types
import json

try:
import ujson as json
Expand Down Expand Up @@ -853,6 +851,8 @@ async def send_data(token, chat_id, data, data_type, reply_to_message_id=None, r
payload['caption_entities'] = json.dumps(types.MessageEntity.to_list_of_dicts(caption_entities))
if allow_sending_without_reply is not None:
payload['allow_sending_without_reply'] = allow_sending_without_reply
if protect_content is not None:
payload['protect_content'] = protect_content
if method_url == 'sendDocument' and disable_content_type_detection is not None:
payload['disable_content_type_detection'] = disable_content_type_detection
return await _process_request(token, method_url, params=payload, files=files, method='post')
Expand Down
Loading

0 comments on commit 9050f4a

Please sign in to comment.