Bot in admin mode react on action in message
This commit is contained in:
parent
cd6d9cf0ea
commit
5d45b7d1f9
171
dan63047bot.py
171
dan63047bot.py
|
@ -26,7 +26,10 @@ except:
|
||||||
handler = logging.FileHandler(log_path, 'w', 'utf-8')
|
handler = logging.FileHandler(log_path, 'w', 'utf-8')
|
||||||
handler.setFormatter(logging.Formatter('%(message)s'))
|
handler.setFormatter(logging.Formatter('%(message)s'))
|
||||||
root_logger.addHandler(handler)
|
root_logger.addHandler(handler)
|
||||||
debug_array = {'vk_warnings': 0, 'db_warnings': 0, 'bot_warnings': 0, 'logger_warnings': 0, 'start_time': 0, 'messages_get': 0, 'messages_answered': 0}
|
debug_array = {'vk_warnings': 0, 'db_warnings': 0, 'bot_warnings': 0,
|
||||||
|
'logger_warnings': 0, 'start_time': 0, 'messages_get': 0, 'messages_answered': 0}
|
||||||
|
|
||||||
|
|
||||||
def log(warning, text):
|
def log(warning, text):
|
||||||
if warning:
|
if warning:
|
||||||
msg = "[" + str(datetime.datetime.now()) + "] [WARNING] " + text
|
msg = "[" + str(datetime.datetime.now()) + "] [WARNING] " + text
|
||||||
|
@ -38,6 +41,7 @@ def log(warning, text):
|
||||||
logging.info(msg)
|
logging.info(msg)
|
||||||
print(msg)
|
print(msg)
|
||||||
|
|
||||||
|
|
||||||
log(False, "Script started")
|
log(False, "Script started")
|
||||||
try:
|
try:
|
||||||
vk = vk_api.VkApi(token=config.vk_group_token)
|
vk = vk_api.VkApi(token=config.vk_group_token)
|
||||||
|
@ -50,7 +54,8 @@ try:
|
||||||
if(config.vk_service_token != None and config.album_for_command):
|
if(config.vk_service_token != None and config.album_for_command):
|
||||||
random_image_command = True
|
random_image_command = True
|
||||||
vk_mda = vk_api.VkApi(token=config.vk_service_token)
|
vk_mda = vk_api.VkApi(token=config.vk_service_token)
|
||||||
vk_mda.method('photos.get',{'owner_id': "-"+str(config.group_id), 'album_id': config.album_for_command, 'count': 1000})
|
vk_mda.method('photos.get', {'owner_id': "-"+str(config.group_id),
|
||||||
|
'album_id': config.album_for_command, 'count': 1000})
|
||||||
if(config.album_for_command == None):
|
if(config.album_for_command == None):
|
||||||
log(False, "Album id for !image is not setted, command will be turned off")
|
log(False, "Album id for !image is not setted, command will be turned off")
|
||||||
if(config.vk_service_token == None):
|
if(config.vk_service_token == None):
|
||||||
|
@ -82,7 +87,9 @@ except Exception:
|
||||||
log(True, "Invalid OpenWeatherMap API key, !weather command will be turned off")
|
log(True, "Invalid OpenWeatherMap API key, !weather command will be turned off")
|
||||||
|
|
||||||
bot = {}
|
bot = {}
|
||||||
errors_array = {"access": "Отказано в доступе", "miss_argument": "Отсуствует аргумент", "command_off": "Команда отключена"}
|
errors_array = {"access": "Отказано в доступе",
|
||||||
|
"miss_argument": "Отсуствует аргумент", "command_off": "Команда отключена"}
|
||||||
|
|
||||||
|
|
||||||
class Database_worker():
|
class Database_worker():
|
||||||
|
|
||||||
|
@ -91,10 +98,10 @@ class Database_worker():
|
||||||
log(False, "Trying to connect to database")
|
log(False, "Trying to connect to database")
|
||||||
try:
|
try:
|
||||||
self._CON = pymysql.connect(
|
self._CON = pymysql.connect(
|
||||||
host= config.mysql_host,
|
host=config.mysql_host,
|
||||||
user= config.mysql_user,
|
user=config.mysql_user,
|
||||||
password= config.mysql_pass,
|
password=config.mysql_pass,
|
||||||
db= config.mysql_db,
|
db=config.mysql_db,
|
||||||
charset='utf8mb4',
|
charset='utf8mb4',
|
||||||
cursorclass=DictCursor
|
cursorclass=DictCursor
|
||||||
)
|
)
|
||||||
|
@ -122,17 +129,18 @@ class Database_worker():
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
cur = self._CON.cursor()
|
cur = self._CON.cursor()
|
||||||
cur.execute("INSERT INTO bot_users (chat_id, awaiting, access, midnight, new_post, admin_mode, game_wins, game_defeats, game_draws) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (peer_id, awaiting, access, midnight, new_post, admin_mode, game_wins, game_defeats, game_draws))
|
cur.execute("INSERT INTO bot_users (chat_id, awaiting, access, midnight, new_post, admin_mode, game_wins, game_defeats, game_draws) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||||
|
(peer_id, awaiting, access, midnight, new_post, admin_mode, game_wins, game_defeats, game_draws))
|
||||||
self._CON.commit()
|
self._CON.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
debug_array['db_warnings'] += 1
|
debug_array['db_warnings'] += 1
|
||||||
log(True, f"Unable to add new user in database: {str(e)}")
|
log(True, f"Unable to add new user in database: {str(e)}")
|
||||||
else:
|
else:
|
||||||
self._DATA_DIST['users'][peer_id] = {"awaiting": awaiting, "access": access, "midnight": midnight, "new_post": new_post, "admin_mode": admin_mode, "game_wins": game_wins, "game_defeats": game_defeats, "game_draws": game_draws}
|
self._DATA_DIST['users'][peer_id] = {"awaiting": awaiting, "access": access, "midnight": midnight, "new_post": new_post,
|
||||||
|
"admin_mode": admin_mode, "game_wins": game_wins, "game_defeats": game_defeats, "game_draws": game_draws}
|
||||||
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
||||||
|
|
||||||
|
|
||||||
def get_all_users(self):
|
def get_all_users(self):
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
|
@ -151,7 +159,8 @@ class Database_worker():
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
cur = self._CON.cursor()
|
cur = self._CON.cursor()
|
||||||
cur.execute("SELECT * FROM bot_users WHERE chat_id = %s", (from_id))
|
cur.execute(
|
||||||
|
"SELECT * FROM bot_users WHERE chat_id = %s", (from_id))
|
||||||
result = cur.fetchall()
|
result = cur.fetchall()
|
||||||
cur.close()
|
cur.close()
|
||||||
return result
|
return result
|
||||||
|
@ -165,7 +174,8 @@ class Database_worker():
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
cur = self._CON.cursor()
|
cur = self._CON.cursor()
|
||||||
cur.execute("SELECT chat_id, game_wins, game_draws, game_defeats FROM bot_users WHERE game_wins > 0 OR game_draws > 0 OR game_defeats > 0")
|
cur.execute(
|
||||||
|
"SELECT chat_id, game_wins, game_draws, game_defeats FROM bot_users WHERE game_wins > 0 OR game_draws > 0 OR game_defeats > 0")
|
||||||
result = cur.fetchall()
|
result = cur.fetchall()
|
||||||
cur.close()
|
cur.close()
|
||||||
return result
|
return result
|
||||||
|
@ -180,12 +190,14 @@ class Database_worker():
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
cur = self._CON.cursor()
|
cur = self._CON.cursor()
|
||||||
cur.execute(f"UPDATE bot_users SET {thing} = %s WHERE bot_users.chat_id = %s;", (new_value, chat_id))
|
cur.execute(
|
||||||
|
f"UPDATE bot_users SET {thing} = %s WHERE bot_users.chat_id = %s;", (new_value, chat_id))
|
||||||
self._CON.commit()
|
self._CON.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
debug_array['db_warnings'] += 1
|
debug_array['db_warnings'] += 1
|
||||||
log(True, f"Unable to update info about user in database: {str(e)}")
|
log(True,
|
||||||
|
f"Unable to update info about user in database: {str(e)}")
|
||||||
else:
|
else:
|
||||||
self._DATA_DIST['users'][str(chat_id)][thing] = new_value
|
self._DATA_DIST['users'][str(chat_id)][thing] = new_value
|
||||||
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
||||||
|
@ -194,7 +206,8 @@ class Database_worker():
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
try:
|
try:
|
||||||
cur = self._CON.cursor()
|
cur = self._CON.cursor()
|
||||||
cur.execute("DELETE FROM bot_users, game_defeats WHERE chat_id = %s", (chat_id))
|
cur.execute(
|
||||||
|
"DELETE FROM bot_users, game_defeats WHERE chat_id = %s", (chat_id))
|
||||||
self._CON.commit()
|
self._CON.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
return True
|
return True
|
||||||
|
@ -206,18 +219,22 @@ class Database_worker():
|
||||||
self._DATA_DIST['users'].pop(str(chat_id))
|
self._DATA_DIST['users'].pop(str(chat_id))
|
||||||
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
open("data.json", "w").write(json.dumps(self._DATA_DIST))
|
||||||
|
|
||||||
|
|
||||||
db = Database_worker()
|
db = Database_worker()
|
||||||
|
|
||||||
|
|
||||||
def load_users():
|
def load_users():
|
||||||
try:
|
try:
|
||||||
log(False, "Reading database")
|
log(False, "Reading database")
|
||||||
get_info = db.get_all_users()
|
get_info = db.get_all_users()
|
||||||
if(config.use_database):
|
if(config.use_database):
|
||||||
for i in get_info:
|
for i in get_info:
|
||||||
bot[int(i['chat_id'])] = VkBot(int(i['chat_id']), bool(i['midnight']), i['awaiting'], int(i['access']), bool(i['new_post']), bool(i['admin_mode']))
|
bot[int(i['chat_id'])] = VkBot(int(i['chat_id']), bool(i['midnight']), i['awaiting'], int(
|
||||||
|
i['access']), bool(i['new_post']), bool(i['admin_mode']))
|
||||||
else:
|
else:
|
||||||
for i in get_info:
|
for i in get_info:
|
||||||
bot[int(i)] = VkBot(int(i), bool(get_info[i]['midnight']), get_info[i]['awaiting'], int(get_info[i]['access']), bool(get_info[i]['new_post']), bool(get_info[i]['admin_mode']))
|
bot[int(i)] = VkBot(int(i), bool(get_info[i]['midnight']), get_info[i]['awaiting'], int(
|
||||||
|
get_info[i]['access']), bool(get_info[i]['new_post']), bool(get_info[i]['admin_mode']))
|
||||||
except Exception as lol:
|
except Exception as lol:
|
||||||
debug_array['bot_warnings'] += 1
|
debug_array['bot_warnings'] += 1
|
||||||
log(True, f"Problem with creating objects: {str(lol)}")
|
log(True, f"Problem with creating objects: {str(lol)}")
|
||||||
|
@ -240,10 +257,12 @@ class MyVkLongPoll(VkBotLongPoll):
|
||||||
time.sleep(15)
|
time.sleep(15)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
def create_new_bot_object(chat_id):
|
def create_new_bot_object(chat_id):
|
||||||
bot[chat_id] = VkBot(chat_id)
|
bot[chat_id] = VkBot(chat_id)
|
||||||
db.set_new_user(chat_id)
|
db.set_new_user(chat_id)
|
||||||
|
|
||||||
|
|
||||||
def get_weather(place):
|
def get_weather(place):
|
||||||
try:
|
try:
|
||||||
weather_request = mgr.weather_at_place(place)
|
weather_request = mgr.weather_at_place(place)
|
||||||
|
@ -289,11 +308,14 @@ class VkBot:
|
||||||
if event == "midnight" and self._MIDNIGHT_EVENT:
|
if event == "midnight" and self._MIDNIGHT_EVENT:
|
||||||
current_time = datetime.datetime.fromtimestamp(time.time() + 10800)
|
current_time = datetime.datetime.fromtimestamp(time.time() + 10800)
|
||||||
|
|
||||||
midnight_text = ["Миднайт!", "Полночь!", "Midnight!", "миднигхт", "Середина ночи", "Смена даты!", "00:00"]
|
midnight_text = ["Миднайт!", "Полночь!", "Midnight!",
|
||||||
|
"миднигхт", "Середина ночи", "Смена даты!", "00:00"]
|
||||||
if(random_image_command):
|
if(random_image_command):
|
||||||
self.send(f"{random.choice(midnight_text)}<br>Наступило {current_time.strftime('%d.%m.%Y')}<br>Картинка дня:", self.random_image())
|
self.send(
|
||||||
|
f"{random.choice(midnight_text)}<br>Наступило {current_time.strftime('%d.%m.%Y')}<br>Картинка дня:", self.random_image())
|
||||||
else:
|
else:
|
||||||
self.send(f"{random.choice(midnight_text)}<br>Наступило {current_time.strftime('%d.%m.%Y')}")
|
self.send(
|
||||||
|
f"{random.choice(midnight_text)}<br>Наступило {current_time.strftime('%d.%m.%Y')}")
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Notified about midnight")
|
log(False, f"[BOT_{self._CHAT_ID}] Notified about midnight")
|
||||||
elif event == "post" and self._NEW_POST:
|
elif event == "post" and self._NEW_POST:
|
||||||
post = f"wall{str(something['from_id'])}_{str(something['id'])}"
|
post = f"wall{str(something['from_id'])}_{str(something['id'])}"
|
||||||
|
@ -308,12 +330,15 @@ class VkBot:
|
||||||
self.send(f"[@id{user_id}|Дебил]")
|
self.send(f"[@id{user_id}|Дебил]")
|
||||||
try:
|
try:
|
||||||
if int(user_id) != int(config.owner_id):
|
if int(user_id) != int(config.owner_id):
|
||||||
vk.method("messages.removeChatUser", {"chat_id": int(self._CHAT_ID)-2000000000, "member_id": user_id})
|
vk.method("messages.removeChatUser", {"chat_id": int(
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] user id{user_id} has been kicked")
|
self._CHAT_ID)-2000000000, "member_id": user_id})
|
||||||
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] user id{user_id} has been kicked")
|
||||||
else:
|
else:
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] can't kick owner")
|
log(False, f"[BOT_{self._CHAT_ID}] can't kick owner")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(True, f"[BOT_{self._CHAT_ID}] can't kick user id{user_id} - {str(e)}")
|
log(True,
|
||||||
|
f"[BOT_{self._CHAT_ID}] can't kick user id{user_id} - {str(e)}")
|
||||||
with open('bad_words.txt', 'r', encoding="utf-8", newline='') as filter:
|
with open('bad_words.txt', 'r', encoding="utf-8", newline='') as filter:
|
||||||
flag = False
|
flag = False
|
||||||
forcheck = message.lower()
|
forcheck = message.lower()
|
||||||
|
@ -325,6 +350,14 @@ class VkBot:
|
||||||
else:
|
else:
|
||||||
if forcheck.find(word[:-1]) != -1:
|
if forcheck.find(word[:-1]) != -1:
|
||||||
flag = True
|
flag = True
|
||||||
|
if event.message.action:
|
||||||
|
action = event.message.action
|
||||||
|
if action['type'] == 'chat_invite_user' or action['type'] == 'chat_invite_user_by_link':
|
||||||
|
user_info = vk.method('users.get', {'user_ids': action["member_id"], 'fields': 'verified,last_seen,sex'})
|
||||||
|
self.send(f'Добро пожаловать в беседу, {user_info[0]["first_name"]} {user_info[0]["last_name"]}')
|
||||||
|
elif action['type'] == 'chat_kick_user':
|
||||||
|
user_info = vk.method('users.get', {'user_ids': action["member_id"], 'fields': 'verified,last_seen,sex'})
|
||||||
|
self.send(f'{user_info[0]["first_name"]} {user_info[0]["last_name"]} покинул беседу')
|
||||||
if self._AWAITING_INPUT_MODE:
|
if self._AWAITING_INPUT_MODE:
|
||||||
if message == "Назад":
|
if message == "Назад":
|
||||||
self.change_await()
|
self.change_await()
|
||||||
|
@ -337,7 +370,8 @@ class VkBot:
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Out from echo mode")
|
log(False, f"[BOT_{self._CHAT_ID}] Out from echo mode")
|
||||||
else:
|
else:
|
||||||
self.send(message)
|
self.send(message)
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Answer in echo mode")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Answer in echo mode")
|
||||||
else:
|
else:
|
||||||
if message.lower() == "бот дай денег":
|
if message.lower() == "бот дай денег":
|
||||||
self.send("Иди нахуй")
|
self.send("Иди нахуй")
|
||||||
|
@ -414,11 +448,13 @@ class VkBot:
|
||||||
if self._MIDNIGHT_EVENT:
|
if self._MIDNIGHT_EVENT:
|
||||||
self.change_midnight(False)
|
self.change_midnight(False)
|
||||||
self.send("Уведомление о миднайте выключено")
|
self.send("Уведомление о миднайте выключено")
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Unsubscribed from event \"Midnight\"")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Unsubscribed from event \"Midnight\"")
|
||||||
else:
|
else:
|
||||||
self.change_midnight(True)
|
self.change_midnight(True)
|
||||||
self.send("Бот будет уведомлять вас о каждом миднайте")
|
self.send("Бот будет уведомлять вас о каждом миднайте")
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Subscribed on event \"Midnight\"")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Subscribed on event \"Midnight\"")
|
||||||
else:
|
else:
|
||||||
respond['text'] = errors_array["access"]
|
respond['text'] = errors_array["access"]
|
||||||
|
|
||||||
|
@ -435,7 +471,8 @@ class VkBot:
|
||||||
respond['text'] = "Некорректный аргумент"
|
respond['text'] = "Некорректный аргумент"
|
||||||
except IndexError:
|
except IndexError:
|
||||||
respond['text'] = errors_array["miss_argument"]
|
respond['text'] = errors_array["miss_argument"]
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Access level changed on {self._ACCESS_LEVEL}")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Access level changed on {self._ACCESS_LEVEL}")
|
||||||
else:
|
else:
|
||||||
respond['text'] = errors_array["access"]
|
respond['text'] = errors_array["access"]
|
||||||
|
|
||||||
|
@ -452,11 +489,14 @@ class VkBot:
|
||||||
if self._NEW_POST:
|
if self._NEW_POST:
|
||||||
self.change_new_post(False)
|
self.change_new_post(False)
|
||||||
self.send("Уведомление о новом посте выключено")
|
self.send("Уведомление о новом посте выключено")
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Unsubscribed from new posts")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Unsubscribed from new posts")
|
||||||
else:
|
else:
|
||||||
self.change_new_post(True)
|
self.change_new_post(True)
|
||||||
self.send("Бот будет уведомлять вас о каждом новом посте")
|
self.send(
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Subscribed on new posts")
|
"Бот будет уведомлять вас о каждом новом посте")
|
||||||
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Subscribed on new posts")
|
||||||
else:
|
else:
|
||||||
respond['text'] = errors_array["access"]
|
respond['text'] = errors_array["access"]
|
||||||
|
|
||||||
|
@ -464,9 +504,11 @@ class VkBot:
|
||||||
try:
|
try:
|
||||||
message[1] = message[1].split(' ', 1)
|
message[1] = message[1].split(' ', 1)
|
||||||
try:
|
try:
|
||||||
respond['text'] = self.random_number(int(message[1][0]), int(message[1][1]))
|
respond['text'] = self.random_number(
|
||||||
|
int(message[1][0]), int(message[1][1]))
|
||||||
except:
|
except:
|
||||||
respond['text'] = self.random_number(0, int(message[1][0]))
|
respond['text'] = self.random_number(
|
||||||
|
0, int(message[1][0]))
|
||||||
except:
|
except:
|
||||||
respond['text'] = self.random_number(0, 10)
|
respond['text'] = self.random_number(0, 10)
|
||||||
elif message[0] == self._COMMANDS[18]:
|
elif message[0] == self._COMMANDS[18]:
|
||||||
|
@ -476,15 +518,18 @@ class VkBot:
|
||||||
respond['text'] = errors_array["access"]
|
respond['text'] = errors_array["access"]
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
vk.method("messages.getConversationMembers", {"peer_id": int(self._CHAT_ID), "group_id": config.group_id})
|
vk.method("messages.getConversationMembers", {
|
||||||
|
"peer_id": int(self._CHAT_ID), "group_id": config.group_id})
|
||||||
if self._ADMIN_MODE:
|
if self._ADMIN_MODE:
|
||||||
respond["text"] = "Режим модерирования выключен"
|
respond["text"] = "Режим модерирования выключен"
|
||||||
self.change_admin_mode(False)
|
self.change_admin_mode(False)
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Admin mode: {self._ADMIN_MODE}")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Admin mode: {self._ADMIN_MODE}")
|
||||||
else:
|
else:
|
||||||
respond["text"] = "Режим модерирования включён"
|
respond["text"] = "Режим модерирования включён"
|
||||||
self.change_admin_mode(True)
|
self.change_admin_mode(True)
|
||||||
log(False, f"[BOT_{self._CHAT_ID}] Admin mode: {self._ADMIN_MODE}")
|
log(False,
|
||||||
|
f"[BOT_{self._CHAT_ID}] Admin mode: {self._ADMIN_MODE}")
|
||||||
except Exception:
|
except Exception:
|
||||||
respond["text"] = "У меня нет прав администратора"
|
respond["text"] = "У меня нет прав администратора"
|
||||||
|
|
||||||
|
@ -517,7 +562,8 @@ class VkBot:
|
||||||
answer = "Статистика игроков в !game"
|
answer = "Статистика игроков в !game"
|
||||||
for i in stats:
|
for i in stats:
|
||||||
try:
|
try:
|
||||||
winrate = (i['game_wins']/(i['game_wins']+i['game_defeats']+i['game_draws'])) * 100
|
winrate = (i['game_wins']/(i['game_wins'] +
|
||||||
|
i['game_defeats']+i['game_draws'])) * 100
|
||||||
except ZeroDivisionError:
|
except ZeroDivisionError:
|
||||||
winrate = 0
|
winrate = 0
|
||||||
answer += f"<br> @id{i['chat_id']} - Сыграл раз: {i['game_wins']+i['game_defeats']+i['game_draws']}, Победы/Ничьи/Поражения: {i['game_wins']}/{i['game_draws']}/{i['game_defeats']}, {toFixed(winrate, 2)}% побед"
|
answer += f"<br> @id{i['chat_id']} - Сыграл раз: {i['game_wins']+i['game_defeats']+i['game_draws']}, Победы/Ничьи/Поражения: {i['game_wins']}/{i['game_draws']}/{i['game_defeats']}, {toFixed(winrate, 2)}% побед"
|
||||||
|
@ -528,10 +574,14 @@ class VkBot:
|
||||||
up_time = time.time() - debug_array['start_time']
|
up_time = time.time() - debug_array['start_time']
|
||||||
time_d = int(up_time) / (3600 * 24)
|
time_d = int(up_time) / (3600 * 24)
|
||||||
time_h = int(up_time) / 3600 - int(time_d) * 24
|
time_h = int(up_time) / 3600 - int(time_d) * 24
|
||||||
time_min = int(up_time) / 60 - int(time_h) * 60 - int(time_d) * 24 * 60
|
time_min = int(up_time) / 60 - int(time_h) * \
|
||||||
time_sec = int(up_time) - int(time_min) * 60 - int(time_h) * 3600 - int(time_d) * 24 * 60 * 60
|
60 - int(time_d) * 24 * 60
|
||||||
str_up_time = '%01d:%02d:%02d:%02d' % (time_d, time_h, time_min, time_sec)
|
time_sec = int(up_time) - int(time_min) * 60 - \
|
||||||
datetime_time = datetime.datetime.fromtimestamp(debug_array['start_time'])
|
int(time_h) * 3600 - int(time_d) * 24 * 60 * 60
|
||||||
|
str_up_time = '%01d:%02d:%02d:%02d' % (
|
||||||
|
time_d, time_h, time_min, time_sec)
|
||||||
|
datetime_time = datetime.datetime.fromtimestamp(
|
||||||
|
debug_array['start_time'])
|
||||||
answer = "UPTIME: " + str_up_time + "<br>Прослушано сообщений: " + str(
|
answer = "UPTIME: " + str_up_time + "<br>Прослушано сообщений: " + str(
|
||||||
debug_array['messages_get']) + "<br>Отправлено сообщений: " + str(
|
debug_array['messages_get']) + "<br>Отправлено сообщений: " + str(
|
||||||
debug_array['messages_answered']) + "<br>Ошибок в работе: " + str(
|
debug_array['messages_answered']) + "<br>Ошибок в работе: " + str(
|
||||||
|
@ -553,7 +603,8 @@ class VkBot:
|
||||||
d = data
|
d = data
|
||||||
if thing == "статистика":
|
if thing == "статистика":
|
||||||
try:
|
try:
|
||||||
winrate = (d['game_wins']/(d['game_wins']+d['game_defeats']+d['game_draws'])) * 100
|
winrate = (d['game_wins']/(d['game_wins'] +
|
||||||
|
d['game_defeats']+d['game_draws'])) * 100
|
||||||
except ZeroDivisionError:
|
except ZeroDivisionError:
|
||||||
winrate = 0
|
winrate = 0
|
||||||
return f"Камень, ножницы, бумага<br>Сыграно игр: {d['game_wins']+d['game_defeats']+d['game_draws']}<br>Из них:<br>•Побед: {d['game_wins']}<br>•Поражений: {d['game_defeats']}<br>•Ничей: {d['game_draws']}<br>Процент побед: {toFixed(winrate, 2)}%"
|
return f"Камень, ножницы, бумага<br>Сыграно игр: {d['game_wins']+d['game_defeats']+d['game_draws']}<br>Из них:<br>•Побед: {d['game_wins']}<br>•Поражений: {d['game_defeats']}<br>•Ничей: {d['game_draws']}<br>Процент побед: {toFixed(winrate, 2)}%"
|
||||||
|
@ -595,7 +646,8 @@ class VkBot:
|
||||||
|
|
||||||
def get_info_user(self, id):
|
def get_info_user(self, id):
|
||||||
try:
|
try:
|
||||||
user_info = vk.method('users.get', {'user_ids': id, 'fields': 'verified,last_seen,sex'})
|
user_info = vk.method(
|
||||||
|
'users.get', {'user_ids': id, 'fields': 'verified,last_seen,sex'})
|
||||||
except vk_api.exceptions.ApiError as lol:
|
except vk_api.exceptions.ApiError as lol:
|
||||||
err = "Method users.get: " + str(lol)
|
err = "Method users.get: " + str(lol)
|
||||||
log(True, err)
|
log(True, err)
|
||||||
|
@ -636,17 +688,20 @@ class VkBot:
|
||||||
else:
|
else:
|
||||||
platform = "тип платформы неизвестен"
|
platform = "тип платформы неизвестен"
|
||||||
|
|
||||||
time = datetime.datetime.fromtimestamp(user_info[0]['last_seen']['time'])
|
time = datetime.datetime.fromtimestamp(
|
||||||
|
user_info[0]['last_seen']['time'])
|
||||||
|
|
||||||
answer = user_info[0]['first_name'] + " " + user_info[0]['last_name'] + "<br>Его ид: " + \
|
answer = user_info[0]['first_name'] + " " + user_info[0]['last_name'] + "<br>Его ид: " + \
|
||||||
str(user_info[0]['id']) + "<br>Профиль закрыт: " + is_closed + "<br>Пол: " + sex \
|
str(user_info[0]['id']) + "<br>Профиль закрыт: " + is_closed + "<br>Пол: " + sex \
|
||||||
+ "<br>Последний онлайн: " + time.strftime('%d.%m.%Y в %H:%M:%S') + " (" + platform + ")"
|
+ "<br>Последний онлайн: " + \
|
||||||
|
time.strftime('%d.%m.%Y в %H:%M:%S') + " (" + platform + ")"
|
||||||
|
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
def get_info_group(self, id):
|
def get_info_group(self, id):
|
||||||
try:
|
try:
|
||||||
group_info = vk.method('groups.getById', {'group_id': id, 'fields': 'description,members_count'})
|
group_info = vk.method(
|
||||||
|
'groups.getById', {'group_id': id, 'fields': 'description,members_count'})
|
||||||
except vk_api.exceptions.ApiError as lol:
|
except vk_api.exceptions.ApiError as lol:
|
||||||
err = "Method groups.getById: " + str(lol)
|
err = "Method groups.getById: " + str(lol)
|
||||||
log(True, err)
|
log(True, err)
|
||||||
|
@ -665,7 +720,8 @@ class VkBot:
|
||||||
group = "-" + str(config.group_id)
|
group = "-" + str(config.group_id)
|
||||||
random_images_query = vk_mda.method('photos.get',
|
random_images_query = vk_mda.method('photos.get',
|
||||||
{'owner_id': group, 'album_id': config.album_for_command, 'count': 1000})
|
{'owner_id': group, 'album_id': config.album_for_command, 'count': 1000})
|
||||||
info = "Method photos.get: " + str(random_images_query['count']) + " photos received"
|
info = "Method photos.get: " + \
|
||||||
|
str(random_images_query['count']) + " photos received"
|
||||||
log(False, info)
|
log(False, info)
|
||||||
random_number = random.randrange(random_images_query['count'])
|
random_number = random.randrange(random_images_query['count'])
|
||||||
return "photo" + str(random_images_query['items'][random_number]['owner_id']) + "_" + str(
|
return "photo" + str(random_images_query['items'][random_number]['owner_id']) + "_" + str(
|
||||||
|
@ -726,11 +782,13 @@ class VkBot:
|
||||||
|
|
||||||
def send(self, message=None, attachment=None):
|
def send(self, message=None, attachment=None):
|
||||||
try:
|
try:
|
||||||
random_id = random.randint(-9223372036854775808, 9223372036854775807)
|
random_id = random.randint(-9223372036854775808,
|
||||||
|
9223372036854775807)
|
||||||
message = vk.method('messages.send',
|
message = vk.method('messages.send',
|
||||||
{'peer_id': self._CHAT_ID, 'message': message, 'random_id': random_id,
|
{'peer_id': self._CHAT_ID, 'message': message, 'random_id': random_id,
|
||||||
'attachment': attachment})
|
'attachment': attachment})
|
||||||
log(False, f'[BOT_{self._CHAT_ID}] id: {message}, random_id: {random_id}')
|
log(False,
|
||||||
|
f'[BOT_{self._CHAT_ID}] id: {message}, random_id: {random_id}')
|
||||||
debug_array['messages_answered'] += 1
|
debug_array['messages_answered'] += 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(True, f'Failed to send message: {str(e)}')
|
log(True, f'Failed to send message: {str(e)}')
|
||||||
|
@ -743,6 +801,8 @@ def bots():
|
||||||
try:
|
try:
|
||||||
if event.type == VkBotEventType.MESSAGE_NEW:
|
if event.type == VkBotEventType.MESSAGE_NEW:
|
||||||
log_msg = f'[MESSAGE] id: {event.message.id}, peer_id: {event.message.peer_id}, user_id: {event.message.from_id}'
|
log_msg = f'[MESSAGE] id: {event.message.id}, peer_id: {event.message.peer_id}, user_id: {event.message.from_id}'
|
||||||
|
if event.message.action:
|
||||||
|
log_msg += f', action: '+event.message.action["type"]+', user id in action: '+ str(event.message.action["member_id"])
|
||||||
if event.message.text != "":
|
if event.message.text != "":
|
||||||
log_msg += f', text: "{event.message.text}"'
|
log_msg += f', text: "{event.message.text}"'
|
||||||
if event.message.attachments:
|
if event.message.attachments:
|
||||||
|
@ -751,9 +811,11 @@ def bots():
|
||||||
if i['type'] == "sticker":
|
if i['type'] == "sticker":
|
||||||
atch += f"sticker_id{i[i['type']]['sticker_id']}"
|
atch += f"sticker_id{i[i['type']]['sticker_id']}"
|
||||||
elif i['type'] == "wall":
|
elif i['type'] == "wall":
|
||||||
atch += i['type'] + str(i[i['type']]['from_id']) + "_" + str(i[i['type']]['id']) + " "
|
atch += i['type'] + str(i[i['type']]['from_id']) + \
|
||||||
|
"_" + str(i[i['type']]['id']) + " "
|
||||||
else:
|
else:
|
||||||
atch += i['type'] + str(i[i['type']]['owner_id']) + "_" + str(i[i['type']]['id']) + " "
|
atch += i['type'] + str(i[i['type']]['owner_id']) + \
|
||||||
|
"_" + str(i[i['type']]['id']) + " "
|
||||||
log_msg += atch
|
log_msg += atch
|
||||||
log(False, log_msg)
|
log(False, log_msg)
|
||||||
debug_array['messages_get'] += 1
|
debug_array['messages_get'] += 1
|
||||||
|
@ -771,7 +833,8 @@ def bots():
|
||||||
else:
|
else:
|
||||||
bot[int(i)].event("post", event.object)
|
bot[int(i)].event("post", event.object)
|
||||||
elif event.type == VkBotEventType.MESSAGE_DENY:
|
elif event.type == VkBotEventType.MESSAGE_DENY:
|
||||||
log(False, f"User {event.object.user_id} deny messages from that group")
|
log(False,
|
||||||
|
f"User {event.object.user_id} deny messages from that group")
|
||||||
del bot[int(event.object.user_id)]
|
del bot[int(event.object.user_id)]
|
||||||
db.delete_user(event.object.user_id)
|
db.delete_user(event.object.user_id)
|
||||||
else:
|
else:
|
||||||
|
@ -781,6 +844,7 @@ def bots():
|
||||||
debug_array['bot_warnings'] += 1
|
debug_array['bot_warnings'] += 1
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
||||||
def midnight():
|
def midnight():
|
||||||
while True:
|
while True:
|
||||||
current_time = time.time()+10800
|
current_time = time.time()+10800
|
||||||
|
@ -797,6 +861,7 @@ def midnight():
|
||||||
else:
|
else:
|
||||||
time.sleep(0.50)
|
time.sleep(0.50)
|
||||||
|
|
||||||
|
|
||||||
load_users()
|
load_users()
|
||||||
tread_bots = threading.Thread(target=bots)
|
tread_bots = threading.Thread(target=bots)
|
||||||
tread_midnight = threading.Thread(target=midnight, daemon=True)
|
tread_midnight = threading.Thread(target=midnight, daemon=True)
|
||||||
|
|
Loading…
Reference in New Issue