コード例 #1
0
def init(access_token, group_id):
    global vk_session, longpoll, upload
    vk_session = vk_api.VkApi(token=access_token)
    upload = vk_api.VkUpload(vk_session)
    longpoll = VkBotLongPoll(vk_session, group_id=group_id)
    return longpoll
コード例 #2
0
ファイル: vk_acc.py プロジェクト: vlzhr/accord-determiner
''' Here is the vk account data to export to other files '''

import vk_api

token = u''
vk = vk_api.VkApi(token=token)

vlzhr_token = u''
vlzhr = vk_api.VkApi(token=vlzhr_token)

token = u''
vk = vk_api.VkApi(token=token)

vlzhr_token = u'52a178721e01cf2dc1ae322988c77239b26dc16351604b5778bcc42f45ef7ab7f6f11e8c7006a14faa7b7'  # it's better to insert your own token (watch README)
vlzhr = vk_api.VkApi(token=vlzhr_token)

vhse_token = u''
vhse = vk_api.VkApi(token=vhse_token)

scope = 33554431
app_id = 5391828
コード例 #3
0
import vk_api

with open("data/acc.txt", "r") as file:
    login = str(file.readline()).rstrip()
    password = str(file.readline()).rstrip()

vk_session = vk_api.VkApi(login, password)
vk_session.auth()

vk = vk_session.get_api()


def write_to_file(posts):
    with open("data/output_with_repost.txt", "a", encoding='utf-8') as file:
        for post in posts['items']:
            file.write(post["text"])
            try:
                for copy_post in post['copy_history']:
                    file.write(copy_post['text'])
            except Exception:
                continue
            finally:
                file.write("\n ---- ---- \n")


posts100 = vk.wall.get(owner_id="-35488145",
                       filter="owner",
                       count=100,
                       offset=0)
