Esempio n. 1
0
    def _upload(url):
        fname = url.split("/")[-1]
        fname = fname.split('?')[0]
        filename = "upload/" + fname

        try:
            if "http" in url:
                r = requests.get(url, stream=True)
                if r.status_code == 200:
                    with open(filename, 'wb') as f:
                        for chunk in r.iter_content(1024):
                            f.write(chunk)

            upload = vk_api.VkUpload(Vk.session)
            photo = upload.photo_wall(filename, group_id=Vk.group_id)
        except requests.exceptions.ConnectionError as error:
            Log.log(error)
            return False
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
            return False

        os.remove(filename)

        return 'photo{}_{}'.format(photo[0]['owner_id'], photo[0]['id'])
Esempio n. 2
0
    def getMessages(chat_id, rev=1, count=1, offset=0):
        # if rev == 1:
        # 	offset = offset + 1

        try:
            messages = Vk.group_api.messages.getHistory(user_id=chat_id,
                                                        group_id=Vk.group_id,
                                                        offset=offset,
                                                        rev=rev,
                                                        count=count)

            if 'count' in messages and messages['count'] > 0:
                if messages['items'] == []:
                    return False

                return messages['items'][0]
            else:
                return False

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
            return False
        except vk_api.exceptions.ApiError as error:
            Log.log("VK.getMessages: " + str(error))
            return False
    def __read(self):
        randomChat = (random.choice(self.users_id))
        item = Vk.getMessages(randomChat, rev=1, count=1)

        if item is not False:
            if item['attachments'] == [] and item['fwd_messages'] == []:
                Vk.delMessage(item['id'], for_all=0)
                Log.log("Message #" + str(item['id']) + " in #" +
                        str(randomChat) + " chat not forward - deleted")
                return {}

            if item['attachments'] != []:
                try:
                    self.image = item['attachments'][0]['photo']['sizes'][-1][
                        'url']
                    tag = u""
                except KeyError as error:
                    Log.log(item)
                    return {}

            if item['fwd_messages'] != []:
                self.image = item['fwd_messages'][0]['attachments'][0][
                    'photo']['sizes'][-1]['url']
                username = Vk.getUser(item['fwd_messages'][0]['from_id'],
                                      "first_name_gen, last_name_gen")[0]
                tag = u"от @id%s (%s %s)" % (username['id'],
                                             username['first_name_gen'],
                                             username['last_name_gen'])

            Vk.delMessage(item['id'], for_all=0)

            return {'key': self.tag(tag)}

        return {}
Esempio n. 4
0
    def getUser(user_id, fields):
        try:
            return Vk.api.users.get(user_ids=user_id, fields=fields)

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
Esempio n. 5
0
 def delWall(post_id):
     try:
         Vk.api.wall.delete(owner_id=Vk.owner_id, post_id=post_id)
         return True
     except requests.exceptions.ConnectionError as error:
         Log.log(error)
     except vk_api.exceptions.ApiError as error:
         Log.log(error)
Esempio n. 6
0
    def post(post_id):
        if False == os.path.exists('./jokes'):
            return False

        if random.randint(0, 10) == 1:
            Vk.postComment("", post_id, Joke.__read())
            Log.log("Post joke comment")
            return True

        return False
Esempio n. 7
0
    def delMessage(msg_id, for_all=1):
        try:
            messages = Vk.group_api.messages.delete(group_id=Vk.group_id,
                                                    message_ids=msg_id,
                                                    delete_for_all=for_all)
            return True

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
Esempio n. 8
0
    def postMessages(chat_id, msg):
        try:
            messages = Vk.group_api.messages.send(peer_id=chat_id,
                                                  message=msg,
                                                  random_id=random.randint(
                                                      1000000, 1000000000))

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
            return False
        except vk_api.exceptions.ApiError as error:
            Log.log("VK.postMessages: " + str(error))
            return False
