Passed
Push — master ( c49a7e...eab792 )
by Anas
01:55
created

modules.logging.get_chat_info()   A

Complexity

Conditions 2

Size

Total Lines 8
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
from telegram.ext import CommandHandler
4
from datetime import datetime
5
import threading
6
import sqlite3
7
import time
8
9
10
def logging_decorator(command_name):
11
    def decorator(func):
12
        def wrapper(bot, update, *args, **kwargs):
13
            time1 = time.time()
14
            current_time = datetime.strftime(datetime.now(), "%d.%m.%Y %H:%M:%S")
15
            data = func(bot, update, *args, **kwargs)
16
            time2 = time.time()
17
            print(
18
                "{} > /{} > {} > {} > {} > {:.0f} ms".format(
19
                    current_time,
20
                    command_name,
21
                    update.message.from_user.username,
22
                    update.message.from_user.id,
23
                    data,
24
                    (time2-time1)*1000
25
                )
26
            )
27
            log_command(bot, update, current_time, command_name)
28
        return wrapper
29
    return decorator
30
    
31
32
33
34
def module_init(gd):
35
    global c, conn, db_lock
36
    db_lock = threading.Lock()
37
    path = gd.config["path"]
38
    conn  = sqlite3.connect(path+"rikka.db", check_same_thread=False)
39
    c = conn.cursor()
40
41
42
def data_entry(table, entry_columns, values):
43
    values_count = ("?, "*len(values))[:-2]
44
    db_lock.acquire()
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable db_lock does not seem to be defined.
Loading history...
45
    c.execute("INSERT INTO "+table+" ("+entry_columns+") VALUES ("+values_count+")", (values))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable c does not seem to be defined.
Loading history...
46
    conn.commit()
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable conn does not seem to be defined.
Loading history...
47
    db_lock.release()
48
49
50
def get_chat_info(bot, update):
51
    user_name = update.effective_message.from_user.name
52
    if user_name.startswith("@"):
53
        user_name = user_name[1:]
54
    chat_id = update.effective_message.chat_id
55
    user_id = update.effective_message.from_user.id
56
    chat = bot.getChat(chat_id)
57
    return chat_id, chat.title, user_id, user_name
58
59
60
def log_command(bot, update, date, command):
61
    table_name = "commands"
62
    entry_columns = "date, user_id, user, command, chat_id, chat_title" 
63
    chat_id, chat_title, user_id, user = get_chat_info(bot, update)
64
    values = [date, user_id, user, command, chat_id, chat_title]
65
    data_entry(table_name, entry_columns, values)
66