posts200 = vk.wall.get(owner_id="-35488145",
                       filter="owner",
コード例 #4
0
import requests
import vk_api
from vk_api import VkUpload
from vk_api.longpoll import VkLongPoll, VkEventType
import random
from random import randint


def ran_func_int(rand_range_x, rand_range_y):
    random_num = str(random.randint(rand_range_x, rand_range_y))
    return random_num


token = "75a28e576079c89b55971015cf685314d4f93f42a8302ab3e774a4307f6bd2bb103b768f2423e8b9b1000"

vk_session = vk_api.VkApi(token=token)
longpoll = VkLongPoll(vk_session)
vk = vk_session.get_api()

for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
        if event.text == 'roll' or event.text == '/roll':
            if event.from_user:
                roll = ran_func_int(0, 100)
                roll = "Roll: " + roll
                vk.messages.send(user_id=event.user_id,
                                 message=roll,
                                 random_id=0)

        if event.text == 'vs' or event.text == 'Vs':
            if event.from_user:
コード例 #5
0
from requests import get
import os
from dotenv import load_dotenv
from datetime import datetime
import vk_api

PATTERN_IN = "%Y-%m-%dT%H:%M:%SZ"

path = os.path.join(os.path.dirname(__file__), '../.env')
if os.path.exists(path):
    load_dotenv(path)

    VK_LOGIN = os.environ.get('VK_LOGIN')
    VK_PASSWORD = os.environ.get('VK_PASSWORD')

    VK_SESSION = vk_api.VkApi(login=VK_LOGIN, password=VK_PASSWORD)
    try:
        VK_SESSION.auth(token_only=True)
    except vk_api.AuthError as error:
        print(error)
        exit(0)

    VK = VK_SESSION.get_api()

cur_page, last_page = None, 1


def get_latest(max_results=10, query='', page=1):
    global last_page, cur_page

    params = {
コード例 #6
0
import keyboards
import random as r
import vk_api
import same_answers
import spreadsheets

vk = vk_api.VkApi(
    token=
    'cb6145a957442835528d14699d5601685ccd389d585ab3f55786b6ec56d0600436670449ef71f0fc70f59'
)
vk._auth_token()


def sit_message(user_id, table_number, partner_id):
    print(user_id)
    string = ''
    for index in same_answers.compare(
            spreadsheets.people_answers()[user_id],
            spreadsheets.people_answers()[partner_id]):
        print(index, "index", type(index))
        string += str(spreadsheets.text_of_question()[3 + index])
        string += '  '
    text = "Привет. Номер твоего стола " + str(
        table_number) + ". Твой собеседник " + "https://vk.com/id" + str(
            partner_id
        ) + ". " + "У вас совпали ответы на такие вопросы: " + string
    vk.method(
        "messages.send", {
            "peer_id": user_id,
            "message": text,
            "random_id": int(r.uniform(0, 2**32)),
コード例 #7
0
 def __init__(self):
     session = vk_api.VkApi(app_id=constants.VK_APP_ID, login=constants.VK_LOGIN, password=constants.VK_PASSWORD, scope=constants.VK_SCOPE, api_version=constants.VK_VERSION)
     session.auth()
     self.api = session
     self.uploader = VkUpload(session)
コード例 #8
0
import random

#vk_data - a class with your vk information, like as login, password and etc.


def photo(id):  #get a photo id of the a user
    avka = vk.photos.get(owner_id=id, album_id='profile', count=1, rev=1)
    return avka


def loyse(ava, id):  #like
    z = vk.likes.add(owner_id=id, type='photo', item_id=ava)
    return z


vk_session = vk_api.VkApi(str(vk_data.login), str(vk_data.pswrd))
vk_session.auth()
vk = vk_session.get_api()

girls = vk.users.search(count="""integer number""",
                        city='CITY ID',
                        sex="""1 is female, 2 is male""",
                        age_from=0,
                        age_to=80,
                        has_photo=1)  #list of the users
n = girls['items']

for i in n:
    id = i['id']
    array_1 = photo(id)
    some = array_1['items']
コード例 #9
0
        if len(args) == 1:
            commands = args[0].lower()
            argss = None

            print(payload)
            test = str(eval(payload))
            messages.write_msg(peer_id, test)
        else:
            commands = args[0].lower()
            argss = args[1:]

            print(payload)
            test = str(eval(payload))
            messages.write_msg(peer_id, "Ответ вк: " + str(test))
        '''
        count = int(count)
        msg_1 = ''.join(payload)
        '''


with open("main/database/database_token.json", "r", encoding="utf-8") as file:
    data = json.loads(file.read())
token = data['token']

# Авторизуемся как сообщество
vk = vk_api.VkApi(app_id=6146827, token=token)

# Работа с сообщениями
longpoll = VkLongPoll(vk, wait=0)
コード例 #10
0
def download_groups(groups):
    assert POSTS_AMOUNT <= 100

    logger.info('Beginning VK auth...')
    vk_session = vk_api.VkApi(
        login=LOGIN,
        password=PASSWORD,
        token=
        '33927ef133927ef133927ef17233fd261f3339233927ef16dbc8da8c274c7bb6c107c20'
    )
    vk_session.auth()
    vk = vk_session.get_api()
    logger.info('VK auth success!')

    model_session = Session()

    for group in groups:
        START_DATE_FROM_FIRST_POST = False
        group_name, insense_name, insense_description = group
        logger.info(f'Processing group: {group_name}/{insense_name}')
        vk_group = vk.groups.getById(group_id=group_name,
                                     fields=[
                                         'counters', 'city', 'country',
                                         'place', 'description',
                                         'members_count', 'status', 'contacts',
                                         'activity', 'start_date'
                                     ])

        vk_group = vk_group[0]

        # for k, v in vk_group.items():
        # 	print(k, ': ', v)

        model_group = VKGroup.from_api(vk_group)
        model_group.insense_name = insense_name
        model_group.insense_description = insense_description
        try:
            logger.info(
                f'Trying to save group [{group_name}/{insense_name}] into db...'
            )
            model_session.add(model_group)
            model_session.commit()
        except IntegrityError:
            logger.warning(f'Group [{group_name}/{insense_name}] exists!')
            model_session.rollback()
            model_session.flush()
            if not UPDATE_GROUP_INFO:
                logger.warning(
                    'Skipping group download and continue with next (to change see "UPDATE_INFO" in settings)'
                )
                continue
            else:
                logger.info(
                    'Getting group from database... (to change see "UPDATE_INFO" in settings)'
                )
                model_group = model_session.query(VKGroup).filter(
                    VKGroup.id == vk_group['id']).first()

        if not model_group.start_date:
            logger.warning(
                'No start date specified. Date will be withdrawn from the first comment'
            )
            START_DATE_FROM_FIRST_POST = True

        group_counters = VKCounters.from_api(vk_group['counters'])
        group_counters.group = model_group
        group_counters.members = vk_group['members_count']

        posts_count = vk.wall.get(owner_id=make_group_wall_id(vk_group),
                                  count=1,
                                  fields=['count'])['count']

        logger.info(f'Found {posts_count} posts on group\'s wall')

        group_counters.wall_posts = posts_count
        model_session.add(group_counters)
        try:
            model_session.commit()
        except IntegrityError:
            model_session.rollback()
            model_session.flush()
            if not UPDATE_COUNTERS:
                raise
            else:
                logger.info('Updating counters...')
                group_counters = model_session.query(VKCounters).filter_by(
                    group=model_group).first()
                group_counters.update_from_api({
                    **vk_group['counters'], 'wall_posts':
                    posts_count,
                    'members':
                    vk_group['members_count']
                })
                model_session.add(group_counters)
                model_session.commit()
                logger.info('Counters updated!')

        post = None
        for i in range(0, int(min(posts_count, POSTS_DOWNLOAD_MAX)),
                       POSTS_AMOUNT):
            logger.info(f'Fetching next {POSTS_AMOUNT} posts from wall...')
            current_query_count = POSTS_AMOUNT if (
                posts_count -
                i) // POSTS_AMOUNT != 0 else posts_count % POSTS_AMOUNT
            group_wall = vk.wall.get(owner_id=make_group_wall_id(vk_group),
                                     count=current_query_count,
                                     extended=1,
                                     offset=i)
            try:
                for post in group_wall['items']:
                    model_post = VKWallPost.from_api(post)
                    model_post.group = model_group
                    model_session.add(model_post)
                    # else:
                    # 	model_post = model_session.query(VKWallPost).filter(VKWallPost.id == post['id']).first()
                    if post['id'] == group_wall['items'][current_query_count //
                                                         4]['id']:
                        logger.info(
                            f'{(current_query_count / 4 + i) / posts_count:.2%} complete'
                        )
                    if post['id'] == group_wall['items'][current_query_count //
                                                         2]['id']:
                        logger.info(
                            f'{(current_query_count / 2 + i) / posts_count:.2%} complete'
                        )
                try:
                    model_session.commit()
                except IntegrityError:
                    model_session.rollback()
                    model_session.flush()
                    if not UPDATE_POSTS_INFO:
                        raise
            except IntegrityError:
                continue
            finally:
                logger.info(
                    f'{(current_query_count + i) / posts_count:.2%} complete')

        if START_DATE_FROM_FIRST_POST and post:
            model_group.start_date = VKWallPost.date_format(post['date'])
            model_session.add(model_group)
            model_session.commit()
            logger.info(
                f'Start date for group [{group_name}/{insense_name}] from the first comment update success!'
            )
コード例 #11
0
import vk_api
import time
import random

my_token = 'token VkKateMobile'
msg = input('Msg: ')

session = vk_api.VkApi(token = my_token)
vk = session.get_api()

while True:
	try:
		vk.messages.send(user_id = айди кому спамить без '', message = msg, random_id = random.randint(0, 9999999999))
	except:
		pass
	time.sleep(3)
コード例 #12
0
ファイル: bot.py プロジェクト: CINCINATI333/bot
                        float(b) + 1
                    )  #Запись в ячейку количества пользователей, отправивших сообщения
                    b += 1
                i += 1

            w_sheet.write(unumber, k + 2,
                          text[1] + '-' + text[2])  #запись счёта
            w_sheet.write(unumber, 0,
                          uname + ' ' + ulastname)  #запись имени и фамилии
            w_sheet.write(
                0, 0,
                b)  #запись количества пользователей, приславших сообщение
            wb.save('2.xls')

            print(res[0]['first_name'])  #Имя
            print(res[0]['last_name'])  #Фамилия

            print(text[0], '  - первый элемент сообщения')
            print(text[1], ' - второй элемент сообщения')
            print(text[2], ' - третий элемент сообщения')

    itheration_num += 1
    print(str(itheration_num) + " итерация")
    time.sleep(4)
    return


vk = vk_api.VkApi(token=TOKEN)
while True:
    itheration()
コード例 #13
0
import vk_api
import random

GROUP_ID = 185779488

with open('/local/abgde/vk_bot_key') as f:
    VK_BOT_TOKEN = f.read().strip()
    vk = vk_api.VkApi(token=VK_BOT_TOKEN)
    api = vk.get_api()


def allowed(vk_user_id):
    res = api.messages.isMessagesFromGroupAllowed(group_id=GROUP_ID,
                                                  user_id=vk_user_id)
    return res['is_allowed']


def send_message(user_id, message):
    api.messages.send(user_id=user_id,
                      random_id=random.randint(0, 10000),
                      peer_id=-GROUP_ID,
                      message=message)
コード例 #14
0
ファイル: BotVK_Code.py プロジェクト: VishLi777/botvk
def main():
    nomer = 0
    locale.setlocale(locale.LC_ALL,
                     'ru_RU.UTF-8')  # для получения даты на русском
    vk_session = vk_api.VkApi(
        token=
        '943d976fd89420888a69ccdeba641e48f71dc04095ca8efe0d77dc72f37574298c4e50dbc517bbb63bf8e'
    )
    vk = vk_session.get_api()
    longpoll = VkLongPoll(vk_session)
    Week = datetime.today().weekday()
    wek = (week_days[Week])  # название недели
    today = datetime.today()
    numweek = today.strftime("%U")
    numberweek = int(numweek) - 5  # номер недели
    tommorow = today + timedelta(days=1)  #завтра
    upload = VkUpload(vk_session)
    attachments = []
    photo = upload.photo_messages(photos="Covid.png")[0]
    attachments.append("photo{}_{}".format(photo["owner_id"], photo["id"]))

    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text:
            print('New from {}, text = {}'.format(event.user_id, event.text))
            respons = event.text
            response = respons.lower()
            keyboard = VkKeyboard(one_time=False)
            proverka_gruppi = gruppa(response)
            groupWeek = GruppaPoNedeli(response)
            proverkaNedeli = Nedeli(response)
            if proverka_gruppi == True:
                num = response.upper()
                nomer += 1
                vk.messages.send(user_id=event.user_id,
                                 random_id=get_random_id(),
                                 message="Я запомнил вашу группу " + num)
            elif response == "показать расписание":
                if (nomer != 0):
                    keyboard.add_button('на сегодня',
                                        color=VkKeyboardColor.POSITIVE)
                    keyboard.add_button('на завтра',
                                        color=VkKeyboardColor.NEGATIVE)
                    keyboard.add_line()
                    keyboard.add_button('на прошлую неделю   ',
                                        color=VkKeyboardColor.PRIMARY)
                    keyboard.add_button('на эту неделю',
                                        color=VkKeyboardColor.PRIMARY)
                    keyboard.add_line()
                    keyboard.add_button('какая неделя?',
                                        color=VkKeyboardColor.DEFAULT)
                    keyboard.add_button('какая группа?',
                                        color=VkKeyboardColor.DEFAULT)
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        keyboard=keyboard.get_keyboard(),
                        message='Показываю расписание для группы ' + num)
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (response == "привет"):
                vk.messages.send(
                user_id = event.user_id,
                random_id = get_random_id(),
                message = 'Привет, ' + \
                vk.users.get(user_id = event.user_id)[0]['first_name'])
            elif (response == "на сегодня"):
                if nomer != 0:
                    if wek != "SUN":
                        if int(numberweek) % 2 == 0:
                            string = Raspisanie(num, wek, 0, 1)
                            vk.messages.send(
                                user_id=event.user_id,
                                random_id=get_random_id(),
                                message="Показываю раписание на " + today.strftime("%x") + ": " "\n" + \
                                        string)
                        else:
                            string = Raspisanie(num, wek, 0, 0)
                            vk.messages.send(
                                user_id=event.user_id,
                                random_id=get_random_id(),
                                message="Показываю раписание на " + today.strftime("%x") + ": " "\n" + \
                                        string)
                    else:
                        vk.messages.send(user_id=event.user_id,
                                         random_id=get_random_id(),
                                         message="Сегодня воскресенье!")
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message="Укажите вашу группу. Например ИКБО-01-19")
            elif (response == "на завтра"):
                wek2 = (week_days[Week - 6])
                if nomer != 0:
                    if wek2 != "SUN":
                        if int(numberweek) % 2 == 0:
                            k = Raspisanie(num, wek2, 0, 1)
                            vk.messages.send(
                            user_id=event.user_id,
                            random_id=get_random_id(),
                            message="Показываю раписание на " + tommorow.strftime("%x") + ": " "\n" + \
                                    k)
                        else:
                            k = Raspisanie(num, wek2, 0, 0)
                            vk.messages.send(
                                user_id=event.user_id,
                                random_id=get_random_id(),
                                message="Показываю раписание на " + tommorow.strftime("%x") + ": " "\n" + \
                                        k)

                    else:
                        vk.messages.send(user_id=event.user_id,
                                         random_id=get_random_id(),
                                         message="Завтра воскресенье!")
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (response == "на прошлую неделю"):
                if nomer != 0:
                    if (numberweek - 1) % 2 == 0:
                        stringMon = Raspisanie(num, "MON", 0, 1)
                        stringTue = Raspisanie(num, "TUE", 0, 1)
                        stringWed = Raspisanie(num, "WED", 0, 1)
                        stringThu = Raspisanie(num, "THU", 0, 1)
                        stringFri = Raspisanie(num, "FRI", 0, 1)
                        stringSat = Raspisanie(num, "SAT", 0, 1)

                        vk.messages.send(
                            user_id=event.user_id,
                            random_id=get_random_id(),
                            message="Показываю раписание на неделю: " + str(numberweek-1) + "\n" + \
                                    stringMon +
                                    "Вторник:" + "\n" +
                                    stringTue +
                                    "Среда:" + "\n" +
                                    stringWed +
                                    "Четверг:" + "\n" +
                                    stringThu +
                                    "Пятница:" + "\n" +
                                    stringFri +
                                    "Cуббота:" + "\n" +
                                    stringSat)
                    else:
                        stringMon = Raspisanie(num, "MON", 0, 0)
                        stringTue = Raspisanie(num, "TUE", 0, 0)
                        stringWed = Raspisanie(num, "WED", 0, 0)
                        stringThu = Raspisanie(num, "THU", 0, 0)
                        stringFri = Raspisanie(num, "FRI", 0, 0)
                        stringSat = Raspisanie(num, "SAT", 0, 0)

                        vk.messages.send(
                            user_id=event.user_id,
                            random_id=get_random_id(),
                            message="Показываю раписание на прошлую неделю: "+ str(numberweek-1) + "\n" + \
                                    stringMon +
                                    "Вторник:" + "\n" +
                                    stringTue +
                                    "Среда:" + "\n" +
                                    stringWed +
                                    "Четверг:" + "\n" +
                                    stringThu +
                                    "Пятница:" + "\n" +
                                    stringFri +
                                    "Cуббота:" + "\n" +
                                    stringSat)
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (response == "на эту неделю"):
                if nomer != 0:
                    if numberweek % 2 == 0:
                        stringMon = Raspisanie(num, "MON", 0, 1)
                        stringTue = Raspisanie(num, "TUE", 0, 1)
                        stringWed = Raspisanie(num, "WED", 0, 1)
                        stringThu = Raspisanie(num, "THU", 0, 1)
                        stringFri = Raspisanie(num, "FRI", 0, 1)
                        stringSat = Raspisanie(num, "SAT", 0, 1)

                        vk.messages.send(
                            user_id=event.user_id,
                            random_id=get_random_id(),
                            message="Показываю раписание на неделю: " + "\n" + \
                                    stringMon +
                        "Вторник:" + "\n" +
                                    stringTue +
                        "Среда:" + "\n" +
                                    stringWed +
                        "Четверг:" + "\n" +
                                    stringThu +
                        "Пятница:" + "\n" +
                                    stringFri +
                        "Cуббота:" + "\n" +
                                    stringSat)

                    else:
                        stringMon = Raspisanie(num, "MON", 0, 0)
                        stringTue = Raspisanie(num, "TUE", 0, 0)
                        stringWed = Raspisanie(num, "WED", 0, 0)
                        stringThu = Raspisanie(num, "THU", 0, 0)
                        stringFri = Raspisanie(num, "FRI", 0, 0)
                        stringSat = Raspisanie(num, "SAT", 0, 0)

                    vk.messages.send(
                            user_id=event.user_id,
                            random_id=get_random_id(),
                            message="Показываю раписание на эту неделю: " + "\n" + \
                                    stringMon +
                                    "Вторник:" + "\n" +
                                    stringTue +
                                    "Среда:" + "\n" +
                                    stringWed +
                                    "Четверг:" + "\n" +
                                    stringThu +
                                    "Пятница:" + "\n" +
                                    stringFri +
                                    "Cуббота:" + "\n" +
                                    stringSat)
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (proverkaNedeli == True):
                if nomer != 0:
                    week = re.findall(
                        r'понедельник|вторник|среда|четверг|пятница|суббота',
                        response)
                    for j in week:
                        n = j
                    if n == "понедельник":
                        k = 'MON'
                    if n == "вторник":
                        k = 'TUE'
                    if n == "среда":
                        k = 'WED'
                    if n == "четверг":
                        k = 'THU'
                    if n == "пятница":
                        k = 'FRI'
                    if n == "суббота":
                        k = 'SAT'
                    string1 = Raspisanie(num, k, 0, 1)

                    string2 = Raspisanie(num, k, 0, 0)
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message="Показываю раписание на чет. "+ n + "\n" + \
                                string1
                                 +"\n"
                    "нечет. " + n + "\n"
                                  +"\n" +
                                string2)
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (groupWeek == True):
                group = re.findall(r'(?:\w+)(?:\-\d+\-\d+)', response)
                for i in group:
                    Group = i.upper()
                week = re.findall(
                    r'понедельник|вторник|среда|четверг|пятница|суббота',
                    response)
                for j in week:
                    weeek = j
                if weeek == "понедельник":
                    k = 'MON'
                if weeek == "вторник":
                    k = 'TUE'
                if weeek == "среда":
                    k = 'WED'
                if weeek == "четверг":
                    k = 'THU'
                if weeek == "пятница":
                    k = 'FRI'
                if weeek == "суббота":
                    k = 'SAT'
                string1 = Raspisanie(Group, k, 0, 1)
                string2 = Raspisanie(Group, k, 0, 0)

                vk.messages.send(
                    user_id=event.user_id,
                    random_id=get_random_id(),
                    message="Показываю раписание для группы "+ Group + " на чет. " + weeek + "\n" + \
                            string1
                                             +  "\n"
                "нечет. " +  "\n"
                             + "\n" +
                            string2)
            elif (response == "какая неделя?"):
                vk.messages.send(user_id=event.user_id,
                                 random_id=get_random_id(),
                                 message="Cейчас идет " + str(numberweek) +
                                 " неделя")
            elif (response == "какая группа?"):
                if nomer != 0:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message="Показываю расписание для группы: " + num)
                else:
                    vk.messages.send(
                        user_id=event.user_id,
                        random_id=get_random_id(),
                        message='Укажите вашу группу. Например ИКБО-01-19')
            elif (response == "команды"):
                vk.messages.send(
                    user_id=event.user_id,
                    random_id=get_random_id(),
                    message=
                    "Для начала введите свою группу. Например ИКБО-01-19" +
                    "\n"
                    "\Показать расписание - появится клавиатура" + "\n"
                    "\ДЕНЬ ДЕНЕЛИ + НОМЕР ГРУППЫ(Бот вторник ИКБО-01-19) - вам покажет расписание на выбранный вами день и группу"
                    + "\n"
                    "\ДЕНЬ НЕДЕЛИ (Бот вторник) - вам покажет расписание на выбранный вами день у сохраненной группы"
                    + "\n"
                    "\Ковид - статистика коронавируса")
            elif (response == "ковид"):
                vk.messages.send(user_id=event.user_id,
                                 attachment=','.join(attachments),
                                 random_id=get_random_id(),
                                 message=str_res)
            else:
                vk.messages.send(user_id=event.user_id,
                                 random_id=get_random_id(),
                                 message="Неизвестная команда")