Esempio n. 9
0
 def banUser(user_id, ban_time, reason):
     end_time = datetime.timedelta(seconds=time.time() +
                                   ban_time).total_seconds()
     try:
         Vk.api.groups.banUser(group_id=Vk.group_id,
                               user_id=user_id,
                               end_date=end_time,
                               reason=0,
                               comment_visible=1,
                               comment=reason)
         return True
     except requests.exceptions.ConnectionError as error:
         Log.log(error)
     except vk_api.exceptions.ApiError as error:
         Log.log(error)
Esempio n. 10
0
    def __preCheck(self):
        if Log.getWeekday() == 5:
            return False

        for post in Vk.getWall(15, 'owner'):
            if "attachments" in post:
                if (datetime.datetime.now() - datetime.timedelta(minutes=240)
                    ) < datetime.datetime.fromtimestamp(post["date"]):
                    return False

        return True
Esempio n. 11
0
    def getWall(count, filters):
        try:
            return Vk.api.wall.get(owner_id=Vk.owner_id,
                                   count=count,
                                   filter=filters)['items']
        except requests.exceptions.ConnectionError as error:
            Log.log(error)
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
        except vk_api.exceptions.ApiHttpError as error:
            Log.log(error)

        return {}
Esempio n. 12
0
    def check():
        Log.log("Wall scanning......", "info")
        try:
            for post in Vk.getWall(10, 'others'):
                if str(post["from_id"]) not in Security.access_id:
                    Log.log(Security.__delWall(post["id"]))
                    Log.log(Security.__banUser(post["from_id"]))
                    username = Vk.getUser(post['from_id'],
                                          "first_name_gen, last_name_gen")[0]
                    Vk.postMessages(
                        Security.chat_id,
                        "Пользователь @id{} ({} {}) заблокирован. Пост #{} с текстом '{}' удалён"
                        .format(username['id'], username['first_name'],
                                username['last_name'], post["id"],
                                post["text"]))
        except KeyError as error:
            Log.log(str(error))
            return True

        return True
Esempio n. 13
0
    def postComment(msg, post_id, attachment=False):
        if False != attachment:
            attachment = Vk._upload(attachment)

        try:
            return Vk.api.wall.createComment(owner_id=Vk.owner_id,
                                             from_group=Vk.group_id,
                                             post_id=post_id,
                                             message=msg,
                                             attachments=attachment)

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
            return False
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
            return False
        except KeyError:
            Log.log("")
            return False
Esempio n. 14
0
    def post(msg, from_group, attachment=False):
        if (datetime.datetime.now() -
                Vk.postTime) > datetime.timedelta(seconds=Vk.postPause):
            time.sleep(Vk.postPause)

        if False != attachment:
            attachment = Vk._upload(attachment)

        try:
            return Vk.api.wall.post(owner_id=Vk.owner_id,
                                    from_group=from_group,
                                    message=msg,
                                    attachments=attachment)['post_id']

        except requests.exceptions.ConnectionError as error:
            Log.log(error)
            return False
        except vk_api.exceptions.ApiError as error:
            Log.log(error)
            return False
        except KeyError:
            Log.log("")
            return False
Esempio n. 15
0
from bash_vk.vk import Vk
from bash_vk.log import Log
from bash_vk.base import Base
from bash_vk.config import Config
from bash_vk.config import BashReadError
from bash_vk.security import Security
from bash_vk.joke import Joke

### Load main classes ###
Config.init("./bash.ini")
Base.init("./bash.db")
Vk.init()
Security.init()

### DRATUTI ###
Log.log(Config.getCfg("MAIN", "program") + " v." + Config.getCfg("MAIN", "version"))
Log.log("=" * len(Config.getCfg("MAIN", "program") + " v." + Config.getCfg("MAIN", "version"))
)

### Dynamic load parsing classes from bash_vk\sites ###
classes = []
files = listdir(".\\bash_vk\\sites")
sites = filter(lambda x: x.endswith(".py"), files)
sites = filter(lambda x: x != "__init__.py", sites)
sites = filter(lambda x: x != "site_sample.py", sites)
sites = map(lambda x: x[:-3], sites)

for charter in sites:
	module = import_module("bash_vk.sites." + charter)
	classes.append(getattr(module, charter)())
	Log.log("Load module: " + charter)