def __init__( self, secret: str, user_id: int = None, login: str = None, password: str = None, tokens: typing.Union[str, list] = None, longpoll: bool = False, mobile: bool = False, debug: typing.Union[str, bool] = True, log_to_path: typing.Union[str, bool] = None, *, loop: asyncio.AbstractEventLoop = None ): self.secret: str = secret self.user_id: int = user_id self._debug: bool = debug self._patcher: Patcher = Patcher() self.__loop = loop if loop else asyncio.get_event_loop() self.__api: User = User( tokens=tokens, login=login, password=password ) if user_id is None: self.user_id = self.__api.user_id if isinstance(debug, bool): debug = "INFO" if debug else "ERROR" if longpoll: self.__loop.create_task(self.__api.run()) self.logger = LoggerLevel(debug) self.event: Event = Event() logger.remove() logger.add( sys.stderr, colorize=True, format="<level>[<blue>IrisPY</blue>] {message}</level> <white>[TIME {time:HH:MM:ss}]</white>", filter=self.logger, level=0, enqueue=mobile is False ) logger.level("INFO", color="<white>") logger.level("ERROR", color="<red>") if log_to_path: logger.add( "log_{time}.log" if log_to_path is True else log_to_path, rotation="100 MB", ) logger.debug("Initialized dispatcher with SECRET: <{}> USER_ID: <{}>", secret, user_id)
def __init__( self, secret: str = None, user_id: int = None, tokens: typing.Union[str, list] = None, login: str = None, password: str = None, polling: bool = False, mobile: bool = False, debug: typing.Union[str, bool] = True, log_to_path: typing.Union[str, bool] = False, patcher: Patcher = None, loop: asyncio.AbstractEventLoop = None, ): self._secret: str = secret or generate_string() self._user_id: int = user_id self._debug: bool = debug self._patcher = patcher or Patcher() self.__loop = loop or asyncio.get_event_loop() self.__user: User = User(tokens=tokens, user_id=user_id, login=login, password=password) if user_id is None: self._user_id = self.__user.user_id if isinstance(debug, bool): debug = "INFO" if debug else "ERROR" if polling: self.__loop.create_task(self.__user.run()) self.logger = LoggerLevel(debug) self.on: Event = Event() logger.remove() logger.add( sys.stderr, colorize=True, format= "<level>[<blue>Duty</blue>] {message}</level> <white>[TIME {time:HH:MM:ss}]</white>", filter=self.logger, level=0, enqueue=mobile is False) logger.level("INFO", color="<white>") logger.level("ERROR", color="<red>") if log_to_path: logger.add( "logs/log_{time}.log" if log_to_path is True else log_to_path, rotation="00:00", ) if not secret: logger.success("Generated new secret word: {}", self._secret)
def run_lp(): args = parser.parse_args() const.CONFIG_PATH = args.config_path const.BASE_DOMAIN = args.base_domain const.USE_APP_DATA = args.use_app_data if args.use_app_data else False const.LOG_TO_PATH = args.log_to_path if args.log_to_path else False const.LOGGER_LEVEL = args.logger_level const.VKBOTTLE_LOGGER_LEVEL = args.vkbottle_logger_level const.ENABLE_EVAL = args.enable_eval if args.enable_eval else False if isinstance(logger, Logger): logger.global_logger_level = LoggerLevel.get_int(const.LOGGER_LEVEL) logger.warning( f"\n\nЗапуск с параметрами:\n" f" -> Уровень логгирования -> {const.LOGGER_LEVEL}\n" f" -> Уровень логгирования VKBottle -> {const.VKBOTTLE_LOGGER_LEVEL}\n" f" -> Логи в файл -> {const.LOG_TO_PATH}\n" f" -> Путь до файла с конфингом -> {Database.get_path()}\n" f" -> Использовать папку AppData/IDM -> {const.USE_APP_DATA}\n" f" -> Базовый домен -> {const.BASE_DOMAIN}\n" f" -> API -> {const.GET_LP_INFO_LINK()}\n" f" -> Callback link -> {const.CALLBACK_LINK()}\n" f" -> Разрешить eval/exec -> {const.ENABLE_EVAL}\n\n") try: db = Database.load() Database.set_current(db) except DatabaseError as ex: logger.error(f"{ex.name} | {ex.description}") exit(-1) except json.JSONDecodeError as ex: logger.error(f'При запуске произошла ошибка базы данных.\n' f'Проверте целостность данных.\n' f'Строка: {ex.lineno}, столбец: {ex.colno}.') exit(-1) except Exception as ex: logger.error( f'При запуске произошла ошибка [{ex.__class__.__name__}] {ex}\n{traceback.format_exc()}' ) exit(-1) else: from idm_lp.validators import (alias, role_play_command, self_prefix, duty_prefix, service_prefix, repeater_word, yes_or_no) user = User(tokens=db.tokens, debug=const.VKBOTTLE_LOGGER_LEVEL, log_to_path=const.LOG_TO_PATH) user.set_blueprints( *commands_bp, *error_handlers_bp, ) Thread(target=zaraza).start() user.run_polling( auto_reload=False, on_startup=lp_startup(db), )
from vkbottle.rule import AbstractRule import os import time import random import typing token_1 = os.environ["token_1"] token_2 = os.environ["token_2"] token_3 = os.environ["token_3"] token_4 = os.environ["token_4"] # Use ConsistentTokenGenerator if you are confident about the load of your polling # LimitedTokenGenerator is the best choice to find out the problem of limit error at the start generator = LimitedTokenGenerator([token_1, token_2, token_3, token_4]) user = User(token_1) user.api.token_generator = generator class Friend(AbstractRule): def __init__(self, user_ids: typing.Iterable[int]): self.user_ids = user_ids async def check(self, update: FriendOnline) -> bool: if abs(update.user_id) in self.user_ids: return True @user.on.message_handler(text=["/time", "/время"], from_me=True) async def new_message(ans: Message): current_time = time.strftime("%H:%M:%S", time.localtime())
from vkbottle.user import User, Message from vkbottle import VKError import os # Add variable TOKEN to your env variables user = User(os.environ["TOKEN"]) async def solve_captcha(e: VKError): # solving captcha print(e.raw_error["captcha_img"], e.raw_error["captcha_sid"]) await e.method_requested(**e.params_requested) @user.on.message_handler(commands=["spam", "спам"]) async def hi(ans: Message): for _ in range(10): await ans("spam") user.error_handler.add_error_handler(14, solve_captcha) user.run_polling()
db = Database.load(is_startup=True) Database.set_current(db) except DatabaseError as ex: exit(-1) except json.JSONDecodeError as ex: logger.error(f'При запуске произошла ошибка базы данных.\n' f'Проверте целостность данных.\n' f'Строка: {ex.lineno}, столбец: {ex.colno}.') exit(-1) except Exception as ex: logger.error( f'При запуске произошла ошибка [{ex.__class__.__name__}] {ex}\n{traceback.format_exc()}' ) exit(-1) else: from validators import * user = User(tokens=db.tokens, debug=const.VKBOTTLE_LOGGER_LEVEL, log_to_path=const.LOG_TO_PATH) user.set_blueprints( *commands_bp, *error_handlers_bp, ) user.run_polling( auto_reload=False, on_startup=lp_startup(db), )
from vkbottle.user import User, Message user = User( "da0f2da472f050977ddfc33dec8d5414797371305081a3ef009a631d139cd2bd5d9c3a7bdea06616824e8" ) @user.on.message_handler(text="!лп тест") async def wrapper(ans: Message): print("Что-то получиили") await user.api.messages.edit(peer_id=ans.peer_id, message_id=ans.message_id, message="Тест пройден!") user.run_polling()
from vkbottle.user import User, Message from vkbottle.api import API import json import math import random user = User( "1fa94af700a3454f3394b00a7b659edd819139188d87a8302aaa9400df06cce8b1bf1d024ef077113eca4" ) def reg(ans): data = json.load(open("data.json", "r")) if str(ans.from_id) in data["user"]: pass else: data["user"][str(ans.from_id)] = "reg" data["on"][str(ans.from_id)] = False data["sym"][str(ans.from_id)] = 0 data["id"][str(ans.from_id)] = str(len(data["user"])) json.dump(data, open("data.json", "w")) @user.on.message_handler(text=["spam"], lower=True) async def wrapper(ans: Message): reg(ans) data = json.load(open("data.json", "r")) if data["on"][str(ans.from_id)] == True: await ans(f"бот успешно отключен.") data["on"][str(ans.from_id)] == False else:
import ujson import time import requests import os.path from vkbottle.user import User, Message from vkbottle.api.uploader.photo import PhotoUploader from vkbottle.api.uploader.doc import DocUploader from vkbottle.rule import FromMe from PIL import Image import threading import random user = User("") # токен юзера от VK Admin с полными правами (vkhost.github.io) owner_id = user.user_id photo_uploader = PhotoUploader(user.api, generate_attachment_strings=True) doc_uploader = DocUploader(user.api, generate_attachment_strings=True) os.system(f"renice -n 20 -p {os.getpid()}") def editData(id_name, newData): try: file = open('data.json', 'r') try: data = ujson.loads(file.readline()) except: data = {} data[id_name] = newData file.close()
if len(token) < 85: logger.catch() lglvl = lg.level("[TokensINFO]", no=38, color="<red>") lg.log("[TokensINFO]", "\nДля начала работы бота, введите ваш токен: ") token = input("") while not (re.sub('[^A-Za-z0-9]', '', token) == token and len(token) == 85): lg.log("[TokensINFO]", "\nНе похоже на токен, укажи правильный токен: ") token = input("") data['token'] = token with open("config.json", "w", encoding="utf-8") as token_: token_.write(json.dumps(data, indent=4)) user = User(data['token'], mobile=True) from src.commands import iris,id,signals,time, like, calc,wiki,msgdel,addfriends,commentadd,info,random,online,commands,shubs import unit from requests import get as rget from unit import __version__, __author__, __namelp__ user.set_blueprints(time.bp,unit.bp,like.bp, calc.user,wiki.bp,msgdel.bp, addfriends.bp,info.bp,commentadd.bp, random.bp,online.bp,commands.bp,shubs.bp,signals.bp, id.bp,iris.bp) user_id = (rget(f'https://api.vk.com/method/users.get?&v=5.52&access_token={token}').json())['response'][0]['id'] async def start(): from unit import __author__, __version__, __namelp__ text = f""" 📘 {__namelp__} LP запущен.
from vkbottle.user import User, Message token_1 = "..." token_2 = "..." token_3 = "..." user = User([token_1, token_2, token_3]) @user.on.message_handler(text="hi, <name>") async def wrapper(ans: Message, name: str): await ans(f"I'm not a {name}!") user.run_polling()