Example #1
0
def testtask():
    VkApi.method(
        'messages.send', {
            'user_id':
            315757448,
            'message':
            'ТЕСТОВЫЙ СКРИПТ ВЫПОЛНИЛСЯ\nне обращай внимания на это сообщение'
        })
Example #2
0
    def __init__(self, setting_filename):
        dir_path = os.path.dirname(os.path.realpath(__file__))

        self.cfg = Config(os.path.join(dir_path, setting_filename))
        self.logger = Log.get_logger(os.path.join(dir_path, self.cfg.LOG_FILE))
        self.cfg.verify_config()
        self.botAPI = VkApi(self.cfg)
        self.uManager = UserManager(os.path.join(dir_path, self.cfg.USERS_FILE))
        self.logger.info("\nVKBot started")
Example #3
0
def on_online(event: MySignalEvent):
    global online_thread
    global stop_thread

    logger.info("Установлен онлайн")

    stop_thread = False
    token = event.db.online_token
    if token == None:
        utils.new_message(
            event.api,
            event.chat.peer_id,
            message=
            f"❗ Токен не установлен.\n Устанувить можно в админ-панеле https://{event.db.host}"
        )
        return "ok"
    if online_thread != None and online_thread.is_alive():
        utils.new_message(event.api,
                          event.chat.peer_id,
                          message="✅ Вечный онлайн  и так запущен")
        return "ok"
    api_ = VkApi(token)
    online_thread = Thread(target=online_th, args=(api_, lambda: stop_thread))
    online_thread.setDaemon(True)
    online_thread.setName('Online Thread')
    online_thread.start()
    utils.new_message(event.api,
                      event.chat.peer_id,
                      message="✅ Вечный онлайн запущен")
    return "ok"
Example #4
0
def set_online(v):
    global stop_thread
    db = DB()
    stop_thread = v
    if v == False:
        api = VkApi(db.online_token)
        afa_thread = Thread(target=online_th, args=(api, lambda: stop_thread))
        afa_thread.setDaemon(True)
        afa_thread.setName('Online Thread')
        afa_thread.start()
Example #5
0
def set_afa(v):
    global stop_thread
    global afa_thread

    db = DB()
    stop_thread = v
    if v == False:
        api = VkApi(db.access_token)
        afa_thread = Thread(target=afa_th, args=(api, lambda: stop_thread))
        afa_thread.setDaemon(True)
        afa_thread.setName('AFA Thread')
        afa_thread.start()
Example #6
0
    def check_token(t: str) -> str:

        if t == "" or t == None:
            return "Токен не задан"

        api = VkApi(t)

        user = api('users.get')

        if type(user) != list:
            return "ошибка | токен поврежден"
        user = user[0]

        return f"ОК, [id{user['id']}|{user['first_name']} {user['last_name']}]"
Example #7
0
    def __init__(self, request: Request, data_: dict = None):

        if request != None and request.data == b'':
            self.user_id = None
            self.message = self.msg = None
            self.object = self.obj = None
            self.secret = None
            self.method = Methods.PING
        else:
            if data_ == None:
                _data = json.loads(request.data)
            else:
                _data = data_
            self.user_id = _data.get('user_id', None)
            self.secret = _data.get('secret', None)
            self.object = self.obj = _data.get('object', {})
            self.message = self.msg = _data.get('message', {})

            self.db = DB()
            self.api = VkApi(self.db.access_token, raise_excepts=True)
            self.method = Methods(_data.get('method', 'ping'))
            self.attachments = []

            if self.method in [
                    Methods.BIND_CHAT, Methods.SEND_SIGNAL,
                    Methods.SEND_MY_SIGNAL, Methods.SUBSCRIBE_SIGNALS,
                    Methods.TO_GROUP
            ]:
                self.set_chat()
            elif self.method == Methods.PING:
                pass
            else:
                self.chat = Chat(self.db.chats[self.obj['chat']],
                                 self.obj['chat'], self.obj['chat'])

                self.message = self.msg = None
                self.reply_message = None

        logger.info(self.__str__().replace('\n', ' '))
