#python #exception #schedule #telethon
Вопрос:
Я пишу метод, который отправит сообщение в список пользователей telegram.
Я создаю его как задание, которое будет выполняться каждый день в 8:30 утра и отправлять «доброе утро».
@catch_exceptions(cancel_on_failure=True)
async def send_message():
message = 'Good Morning'
list_of_user_to_send_message = bot_team_data() # method to fetch data from DB
if type(list_of_user_to_send_message) is not list:
return
for telegramId in list_of_user_to_send_message:
if type(telegramId) is not int:
user = int(telegramId)
logger.info('Good morning message sent to {user}'.format(user=telegramId))
try:
await bot.send_message(user, message)
except ValueError as e:
logger.exception(
'User with telegramId {id} is not interacted with the bot, {e}'.format(id=telegramId, e=e),
stack_info=True)
continue
except Exception as e:
logger.exception(
'Error occurred for the telegramId {id} and the error is {e}'.format(id=telegramId, e=e),
stack_info=True)
continue
Я использую пакет aioschedule для запуска метода в качестве задания.
Я также создал метод для перехвата любого неизвестного исключения и отмены задания.
Но это не в состоянии работать.
Ниже приведен код, в котором я реализовал перехват исключений.
import functools
import aioschedule as schedule
import asyncio
def catch_exceptions(cancel_on_failure=False):
def catch_exceptions_decorator(job_func):
@functools.wraps(job_func)
def wrapper(*args, **kwargs):
try:
return job_func(*args, **kwargs)
except:
import traceback
if cancel_on_failure:
return schedule.CancelJob
return wrapper
return catch_exceptions_decorator
def main():
bot.start()
schedule.every().day.at("10:00").do(send_message)
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(schedule.run_pending())
bot.run_until_disconnected()
if __name__ == '__main__':
main()
I am trying this code to generate an error :
import configparser
import functools
import aioschedule as schedule
import asyncio
from telethon import TelegramClient
parser = configparser.ConfigParser()
parser.read("../application.yml")
api_id = parser.get("telegram-config", "api_id")
api_hash = parser.get("telegram-config", "api_hash")
bot_token = parser.get("telegram-config", "bot_token")
bot = TelegramClient('session', api_id, api_hash).start(bot_token=bot_token)
def catch_exceptions(cancel_on_failure=False):
print('try 1')
def catch_exceptions_decorator(job_func):
print('try 2')
@functools.wraps(job_func)
def wrapper(*args, **kwargs):
try:
print('try 3')
return job_func(*args, **kwargs)
except Exception as e:
print('exception')
import traceback
if cancel_on_failure:
return schedule.CancelJob
return wrapper
return catch_exceptions_decorator
@catch_exceptions(cancel_on_failure=True)
async def send_message():
message = 'Good Morning'
print('send message')
await bot.send_message('1234', message)
def main():
bot.start()
schedule.every().day.at("10:00").do(send_message)
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(schedule.run_pending())
bot.run_until_disconnected()
if __name__ == '__main__':
main()
Выход:
try 1
try 2
try 3
send message
Task exception was never retrieved
future: <Task finished name='Task-115736' coro=<Job.run() done, defined at D:Projecttelegram_botvenvlibsite-packagesaioschedule__init__.py:455> exception=ValueError('Cannot get entity by phone number as a bot (try using integer IDs, not strings)')>
Traceback (most recent call last):
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 501, in _get_entity_from_string
for user in (await self(
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 77, in _call
result = await future
telethon.errors.rpcerrorlist.BotMethodInvalidError: The API access for bot users is restricted. The method you tried to invoke cannot be executed as a bot (caused by GetContactsRequest)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:Projecttelegram_botvenvlibsite-packagesaioschedule__init__.py", line 462, in run
ret = await self.job_func()
File "D:/Project/telegram_bot/src/try_exception_catch.py", line 64, in send_message
await bot.send_message('1234', message)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientmessages.py", line 697, in send_message
entity = await self.get_input_entity(entity)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 413, in get_input_entity
await self._get_entity_from_string(peer))
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 506, in _get_entity_from_string
raise ValueError('Cannot get entity by phone number as a '
ValueError: Cannot get entity by phone number as a bot (try using integer IDs, not strings)
try 3
send message
Task exception was never retrieved
future: <Task finished name='Task-115738' coro=<Job.run() done, defined at D:Projecttelegram_botvenvlibsite-packagesaioschedule__init__.py:455> exception=ValueError('Cannot get entity by phone number as a bot (try using integer IDs, not strings)')>
Traceback (most recent call last):
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 501, in _get_entity_from_string
for user in (await self(
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 77, in _call
result = await future
telethon.errors.rpcerrorlist.BotMethodInvalidError: The API access for bot users is restricted. The method you tried to invoke cannot be executed as a bot (caused by GetContactsRequest)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:Projecttelegram_botvenvlibsite-packagesaioschedule__init__.py", line 462, in run
ret = await self.job_func()
File "D:/Project/telegram_bot/src/try_exception_catch.py", line 64, in send_message
await bot.send_message('1234', message)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientmessages.py", line 697, in send_message
entity = await self.get_input_entity(entity)
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 413, in get_input_entity
await self._get_entity_from_string(peer))
File "D:Projecttelegram_botvenvlibsite-packagestelethonclientusers.py", line 506, in _get_entity_from_string
raise ValueError('Cannot get entity by phone number as a '
ValueError: Cannot get entity by phone number as a bot (try using integer IDs, not strings)
Ошибка значения непрерывно поступает в терминал.
Комментарии:
1. У вас есть
bot
связь? Тыbot.start()
это где-нибудь делаешь?2. да, мне жаль, что я буду редактировать его.
3. Вы уверены, что код вообще выполняется (например, добавив a
4. Да, код выполняется, но не может перейти к части «Кроме» оболочки метода в части catch_exceptions.
5. Добавлен код, который я пытаюсь сгенерировать с ошибкой, и добавлен вывод.