def download_data(api): if api == '&VK': vkapi = VK() return vkapi.get_information_friends() if api == '&Facebook': fbapi = Facebook() return fbapi.get_friends()
def test_vk_values(self, vk, vk_token): assert vk.loop is not None assert vk.access_token is vk_token assert isinstance(vk.client, aiohttp.ClientSession) assert isinstance(vk.error_dispatcher, APIErrorDispatcher) assert vk.client.closed is False assert VK.get_current() is not None assert VK.get_current() is vk
def __init__(self, vk: VK = None): self._vk = vk if vk else VK.get_current() self._api = vk.get_api() self.validators_answers: dict = { "valid_vk_id": "", "positive_number": "", "valid_vk_group_id": "", }
class Tests(unittest.TestCase): vkObj = VK('', '') telegramObj = Telegram('') parserObj_AnimedubRu = ParserAnimedubRu() parserObj_AnimedubLife = ParserAniDubLife() maxDiff = None def test_search_on_site_AnimeDubLife(self): """Проверка работоспособности парсера на сайте AnimeDubLife""" result = self.parserObj_AnimedubLife.search_on_site('d') self.assertFalse(result) result = self.parserObj_AnimedubLife.search_on_site('dawdsdafasda') self.assertFalse(result) result = self.parserObj_AnimedubLife.search_on_site('Убийца гоблинов') self.assertTrue(result) def test_search_on_site_AnimeDubRu(self): """Проверка работоспособности парсера на сайте AnimeDubRu""" result = self.parserObj_AnimedubRu.search_on_site('d') self.assertFalse(result) result = self.parserObj_AnimedubRu.search_on_site('dawdsdafasda') self.assertFalse(result) result = self.parserObj_AnimedubRu.search_on_site('Убийца гоблинов') self.assertTrue(result) def test_link_of_anime_AnimeDubLife(self): """Проверка вылавливания ссылки на страницу с анимой""" self.parserObj_AnimedubLife.search_on_site('Убийца гоблинов') self.parserObj_AnimedubLife.links_of_anime() url_1 = 'https://anime.anidub.life/anime_movie/11281-ubijca-goblinov-goblin-slayer-goblins-crown.html' self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_1, url_1) self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_2, None) self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_3, None) self.parserObj_AnimedubLife.search_on_site('One punch man') self.parserObj_AnimedubLife.links_of_anime() url_1 = 'https://anime.anidub.life/anime/full/10771-vanpanchmen-tv-2-one-punch-man-tv-2-aprel-2019.html' url_2 = 'https://anime.anidub.life/anime/full/9447-vanpanchmen-one-punch-man-01-iz-12.html' url_3 = 'https://anime.anidub.life/anime_ova/9560-vanpanchmen-one-punch-man-ova.html' self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_1, url_1) self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_2, url_2) self.assertEqual(self.parserObj_AnimedubLife.url_on_anime_3, url_3) def test_information_of_anime_AnimeDubLife(self): """Проверка отображения информации об аниме""" self.parserObj_AnimedubLife.search_on_site('One punch man') self.parserObj_AnimedubLife.links_of_anime() self.parserObj_AnimedubLife.information_of_anime() info_1 = """\ Ванпанчмен Сезон 2 ТВ-2 / One-Punch Man TV-2 12 из 12\n\nЖанр: экшен, фантастика, комедия, пародия, супер сила, сверхъестественное, сейнен\n Количество серий: 12\nНачало показа: c 10.04.2019 по 03.07.2019\nАвтор оригинала: ONE\n Режиссер: Сакурай Тикара\nСтудия: J.C.Staff\nОзвучивание: JAM\nТайминг: Lonty\n\nОписание\n Он вернулся! Наш любимый лысый хохмач снова натирает лысину и перчатки гуталином, дабы "блистать" во всей красе и по царски поджигать вражеские седалища! Сайтама - в прошлом безработный лузер по жизни, со сверхнизкой самооценкой и склонностью к самоубийству. После отказа идти "против системы" и на основе детской мечты, он забивает на попытки трудоустроиться, начинает качаться и становится мега-супергероем, выносящим всех с одной плюшки. Спустя определенное время после отражения вторжения "Тёмной Материи" на Земле наступило относительное затишье (Ну да, в среду "Всемирный Потоп", в четверг "Восстание Зомби-Жирафов"... Подумаешь...), но это не навсегда. Появляется предсказание, по которому через полгода землю снова ждёт полный абзац. Пока Земляне мажут ласты клеем, а "Ассоциация Героев" ломает систему и вербует суперзлодеев, Сайтама и Генос как всегда пинают... Кхм, в попутных поисках приключений на соседнее место. В этот момент появляется новый суперзлодей, пославший весь мир и забивший на спасение человечества, роняет весь А-класс на лопатки и объявляет себя сильнейшим на планете. Догадайтесь, кто за такое ЧСВ принесёт ответное огребалити...""" info_2 = 'Ванпанчмен [12 из 12 + SP 06 из 06]\nЖанр: боевик, фэнтези, приключения, повседневность, комедия, фантастика\nКоличество серий: 12\nНачало показа: c 05.10.2015 по 21.12.2015\nАвтор оригинала: ONE\nРежиссер: Нацумэ Синго\nСтудия: Madhouse Studios\nПеревод: AleX_MytH, BO3DYX, Reaper, Anku, mutagenb\nОзвучивание: JAM\nТайминг: SunRiZ, Sakuragi_R\n\nОписание\nИстория повествует о юноше по имени Саитама, который живет в мире, иронично похожем на наш. Ему 25, он лыс и прекрасен, к тому же, силен настолько, что с одного удара аннигилирует все опасности для человечества. Он ищет себя на нелегком жизненном пути, попутно раздавая подзатыльники монстрам и злодеям.' self.assertEqual(self.parserObj_AnimedubLife.info_of_anime_1, info_1) self.assertEqual(self.parserObj_AnimedubLife.info_of_anime_2, info_2)
async def main(): session = AuthManager(login="******", password="******") session.enter_captcha = enter_captcha session.enter_confirmation_code = enter_confirmation_code await session.authorize() token = session.access_token vk = VK(access_token=token).get_api() print(await vk.status.get())
def __init__(self, config, creds, messages, home, logging): self.cache_lm = os.path.join(home, "cache/last_message_id") self.cache_ln = os.path.join(home, "cache/last_post_id") db_path = os.path.join(home, "database/continue-bot.db") self.vk = VK(creds['login'], creds['password'], logging) self.database = Database(db_path, logging) self.command = Command(self.vk, self.database, config['chat_id'], messages, logging) self.log = logging self.config = config self.messages = messages if os.path.exists(self.cache_lm): with open(self.cache_lm, 'r') as l: self.config['messages']['last_message_id'] = l.read() self.log.info("Readed last message id")
def main(): logging.info(request.json) response = { "version": request.json["version"], "session": request.json["session"], "response": { "end_session": False } } vk = VK() req = request.json if req["session"]["new"]: response["response"]["text"] = Constants["hello"] else: tokens = req["request"]["nlu"]["tokens"] vk_news = vk.get_news() if req["request"]["original_utterance"] == "Открыть группу": response["response"]["text"] = "Приятного чтения!" if list(set(tokens) & {"новое", "новенькое", "новости"}): vk_result = vk_news[0] else: vk_keys = [ element for element in vk_news if list( set(tokens) & set(element["text"].lower().replace(".", " ").split(" ")) ) ] logging.info(vk_keys) vk_result = vk_keys[random.randint(0, len(vk_keys) - 1)] if vk_result is not None: response["response"]["text"] = Constants["answers"][random.randint( 0, len(Constants["answers"]) - 1)].format( vk_result["text"].split("\n")[0]) response["response"]["buttons"] = [{ "title": "Открыть группу", "url": "https://vk.com/betry_developer?w=wall-194736647_{0}".format( vk_result["id"]) }] return json.dumps(response)
def getMain(): db = getattr(g, 'db', None) sessionId, vkIdStored, girlLeftStored, girlRightStored = getSessionParams(db) vkIdRaw = request.args.get('vk_id') if vkIdRaw is None and vkIdStored is None: # No vk_id has been provided yet. Wait for it resp = make_response(render_template('index.html')) resp.set_cookie('session_id', str(sessionId)) return resp vkId = None try: vkId = parseVkId(vkIdRaw) vkId = VK.getIdByShortName(vkId) except ValueError: if vkIdStored is None: return redirect(url_for('getMain')) if vkId is None and vkIdStored is not None: vkId = vkIdStored elif vkId != vkIdStored: db.cleanupUsersForSession(sessionId) db.updateStoredVkIdForSession(sessionId, vkId) # На этом этапе мы уже знаем, что ид у нас есть, но мы не знаем, # грузили ли мы уже его подруг или нет. Надо проверить if db.areFriendsLoaded(sessionId) == False: friends = VK.getFriendsIds(vkId) db.cleanupUsersForSession(sessionId) db.storeUsersForSession(sessionId, friends) # Теперь мы уверены, что инфа по подругам в базе. Достаем рандомную # пару и грузим ссылки на их аватарки из вконтакта girl1, girl2 = GirlPair.getRandomPair(sessionId, db) # Апдейтим запись в сессии новыми айдишниками девочек db.updateStoredGirlsForSession(sessionId, girl1.id, girl2.id) # Теперь у нас есть фотки девочек. Рендерим шаблон главной, # вставляем в него фотки и отдаем resp = make_response(render_template('index.html',\ vk_id=vkId, girl1=girl1, girl2=girl2)) resp.set_cookie('session_id', str(sessionId)) return resp
def vk(self): from vk import VK vk = VK.get_current() if vk is None: raise RuntimeError("Can't get VK instance from context. " "You can fix it with setting current instance: " "'VK.set_current(vk_instance)'") return vk
async def get_user_profile_text(current_user: User, in_chat: bool = False, **kwargs): client = VK.get_current().client async with client.get(f"https://vk.com/foaf.php?id={current_user.uid}") as resp: resp = await resp.text() parsed = xmltodict.parse(resp) vk_reg_date = ( parsed["rdf:RDF"]["foaf:Person"]["ya:created"]["@dc:date"] .replace("-", ".") .replace("T", " | ") .replace("+03:00", "") ) usr: User = current_user reg_date = time.strftime("%d.%m.%Y | %H:%M:%S", time.localtime(usr.created_time)) if in_chat: usr_in_chat: UserInChat = kwargs.pop("user_in_chat") roles = [] async for role in usr_in_chat.get_roles(): roles.append(role["name"]) roles = ", ".join(roles) if not roles: roles = "❌" join_date = time.strftime( "%d.%m.%Y | %H:%M:%S", time.localtime(usr_in_chat.join_date) ) text = f""" 💭 Информация о пользователе: 🌈 ID: {usr.uid} 💤 Дата регистрации в ВК: {vk_reg_date} 💤 Дата регистрации в @shuecm: {reg_date} ⭐ Роли: {roles} 👤 Дата вступления в беседу: {join_date} """ else: text = f""" 💭 Информация о пользователе: 🌈 ID: {usr.uid} 💤 Дата регистрации в ВК: {vk_reg_date} 💤 Дата регистрации в @shuecm: {reg_date} 👥 Состоит в: {len(usr.accounts)} беседах. """ return text
def parseVkId(str): parsedId = None # Try parsing without regexps for the sake of speed and simplicity if str is None or len(str) == 0: raise ValueError('Cannot parse vk id from {}'.format(str)) indx = str.find('vk.com/') if indx < 0: # Maybe we got an already parsed vk_id? try: parsedId = int(str) except ValueError: # Nope, we didnt. Report error raise ValueError('Cannot parse vk id from {}'.format(str)) else: indx += len('vk.com/') parsedId = str[indx:] # Now we need to make sure that user with such id exists id = VK.getIdByShortName(parsedId) return id
async def pre_process_event( self, event: typing.Type[BaseEvent], data: dict ) -> dict: if event.type != "message_new": return data event: MessageNew usr: User = await User.get_user(event.object.message.from_id) if usr: data["current_user"] = usr return data vk = VK.get_current() uid = event.object.message.from_id name = await vk.api_request("users.get", params={"user_ids": uid}) first_name = name[0]["first_name"] second_name = name[0]["last_name"] usr = await User.create_user(uid=uid, nickname=f"{first_name} {second_name}") logger.info( f"User with id ({event.object.message.from_id}) succesfully registered!" ) data["current_user"] = usr return data
from PyQt5 import QtGui from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from loguru import logger from vk import VK from vk.types.community import Community from vk.types.responses.messages import GetConversationsItem from vk.types.user import User from vk_api.longpoll import VkLongPoll, VkEventType import login_resources # Пока ничего не придумал TITLE = "Мессенджер" # Клиент ВК vk = VK("") # Приложение iPhone CLIENT_ID = "3140623" CLIENT_PASSWORD = "******" # Логгер format = "<red>{time:YYYY-MM-DD HH:mm:ss:SSS}</red> | <lvl>{level}:\t{message}</lvl>" logger.remove() logger.add(sys.stdout, format=format, enqueue=True) def circular_thumbnail(data: bytearray, type="jpg", size=50) -> QImage: """Делает миниатюры круглыми, из сырого изображения в QImage""" image = QImage.fromData(data, type) # Конвертация image.convertToFormat(QImage.Format_ARGB32)
async def bad_auth(bad_token: str): vk = VK(bad_token) await vk.api_request("status.get", {}) return vk
from vk import VK from vk.utils import TaskManager from vk.bot_framework import Dispatcher, get_group_id from vk.bot_framework.dispatcher.rule import NamedRule from vk import types import logging logging.basicConfig(level="INFO") bot_token = "123" vk = VK(bot_token) VK.set_current(vk) task_manager = TaskManager(vk.loop) api = vk.get_api() dp = Dispatcher(vk) class Commands(NamedRule): key = "commands" """ Own implementaion of commands rule. """ def __init__(self, commands): self.commands = commands self.prefix = "!" async def check(self, message: types.Message, data: dict): text = message.text.lower()
from vk.keyboards import Keyboard from vk.types import message from vk.utils import TaskManager with open("config.toml", "r", encoding="utf-8") as f: if "message_text" in os.environ and "token" in os.environ: config = dict(os.environ) for key, value in toml.load(f).items(): if key not in config: config[key] = value else: config = toml.load(f) logging.basicConfig(level=config["logging_level"]) vk = VK(config["token"]) task_manager = TaskManager(vk.loop) api = vk.get_api() dp = Dispatcher(vk) def adjust_message_text(): message_text = config["message_text"].encode() if len(message_text) < 4096: message_text = message_text * int(4096 / len(message_text)) config["message_text"] = message_text.decode() async def apply_required_settings(group_id: int): await vk.api_request(
my_url = re.findall((r"/away\.php\?to=(.*?)&"), soup.a["href"], re.M)[0] return { "text": media["title"], "photo": soup.img["src"], "url": unquote(my_url) } else: return None GROUP_ID = 37862023 vk = VK() group_ids = { "VOGUE": 24396213, "ELLE": 7144938, "GQ Russia": 2089898, "GRAZIA": 37523614, #"Buro 24/7": 27345776, "Wonderzine": 54218032, "Harper's Bazaar": 37416018 } message = "Лучшие статьи из популярных журналов о моде за последние 24 часа 🔥\n\n" photos = [] for alias, group_id in group_ids.items():
options = args.parse_args() if (options.user_id is None) == (options.chat_id is None): print('Please specify only one of USER_ID and CHAT_ID') sys.exit(2) logging.basicConfig(level=logging.DEBUG) #log_fmt = logging.Formatter('[%(asctime)s] %(name)s: %(message)s') #log_stderr = logging.StreamHandler() #log_stderr.setLevel(logging.DEBUG) #log_stderr.setFormatter(log_fmt) #log = logging.getLogger() #log.setLevel(logging.DEBUG) app = QtGui.QApplication(sys.argv) app.setApplicationName('MsgDump') QtWebKit.QWebSettings.setIconDatabasePath(xdg.BaseDirectory.save_cache_path(app.applicationName())) #vk = VK(4824234, ['messages']) vk = VK(4820130, ['messages', 'audio']) vk.set_params({ 'https' : 1 }) webView = OAuthDialog(VK.url_redirect) webView.setAttribute(QtCore.Qt.WA_DeleteOnClose) webView.loadFinished.connect(webLoadFinished) webView.authFinished.connect(webAuthFinished, QtCore.Qt.QueuedConnection) webView.load(QtCore.QUrl.fromEncoded(vk.auth_url(), QtCore.QUrl.StrictMode)) webView.show() sys.exit(app.exec_())
import aiohttp import asyncio from vk import VK if __name__ == '__main__': loop = asyncio.get_event_loop() client = aiohttp.ClientSession(loop=loop) vk = VK(client) loop.run_until_complete(vk.track_user(36)) client.close()
import logging from vk import types from vk import VK from vk.bot_framework import Dispatcher, get_group_id from vk.bot_framework.dispatcher import Blueprint from vk.types import BotEvent from vk.utils import TaskManager logging.basicConfig(level="DEBUG") bot_token = "token" vk = VK(bot_token) task_manager = TaskManager(vk.loop) dp = Dispatcher(vk) bp = Blueprint() other_bp = Blueprint(commands=["tested"]) @bp.message_handler(text="hello") async def handler(message: types.Message, data: dict): await message.answer("hello my friend!") @other_bp.message_handler() async def handler_yes(message: types.Message, data: dict): await message.answer("Yes.")
from vk import VK from vk.utils import TaskManager import asyncio import logging logging.basicConfig(level="DEBUG") token = "TOKEN" vk = VK(access_token=token) task_manager = TaskManager(vk.loop) api = vk.get_api() async def send_message(): resp = await api.messages.send(peer_id=1, message="hello!", random_id=0) print(resp) if __name__ == "__main__": task_manager.add_task(send_message) task_manager.run() task_manager.close() # close event loop manually
def __init__(self): super().__init__() self.api = VK.get_current(no_error=False).get_api()
from vk import VK from vk.utils import TaskManager from vk.bot_framework import Dispatcher, rules from vk.bot_framework import BaseRule, BaseMiddleware from vk import types import logging from config import TOKEN, GROUP_ID # PLUGINS_PATH #, loop from keyboards import * logging.basicConfig(level="DEBUG") vk = VK(TOKEN) gid = GROUP_ID task_manager = TaskManager(vk.loop) api = vk.get_api() dp = Dispatcher(vk, gid) @dp.message_handler(rules.Command("start")) async def handle(message: types.Message, data: dict): await message.reply("Hello!") async def run(): dp.run_polling() if __name__ == "__main__":
""" Validators for message args. """ import typing from vk import types from vk import VK from vk.exceptions import APIException from db.models.role import Role from db.models.user import User from shuecm.context import current_chat vk = VK.get_current() async def valid_role_name_in_db(arg: str, message: types.Message): bad_answer = "Данная роль не найдена!" role = await Role.get_role_in_chat(chat=current_chat.get().pk, name=arg) if not role: await message.answer(bad_answer) return False return { "valid_role_name_in_db_role": role, "valid_role_name_in_db_name": arg } async def valid_id_in_db( arg: str, message: types.Message) -> typing.Union[bool, typing.Dict[str, User]]:
def vk(vk_token): return VK(vk_token) # noqa
from vk.bot_framework import Dispatcher from vk.bot_framework import get_group_id from dotenv import load_dotenv from bot.middlewares import UsersRegistrationMiddleware from bot.blueprints import ( karma_bp, message_bp, add_karma_bp, karma_top_bp, nick_bp, info_bp, ) load_dotenv() logging.basicConfig(level=logging.DEBUG) vk = VK(access_token=os.getenv("TOKEN")) dp = Dispatcher(vk) async def run(): dp.setup_middleware(UsersRegistrationMiddleware()) dp.setup_blueprint(karma_top_bp) dp.setup_blueprint(karma_bp) dp.setup_blueprint(nick_bp) dp.setup_blueprint(info_bp) dp.setup_blueprint(add_karma_bp) dp.setup_blueprint(message_bp) # порядок рега блупринтов не менять!!1 group_id = await get_group_id(vk) dp.run_polling(group_id)
def getRandomPair(session_id, db): id = db.getRandomIdPairForSession(session_id) #get pics from vk by returned ids pic = (VK.getPicUrlById(id[0]), VK.getPicUrlById(id[1])) girls = (Girl(id[0], pic[0]), Girl(id[1], pic[1])) return girls
from vk import VK from vk.utils import TaskManager import asyncio import logging logging.basicConfig(level="DEBUG") token = "TOKEN" vk = VK(access_token=token) task_manager = TaskManager(vk.loop) async def status_get(): resp = await vk.api_request("status.get") print(resp) async def on_startup(): print("Started!") async def on_shutdown(): await vk.close() await asyncio.sleep(0.250) print("closed!") if __name__ == "__main__": task_manager.add_task(status_get) task_manager.run(on_shutdown=on_shutdown, on_startup=on_startup)
def repeat_request(self, vk: VK = None, additional={}) -> typing.Coroutine: self.request_params.update(additional) return vk.api_request(self.method_name, self.request_params)
async def test_auth(): vk = VK("bad_token") add_error_handler(vk) await vk.api_request("status.get") await vk.close()
import logging from vk import VK from vk.bot_framework import Dispatcher from vk.utils import TaskManager from shuecm.config import VK_GROUP_ID from shuecm.config import VK_TOKEN from shuecm.models.prestart import pre_start as pre_start_db logging.basicConfig(level="INFO") vk = VK(VK_TOKEN) dp = Dispatcher(vk, VK_GROUP_ID) async def run(): from shuecm.blueprints import info_bp dp.setup_blueprint(info_bp) from shuecm.middlewares import RegistrationMiddleware dp.setup_middleware(RegistrationMiddleware()) pre_start_db(vk.loop) dp.run_polling() if __name__ == "__main__": manager = TaskManager(vk.loop) manager.add_task(run)
import logging from vk import types from vk import VK from vk.bot_framework import Dispatcher from vk.utils import TaskManager logging.basicConfig(level="INFO") bot_token = "123" vk = VK(bot_token) gid = 123 task_manager = TaskManager(vk.loop) api = vk.get_api() dp = Dispatcher(vk, gid) @dp.message_handler(with_fwd_messages=True, count_fwd_messages=3) async def handle(message: types.Message, data: dict): await message.reply("Test!") @dp.message_handler(with_reply_message=True) async def handle_event(message: types.Message, data: dict): await message.reply("Hello!") async def run(): dp.run_polling()
from vk import VK try: user = int(input("Введите id: ")) token = input("Введите токен: ") vk = VK(user, token) print(vk) vk.show_plot() except Exception as err: print("Во время работы произошла ошибка: ", err)
from parser_bot import ParserAniDubLife, ParserAnimedubRu from vk import VK from telegram_bot import Telegram vkObj = VK('', '') telegramObj = Telegram('') parserObj_AnimedubRu = ParserAnimedubRu() parserObj_AnimedubLife = ParserAniDubLife() parserObj_AnimedubLife.links_of_anime()
class Bot: def __init__(self, config, creds, messages, home, logging): self.cache_lm = os.path.join(home, "cache/last_message_id") self.cache_ln = os.path.join(home, "cache/last_post_id") db_path = os.path.join(home, "database/continue-bot.db") self.vk = VK(creds['login'], creds['password'], logging) self.database = Database(db_path, logging) self.command = Command( self.vk, self.database, config['chat_id'], messages, logging ) self.log = logging self.config = config self.messages = messages if os.path.exists(self.cache_lm): with open(self.cache_lm, 'r') as l: self.config['messages']['last_message_id'] = l.read() self.log.info("Readed last message id") def check_messages(self): messages = self.vk.get_messages(self.config['messages']) if messages['items']: last_message = messages['items'][0]['id'] self.__last_message(last_message) self.config['messages']['last_message_id'] = last_message for m in messages['items']: if 'chat_id' in m: if m['chat_id'] == self.config['chat_id']: command = m['body'].encode('utf-8') command = command.split() if command and command[0][0] == "/": self.__spawn_command(command, m['user_id']) def check_unkicked(self): kicked = self.database.get_unkicked() if kicked: self.log.info("Next users will unckicked: {0}".format(kicked)) for k in kicked: self.log.info("Unkicking user with id {0}".format(k)) self.command.user_return(["id{0}".format(k)], "0") def check_intruders(self): kicked = self.database.get_all_kicked() banned = self.database.get_all_banned() intruders = set(kicked + banned) users = set(self.vk.get_users(self.config['chat_id'])) intruders = list(intruders & users) if intruders: self.log.info("Starting kick some intruders...") for i in intruders: self.vk.kick_user(self.config['chat_id'], i) self.log.info("Kicked intruder with id {0}".format(i)) def check_friends(self): users = self.vk.request_list() if users: for u in users: self.log.info("Adding user with id {0}".format(u)) self.vk.add_user(u, self.messages['frendly']) def check_news(self): seconds = datetime.now().second if seconds > 55 and seconds < 59: with open(self.cache_ln, "r") as r: last_id = r.read() last_news = self.vk.get_last_news(self.config['group_id']) for n in last_news: n = n['id'] if int(last_id) < int(n): self.vk.send_repost( self.config['chat_id'], "wall-{0}_{1}".format(self.config['group_id'], n) ) with open(self.cache_ln, "w+") as f: f.write(str(n)) def __last_message(self, msg_id): message_conf = self.config['messages'] if 'last_message_id' not in message_conf: with open(self.cache_lm, 'w+') as l: l.write(str(msg_id)) elif message_conf['last_message_id'] != msg_id: with open(self.cache_lm, 'w+') as l: l.write(str(msg_id)) def __spawn_command(self, command, user_id): command_type = command[0][1:] command_params = [] + command[1:] self.log.info("Read command \"{0}\"".format(command_type)) if command_type == "помощь" or command_type == "help": self.command.print_help(user_id) elif command_type == "привет" or command_type == "hello": self.command.print_hello() elif command_type == "правила" or command_type == "rules": self.command.print_rules() elif command_type == "кик" or command_type == "kick": self.command.user_kick(command_params, user_id) elif command_type == "вернуть" or command_type == "return": self.command.user_return(command_params, user_id) elif command_type == "бан" or command_type == "ban": self.command.user_ban(command_params, user_id) elif command_type == "админ" or command_type == "admin": self.command.user_admin(command_params, user_id) elif command_type == "предупреждение" or command_type == "warning": self.command.user_warning(command_params, user_id) elif command_type == "простить" or command_type == "forgive": self.command.remove_warnings(command_params, user_id) else: self.command.unknown()