Example #8
0
class VKBotApplication:
    cfg = None
    logger = None
    botAPI = None
    uManager = None

    def __init__(self, setting_filename):
        dir_path = os.path.dirname(os.path.realpath(__file__))

        self.cfg = Config(os.path.join(dir_path, setting_filename))
        self.logger = Log.get_logger(os.path.join(dir_path, self.cfg.LOG_FILE))
        self.cfg.verify_config()
        self.botAPI = VkApi(self.cfg)
        self.uManager = UserManager(os.path.join(dir_path, self.cfg.USERS_FILE))
        self.logger.info("\nVKBot started")

    def get_id_that_members(self, vk_id_string):
        vk_id_arr = vk_id_string.split(",")
        result_id = []
        members = self.get_members()
        for vk_id in vk_id_arr:
            if int(vk_id) not in members:
                self.logger.info("skip user {0} because he is not group member".format(vk_id))
            else:
                result_id.append(int(vk_id))
        return result_id


    def get_members(self):
        self.logger.info("getting_members")
        r = self.botAPI.get_members_list()
        # count = int(r['response']['count'])
        member_user_ids = r['response']['items']

        # check if users in memory
        for user_id in member_user_ids:
            # new user detected
            if not self.uManager.has_user(user_id):
                # TODO try/catch
                # TODO multiple list
                # TODO check if user leave group
                user_info = self.get_user_info(user_id)
                first_name = user_info['response'][0]['first_name'].encode("utf-8")
                last_name = user_info['response'][0]['last_name'].encode("utf-8")
                self.uManager.add_user(user_id, -1, 0, "{0} {1}".format(first_name, last_name), "")

        self.logger.info("members are {0}".format(member_user_ids))
        return member_user_ids

    def check_allowed_receive_message(self, member_user_ids):
        self.logger.info("Check allowed receive message")
        allowed_members = []
        for member_user_id in member_user_ids:
            r = self.botAPI.is_messages_from_group_allowed(member_user_id)
            if r['response']['is_allowed'] == 1:
                self.uManager.set_user_property(member_user_id, "allow", 1)
                allowed_members.append(member_user_id)
            else:
                self.uManager.set_user_property(member_user_id, "allow", 0)
                time = self.uManager.get_user_property(member_user_id, "time")
                if time is None or time == "":
                    # try to send message first time anyway
                    allowed_members.append(member_user_id)

        self.logger.info("Allowed members are : {0}".format(allowed_members))
        return allowed_members

    def skip_blocked_users(self, user_ids):
        non_blocked = []
        for user_id in user_ids:
            if self.uManager.get_user_property(user_id, "blocked") == 0:
                non_blocked.append(user_id)

        self.logger.info("Non blocked users : {0}".format(non_blocked))
        return non_blocked

    def get_user_info(self, user_id):
        self.logger.info("Get user {0} info".format(user_id))
        r = self.botAPI.get_user_info(user_id)
        return r

    def send_message(self, message, user_ids):
        cap = 100

        if not user_ids:
            self.logger.info("no user to send message")
            return

        if message == "" or not message:
            self.logger.info("no message to send")
            return

        msg = message.decode('string_escape')

        batch_users = []
        if len(user_ids) > 1:
            for user_id in user_ids:
                batch_users.append(user_id)
                if len(batch_users) == cap:
                    user_ids_str = ','.join(str(e) for e in batch_users)
                    self.botAPI.send_messages(msg, user_ids_str)
                    batch_users = []

            if len(batch_users) > 0:
                user_ids_str = ','.join(str(e) for e in batch_users)
                self.botAPI.send_messages(msg, user_ids_str)
        else:
            self.botAPI.send_message(msg, user_ids[0])

        time = datetime.datetime.now().strftime("%d %B %Y %I:%M%p")
        for user_id in user_ids:
            self.uManager.set_user_property(user_id, "time", time)

        self.uManager.save_users()