コード例 #15
0
 def __init__(self, token, group_id):
     self.vk = vk_api.VkApi(token=token)
     self.long_poll = VkBotLongPoll(self.vk, group_id)
     self.vk_api = self.vk.get_api()
     self.random_id = 0
コード例 #16
0
from vk_api.longpoll import VkLongPoll, VkEventType
import vk_api
from datetime import datetime

login, password = "******", "password"
vk_session = vk_api.VkApi(login=login, password=password, app_id=2685278)
vk_session.auth(token_only=True)

# token = "ЗдесьЕстьВашТокен"
# vk_session = vk_api.VkApi(token=token)

session_api = vk_session.get_api()
longpoll = VkLongPoll(vk_session)
#While True здесь оказался не нужен. Его функцию выполняет for event in longpoll.listen(): Спасибо подписчику за это уточнение.

for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        print('Сообщение пришло в: ' +
              str(datetime.strftime(datetime.now(), "%H:%M:%S")))
        print('Текст сообщения: ' + str(event.text))
コード例 #17
0
ファイル: setup.py プロジェクト: Ba-dot/chat_bot_from_vk
import vk_api
from vk_api.longpoll import VkLongPoll,VkEventType
from datetime import datetime
import random
import time

session = vk_api.VkApi(token='ваш токен')
session_api = session.get_api()
longpool = VkLongPoll(session)

