-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.py
88 lines (61 loc) · 2.59 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
import functools
import logging
import sys
from pathlib import Path
from telegram import Update
from telegram.ext import CallbackContext
import config
def get_logger(file_name: str, dir_name='logs'):
dir_name = Path(dir_name).resolve()
dir_name.mkdir(parents=True, exist_ok=True)
file_name = str(dir_name / Path(file_name).resolve().name) + '.log'
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s] %(filename)s[LINE:%(lineno)d] %(levelname)-8s %(message)s')
fh = logging.FileHandler(file_name, encoding='utf-8')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler(stream=sys.stdout)
ch.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
log.addHandler(fh)
log.addHandler(ch)
return log
def log_func(log: logging.Logger):
def actual_decorator(func):
@functools.wraps(func)
def wrapper(update: Update, context: CallbackContext):
if update:
chat_id = user_id = first_name = last_name = username = language_code = None
if update.effective_chat:
chat_id = update.effective_chat.id
if update.effective_user:
user_id = update.effective_user.id
first_name = update.effective_user.first_name
last_name = update.effective_user.last_name
username = update.effective_user.username
language_code = update.effective_user.language_code
try:
message = update.effective_message.text
except:
message = ''
try:
query_data = update.callback_query.data
except:
query_data = ''
msg = f'[chat_id={chat_id}, user_id={user_id}, ' \
f'first_name={first_name!r}, last_name={last_name!r}, ' \
f'username={username!r}, language_code={language_code}, ' \
f'message={message!r}, query_data={query_data!r}]'
msg = func.__name__ + msg
log.debug(msg)
return func(update, context)
return wrapper
return actual_decorator
def reply_error(log: logging.Logger, update: Update, context: CallbackContext):
log.error('Error: %s\nUpdate: %s', context.error, update, exc_info=context.error)
if update:
update.effective_message.reply_text(config.ERROR_TEXT)