2020-08-27 09:43:09 +00:00
""" Here you can found Bot class and Database worker class """
2020-04-04 16:07:39 +00:00
import vk_api
import datetime
2020-04-11 14:40:25 +00:00
import time
2020-04-04 16:07:39 +00:00
import requests
2020-04-04 21:18:12 +00:00
import logging
2020-04-05 14:41:33 +00:00
import pyowm
2020-04-05 22:46:06 +00:00
import random
2020-04-07 16:00:49 +00:00
import json
2022-04-02 15:47:39 +00:00
import re
2020-05-08 19:30:43 +00:00
import threading
2020-06-07 20:29:57 +00:00
import pymysql
2020-04-06 10:26:50 +00:00
import wikipediaapi as wiki
2020-07-01 15:09:54 +00:00
import config
2020-07-02 09:17:36 +00:00
from pymysql . cursors import DictCursor
from pyowm . utils . config import get_default_config
from collections import deque
2020-04-11 21:50:14 +00:00
from vk_api . bot_longpoll import VkBotLongPoll , VkBotEventType
2020-04-13 18:25:48 +00:00
root_logger = logging . getLogger ( )
2020-04-11 21:50:14 +00:00
root_logger . setLevel ( logging . INFO )
2020-06-07 20:29:57 +00:00
try :
2020-06-08 18:52:51 +00:00
log_path = f ' logs/bot_log { str ( datetime . datetime . now ( ) ) } .log '
handler = logging . FileHandler ( log_path , ' w ' , ' utf-8 ' )
2020-06-07 20:29:57 +00:00
except :
2020-06-08 18:52:51 +00:00
log_path = ' bot.log '
handler = logging . FileHandler ( log_path , ' w ' , ' utf-8 ' )
2020-06-10 17:42:30 +00:00
handler . setFormatter ( logging . Formatter ( ' %(message)s ' ) )
2020-04-11 21:50:14 +00:00
root_logger . addHandler ( handler )
2020-07-25 18:51:32 +00:00
debug_array = { ' vk_warnings ' : 0 , ' db_warnings ' : 0 , ' bot_warnings ' : 0 ,
' logger_warnings ' : 0 , ' start_time ' : 0 , ' messages_get ' : 0 , ' messages_answered ' : 0 }
2020-04-27 11:48:20 +00:00
def log ( warning , text ) :
if warning :
2020-06-10 17:42:30 +00:00
msg = " [ " + str ( datetime . datetime . now ( ) ) + " ] [WARNING] " + text
logging . warning ( msg )
print ( msg )
2020-05-04 20:26:22 +00:00
debug_array [ ' logger_warnings ' ] + = 1
2020-04-27 11:48:20 +00:00
else :
2020-06-10 17:42:30 +00:00
msg = " [ " + str ( datetime . datetime . now ( ) ) + " ] " + text
logging . info ( msg )
print ( msg )
2020-04-27 11:48:20 +00:00
2020-08-27 09:43:09 +00:00
bot = { }
2022-04-10 16:13:38 +00:00
SPAMMER_LIST = { }
2020-08-27 09:43:09 +00:00
errors_array = { " access " : " Отказано в доступе " ,
2022-04-09 12:57:05 +00:00
" miss_argument " : " Отсуствует аргумент " ,
" command_off " : " Команда отключена " ,
" not_a_multichat " : " Данный чат не является беседой " }
2020-07-25 18:51:32 +00:00
2020-07-02 09:17:36 +00:00
try :
vk = vk_api . VkApi ( token = config . vk_group_token )
longpoll = VkBotLongPoll ( vk , config . group_id )
except Exception as e :
log ( True , " Can ' t connect to longpull: " + str ( e ) )
exit ( log ( False , " [SHUTDOWN] " ) )
try :
if ( config . vk_service_token != None and config . album_for_command ) :
random_image_command = True
vk_mda = vk_api . VkApi ( token = config . vk_service_token )
2020-07-25 18:51:32 +00:00
vk_mda . method ( ' photos.get ' , { ' owner_id ' : " - " + str ( config . group_id ) ,
' album_id ' : config . album_for_command , ' count ' : 1000 } )
2020-07-02 09:17:36 +00:00
if ( config . album_for_command == None ) :
log ( False , " Album id for !image is not setted, command will be turned off " )
if ( config . vk_service_token == None ) :
random_image_command = False
log ( False , " Service token is ' None ' , !image command will be turned off " )
except vk_api . ApiError :
random_image_command = False
log ( True , " Invalid service token, !image command will be turned off " )
except AttributeError :
random_image_command = False
log ( True , " Service token or album id not found, !image command will be turned off " )
try :
if ( config . openweathermap_api_key != None ) :
owm_dict = get_default_config ( )
owm_dict [ ' language ' ] = ' ru '
owm = pyowm . OWM ( config . openweathermap_api_key , owm_dict )
mgr = owm . weather_manager ( )
mgr . weather_at_place ( " Минск " )
weather_command = True
else :
log ( False , " OpenWeatherMap API key is ' None ' , !weather command will be turned off " )
weather_command = False
except AttributeError :
weather_command = False
log ( True , " OpenWeatherMap API key not found, !image command will be turned off " )
except Exception :
weather_command = False
log ( True , " Invalid OpenWeatherMap API key, !weather command will be turned off " )
2020-06-07 20:29:57 +00:00
2020-07-01 15:09:54 +00:00
class Database_worker ( ) :
2020-07-25 18:51:32 +00:00
2020-06-07 20:29:57 +00:00
def __init__ ( self ) :
2022-04-10 16:13:38 +00:00
try :
with open ( " data.json " , " r " ) as data :
self . _DATA_DIST = json . load ( data )
data . close ( )
except Exception :
log ( True , " data.json is not exist, it will be created " )
self . _DATA_DIST = { " users " : { } , " spammers " : [ ] }
open ( " data.json " , " w " ) . write ( json . dumps ( self . _DATA_DIST ) )
2020-07-25 18:51:32 +00:00
2022-04-03 14:07:11 +00:00
def set_new_user ( self , peer_id , midnight = False , awaiting = None , access = 1 , new_post = False , admin_mode = False , game_wins = 0 , game_defeats = 0 , game_draws = 0 , banned = False ) :
2022-04-10 16:13:38 +00:00
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 , " banned " : banned }
open ( " data.json " , " w " ) . write ( json . dumps ( self . _DATA_DIST ) )
2020-07-01 15:09:54 +00:00
2020-06-07 20:29:57 +00:00
def get_all_users ( self ) :
2022-04-10 16:13:38 +00:00
with open ( " data.json " , " r " ) as data :
self . _DATA_DIST = json . load ( data )
data . close ( )
return self . _DATA_DIST [ ' users ' ]
2020-06-07 20:29:57 +00:00
def get_from_users ( self , from_id ) :
2022-04-10 16:13:38 +00:00
with open ( " data.json " , " r " ) as data :
self . _DATA_DIST = json . load ( data )
data . close ( )
if not self . _DATA_DIST [ ' users ' ] . get ( str ( from_id ) ) :
self . set_new_user ( str ( from_id ) )
return self . _DATA_DIST [ ' users ' ] [ str ( from_id ) ]
2020-06-09 10:19:10 +00:00
def get_game_stat ( self ) :
2022-04-10 16:13:38 +00:00
return self . _DATA_DIST [ ' users ' ]
def update_user ( self , 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 ) )
2020-06-07 20:29:57 +00:00
def delete_user ( self , chat_id ) :
2022-04-10 16:13:38 +00:00
self . _DATA_DIST [ ' users ' ] . pop ( str ( chat_id ) )
open ( " data.json " , " w " ) . write ( json . dumps ( self . _DATA_DIST ) )
2020-06-07 20:29:57 +00:00
2022-04-10 16:13:38 +00:00
def add_spammer ( self , user_id ) :
SPAMMER_LIST . append ( int ( user_id ) )
self . _DATA_DIST [ " spammers " ] . append ( int ( user_id ) )
open ( " data.json " , " w " ) . write ( json . dumps ( self . _DATA_DIST ) )
2020-07-25 18:51:32 +00:00
2022-04-10 16:13:38 +00:00
def remove_spammer ( self , user_id ) :
SPAMMER_LIST . pop ( int ( user_id ) )
self . _DATA_DIST [ " spammers " ] . pop ( int ( user_id ) )
open ( " data.json " , " w " ) . write ( json . dumps ( self . _DATA_DIST ) )
2020-06-07 20:29:57 +00:00
2022-04-10 16:13:38 +00:00
def read_spammers ( self ) :
return self . _DATA_DIST [ " spammers " ]
db = Database_worker ( )
2020-07-25 18:51:32 +00:00
2020-06-07 20:29:57 +00:00
2020-04-27 11:48:20 +00:00
2020-04-13 18:25:48 +00:00
def toFixed ( numObj , digits = 0 ) :
return f " { numObj : . { digits } f } "
2020-04-11 21:50:14 +00:00
class MyVkLongPoll ( VkBotLongPoll ) :
def listen ( self ) :
while True :
2020-04-13 18:25:48 +00:00
try :
2022-04-03 14:07:11 +00:00
yield from self . check ( )
2020-04-11 21:50:14 +00:00
except Exception as e :
2022-04-03 14:07:11 +00:00
err = f " A problem with VK LongPull: { str ( e ) } "
2020-04-27 11:48:20 +00:00
log ( True , err )
2020-05-04 20:26:22 +00:00
debug_array [ ' vk_warnings ' ] + = 1
2020-04-11 21:50:14 +00:00
time . sleep ( 15 )
continue
2020-04-04 16:07:39 +00:00
2020-07-25 18:51:32 +00:00
2020-06-07 20:29:57 +00:00
def create_new_bot_object ( chat_id ) :
bot [ chat_id ] = VkBot ( chat_id )
db . set_new_user ( chat_id )
2020-04-13 18:25:48 +00:00
2020-07-25 18:51:32 +00:00
2020-04-13 18:25:48 +00:00
def get_weather ( place ) :
try :
2020-07-02 09:17:36 +00:00
weather_request = mgr . weather_at_place ( place )
2020-07-01 15:09:54 +00:00
except Exception as i :
2022-04-03 14:07:11 +00:00
err = f " A problem with OpenWeather API: { str ( i ) } "
2020-04-27 11:48:20 +00:00
log ( True , err )
2020-04-13 18:25:48 +00:00
return " Такого города нет, либо данных о погоде нет "
2020-07-01 15:09:54 +00:00
weather_status = weather_request . weather . detailed_status
weather_temp = weather_request . weather . temperature ( ' celsius ' )
weather_humidity = weather_request . weather . humidity
weather_wing = weather_request . weather . wind ( )
return f " Погода в городе { place } <br> { str ( round ( weather_temp [ ' temp ' ] ) ) } °C, { weather_status } <br>Влажность: { weather_humidity } %<br>Ветер: { weather_wing [ ' speed ' ] } м/с "
2020-04-13 18:25:48 +00:00
2020-04-03 21:18:34 +00:00
class VkBot :
2020-08-27 09:43:09 +00:00
""" Bot object, which can answer to user commands \n \n
Keyword arguments : \n
peer_id - - id of conversation with user for answering . Int \n
midnight - - flag of midnight function , which send every midnigtht a message . Defalt : False . Bool \n
awaiting - - strind , what show , which function awaiting input . Defalt : None . Str \n
access - - flag , what set access level to bot functions . Defalt : True . Bool \n
new_post - - flag of notificaton function about new post on group . Defalt : False . Bool \n
admin_mode - - flag of moderating function , which moderate conversation . Defalt : False . Bool
"""
2022-04-03 14:07:11 +00:00
def __init__ ( self , peer_id , midnight = False , awaiting = None , access = True , new_post = False , admin_mode = False , banned = False ) :
2020-08-27 09:43:09 +00:00
""" Initialise the bot object \n \n
Keyword arguments : \n
peer_id - - id of conversation with user for answering . Int \n
midnight - - flag of midnight function , which send every midnigtht a message . Defalt : False . Bool \n
awaiting - - strind , what show , which function awaiting input . Defalt : None . Str \n
access - - flag , what set access level to bot functions . Defalt : True . Bool \n
new_post - - flag of notificaton function about new post on group . Defalt : False . Bool \n
admin_mode - - flag of moderating function , which moderate conversation . Defalt : False . Bool
"""
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { peer_id } ] Created new bot-object " )
2020-04-05 16:24:24 +00:00
self . _CHAT_ID = peer_id
2020-05-21 19:52:49 +00:00
self . _AWAITING_INPUT_MODE = awaiting
2020-08-27 09:43:09 +00:00
self . _ACCESS_TO_ALL = access
2020-05-23 07:48:05 +00:00
self . _MIDNIGHT_EVENT = midnight
self . _NEW_POST = new_post
2020-05-31 12:25:53 +00:00
self . _ADMIN_MODE = admin_mode
2022-04-03 14:07:11 +00:00
self . _BANNED = banned
self . _OWNER = int ( self . _CHAT_ID ) == int ( config . owner_id )
2022-04-03 17:58:55 +00:00
self . _COMMANDS = [ " !image " , " !my_id " , " !h " , " !help " , " !user_id " , " !group_id " , " !weather " , " !wiki " , " !byn " , " !echo " , " !game " ,
" !debug " , " !midnight " , " !access " , " !turnoff " , " !ban " , " !subscribe " , " !random " , " !admin_mode " , " !resist " , " !restore " ,
" !картинка " , " !ид " , " !п " , " !помощь " , " !пользователь " , " !группа " , " !погода " , " !вики " , " !белруб " , " !эхо " , " !игра " ,
" !дебаг " , " !полночь " , " !доступ " , " !выкл " , " !бан " , " !подписаться " , " !рандом " , " !админмод " , " !запретить " , " !разрешить " ]
2020-05-16 19:09:52 +00:00
def __str__ ( self ) :
2022-04-03 14:07:11 +00:00
return f " [BOT_ { str ( self . _CHAT_ID ) } ] a: { str ( self . _ACCESS_TO_ALL ) } , mn: { str ( self . _MIDNIGHT_EVENT ) } , await: { str ( self . _AWAITING_INPUT_MODE ) } , sub: { str ( self . _NEW_POST ) } , adm: { str ( self . _ADMIN_MODE ) } , ban: { str ( self . _BANNED ) } "
2020-05-16 19:09:52 +00:00
def __del__ ( self ) :
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { str ( self . _CHAT_ID ) } ] Bot-object has been deleted " )
2020-04-04 16:07:39 +00:00
2020-05-23 07:48:05 +00:00
def event ( self , event , something = None ) :
2020-05-08 19:30:43 +00:00
if event == " midnight " and self . _MIDNIGHT_EVENT :
2020-05-09 13:25:34 +00:00
current_time = datetime . datetime . fromtimestamp ( time . time ( ) + 10800 )
2020-05-09 21:46:09 +00:00
2020-07-25 18:51:32 +00:00
midnight_text = [ " Миднайт! " , " Полночь! " , " Midnight! " ,
" миднигхт " , " Середина ночи " , " Смена даты! " , " 00:00 " ]
2020-07-02 09:17:36 +00:00
if ( random_image_command ) :
2020-07-25 18:51:32 +00:00
self . send (
f " { random . choice ( midnight_text ) } <br>Наступило { current_time . strftime ( ' %d . % m. % Y ' ) } <br>Картинка дня: " , self . random_image ( ) )
2020-07-02 09:17:36 +00:00
else :
2020-07-25 18:51:32 +00:00
self . send (
f " { random . choice ( midnight_text ) } <br>Наступило { current_time . strftime ( ' %d . % m. % Y ' ) } " )
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Notified about midnight " )
2020-05-23 07:48:05 +00:00
elif event == " post " and self . _NEW_POST :
post = f " wall { str ( something [ ' from_id ' ] ) } _ { str ( something [ ' id ' ] ) } "
2022-04-03 14:07:11 +00:00
self . send ( " Вышел новый пост " , post )
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Notified about new post " )
2020-05-08 19:30:43 +00:00
2020-05-31 12:25:53 +00:00
def get_message ( self , event ) :
message = event . message . text
user_id = event . message . from_id
if self . _ADMIN_MODE :
2020-05-31 12:45:50 +00:00
if message . find ( " @all " ) != - 1 or message . find ( " @online " ) != - 1 or message . find ( " @here " ) != - 1 or message . find ( " @everyone " ) != - 1 or message . find ( " @здесь " ) != - 1 or message . find ( " @все " ) != - 1 :
2020-06-09 19:50:37 +00:00
self . send ( f " [@id { user_id } |Дебил] " )
2020-05-31 12:25:53 +00:00
try :
2020-07-01 15:09:54 +00:00
if int ( user_id ) != int ( config . owner_id ) :
2020-07-25 18:51:32 +00:00
vk . method ( " messages.removeChatUser " , { " chat_id " : int (
self . _CHAT_ID ) - 2000000000 , " member_id " : user_id } )
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] user id { user_id } has been kicked " )
2020-05-31 12:25:53 +00:00
else :
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t kick owner " )
except Exception as e :
2020-07-25 18:51:32 +00:00
log ( True ,
f " [BOT_ { self . _CHAT_ID } ] can ' t kick user id { user_id } - { str ( e ) } " )
2020-07-01 15:09:54 +00:00
with open ( ' bad_words.txt ' , ' r ' , encoding = " utf-8 " , newline = ' ' ) as filter :
2020-06-09 20:49:28 +00:00
flag = False
2020-07-01 15:09:54 +00:00
forcheck = message . lower ( )
2020-06-09 19:50:37 +00:00
for word in filter :
if flag :
2020-07-01 15:09:54 +00:00
if random . randint ( 0 , 5 ) == 1 :
2020-06-09 19:50:37 +00:00
self . send ( " З а м*т извенись" )
break
2020-07-01 15:09:54 +00:00
else :
if forcheck . find ( word [ : - 1 ] ) != - 1 :
flag = True
2020-07-25 18:51:32 +00:00
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 ' } )
2022-04-10 16:13:38 +00:00
if int ( action [ " member_id " ] ) in SPAMMER_LIST :
self . send ( f ' [id { action [ " member_id " ] } |Данный пользователь] находится в антиспам базе. Исключаю... ' )
vk . method ( " messages.removeChatUser " , { " chat_id " : int ( self . _CHAT_ID ) - 2000000000 , " member_id " : action [ " member_id " ] } )
return
2020-07-25 18:51:32 +00:00
self . send ( f ' Добро пожаловать в беседу, { user_info [ 0 ] [ " first_name " ] } { user_info [ 0 ] [ " last_name " ] } ' )
elif action [ ' type ' ] == ' chat_kick_user ' :
2022-04-09 12:57:05 +00:00
pass
# 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"]} покинул беседу')
2022-04-10 16:13:38 +00:00
if event . message . peer_id > 2000000000 and int ( user_id ) in SPAMMER_LIST :
self . send ( f ' [id { user_id } |Данный пользователь] находится в антиспам базе. Исключаю... ' )
vk . method ( " messages.removeChatUser " , { " chat_id " : int ( self . _CHAT_ID ) - 2000000000 , " member_id " : user_id } )
return
2020-05-21 19:52:49 +00:00
if self . _AWAITING_INPUT_MODE :
2020-05-20 16:36:28 +00:00
if message == " Назад " :
2020-05-21 19:52:49 +00:00
self . change_await ( )
self . send ( " Отменено " )
2020-05-20 16:36:28 +00:00
else :
2020-07-01 15:09:54 +00:00
if self . _AWAITING_INPUT_MODE == " echo " :
2020-05-21 19:52:49 +00:00
if message == " !echo off " :
self . send ( " Эхо режим выключен " )
self . change_await ( )
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Out from echo mode " )
2020-05-21 19:52:49 +00:00
else :
self . send ( message )
2020-07-25 18:51:32 +00:00
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] Answer in echo mode " )
2020-04-12 09:47:30 +00:00
else :
2020-07-01 15:09:54 +00:00
if message . lower ( ) == " бот дай денег " :
self . send ( " Иди нахуй " )
2020-05-08 19:30:43 +00:00
respond = { ' attachment ' : None , ' text ' : None }
message = message . split ( ' ' , 1 )
2022-04-03 14:07:11 +00:00
if ( self . _BANNED or db . get_from_users ( int ( event . message . from_id ) ) [ " banned " ] ) and message [ 0 ] in self . _COMMANDS :
respond [ ' text ' ] = " Вам запрещено использовать бота "
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !image " or message [ 0 ] == " !картинка " :
2020-07-02 09:17:36 +00:00
if ( random_image_command ) :
2020-07-01 15:09:54 +00:00
respond [ ' attachment ' ] = self . random_image ( )
else :
respond [ ' text ' ] = errors_array [ " command_off " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !my_id " or message [ 0 ] == " !ид " :
2020-05-21 19:52:49 +00:00
respond [ ' text ' ] = " Ваш ид: " + str ( user_id )
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] in [ " !h " , " !help " , " !п " , " !помощь " ] :
2020-05-25 20:03:42 +00:00
with open ( ' help.txt ' , ' r ' ) as h :
help = h . read ( )
respond [ ' text ' ] = help
h . close ( )
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !user_id " or message [ 0 ] == " !пользователь " :
2020-05-08 19:30:43 +00:00
try :
respond [ ' text ' ] = self . get_info_user ( message [ 1 ] )
except IndexError :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " miss_argument " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !group_id " or message [ 0 ] == " !группа " :
2020-05-08 19:30:43 +00:00
try :
respond [ ' text ' ] = self . get_info_group ( message [ 1 ] )
except IndexError :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " miss_argument " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !weather " or message [ 0 ] == " !погода " :
2020-07-02 09:17:36 +00:00
if ( weather_command ) :
2020-07-01 15:09:54 +00:00
try :
respond [ ' text ' ] = get_weather ( message [ 1 ] )
except IndexError :
respond [ ' text ' ] = errors_array [ " miss_argument " ]
else :
respond [ ' text ' ] = errors_array [ " command_off " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !wiki " or message [ 0 ] == " !вики " :
2020-05-08 19:30:43 +00:00
try :
respond [ ' text ' ] = self . wiki_article ( message [ 1 ] )
except IndexError :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " miss_argument " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !byn " or message [ 0 ] == " !белруб " :
2020-05-08 19:30:43 +00:00
respond [ ' text ' ] = self . exchange_rates ( )
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !echo " or message [ 0 ] == " !эхо " :
2020-05-21 19:52:49 +00:00
respond [ ' text ' ] = " Теперь бот работает в режиме эхо. Чтобы это выключить, введить \" !echo off \" "
self . change_await ( " echo " )
2020-05-24 11:57:02 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Enter in echo mode " )
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !game " or message [ 0 ] == " !игра " :
2020-05-08 19:30:43 +00:00
try :
message [ 1 ] = message [ 1 ] . lower ( )
2020-06-07 20:29:57 +00:00
respond [ ' text ' ] = self . game ( message [ 1 ] , user_id )
2020-05-08 19:30:43 +00:00
except IndexError :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " miss_argument " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !debug " or message [ 0 ] == " !дебаг " :
2020-08-27 09:43:09 +00:00
if self . _ACCESS_TO_ALL or int ( user_id ) == int ( config . owner_id ) :
2020-05-11 18:24:34 +00:00
try :
respond [ ' text ' ] = self . debug ( message [ 1 ] )
except IndexError :
respond [ ' text ' ] = self . debug ( )
else :
2020-05-16 19:09:52 +00:00
respond [ " text " ] = errors_array [ " access " ]
2020-05-08 19:30:43 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !midnight " or message [ 0 ] == " !полночь " :
2020-08-27 09:43:09 +00:00
if self . _ACCESS_TO_ALL or int ( user_id ) == int ( config . owner_id ) :
2020-05-11 18:24:34 +00:00
if self . _MIDNIGHT_EVENT :
2020-08-27 09:43:09 +00:00
self . change_flag ( ' midnight ' , False )
2020-05-11 18:24:34 +00:00
self . send ( " Уведомление о миднайте выключено " )
2020-07-25 18:51:32 +00:00
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] Unsubscribed from event \" Midnight \" " )
2020-05-11 18:24:34 +00:00
else :
2020-08-27 09:43:09 +00:00
self . change_flag ( ' midnight ' , True )
2020-05-11 18:24:34 +00:00
self . send ( " Бот будет уведомлять вас о каждом миднайте " )
2020-07-25 18:51:32 +00:00
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] Subscribed on event \" Midnight \" " )
2020-05-11 18:24:34 +00:00
else :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " access " ]
2020-05-11 18:24:34 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !access " or message [ 0 ] == " !доступ " :
2020-07-01 15:09:54 +00:00
if int ( user_id ) == int ( config . owner_id ) :
2020-05-11 18:24:34 +00:00
try :
2022-04-03 17:58:55 +00:00
if message [ 1 ] == " owner " or message [ 1 ] == " владелец " :
2020-05-11 18:24:34 +00:00
respond [ ' text ' ] = " Теперь некоторыми командами может пользоваться только владелец бота "
2022-04-02 15:47:39 +00:00
self . _ACCESS_TO_ALL = False
2022-04-03 17:58:55 +00:00
elif message [ 1 ] == " all " or message [ 1 ] == " все " :
2020-05-11 18:24:34 +00:00
respond [ ' text ' ] = " Теперь все могут пользоваться всеми командами "
2022-04-02 15:47:39 +00:00
self . _ACCESS_TO_ALL = True
2020-05-11 18:24:34 +00:00
else :
respond [ ' text ' ] = " Некорректный аргумент "
except IndexError :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " miss_argument " ]
2020-07-25 18:51:32 +00:00
log ( False ,
2020-08-27 09:43:09 +00:00
f " [BOT_ { self . _CHAT_ID } ] Access level changed on { self . _ACCESS_TO_ALL } " )
2020-05-08 19:30:43 +00:00
else :
2020-05-16 19:09:52 +00:00
respond [ ' text ' ] = errors_array [ " access " ]
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !turnoff " or message [ 0 ] == " !выкл " :
2020-07-01 15:09:54 +00:00
if self . _OWNER or int ( user_id ) == int ( config . owner_id ) :
2020-05-16 19:09:52 +00:00
self . send ( " Бот выключается " )
2020-05-24 11:57:02 +00:00
exit ( log ( False , " [SHUTDOWN] " ) )
2020-05-16 19:09:52 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !ban " or message [ 0 ] == " !бан " :
2022-04-02 15:47:39 +00:00
if ( self . _OWNER or int ( user_id ) in config . admins or int ( user_id ) == int ( config . owner_id ) ) and self . _ADMIN_MODE and int ( self . _CHAT_ID ) > 2000000000 :
try :
2022-04-03 14:46:17 +00:00
victum = re . search ( r ' id \ d+ ' , message [ 1 ] )
victum = victum [ 0 ] [ 2 : ]
if int ( victum ) != int ( config . owner_id ) :
vk . method ( " messages.removeChatUser " , { " chat_id " : int ( self . _CHAT_ID ) - 2000000000 , " member_id " : victum } )
log ( False , f " [BOT_ { self . _CHAT_ID } ] user { victum } has been kicked " )
2022-04-02 15:47:39 +00:00
else :
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t kick owner " )
except IndexError :
respond [ ' text ' ] = errors_array [ " miss_argument " ]
except Exception as e :
respond [ ' text ' ] = f " Ошибка: { str ( e ) } "
log ( True ,
2022-04-03 14:46:17 +00:00
f " [BOT_ { self . _CHAT_ID } ] can ' t kick user { victum } - { str ( e ) } " )
2022-04-02 15:47:39 +00:00
else :
if int ( self . _CHAT_ID ) < = 2000000000 :
2022-04-09 12:57:05 +00:00
respond [ ' text ' ] = errors_array [ " not_a_multichat " ]
2022-04-02 15:47:39 +00:00
if not self . _ADMIN_MODE :
respond [ " text " ] = " Бот не в режиме модерирования "
else :
respond [ " text " ] = errors_array [ " access " ]
2020-07-25 18:51:32 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !subscribe " or message [ 0 ] == " !подписаться " :
2020-08-27 09:43:09 +00:00
if self . _ACCESS_TO_ALL or int ( user_id ) == int ( config . owner_id ) :
2020-05-23 07:48:05 +00:00
if self . _NEW_POST :
2020-08-27 09:43:09 +00:00
self . change_flag ( ' new_post ' , False )
2020-05-23 07:48:05 +00:00
self . send ( " Уведомление о новом посте выключено " )
2020-07-25 18:51:32 +00:00
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] Unsubscribed from new posts " )
2020-05-23 07:48:05 +00:00
else :
2020-08-27 09:43:09 +00:00
self . change_flag ( ' new_post ' , True )
2020-07-25 18:51:32 +00:00
self . send (
" Бот будет уведомлять вас о каждом новом посте " )
log ( False ,
f " [BOT_ { self . _CHAT_ID } ] Subscribed on new posts " )
2020-05-23 07:48:05 +00:00
else :
respond [ ' text ' ] = errors_array [ " access " ]
2020-07-25 18:51:32 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !random " or message [ 0 ] == " !рандом " :
2020-05-27 15:26:50 +00:00
try :
message [ 1 ] = message [ 1 ] . split ( ' ' , 1 )
try :
2020-07-25 18:51:32 +00:00
respond [ ' text ' ] = self . random_number (
int ( message [ 1 ] [ 0 ] ) , int ( message [ 1 ] [ 1 ] ) )
2020-05-27 15:26:50 +00:00
except :
2020-07-25 18:51:32 +00:00
respond [ ' text ' ] = self . random_number (
0 , int ( message [ 1 ] [ 0 ] ) )
2020-05-27 15:26:50 +00:00
except :
respond [ ' text ' ] = self . random_number ( 0 , 10 )
2022-04-02 15:47:39 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !admin_mode " or message [ 0 ] == " !админмод " :
2020-05-31 12:25:53 +00:00
if int ( self . _CHAT_ID ) < = 2000000000 :
2022-04-09 12:57:05 +00:00
respond [ ' text ' ] = errors_array [ " not_a_multichat " ]
2020-07-01 15:09:54 +00:00
elif int ( user_id ) != int ( config . owner_id ) :
2020-05-31 12:25:53 +00:00
respond [ ' text ' ] = errors_array [ " access " ]
else :
try :
2020-07-25 18:51:32 +00:00
vk . method ( " messages.getConversationMembers " , {
" peer_id " : int ( self . _CHAT_ID ) , " group_id " : config . group_id } )
2020-05-31 12:25:53 +00:00
if self . _ADMIN_MODE :
respond [ " text " ] = " Режим модерирования выключен "
2020-08-27 09:43:09 +00:00
self . change_flag ( ' admin_mode ' , False )
2022-04-10 10:23:35 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Admin mode: { self . _ADMIN_MODE } " )
2020-05-31 12:25:53 +00:00
else :
respond [ " text " ] = " Режим модерирования включён "
2020-08-27 09:43:09 +00:00
self . change_flag ( ' admin_mode ' , True )
2022-04-10 10:23:35 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] Admin mode: { self . _ADMIN_MODE } " )
except Exception as e :
respond [ " text " ] = f " Ошибка: { str ( e ) } "
2022-04-02 15:47:39 +00:00
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !resist " or message [ 0 ] == " !запретить " :
2022-04-03 14:07:11 +00:00
if ( self . _OWNER or int ( user_id ) in config . admins or int ( user_id ) == int ( config . owner_id ) ) :
2022-04-02 15:47:39 +00:00
try :
2022-04-03 14:46:17 +00:00
victum = re . search ( r ' id \ d+ ' , message [ 1 ] )
victum = victum [ 0 ] [ 2 : ]
if int ( victum ) != int ( config . owner_id ) :
if int ( victum ) not in bot :
create_new_bot_object ( int ( victum ) )
2022-04-03 17:58:55 +00:00
db . set_new_user ( int ( victum ) )
2022-04-03 14:46:17 +00:00
if not db . get_from_users ( int ( victum ) ) [ " banned " ] :
bot [ int ( victum ) ] . change_flag ( " banned " , True )
2022-04-03 14:07:11 +00:00
respond [ " text " ] = " Теперь он не сможет воспользоваться ботом "
2022-04-03 14:46:17 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] user { victum } has been resisted " )
2022-04-03 14:07:11 +00:00
else :
respond [ " text " ] = " Он и так не может пользоваться ботом, вы уже делали это "
2022-04-02 15:47:39 +00:00
else :
2022-04-03 14:07:11 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t resist owner " )
2022-04-02 15:47:39 +00:00
except IndexError :
respond [ ' text ' ] = errors_array [ " miss_argument " ]
except Exception as e :
respond [ ' text ' ] = f " Ошибка: { str ( e ) } "
log ( True ,
2022-04-03 14:46:17 +00:00
f " [BOT_ { self . _CHAT_ID } ] can ' t resist user { victum } - { str ( e ) } " )
2022-04-02 15:47:39 +00:00
else :
2022-04-03 14:07:11 +00:00
respond [ " text " ] = errors_array [ " access " ]
2022-04-03 17:58:55 +00:00
elif message [ 0 ] == " !restore " or message [ 0 ] == " !разрешить " :
2022-04-03 14:07:11 +00:00
if ( self . _OWNER or int ( user_id ) in config . admins or int ( user_id ) == int ( config . owner_id ) ) :
try :
victum = re . search ( r ' id \ d+ ' , message [ 1 ] )
2022-04-03 14:46:17 +00:00
victum = victum [ 0 ] [ 2 : ]
if int ( victum ) not in bot :
create_new_bot_object ( int ( victum ) )
2022-04-03 17:58:55 +00:00
db . set_new_user ( int ( victum ) )
2022-04-03 14:46:17 +00:00
if int ( victum ) != int ( config . owner_id ) :
if db . get_from_users ( int ( victum ) ) [ " banned " ] :
bot [ int ( victum ) ] . change_flag ( " banned " , False )
2022-04-03 14:07:11 +00:00
respond [ " text " ] = " Теперь он снова сможет воспользоваться ботом "
2022-04-03 14:46:17 +00:00
log ( False , f " [BOT_ { self . _CHAT_ID } ] user { victum } has been restored " )
2022-04-03 14:07:11 +00:00
else :
2022-04-03 14:46:17 +00:00
respond [ " text " ] = " Он и так может пользоваться ботом "
2022-04-03 14:07:11 +00:00
else :
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t restore owner " )
except IndexError :
respond [ ' text ' ] = errors_array [ " miss_argument " ]
except Exception as e :
respond [ ' text ' ] = f " Ошибка: { str ( e ) } "
log ( True ,
2022-04-03 14:46:17 +00:00
f " [BOT_ { self . _CHAT_ID } ] can ' t restore user { victum } - { str ( e ) } " )
2022-04-03 14:07:11 +00:00
else :
respond [ " text " ] = errors_array [ " access " ]
2020-07-25 18:51:32 +00:00
2022-04-09 12:57:05 +00:00
elif message [ 0 ] == " !spammer " or message [ 0 ] == " !спаммер " :
if int ( self . _CHAT_ID ) < = 2000000000 :
respond [ ' text ' ] = errors_array [ " not_a_multichat " ]
elif ( self . _OWNER or int ( user_id ) in config . admins or int ( user_id ) == int ( config . owner_id ) ) :
try :
message = message [ 1 ] . split ( ' ' , 1 )
victum = re . search ( r ' id \ d+ ' , message [ 1 ] )
victum = victum [ 0 ] [ 2 : ]
2022-04-10 16:13:38 +00:00
if message [ 0 ] == " add " or message [ 0 ] == " добавить " :
2022-04-09 12:57:05 +00:00
if int ( victum ) != int ( config . owner_id ) :
2022-04-10 16:13:38 +00:00
if int ( victum ) not in SPAMMER_LIST :
db . add_spammer ( int ( victum ) )
2022-04-09 12:57:05 +00:00
respond [ " text " ] = " Теперь он считается спамером "
log ( False , f " [BOT_ { self . _CHAT_ID } ] user { victum } added to spammer list " )
else :
respond [ " text " ] = " Он и так уже в этой базе "
else :
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t add to spammer list owner " )
elif message [ 0 ] == " remove " or message [ 0 ] == " удалить " :
if int ( victum ) != int ( config . owner_id ) :
2022-04-10 16:13:38 +00:00
if int ( victum ) in SPAMMER_LIST :
db . remove_spammer ( int ( victum ) )
2022-04-09 12:57:05 +00:00
respond [ " text " ] = " Теперь он не считается спамером "
log ( False , f " [BOT_ { self . _CHAT_ID } ] user { victum } removed to spammer list " )
else :
respond [ " text " ] = " Е г о нет в этой базе"
else :
log ( False , f " [BOT_ { self . _CHAT_ID } ] can ' t restore owner " )
except IndexError :
respond [ ' text ' ] = errors_array [ " miss_argument " ]
except Exception as e :
respond [ ' text ' ] = f " Ошибка: { str ( e ) } "
log ( True , f " [BOT_ { self . _CHAT_ID } ] spammer action { message [ 1 ] } with { victum } - { str ( e ) } " )
2020-05-08 19:30:43 +00:00
if respond [ ' text ' ] or respond [ ' attachment ' ] :
self . send ( respond [ ' text ' ] , respond [ ' attachment ' ] )
def debug ( self , arg = None ) :
2022-04-03 17:58:55 +00:00
if arg in [ " log " , " лог " ] :
if not self . _OWNER :
2020-05-16 19:09:52 +00:00
return errors_array [ " access " ]
2022-04-03 17:58:55 +00:00
with open ( log_path , ' r ' ) as f :
log = list ( deque ( f , 10 ) )
text_log = " <br>Последние 10 строк из лога:<br> "
for item in log :
text_log + = item
f . close ( )
return text_log
elif arg in [ " bots " , " боты " ] :
if not self . _OWNER :
2020-05-16 19:09:52 +00:00
return errors_array [ " access " ]
2022-04-03 17:58:55 +00:00
answer = " Обьекты бота: "
for i in bot :
answer + = f " <br> { str ( bot [ i ] ) } "
return answer
elif arg in [ " game " , " игра " ] :
2020-06-09 10:19:10 +00:00
stats = db . get_game_stat ( )
if len ( stats ) > 0 :
answer = " Статистика игроков в !game "
for i in stats :
try :
2020-07-25 18:51:32 +00:00
winrate = ( i [ ' game_wins ' ] / ( i [ ' game_wins ' ] +
i [ ' game_defeats ' ] + i [ ' game_draws ' ] ) ) * 100
2020-06-09 10:19:10 +00:00
except ZeroDivisionError :
winrate = 0
2020-06-09 10:30:51 +00:00
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 ) } % побед "
2020-06-09 10:19:10 +00:00
else :
answer = " Никто не пользуется !game "
return answer
2020-05-08 19:30:43 +00:00
else :
up_time = time . time ( ) - debug_array [ ' start_time ' ]
time_d = int ( up_time ) / ( 3600 * 24 )
time_h = int ( up_time ) / 3600 - int ( time_d ) * 24
2020-07-25 18:51:32 +00:00
time_min = int ( up_time ) / 60 - int ( time_h ) * \
60 - int ( time_d ) * 24 * 60
time_sec = int ( up_time ) - int ( time_min ) * 60 - \
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 ' ] )
2022-04-03 17:58:55 +00:00
answer = (
(
(
(
(
(
(
(
f " UPTIME: { str_up_time } <br>Прослушано сообщений: "
+ str ( debug_array [ ' messages_get ' ] )
)
+ " <br>Отправлено сообщений: "
)
+ str ( debug_array [ ' messages_answered ' ] )
+ " <br>Ошибок в работе: "
)
+ str ( debug_array [ ' logger_warnings ' ] )
+ " , из них:<br> •Беды с В К : "
)
+ str ( debug_array [ ' vk_warnings ' ] )
+ " <br> •Беды с БД: "
)
+ str ( debug_array [ ' db_warnings ' ] )
+ " <br> •Беды с ботом: "
)
+ str ( debug_array [ ' bot_warnings ' ] )
+ " <br>Обьектов бота: "
)
+ str ( len ( bot ) )
+ " <br>Запуск бота по часам сервера: "
) + datetime_time . strftime ( ' %d . % m. % Y % H: % M: % S UTC ' )
2020-05-08 19:30:43 +00:00
return answer
2020-05-04 20:26:22 +00:00
2020-06-07 20:29:57 +00:00
def game ( self , thing , user_id ) :
2022-04-10 16:13:38 +00:00
d = db . get_from_users ( user_id )
2020-04-13 18:25:48 +00:00
if thing == " статистика " :
2020-06-07 20:29:57 +00:00
try :
2020-07-25 18:51:32 +00:00
winrate = ( d [ ' game_wins ' ] / ( d [ ' game_wins ' ] +
d [ ' game_defeats ' ] + d [ ' game_draws ' ] ) ) * 100
2020-06-07 20:29:57 +00:00
except ZeroDivisionError :
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 ) } % "
2020-04-13 18:25:48 +00:00
elif thing == " камень " or thing == " ножницы " or thing == " бумага " :
things = [ " камень " , " ножницы " , " бумага " ]
bot_thing = random . choice ( things )
if thing == " камень " and bot_thing == " ножницы " :
result = 2
elif thing == " ножницы " and bot_thing == " бумага " :
result = 2
elif thing == " бумага " and bot_thing == " камень " :
result = 2
elif thing == " ножницы " and bot_thing == " камень " :
result = 1
elif thing == " бумага " and bot_thing == " ножницы " :
result = 1
elif thing == " камень " and bot_thing == " бумага " :
result = 2
elif thing == " камень " and bot_thing == " камень " :
result = 0
elif thing == " ножницы " and bot_thing == " ножницы " :
result = 0
elif thing == " бумага " and bot_thing == " бумага " :
result = 0
if result == 2 :
response = f " Камень, ножницы, бумага<br> { thing } vs. { bot_thing } <br>Вы выиграли! "
2020-06-07 20:29:57 +00:00
db . update_user ( user_id , " game_wins " , d [ ' game_wins ' ] + 1 )
2020-04-13 18:25:48 +00:00
elif result == 1 :
response = f " Камень, ножницы, бумага<br> { thing } vs. { bot_thing } <br>Вы проиграли! "
2020-06-07 20:29:57 +00:00
db . update_user ( user_id , " game_defeats " , d [ ' game_defeats ' ] + 1 )
2020-04-13 18:25:48 +00:00
elif result == 0 :
response = f " Камень, ножницы, бумага<br> { thing } vs. { bot_thing } <br>Ничья! "
2020-06-07 20:29:57 +00:00
db . update_user ( user_id , " game_draws " , d [ ' game_draws ' ] + 1 )
2020-04-13 18:25:48 +00:00
2020-06-07 20:29:57 +00:00
return response
2020-04-13 18:25:48 +00:00
else :
return " Неверный аргумент<br>Использование команды:<br>!game *камень/ножницы/бумага/статистика* "
2020-04-05 14:41:33 +00:00
2020-04-04 16:07:39 +00:00
def get_info_user ( self , id ) :
try :
2020-07-25 18:51:32 +00:00
user_info = vk . method (
' users.get ' , { ' user_ids ' : id , ' fields ' : ' verified,last_seen,sex ' } )
2020-04-04 16:07:39 +00:00
except vk_api . exceptions . ApiError as lol :
2020-05-24 11:57:02 +00:00
err = " Method users.get: " + str ( lol )
2020-04-27 11:48:20 +00:00
log ( True , err )
2020-04-13 18:25:48 +00:00
return " Пользователь не найден<br> " + str ( lol )
2020-04-15 10:45:05 +00:00
if " deactivated " in user_info [ 0 ] :
if user_info [ 0 ] [ ' deactivated ' ] == ' banned ' :
return user_info [ 0 ] [ ' first_name ' ] + " " + user_info [ 0 ] [ ' last_name ' ] + " забанен "
elif user_info [ 0 ] [ ' deactivated ' ] == ' deleted ' :
return " Профиль был удалён "
2020-04-15 10:36:12 +00:00
2020-04-04 16:07:39 +00:00
if user_info [ 0 ] [ ' is_closed ' ] :
is_closed = " Да "
else :
is_closed = " Нет "
if user_info [ 0 ] [ ' sex ' ] == 1 :
sex = " Женский "
elif user_info [ 0 ] [ ' sex ' ] == 2 :
sex = " Мужской "
else :
sex = " Неизвестно "
if user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 1 :
platform = " m.vk.com "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 2 :
platform = " iPhone "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 3 :
platform = " iPad "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 4 :
platform = " Android "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 5 :
platform = " Windows Phone "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 6 :
platform = " Windows 10 "
elif user_info [ 0 ] [ ' last_seen ' ] [ ' platform ' ] == 7 :
platform = " vk.com "
else :
platform = " тип платформы неизвестен "
2020-07-25 18:51:32 +00:00
time = datetime . datetime . fromtimestamp (
user_info [ 0 ] [ ' last_seen ' ] [ ' time ' ] )
2020-04-04 16:07:39 +00:00
2020-04-27 11:48:20 +00:00
answer = user_info [ 0 ] [ ' first_name ' ] + " " + user_info [ 0 ] [ ' last_name ' ] + " <br>Е г о ид: " + \
2020-07-25 18:51:32 +00:00
str ( user_info [ 0 ] [ ' id ' ] ) + " <br>Профиль закрыт: " + is_closed + " <br>Пол: " + sex \
+ " <br>Последний онлайн: " + \
time . strftime ( ' %d . % m. % Y в % H: % M: % S ' ) + " ( " + platform + " ) "
2020-04-04 16:07:39 +00:00
return answer
def get_info_group ( self , id ) :
try :
2020-07-25 18:51:32 +00:00
group_info = vk . method (
' groups.getById ' , { ' group_id ' : id , ' fields ' : ' description,members_count ' } )
2020-04-04 16:07:39 +00:00
except vk_api . exceptions . ApiError as lol :
2020-05-24 11:57:02 +00:00
err = " Method groups.getById: " + str ( lol )
2020-04-27 11:48:20 +00:00
log ( True , err )
2020-04-13 18:25:48 +00:00
return " Группа не найдена<br> " + str ( lol )
2020-04-04 16:07:39 +00:00
if group_info [ 0 ] [ ' description ' ] == " " :
description = " Отсутствует "
else :
description = group_info [ 0 ] [ ' description ' ]
2020-04-13 18:25:48 +00:00
answer = group_info [ 0 ] [ ' name ' ] + " <br>Описание: " + description + " <br>Ид группы: " + str (
group_info [ 0 ] [ ' id ' ] ) + " <br>Подписчиков: " + str ( group_info [ 0 ] [ ' members_count ' ] )
2020-04-04 16:07:39 +00:00
return answer
2020-04-03 19:56:57 +00:00
2020-04-05 22:46:06 +00:00
def random_image ( self ) :
2020-07-01 15:09:54 +00:00
group = " - " + str ( config . group_id )
2020-07-02 09:17:36 +00:00
random_images_query = vk_mda . method ( ' photos.get ' ,
2020-07-01 15:09:54 +00:00
{ ' owner_id ' : group , ' album_id ' : config . album_for_command , ' count ' : 1000 } )
2020-07-25 18:51:32 +00:00
info = " Method photos.get: " + \
str ( random_images_query [ ' count ' ] ) + " photos received "
2020-04-27 11:48:20 +00:00
log ( False , info )
2020-04-06 10:26:50 +00:00
random_number = random . randrange ( random_images_query [ ' count ' ] )
2020-04-13 18:25:48 +00:00
return " photo " + str ( random_images_query [ ' items ' ] [ random_number ] [ ' owner_id ' ] ) + " _ " + str (
random_images_query [ ' items ' ] [ random_number ] [ ' id ' ] )
2020-04-05 22:46:06 +00:00
2020-04-06 10:26:50 +00:00
def wiki_article ( self , search ) :
w = wiki . Wikipedia ( ' ru ' )
page = w . page ( search )
if page . exists ( ) :
2020-04-13 18:25:48 +00:00
answer = page . title + " <br> " + page . summary
2020-04-06 10:26:50 +00:00
else :
answer = " Такой статьи не существует "
return answer
2020-05-08 19:30:43 +00:00
def exchange_rates ( self ) :
2020-04-10 16:06:15 +00:00
try :
2020-04-13 18:25:48 +00:00
rates_USD = json . loads (
requests . get ( " https://www.nbrb.by/api/exrates/rates/145?periodicity=0 " , timeout = 10 ) . text )
rates_EUR = json . loads (
requests . get ( " https://www.nbrb.by/api/exrates/rates/292?periodicity=0 " , timeout = 10 ) . text )
rates_RUB = json . loads (
requests . get ( " https://www.nbrb.by/api/exrates/rates/298?periodicity=0 " , timeout = 10 ) . text )
return " Текущий курс валют по данным НБ РБ:<br> " + rates_USD [ ' Cur_Name ' ] + " : " + str (
rates_USD [ ' Cur_Scale ' ] ) + " " + rates_USD [ ' Cur_Abbreviation ' ] + " = " + str (
rates_USD [ ' Cur_OfficialRate ' ] ) + " BYN<br> " + rates_EUR [ ' Cur_Name ' ] + " : " + str (
rates_EUR [ ' Cur_Scale ' ] ) + " " + rates_EUR [ ' Cur_Abbreviation ' ] + " = " + str (
rates_EUR [ ' Cur_OfficialRate ' ] ) + " BYN<br> " + " Российский рубль " + " : " + str (
rates_RUB [ ' Cur_Scale ' ] ) + " " + rates_RUB [ ' Cur_Abbreviation ' ] + " = " + str (
rates_RUB [ ' Cur_OfficialRate ' ] ) + " BYN "
2020-04-10 16:06:15 +00:00
except Exception as mda :
2020-05-24 11:57:02 +00:00
err = " НБ РБ API: " + str ( mda )
2020-04-27 11:48:20 +00:00
log ( True , err )
2020-04-13 18:25:48 +00:00
return " Невозможно получить данные из НБ РБ: " + str ( mda )
2020-04-10 16:06:15 +00:00
2020-05-27 15:26:50 +00:00
def random_number ( self , lower , higher ) :
r = random . randint ( lower , higher )
return f " Рандомное число от { lower } до { higher } :<br> { r } "
2020-05-21 19:52:49 +00:00
def change_await ( self , awaiting = None ) :
2020-08-27 09:43:09 +00:00
""" Change the awaiting input state
Keyword arguments :
awaiting - - name of function , what awaiting input from user . Defalt : None . String
"""
2020-05-21 19:52:49 +00:00
self . _AWAITING_INPUT_MODE = awaiting
2020-06-07 20:29:57 +00:00
db . update_user ( self . _CHAT_ID , " awaiting " , self . _AWAITING_INPUT_MODE )
2020-07-25 18:51:32 +00:00
2020-08-27 09:43:09 +00:00
def change_flag ( self , flag , value ) :
""" Change ' flag ' to ' value '
Keyword arguments :
flag - - name of flag . Can be ' access ' , ' new_post ' , ' midnight ' , ' admin_mode ' . String
value - - set the flag state . Bool
"""
if flag == ' access ' :
self . _ACCESS_TO_ALL = value
db . update_user ( self . _CHAT_ID , " access " , self . _ACCESS_TO_ALL )
elif flag == ' new_post ' :
self . _NEW_POST = value
db . update_user ( self . _CHAT_ID , " new_post " , self . _NEW_POST )
elif flag == ' midnight ' :
self . _MIDNIGHT_EVENT = value
db . update_user ( self . _CHAT_ID , " midnight " , self . _MIDNIGHT_EVENT )
elif flag == ' admin_mode ' :
self . _ADMIN_MODE = value
db . update_user ( self . _CHAT_ID , " admin_mode " , self . _ADMIN_MODE )
2022-04-03 14:07:11 +00:00
elif flag == " banned " :
self . _BANNED = value
db . update_user ( self . _CHAT_ID , " banned " , self . _BANNED )
2020-05-23 07:48:05 +00:00
2020-05-08 19:30:43 +00:00
def send ( self , message = None , attachment = None ) :
2020-08-27 09:43:09 +00:00
""" Send to user something.
Keyword arguments :
message - - text of message . string
attachment - - name of attachment . string
"""
2020-05-24 11:57:02 +00:00
try :
2020-07-25 18:51:32 +00:00
random_id = random . randint ( - 9223372036854775808 ,
9223372036854775807 )
2020-07-02 09:17:36 +00:00
message = vk . method ( ' messages.send ' ,
2020-05-24 11:57:02 +00:00
{ ' peer_id ' : self . _CHAT_ID , ' message ' : message , ' random_id ' : random_id ,
2020-07-25 18:51:32 +00:00
' attachment ' : attachment } )
log ( False ,
f ' [BOT_ { self . _CHAT_ID } ] id: { message } , random_id: { random_id } ' )
2020-05-24 11:57:02 +00:00
debug_array [ ' messages_answered ' ] + = 1
except Exception as e :
log ( True , f ' Failed to send message: { str ( e ) } ' )