hello_list = ('и тебе привет','привет','доброго времени суток)','привет ковбой)','здрасти',)
while True:
    for event in longpool.listen():
        if event.type == VkEventType.MESSAGE_NEW:
            print("сообщение пришло в ", event.datetime)
            print("текст сообщения", event.text)
            response = event.text.lower()
            if event.from_user and not event.from_me:
                if response.find('привет') >= 0 or response.find('здравствуй') >= 0 or response.find('hello') >= 0:
                    time.sleep(random.uniform(0.5,4.0))
                    session.method('messages.send', {'user_id': event.user_id,
                                                    'message' : random.choice(hello_list),
                                                    'random_id':'0'})
                elif response.find('как дела?') >= 0:
                    time.sleep(random.uniform(0.5,4.0))
                    session.method('messages.send', {'user_id': event.user_id,
                                                    'message' : '',
                                                    'random_id':'0',
                                                    'sticker_id':'9045'})
                elif response.find('фото') >= 0:
                    time.sleep(random.uniform(0.5, 4.0))
コード例 #18
0
ファイル: main.py プロジェクト: Danillchen/bot_vk_pythonTest
import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from random import randint
from vk_api.utils import get_random_id
import re
import requests
from time import sleep
from vk_api import VkApi
from vk_api.upload import VkUpload
vk_session = vk_api.VkApi(token='token')
longpoll = VkBotLongPoll(vk_session, id)
vk = vk_session.get_api()   # Выполняем авторизацию от имени сообщества
upload = VkUpload(vk)

