def __init__(self, api_token, api_app_token, group_id, server_name: str = "Empty"): # Даем серверу имя self.server_name = server_name # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использования Long Poll API self.long_poll = VkBotLongPoll(self.vk, group_id) # Для вызова методов vk_api self.vk_api = self.vk.get_api() # Для проверки постов других групп self.vk_api_app = vk_api.VkApi(token=api_app_token).get_api() self.users = {} self.kill = False self.keyboard = self.add_keyboard() self.last_function = None print('Сервер поднят!')
def __init__(self, api_token, group_id, server_name: str = "noname"): self.server_name = server_name self.vk = vk_api.VkApi(token=api_token) self.long_poll = VkBotLongPoll(self.vk, group_id) self.vk_api = self.vk.get_api() print("Сервер " + self.server_name + " запущен!") self.users = {}
def __init__(self, token=TOKEN, group_id=VK_GROUP_ID): self._chat_id = 0 # Авторизация self._api = vk_api.VkApi(token=token) # Работа с сообщениями self._longpoll = VkBotLongPoll(self._api, group_id) self._people_queue = PeopleQueue()
def __init__(self, group_id, token): self.group_id = group_id self.token = token self.vk = vk_api.VkApi(token=token) self.long_poll = vk_api.bot_longpoll.VkBotLongPoll( self.vk, self.group_id) self.api = self.vk.get_api()
def main(): load_dotenv() vk_session = vk_api.VkApi(os.getenv('VK_LOGIN'), os.getenv('VK_PASS')) vk_session.auth() vk = vk_session.get_api() with open('simple.csv', 'r', encoding='utf-8') as f: fields = [ 'name', 'price', 'description', 'calories', 'picture', ] reader = csv.DictReader(f, fields, delimiter=';') for row in reader: available = os.path.exists( os.path.join('data', f'{row["name"]}.jpg')) if available: print('file exists') continue else: save_item_picture_from_web(row['picture'], row['name']) picture = set_item_picture( vk, os.path.join('data', f'{row["name"]}.jpg')) vk.market.add(owner_id=f'-{os.getenv("GROUP_ID")}', name=row["name"], description=row['description'], category_id='1', price=float(row['price'].replace('$', '')), main_photo_id=picture[0]['id'], v='5.95')
def __init__(self, api_token, group_id, server_name: str = "Empty"): # Даем серверу имя self.server_name = server_name # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использования Long Poll API self.long_poll = VkBotLongPoll(self.vk, group_id) # Для вызова методов vk_api self.vk_api = self.vk.get_api() # Словарь для каждого отдельного пользователя self.users = {} self.id_user = -1 # Токен self.tok = '' self.isTok = False # Группа self.id_group = -1 # v self.v = '5.103'
def __init__(self, api_token, group_id, server_name: str = "Empty"): self.server_name = server_name self.group_id = group_id self.vk = vk_api.VkApi(token=api_token) self.long_poll = VkBotLongPoll(self.vk, group_id, wait=30) self.vk_api = self.vk.get_api() self.userSessions = {}
def __init__(self, api_token, group_id, server_name: str = "Empty"): self.server_name = server_name self.vk = vk_api.VkApi(token=api_token) self.long_poll = VkBotLongPoll(self.vk, group_id) self.vk_api = self.vk.get_api() # Словарь для каждого отдельного пользователя self.users = {}
def __init__(self, main_token, group_id, *args, **kwargs): # Инициализация бота super(Bot, self).__init__(*args, **kwargs) self.group_id = group_id # id группы передаётся из файла settings.py self.vk_session = vk_api.VkApi( token=main_token) # Запуск ВК сессии при помощи токена API self.vk = self.vk_session.get_api() self.longpool = None self.upload = VkUpload(self.vk)
def __init__(self, api_token, group_id, server_name: str = "Empty"): self.api_token = api_token # TOKEN группы self.group_id = group_id # ID группы self.server_name = server_name # Имя сервера self.vk = vk_api.VkApi(token=api_token) # Сессия self.longpoll = VkBotLongPoll(self.vk, group_id) # LongPoll сервер self.vk_api = self.vk.get_api() # Для вызова методов из vk_api self.users = {} # Словарь для каждого пользователя
def __init__(self, api_token, group_id): self.group_id = group_id self.vk = vk_api.VkApi(token=api_token) self.bot_long_poll = VkBotLongPoll(self.vk, group_id) self.vk_api = self.vk.get_api() self.upload = vk_api.upload.VkUpload(self.vk) self.session = requests.session()
def __init__(self): login = input('Введите номер телефона:') self.login = login password = input('Введите пароль:') self.session = vk_api.VkApi(login, password, auth_handler=self.auth_handler) self.session.auth() self.token = self.session.token['access_token'] self.user = self.session.token['user_id']
def __init__(self): super().__init__() self.id = env.int('VK_USER_ID') vk_session = vk_api.VkApi( env.str('VK_USER_LOGIN'), env.str('VK_USER_PASSWORD'), auth_handler=self.auth_handler, config_filename=f"{BASE_DIR}/secrets/vk_user_config.json") vk_session.auth() self.upload = VkUpload(vk_session) self.vk = vk_session.get_api()
def __init__(self): self.vk = vk_api.VkApi(token='group_token') self.long_poll = VkBotLongPoll(self.vk, group_id='group_id') self.vk_api = self.vk.get_api() self.warns = {} with open('warns.txt', 'rb') as inp: try: self.warns = pickle.load(inp) except EOFError: self.warns = {}
def __init__(self): super().__init__() self.id = int(secrets['vk']['user']['id']) vk_session = vk_api.VkApi(secrets['vk']['user']['login'], secrets['vk']['user']['password'], auth_handler=self.auth_handler, config_filename=f"{BASE_DIR}/secrets/vk_user_config.json" ) vk_session.auth() self.upload = VkUpload(vk_session) self.vk = vk_session.get_api()
def __init__(self, api_token, server_name: str = "Empty"): # Даем серверу имя self.server_name = server_name # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использования Long Poll API self.long_poll = VkLongPoll(self.vk) # Для вызова методов vk_api self.vk_api = self.vk.get_api()
def __init__(self, token, hash_tag, cnt_hours): """ Конструктор :param token: токен приложения из VK :type token: str :param hash_tag: хэштег для поиска :type hash_tag: str :param cnt_hours: количество часов для поиска :type cnt_hours: int """ self.hours_for_search, self.hash_tag_text = cnt_hours, hash_tag self.vk_func = vk_api.VkApi(api_version='5.102', access_token=token)
def __init__(self, api_token, group_id, server_name): # Даем серверу имя self.server_name = server_name # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использования Long Poll API self.long_poll = VkBotLongPoll(self.vk, group_id) # Для вызова методов vk_api self.vk_api = self.vk.get_api()
def __init__(self, group_id, token, logger): """ :param group_id: group id из группы в vk :param token: секретный токен :param logger: Logger Objects """ self.gid = group_id self.token = token self.vk_session = vk_api.VkApi(token=self.token) self.bot_longpoller = VkBotLongPoll(vk=self.vk_session, group_id=self.gid) self.api = self.vk_session.get_api() self.logger = logger
def post(self): print(request) vk_session = vk_api.VkApi(app_id=3380204, client_secret='Ky3xN0ohvtMzaVgCYU80') vk_session.code_auth(request.json()['code'], request.json()['redirectUri']) token = vk_session.token['access_token'] vkaudio = VkAudio(vk_session) print([x for x in vkaudio.search('sandstorm')]) """ 'code' (139893782146720) = {str} 'f2addb2855bb6b95b5' 'clientId' (139893782181168) = {str} '3380204' 'redirectUri' (139893782180784) = {str} 'https://192.168.20.37:8080/' """ return {"status": request, 'access_token': 'fdsafsad'}, 200
def run(self): vk_session = vk_api.VkApi(token=self.vk_token) vk = vk_session.get_api() long_poll = VkLongPoll(vk_session) for event in long_poll.listen(): if self.paused: continue if event.type == VkEventType.MESSAGE_NEW: if event.to_me: user_message = vk.users.get(user_ids=event.user_id)[0] manage.bot.send_message( self.chat_id, f'Новое сообщение {event.message} от: {user_message["first_name"]} ' f'{user_message["last_name"]}')
def __init__(self, api_token, group_id, server_name: str = "Empty"): self.server_name = server_name self.vk = vk_api.VkApi(token=api_token) self.long_poll = VkBotLongPoll(self.vk, group_id) self.vk_api = self.vk.get_api() # Словарь дял каждого отдельного пользователя/группы self.users = {} #self.group = {}#нужно ли self.lastCayBoard: VkKeyboard = VkKeyboard(one_time=True) self.lastCayBoard.add_button('Привет')
def run_bot(): """Start long polling Bot for VK group """ vk_token = os.environ.get('VK_TOKEN') vk_session = vk_api.VkApi(token=vk_token) session_api = vk_session.get_api() polling = VkLongPoll(vk_session) logger.info('Start polling') for event in polling.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me: handle_message(event, session_api)
def auth(token: str): """ Авторизуется в системе Vk :param token: токен :return: авторизованная сессия vk_api.VkApi """ vk_session = vk_api.VkApi(token=token) try: vk_session._auth_token(reauth=True) except vk_api.AuthError as error_msg: print(error_msg) return vk = vk_session.get_api() return vk
def login() -> vk.VkApi: """Sign in to vk.com with login and password.""" login, password, tg_login = auth() vk_session = vk.VkApi(login, password) # Free login and password memory. del login del password try: vk_session.auth(token_only=True) print_msg('ok', 'Connected succesfully.') except vk.AuthError as err: print_msg('error', f'{err}!') exit() return vk_session, tg_login
def __init__(self, api_token, group_id, func): self.token = api_token self.group = group_id self.func = func # Для Long Poll self.vk_session = vk_api.VkApi(token=api_token, scope=4096) # Для загрузки файлов self.upload = VkUpload(self.vk_session) # Для использования Long Poll API self.long_poll = VkBotLongPoll(self.vk_session, group_id) # Для вызова методов vk_api self.vk = self.vk_session.get_api()
def __init__(self, code_manager, coin_api): self.coin_api = coin_api self.code_manager = code_manager self.session = vk_api.VkApi(token=group_token) self.bot = VkBotLongPoll(self.session, group_id) self.api = self.session.get_api() self.main_keyboard = VkKeyboard(one_time=False) def add_button(text, color=VkKeyboardColor.DEFAULT, payload=''): self.main_keyboard.add_button(text, color=color, payload=payload) add_button('Купить', color=VkKeyboardColor.POSITIVE) add_button('Инструкция') self.main_keyboard.add_line() add_button('Цены', color=VkKeyboardColor.DEFAULT)
def __init__(self, api_token, group_id, server_name: str = "Empty"): # Даем серверу имя self.server_name = server_name self.group_id = group_id # Для Long Poll self.vk = vk_api.VkApi(token=api_token) # Для использоания Long Poll API self.long_poll = VkBotLongPoll(self.vk, group_id, wait=30) # Для вызова методов vk_api self.vk_api = self.vk.get_api() # Словарь дял каждого отдельного пользователя self.users = {}
def __init__(self, api_token, group_id, server_name: str = "Empty"): # Даем серверу имя self.server_name = server_name # Vk stuff self.vk = vk_api.VkApi(token=api_token) self.long_poll = VkBotLongPoll(self.vk, group_id) self.vk_api = self.vk.get_api() self.gmail = GmailAgent() self.lock = threading.Lock() # logger config self.logger = logging.getLogger("vk_bot") handler = logging.FileHandler('sample.log', 'a+', 'utf-8') formatter = logging.Formatter("%(asctime)s %(name)s:%(levelname)s:%(message)s") handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.setLevel(logging.INFO)
def main(): """ Пример получения access_token из сode после OAuth авторизации на сайте """ code = '18dczc1337a63427fa' redirect_url = 'http://example.com' app = 000000 secret = 'dGbpoJdqNuMlGDECgO9I' vk_session = vk_api.VkApi(app_id=app, client_secret=secret) try: vk_session.code_auth(code, redirect_url) except vk_api.AuthError as error_msg: print(error_msg) return print(vk_session.token['user_id']) print(vk_session.token['access_token'])