Skip to content

Commit

Permalink
Added logs dir and fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
kanewi11 committed Dec 5, 2022
1 parent eb1096a commit 555358a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
1 change: 0 additions & 1 deletion converters/tdata_to_telethon.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import os
import struct
import hashlib
import asyncio
import ipaddress
from typing import Union
from pathlib import Path
Expand Down
49 changes: 34 additions & 15 deletions reactionbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

BASE_DIR = Path(__file__).parent
WORK_DIR = BASE_DIR.joinpath('sessions')
LOGS_DIR = BASE_DIR.joinpath('logs')
TDATAS_DIR = BASE_DIR.joinpath('tdatas')
SUCCESS_CONVERT_TDATA_DIR = TDATAS_DIR.joinpath('success')
UNSUCCESSFUL_CONVERT_TDATA_DIR = TDATAS_DIR.joinpath('unsuccessful')
Expand All @@ -32,8 +33,22 @@

CONFIG_FILE_SUFFIXES = ('.ini', '.json')

logging.basicConfig(filename='logs.log', level=logging.WARNING, format='%(asctime)s %(levelname)s %(message)s')
logging.warning('Start reaction bot.')
LOGS_DIR.mkdir(exist_ok=True)

loggers = ['info', 'error']
formatter = logging.Formatter('%(name)s %(asctime)s %(levelname)s %(message)s')

for logger_name in loggers:
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
log_filepath = LOGS_DIR.joinpath(logger_name + '.log')
handler = logging.FileHandler(log_filepath, mode='w')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.warning('Start reaction bot.')

error = logging.getLogger('warning')
info = logging.getLogger('info')


async def send_reaction(client: Client, message: types.Message) -> None:
Expand All @@ -42,11 +57,11 @@ async def send_reaction(client: Client, message: types.Message) -> None:
try:
await client.send_reaction(chat_id=message.chat.id, message_id=message.id, emoji=emoji)
except ReactionInvalid:
logging.warning(f'{emoji} - INVALID REACTION')
error.warning(f'{emoji} - INVALID REACTION')
except UserDeactivatedBan:
logging.warning('Session banned')
error.warning('Session banned - ' + client.name)
except Exception:
logging.warning(traceback.format_exc())
error.warning(traceback.format_exc())


async def make_work_dir() -> None:
Expand Down Expand Up @@ -108,7 +123,7 @@ async def create_apps(config_files_paths: List[Path]) -> List[Tuple[Client, Dict
session_file_path = WORK_DIR.joinpath(config_file_path.with_suffix('.session'))
apps.append((Client(workdir=WORK_DIR.__str__(), **config_dict), config_dict, session_file_path))
except Exception:
logging.warning(traceback.format_exc())
error.warning(traceback.format_exc())
return apps


Expand All @@ -124,9 +139,10 @@ async def try_convert(session_path: Path, config: Dict) -> bool:
config_file_path = session_path.with_suffix(suffix)
if config_file_path.exists():
await convertor.move_file_to_unnecessary(config_file_path)
logging.warning('Preservation of the session failed ' + session_path.stem)
error.warning('Preservation of the session failed ' + session_path.stem)
return False
except Exception:
error.warning(traceback.format_exc())
return False
else:
return True
Expand Down Expand Up @@ -172,7 +188,7 @@ async def main():
try:
await convert_tdata(tdata_path, WORK_DIR)
except Exception:
logging.warning(traceback.format_exc())
error.warning(traceback.format_exc())
await move_file(tdata_path, UNSUCCESSFUL_CONVERT_TDATA_DIR)
else:
await move_file(tdata_path, SUCCESS_CONVERT_TDATA_DIR)
Expand All @@ -189,37 +205,40 @@ async def main():
await app.start()
except OperationalError:
is_converted = await try_convert(session_file_path, config_dict)
apps.remove((app, config_dict, session_file_path))
if not is_converted:
apps.remove((app, config_dict, session_file_path))
continue
try:
app = Client(workdir=WORK_DIR.__str__(), **config_dict)
app.add_handler(message_handler)
await app.start()
except Exception:
logging.warning(traceback.format_exc())
error.warning(traceback.format_exc())
else:
apps.append((app, config_dict, session_file_path))
except UserDeactivatedBan:
await move_session_to_ban_dir(session_file_path)
logging.warning('Session banned - ' + app.name)
error.warning('Session banned - ' + app.name)
apps.remove((app, config_dict, session_file_path))
continue
except Exception:
apps.remove((app, config_dict, session_file_path))
logging.warning(traceback.format_exc())
error.warning(traceback.format_exc())
continue

info.info('Session started - ' + app.name)
for channel in CHANNELS:
await app.join_chat(channel)

if not apps:
raise Exception('No apps!')

info.info('All sessions started!')
await idle()

for app, _, _ in apps:
try:
logging.warning(f'Stopped - {app.name}')
info.warning(f'Stopped - {app.name}')
await app.stop()
except ConnectionError:
pass
Expand All @@ -232,8 +251,8 @@ def start():
try:
loop.run_until_complete(main())
except Exception:
logging.critical(traceback.format_exc())
logging.warning(f'Waiting {TRY_AGAIN_SLEEP} sec. before restarting the program...')
error.critical(traceback.format_exc())
error.warning(f'Waiting {TRY_AGAIN_SLEEP} sec. before restarting the program...')
time.sleep(TRY_AGAIN_SLEEP)


Expand Down

0 comments on commit 555358a

Please sign in to comment.