#отправляет сообщение
def mes(vk, chat_id, message=None, attachment=None, wait=25):
    vk.messages.send(random_id=get_random_id(), chat_id=chat_id, message=message, attachment=attachment)

#загружает фото
def say_photo():
    ph = event.object.attachments[0]['photo']['sizes'][4]['url']
    p = requests.get(ph)
    out = open("file.png", "wb")
    out.write(p.content)
    out.close()
    res = upload.photo_messages('file.png')[0]
    owner_id = res['owner_id']
    photo_id = res['id']
    access_key = res['access_key']
    attachment = f'photo{owner_id}_{photo_id}_{access_key}'
コード例 #19
0
def send_message(message):
    token = "bb6cff0b111d5b04c2a1269a41475d3e72f8ccb2f573b9c62fc42d41499e50acf03887dcfa442aba4fcc8"
    vk = vk_api.VkApi(token=token)
    subscribers = [57701130, 113761714]
    for i in subscribers:
        write_msg(i, vk, message)
コード例 #20
0
def main():
    login, password = open("vkpasswd").read().rstrip().split(':')
    vk_session = vk_api.VkApi(login, password)
    ftc = open('todaycount.txt')
    #vk_session = vk_api.VKApi(token=token)
    for ltc in ftc:
      todaycount=int(ltc)
    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)

    def cmdline(command):
      process = Popen(
        args=command,
        stdout=PIPE,
        shell=True
      )
      return process.communicate()[0]

    def isFake(owner_id):#True если фэйк (id>=0 или members_count<60)
      if (owner_id<0):
        with vk_api.VkRequestsPool(vk_session) as pool:
          requests=pool.method('groups.getById', {
           'group_id':-owner_id,
            'fields':['members_count']
            })
        if (int(requests.result[0]['members_count'])>60):
          return False
        else:
          print 'Fake: id'+ str(owner_id)+' count:'+ str(int(requests.result[0]['members_count']))
      return True

    def isStop(description):#True если описание содержит стоп слова
      fstop = open('stopwords.txt')
      for stopword in fstop:
        if description.decode('utf-8').lower().find(stopword.decode('utf-8').lower().strip())>-1:
          print description+'\n'+stopword+'\n'
          return True
      return False

    def makeRepostSteampunk():#Репостим стимпанк группу в конце дня, чтобы быть похожими на человека
     print 'Парсим группу: 39009769'
     with vk_api.VkRequestsPool(vk_session) as pool:
        requests=pool.method('wall.get', {
           'owner_id': '-39009769',
           'count':'300'
            })
     for k in requests.result['items']:
          try:
            if k['copy_history'][0]['owner_id']:
              owner_id=int(k['copy_history'][0]['owner_id'])
              post_id=int(k['copy_history'][0]['id'])
          except:
            owner_id=int(k['owner_id'])
            post_id=int(k['id'])
          if not isReposted(owner_id, post_id):
            if len(open("reposted.txt").read().split())-todaycount<149*askDayNum():
              repname='wall'+str(owner_id)+'_'+str(post_id)
              with vk_api.VkRequestsPool(vk_session) as pool:
                requests=pool.method('wall.repost', {
                'object':repname
                })
              print 'owner_id '+str(owner_id)+' post_id '+str(post_id)
              frep = open('reposted.txt','a+')
              frep.write(str(owner_id)+','+str(post_id)+'\n')
              frep.close()
              break
    def askDayNum():
        return int(open("daycount").read(1))
    
    def makeRepost(owner_id, post_id):
     if len(open("reposted.txt").read().split())-todaycount<144*askDayNum():
      repname='wall'+str(owner_id)+'_'+str(post_id)
      with vk_api.VkRequestsPool(vk_session) as pool:
          requests=pool.method('wall.repost', {
           'object':repname
            })
      print 'owner_id '+str(owner_id)+' post_id '+str(post_id)
      frep = open('reposted.txt','a+')
      frep.write(str(owner_id)+','+str(post_id)+'\n')
      frep.close()
      time.sleep(120.0+random.random()*180.0)
     else:
      print 'На сегодня хватит'
      while len(open("reposted.txt").read().split())-todaycount<149*askDayNum():
        time.sleep(120.0+random.random()*200.0)
        makeRepostSteampunk()
      open("daycount","w").write(askDayCount()+1)
      sys.exit(0)

    def isMember(owner_id):
      fjoin = open('joined.txt')
      for group in fjoin:
        if (group.strip()==str(owner_id)):
          return True
      return False

    def joinGroup(owner_id):
      with vk_api.VkRequestsPool(vk_session) as pool:
       if int(owner_id)<0:
        requests=pool.method('groups.join', {
           'group_id':-int(owner_id)
            })
      fjoin = open('joined.txt','a+')
      fjoin.write(str(owner_id)+'\n')
      fjoin.close()

    def isReposted(owner_id, post_id):
      frep = open('reposted.txt')
      for repost in frep:
        if (repost.strip()==str(owner_id)+','+str(post_id)):
          print 'Уже репостили '+str(owner_id)+','+str(post_id)
          return True
      return False

    def checkResults(requests):
     for i in requests.result['items']:
      description=unicode(json.dumps(i['text']),'raw-unicode-escape').encode('utf-8')
      if not isStop(description):
        if not isReposted(int(i['owner_id']),int(i['id'])):
          if not isFake(int(i['owner_id'])):
            print 'Репостим:\n'+description
            makeRepost(i['owner_id'],i['id'])
            for j in re.findall(r'wall-\d{1,10}_\d{1,10}', description):
              j_owner_id=re.search(r'-\d{1,10}',j).group(0)
              j_id=re.search(r'\d{1,10}$',j).group(0)
              if not isReposted(int(j_owner_id),int(j_id)):
                print 'Репостим детей:\n'
                makeRepost(int(j_owner_id),int(j_id))
              if not isMember(int(j_owner_id)):
                joinGroup(int(j_owner_id))
            if not isMember(int(i['owner_id'])):
              joinGroup(int(i['owner_id']))
            for j in re.findall(r'club\d{1,10}', description):
              j_owner_id=-int(re.search(r'\d{1,10}',j).group(0))
              if not isMember(int(j_owner_id)):
                joinGroup(int(j_owner_id))

    def readWall(group_id):
      print 'Парсим группу: ' + str(group_id)
      with vk_api.VkRequestsPool(vk_session) as pool:
        requests=pool.method('wall.get', {
           'owner_id': group_id,
           'count':'9'
            })
      for k in requests.result['items']:
          try:
            if k['copy_history'][0]['owner_id']:
              description=unicode(json.dumps(k['copy_history'][0]['text']),'raw-unicode-escape').encode('utf-8')
              owner_id=k['copy_history'][0]['owner_id']
              post_id=k['copy_history'][0]['id']
          except:
            description=unicode(json.dumps(k['text']),'raw-unicode-escape').encode('utf-8')
            owner_id=k['owner_id']
            post_id=k['id']
          if (description.lower().find('лайк')>-1) or (description.lower().find('Лайк')>-1) or (description.lower().find('Репост')>-1) or (description.lower().find('РЕПОСТ')>-1) or (description.lower().find('друзьям')>-1) or (description.lower().find('репост')>-1) or (description.lower().find('поделит')>-1):
              print description+'\n'
              if not isStop(description):
                if not isReposted(int(owner_id),int(post_id)):
                    print 'Репостим:\n'+description
                    makeRepost(owner_id,post_id)
                    for j in re.findall(r'wall-\d{1,10}_\d{1,10}', description):
                      j_owner_id=re.search(r'-\d{1,10}',j).group(0)
                      j_id=re.search(r'\d{1,10}$',j).group(0)
                      if not isReposted(int(j_owner_id),int(j_id)):
                        print 'Репостим детей:\n'
                        makeRepost(int(j_owner_id),int(j_id))
                      if not isMember(int(j_owner_id)):
                        joinGroup(int(j_owner_id))
                    if not isMember(int(owner_id)):
                      joinGroup(int(owner_id))
                    for j in re.findall(r'club\d{1,10}', description):
                      j_owner_id=-int(re.search(r'\d{1,10}',j).group(0))
                      if not isMember(int(j_owner_id)):
                        joinGroup(int(j_owner_id))
          else:
              print description
              print "Нет слова Репостим"

    with vk_api.VkRequestsPool(vk_session) as pool:
      requests=pool.method('newsfeed.search', {
           'q':u'Конкурс репост подарки Новосибирск',
            'count':'150'
            })

    with vk_api.VkRequestsPool(vk_session) as pool:
      requests3=pool.method('newsfeed.search', {
           'q':u'репост подакрки Новосибирск',
            'count':'150'
            })

    with vk_api.VkRequestsPool(vk_session) as pool:
      requests2=pool.method('newsfeed.search', {
           'q':u'Конкурс репост подарки Россия',
            'count':'150'
            })
    #Репостим золотые группы
    #fgc = open('goldclub.txt')
    #for club in fgc:
    #  time.sleep(1.2)
    #  try:
    #    readWall(int(club))
    #  except:
    #    print 'Не парсится группа '+str(club)

    checkResults(requests)
    checkResults(requests2)
    checkResults(requests3)

    if (int(time.asctime().split(' ')[3].split(':')[0]) > 22) or (len(open("reposted.txt").read().split())-todaycount>149*askDayNum()): # stop reposting after 10 PM
      print 'На сегодня хватит'
      #while ((len(open("reposted.txt").read().split())-todaycount<149*askDayNum())) and (int(time.asctime().split(' ')[3].split(':')[0]) < 21):
      #  time.sleep(120.0+random.random()*200.0)
      #  makeRepostSteampunk()
      sys.exit(0)