Example #9
0
from vkapi import VkApi
from autocomplete import autocomplete
from utils import getch, read_message, read_config
import time


if __name__ == "__main__":
    while True:
        token = read_config()['access_token']
        api = VkApi(token)
        print('Dialog list')
        for dialog in api.get_dialogs():
            dialog.print()
        dialog_title = autocomplete('Select dialog:', api.dialog_names())
        dialog = api.dialog_history(dialog_title)
        dialog.print()
        message = read_message('Message (press [Enter] to send, [Backspace] to back, [ESC] to exit):')
        if message:
            api.send_dialog(dialog, message)
        print('Wait to refresh dialogs...')
        time.sleep(3)

Example #10
0

def downloadPhotos(outDir, urls):
    if not os.path.exists(outDir):
        os.makedirs(outDir)

    for photoUrl in urls:
        file = '%s/%s' % (outDir, photoUrl.rsplit('/', 1)[-1])
        if not os.path.exists(file):
            print('        ', photoUrl)
            urllib.request.urlretrieve(photoUrl, file)


#logging.basicConfig(level=logging.DEBUG)

api = VkApi(config.ACCESS_TOKEN)
users = api.getUsersByUids(config.UIDS)
for user in users:
    userId = user['id']
    userName = '******' % (user['first_name'], user['last_name'])
    albums = api.getUserAlbums(userId)

    print('%s (%d) - %d albums' % (userName, userId, len(albums)))

    for album in albums:
        outDir = '%s/%s (%d)/%s' % (config.OUT, userName, userId,
                                    album['title'])

        print('    "%s" - %d photos' % (album['title'], album['size']))

        photoUrls = getPhotoUrls(api.getPhotosFromAlbum(album))
Example #11
0

if args['script'] is None:
    availableScripts()

if args['script']:
    if not args['script'].replace('_', '').isalpha():
        print('Invalid script')
        availableScripts()
    log.script_name = args['script'].lower()
    try:
        main = importlib.import_module('scripts.' + args['script'].lower()).main
    except ImportError:
        print('Invalid script')
        availableScripts()
    v = VkApi(login, password, timeout=config.get('vkbot.default_timeout', 'i'), token_file=accounts.getFile('token.txt'),
              log_file=accounts.getFile('inf.log') if args['logging'] else '', captcha_handler=captcha.CaptchaHandler())
    v.initLongpoll()
    main(v, args['args'])
    v.sync()
    sys.exit()

import fcntl

pid_file = accounts.getFile('inf.pid')
lock_file = accounts.getFile('inf.lock')
fp = open(lock_file, 'w')
single = False
for attempt in range(100):
    try:
        fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except IOError:
Example #12
0
    if not args['script'].replace('_', '').isalpha():
        print('Invalid script')
        availableScripts()
        sys.exit()
    log.script_name = args['script'].lower()
    try:
        script = importlib.import_module('scripts.' + args['script'].lower())
        main = script.main
        need_auth = getattr(script, 'need_auth', False)
    except ImportError:
        print('Invalid script')
        availableScripts()
        sys.exit()
    v = VkApi(login,
              password,
              timeout=config.get('vkbot_timing.default_timeout', 'i'),
              token_file=accounts.getFile('token.txt'),
              log_file=accounts.getFile('inf.log') if args['logging'] else '',
              captcha_handler=createCaptchaHandler())
    if need_auth:
        v.initLongpoll()
    main(v, args['args'])
    v.sync()
    sys.exit()

import fcntl

pid_file = accounts.getFile('inf.pid')
lock_file = accounts.getFile('inf.lock')
fp = open(lock_file, 'w')
try:
    fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
    return photoUrls

def downloadPhotos(outDir, urls):
    if not os.path.exists(outDir):
        os.makedirs(outDir)
        
    for photoUrl in urls:
        file = '%s/%s' % (outDir, photoUrl.rsplit('/', 1)[-1])
        if not os.path.exists(file):
            print('        ',  photoUrl)
            urllib.request.urlretrieve(photoUrl, file)