コード例 #21
0
import vk_api, math, datetime, random
import requests
from vk_api.utils import get_random_id
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType

kbfile = open("keyboard.json",'r',encoding="UTF-8")
keyboard = kbfile.read()

vk_session = vk_api.VkApi(token="878fce9d7476eb28d019f8aa393e2a720030c1350acb857e3cbe4150c96fc6981de6417ae556611573220")
vk = vk_session.get_api()
longpoll = VkBotLongPoll(vk_session, "187553815")
att = ''

for event in longpoll.listen(): 
    if event.type == VkBotEventType.MESSAGE_NEW:
        if event.obj.text != '': 
            if event.from_user:
                text = event.obj.text.lower()
                text = text.split(' ')
                if (len(text) == 2) and (text[0] == "погода"):
                    now = datetime.datetime.now()
                    city = text[1]
                    res = requests.get("http://api.openweathermap.org/data/2.5/weather",
                    params={'q': city, 'units': 'metric', 'lang': 'ru', 'APPID': 'ff804351b97f7a93823cbf829df18b62'})
                    data = res.json()
                    print(data)
                    if data['cod'] == '404':
                        reply = "Такого города не существует"
                        att = 'photo-187553815_457239027'
                    else:
                        descr = data['weather'][0]['description'].title()
コード例 #22
0
from math import ceil
import json, time

import vk_api
token = '7e04d8f1ad225832d1b42835499a5c65b8c46a3cab83cd25a9cb2f2d87542b8927d3e61133d23c13c02bc'
vk = vk_api.VkApi(token=token)  # Ваш токен
api = vk.get_api()

posts = api.wall.getById(
    posts='{owner_id}_{post_id}'.format(owner_id='-88245281',
                                        post_id='<post_id>')
)  # Где <owner_id> - id пользователя/группы, post_id - id поста. *см. комментарии после кода

if not posts:
    print('No posts found!')

post = posts[0]
posts = []

for offset in range(ceil(post['comments']['count'] // 2500)):
    posts.extend(
        api.execute.getCommentsFromPost(
            owner_id='<owner_id>',
            post_id='<post_id>',
            offset=2500 * offset,
            count=2500)['items'])  # тут всё по аналогии, как и в первый раз
    time.sleep(0.34)  # избегаем flood control

with open('output.json', 'w') as file:
    json.dump(posts, file)
コード例 #23
0
ファイル: main.py プロジェクト: Egoluback/home_task_Bot
import vk_api

driveManager = DriveManager('data/dataFile.json',
                            '1-3NBgarr57RzAn7iyr3-jQP8CEkEaf0S')

driveManager.setFileId(driveManager.findFile())
driveManager.download()

data = []
try:
    with open('data/dataFile.json', 'r') as file:
        data = json.load(file)
except:
    pass

vk_session = vk_api.VkApi(token=TOKEN)
vk_session._auth_token()

vk = vk_session.get_api()
longpoll = VkBotLongPoll(vk_session, PUBLIC_ID)

print("Bot has been launched.")

while True:
    try:
        for event in longpoll.listen():
            print("there is new event - " + str(event.type))
            if (event.type == VkBotEventType.MESSAGE_NEW):
                print(str(event.object.from_id) + " - " + event.object.text)
                if (event.from_chat):
                    request = event.object.text
コード例 #24
0

def write_msg(peer_id, message):
    if len(message) == 0: return
    session.method(
        'messages.send', {
            'peer_id': peer_id,
            'message': message,
            'random_id': random.randint(0, 999999999999)
        })


#print(bal.get_user_id(1))

session = vk_api.VkApi(
    token=
    '69a17e5303be5bc5218137622fa9684f6ac9b11d32f15c6b0b58cd3d1e1e8eee8ad89b443fb66c77d0c77'
)

#api = vk.get_api()
longpoll = VkBotLongPoll(session, 182437918)
bot = VkBot()

for event in longpoll.listen():
    if event.type == VkBotEventType.MESSAGE_NEW:
        if event.from_user:
            if event.message.text != '':
                write_msg(event.message.peer_id,
                          bot.new_message(event.message.text))

        elif event.from_chat:
            if event.message.text != '':
コード例 #25
0
status1 = 0
status2 = 0
status3 = 0

users = []
users_money = []

part = 0

manNUM = 0

# API-ключ созданный ранее
token = "be8178cc475050be3a9b6ecfab3dadaa0e58526727e5b9d51f0584f2c683eddc2f677770797be444e4cf7"
# Авторизуемся как сообщество
vk = vk_api.VkApi(token=token)
# Работа с сообщениями
longpoll = VkLongPoll(vk)
#URL
URL = 'https://static.zerochan.net/Hatsune.Miku.full.1685469.jpg'


def write_msg(user_id, message):
    vk.method('messages.send', {
        'user_id': user_id,
        'message': message,
        'random_id': 0
    })


# Основной цикл
コード例 #26
0
def main():
    l, p, queries = read_data()
    vk_session = vk_api.VkApi(l, p)

    try:
        vk_session.auth()
    except Exception as e:
        print('could not authenticate to vk.com')
        print(e)
        print('please, check your user data in the file')
        sys.exit(1)

    api = vk_session.get_api()
    l = None
    p = None

    print('number of albums to download: {}'.format(queries.__len__()))
    for q in queries:
        o = q['owner_id']
        a = q['album_id']

        try:
            album = api.photos.getAlbums(owner_id=o, album_ids=a)['items'][0]
            title = album['title']
            title = fix_illegal_album_title(title)
            images_num = album['size']
            photos = api.photos.get(owner_id=o, album_id=a,
                                    photo_sizes=1)['items']
        except vk_api.exceptions.ApiError as e:
            print('exception:')
            print(e)
            return

        album_path = path_to_downloaded_albums + '/' + title
        if not os.path.exists(album_path):
            os.makedirs(album_path)
        else:
            album_path += '.copy_{:%Y-%m-%d_%H-%M-%S}'.format(
                datetime.datetime.now())
            os.makedirs(album_path)

        print('downloading album: ' + title)
        cnt = 0
        for p in photos:
            largest_image_width = p['sizes'][0]['width']
            largest_image_src = p['sizes'][0]['src']

            if largest_image_width == 0:
                largest_image_src = p['sizes'][p['sizes'].__len__() - 1]['src']
            else:
                for size in p['sizes']:
                    if size['width'] > largest_image_width:
                        largest_image_width = size['width']
                        largest_image_src = size['src']

            extension = re.findall(r'\.[\w\d.-]+$', largest_image_src)[0]
            download_image(largest_image_src,
                           album_path + '/' + str(p['id']) + extension)
            cnt += 1
            print_progress(cnt, images_num)
        print()
コード例 #27
0
def login_in():
    vk_session = vk_api.VkApi('', '',
                              auth_handler=auth_handler)  # ввод токена группы
    vk_session.auth()
    return vk_session.get_api()
コード例 #28
0
                requests.get(captcha.get_url(),
                             headers=headers).content).decode("utf-8"))
    print(code)
    if 'solution' in code and 'text' in code['solution']:
        key = code['solution']['text']
    else:
        key = input("Enter captcha code {0}: ".format(
            captcha.get_url())).strip()
    print(f"key={key}")
    # Пробуем снова отправить запрос с капчей
    return captcha.try_again(key)