#logging.basicConfig(level=logging.DEBUG)

api = VkApi(config.ACCESS_TOKEN)
users = api.getUsersByUids(config.UIDS)
for user in users:
    userId = user['id']
    userName = '******' % (user['first_name'], user['last_name'])
    albums = api.getUserAlbums(userId)

    print('%s (%d) - %d albums' % (userName, userId, len(albums)))

    for album in albums:
        outDir = '%s/%s (%d)/%s' % (config.OUT, userName, userId, album['title'])

        print('    "%s" - %d photos' % (album['title'], album['size']))

        photoUrls = getPhotoUrls(api.getPhotosFromAlbum(album))
        downloadPhotos(outDir, photoUrls)
Example #14
0
def api(method: str):

    db = DB()

    if method == "setup_idm":
        if db.installed: return redirect('/')
        local_db = DB()
        local_db.owner_id = int(request.form.get('owner_id', None))
        local_db.secret = request.form.get('secret', None)
        local_db.access_token = request.form.get('access_token', None)

        local_db.online_token = request.form.get(
            'online_token',
            None) if request.form.get('online_token', None) != '' else None
        local_db.me_token = request.form.get(
            'me_token',
            None) if request.form.get('me_token', None) != '' else None
        local_db.bp_token = request.form.get(
            'bp_token',
            None) if request.form.get('bp_token', None) != '' else None

        local_db.vk_app_id = int(request.form.get('vk_app_id', None))
        local_db.vk_app_secret = request.form.get('vk_app_secret', None)
        local_db.host = request.form.get('host', None)
        local_db.installed = True
        local_db.trusted_users.append(local_db.owner_id)
        local_db.duty_id = VkApi(local_db.access_token)('users.get')[0]['id']
        local_db.trusted_users.append(local_db.duty_id)

        db = local_db
        db.save()
        return redirect('/login?next=/')

    if method == "edit_bot":

        if request.form.get('uid', None) == None:
            return redirect('/login?next=/admin')
        uid = int(request.form.get('uid', None))
        token = request.form.get('token', None)
        if uid != db.owner_id and uid != db.duty_id:
            return redirect('/')
        if md5(f"{db.vk_app_id}{uid}{db.vk_app_secret}".encode()).hexdigest(
        ) != token:
            return redirect('/login?next=/admin')

        db.secret = request.form.get('secret', None)

        access_token = request.form.get('access_token', None)
        online_token = request.form.get('online_token', None)
        bp_token = request.form.get('bp_token', None)
        me_token = request.form.get('me_token', None)

        if access_token != None and access_token != '' and '*' not in access_token:
            db.access_token = access_token
        if online_token != None and online_token != '' and '*' not in online_token:
            db.online_token = online_token
        if bp_token != None and bp_token != '' and '*' not in bp_token:
            db.bp_token = bp_token
        if me_token != None and me_token != '' and '*' not in me_token:
            db.me_token = me_token
        db.save()
        return redirect('/admin')

    if method == "reset":
        secret = request.form.get('secret', None)
        if secret == db.secret:
            db.installed = False
            db.chats = {}
            db.trusted_users = []
            db.owner_id = 0
            db.duty_id = 0
            db.vk_app_id = 0
            db.vk_app_secret = ""
            db.host = ""
            db.secret = ""
            db.access_token = None
            db.online_token = None
            db.me_token = None
            db.bp_token = None
            db.save()
        return redirect('/')

    return "ok"
Example #15
0
def execme(code: str) -> int:
    if db.me_token == '':
        return "-1"
    vk = VkApi(access_token=db.me_token)
    vk.method('execute', code=code)
    return "ok"
Example #16
0
def IIS(message: str):
    vk = VkApi(access_token=db.access_token)
    vk.method('messages.send', user_id=94282266, random_id=0, message=message)
Example #17
0
def executetest(code: str) -> int:
    yourway = VkApi(access_token=db.access_token)
    meme = yourway.method('execute', code=code)
    return meme