pwd = open('token.txt', 'r').readlines()[0]
vk_session = vk_api.VkApi(token=pwd,
                          app_id=3140623,
                          client_secret="VeWdmVclDCtn6ihuP1nt",
                          captcha_handler=captcha_handler)
vk = vk_session.get_api()
long_poll = VkLongPoll(vk_session)
withdrawal = False
incorrect = False
last_task = 0


def main():
    global incorrect, withdrawal, last_task
    for event in long_poll.listen():
        try:
            if time.time() - last_task >= random.randint(100, 248):
                vk.messages.send(peer_id=-181521013,
                                 message="Вывод",
コード例 #29
0
 def handler(self, msg):
     vk = vk_api.VkApi(token=kbotlib.KBot().SETTINGS['TOKEN'])
     vk = vk.get_api()
     vk.messages.send(user_id=msg[3], message='Hello, ' + user + '!')
     time.sleep(10)
コード例 #30
0
ファイル: longpool.py プロジェクト: sergak01/Vk_bot
def main(longpoll=None):
    try:
        """ Пример использования longpoll
            https://vk.com/dev/using_longpoll
            https://vk.com/dev/using_longpoll_2
        """

        #login, password = '', ''
        #vk_session = vk_api.VkApi(login, password)
        print("Запускаю новую сессию!")
        token = settings.vk_token
        vk_session = vk_api.VkApi(token = token)
        vk_user_session = vk_api.VkApi(token = settings.vk_user_token)
        vk_empty_session = vk_api.VkApi()

        try:
            vk_session.auth()
        except vk_api.AuthError as error_msg:
            print(error_msg)
            return
        if longpoll == None:
            longpoll = VkLongPoll(vk_session)
        else:
            longpoll.update_longpoll_server()

        for event in longpoll.listen():
            try:
                if event.type == VkEventType.MESSAGE_NEW:
                    print('Новое сообщение:')

                    if event.from_me:
                        print('От меня для: ', end='')
                    elif event.to_me:
                        print('Для меня от: ', end='')

                    if event.from_user:
                        print(event.user_id)
                        if int(event.user_id) == 57008075:
                            reg = r'(id)?(\d*)? ?([^$]+)'
                            parser=re.compile(reg)
                            answer = parser.sub(r'\2', str(event.text))
                            if answer != "":
                                answer = parser.sub(r'\2', str(event.text))
                                try:
                                    if parser.sub(r'\3', str(event.text)) != "":
                                        write_msg(int(answer), parser.sub(r'\3', str(event.text)), vk_session)
                                    else:
                                        write_msg(int(answer), u".", vk_session)
                                except Exception as e:
                                    print(e)
                                user_name = vk_empty_session.method('users.get', {'user_id':int(answer)})
                                write_msg(57008075, u'Сообщение отправлено пользователю [id' + str(answer) + u'|' + 
                                    str(user_name[0]["first_name"]) + " " + str(user_name[0]["last_name"]) + 
                                    ']', vk_session)
                                continue;
                    elif event.from_chat:
                        print(event.user_id, 'в беседе', event.chat_id)
                    elif event.from_group:
                        print('группы', event.group_id)
                    try:
                        print('Текст: ', event.text)
                    except Exception as e:
                        print(e)
                    print()
                    if not event.from_me:
                        user_name = vk_empty_session.method('users.get', {'user_id':int(event.user_id)})
                        write_msg(57008075, u'[id' + str(event.user_id) + u'|' + 
                            str(user_name[0]["first_name"]) + " " + 
                            str(user_name[0]["last_name"]) +'] написал: ' + 
                            str(event.text) + '\nОтветить: https://vk.com/gim90818758?sel=' + 
                            str(event.user_id) + "\nОтветить через чат: id" + str(event.user_id), vk_session, event.raw[1])
                        #write_msg(int(event.user_id), u'Ваше сообщение переслано администратору сообщества! ;-)\nОн ответит Вам в ближайшее время.\nВ группе тестируеться бот, просим прощение за неудобства.', vk_session)

                elif event.type == VkEventType.USER_TYPING:
                    print('Печатает ', end='')

                    if event.from_user:
                        print(event.user_id)
                    elif event.from_group:
                        print('администратор группы', event.group_id)

                elif event.type == VkEventType.USER_TYPING_IN_CHAT:
                    print('Печатает ', event.user_id, 'в беседе', event.chat_id)

                elif event.type == VkEventType.USER_ONLINE:
                    print('Пользователь', event.user_id, 'онлайн', event.platform)

                elif event.type == VkEventType.USER_OFFLINE:
                    print('Пользователь', event.user_id, 'оффлайн', event.offline_type)

                else:
                    print(event.type, event.raw[1:])
            except requests.exceptions.ReadTimeout as e:
                print(e)
                time.sleep(10)
            except requests.packages.urllib3.exceptions.ReadTimeoutError as e:
                print(e)
                longpoll.update_longpoll_server()
    except Exception as e:
        print(e)
        time.sleep(10)
        main(longpoll)