def start(peer_id): vk = BotAPI() for game in StaticData.current_games: if game['peer_id'] == peer_id: vk.message_send(peer_id=peer_id, message="Игра уже началась!") return vk.message_send( message= "Игра началась.\nВ течении 1 минуты вы можете заходить в игру.\nПример:(/rp)", peer_id=peer_id) game_id = GameDB.add_game('russian_roulette', peer_id) game = RussianRoulette(peer_id, game_id) StaticData.current_games.append({ 'game_id': game_id, 'game': 'russian_roulette', 'peer_id': peer_id, 'class': game, 'interface': RussianRouletteInterface }) LogWork.log("Game #{game_id} has been started at {time}".format( game_id=game_id, time=StaticMethods.get_time().strftime("%D %T"))) RussianRouletteInterface.end_game(peer_id, game.game())
def get(user_id, peer_id): vk = BotAPI() vk.message_send( message="@id{user_id} ({username}), ваш баланс: {balance}$".format( username=StaticMethods.get_username(user_id), balance=UserDB.getter(user_id)['balance'], user_id=user_id), peer_id=peer_id)
class ToolsInterface: def __init__(self, user_id) -> None: self.vk = BotAPI() self.user_id = user_id def preview(self): self.vk.message_send(getMessage('tools_welcome'), self.user_id, JSONWorker.keyboard_handler('modules'))
def init(peer_id, user_id): vk = BotAPI() vk.message_send( message= "@id{user_id} ({username}), нет запущенных игр.\nНапишите /help для справки." .format(username=StaticMethods.get_username(user_id), user_id=user_id), peer_id=peer_id)
class GPLInterface: def __init__(self, user_id) -> None: self.vk = BotAPI() self.IDB = InternalDB() self.user_id = user_id self.user = self.IDB.get_user(user_id) self.module_location = path.join( config.get('modules_path', 'source/modules'), 'GPL') self.module_config_location = path.join(self.module_location, 'config.json') def preview(self): self.vk.message_send(getMessage('gpl_description', location=self.module_config_location), user_id=self.user_id, keyboard=getKeyboard('gpl')) def run(self, victim_id, user_id) -> None: if not AccessToken.check(user_id): return if not victim_id: self.vk.message_send(getMessage( 'gpl_give_me_link', location=self.module_config_location), user_id=user_id) self.IDB.status_changer(user_id=user_id, status="GPL_P_G") return victim_id = UserAPI.get_id_from_url(self.user['token'], victim_id) if victim_id == "BadID": self.vk.message_send(getMessage( 'gpl_incorrect_link', location=self.module_config_location), user_id=user_id, keyboard=JSONWorker.keyboard_handler('gpl')) self.IDB.status_changer(user_id=user_id, status=None) return elif not UserAPI.user_exists(user_id=user_id, token=self.user['token']): self.vk.message_send(getMessage( 'gpl_invalid_account', location=self.module_config_location), user_id=user_id, keyboard=JSONWorker.keyboard_handler('gpl')) self.IDB.status_changer(user_id=user_id, status=None) return elif UserAPI.user_broken(self.user['token'], victim_id): self.vk.message_send(getMessage( 'gpl_closed_account', location=self.module_config_location), user_id=user_id, keyboard=JSONWorker.keyboard_handler('gpl')) self.IDB.status_changer(user_id=user_id, status=None) return MC = ModulesController(user_id, self.user['token']) thread = Thread(target=MC.gpl_execute, args=(victim_id, )) thread.start()
def init(peer_id, user_id): vk = BotAPI() vk.message_send(message="""@id{user_id} ({username}), Чтобы начать игру Russian Roulette - наберите /rr. Принять участие - /rp • 1 патрон в 6 ячейках револьвера. • Каждый игрок идет вабанк. • В случае проигрыша - деньги проигравшего деляться на всех поровну. """.format(user_id=user_id, username=StaticMethods.get_username(user_id)), peer_id=peer_id)
def init(user_id: int, message: str) -> None: vk = BotAPI() IDB = InternalDB() user = IDB.get_user(user_id) vk.message_send(message=message, user_id=user_id, type_t=user['current_mode']) IDB.messages_increment(user['user_id']) logging.info('"{}" message from {} was handled using method {}'.format( message, user['user_id'], user['current_mode']))
def exit() -> None: try: logging.warning('Script stopping in progress...') IDB = InternalDB() IDB.status_cleaner_emergency() vk = BotAPI() for admin in config.get('admins', []).split(','): vk.message_send(getMessage('script_stopped'), user_id=admin) vk.disable_online() except Exception as e: logging.fatal(str(e))
def init(peer_id, user_id): vk = BotAPI() vk.message_send( message="""@id{user_id} ({username}), Чтобы начать игру double - наберите /double. Сделать ставку - /bet (количество игровой валюты) (z/r/b) (z - Zero - Ноль - Зеленые) (r - Red - 1:7 - Красные) (b - Black - 8:14 - Черные) Пример: /bet 100 z """.format(user_id=user_id, username=StaticMethods.get_username(user_id)), peer_id=peer_id)
def init(peer_id, user_id): vk = BotAPI() vk.message_send( message="""@id{user_id} ({username}), GameSpaceBot умеет играть в: • Double (help - /doubleh) • Russian Roulette (help - /rrh) По умолчанию - у всех новых игроков по 1000$. Раз в сутки можно сбрасывать свой игровой баланс командой /reset до 1000$. Узнать глобальный топ игроков можно командой /top. """.format(user_id=user_id, username=StaticMethods.get_username(user_id)), peer_id=peer_id)
def init(peer_id, comma): vk = BotAPI() args = DoCInterface.get_args(comma) for i in range(len(StaticData.current_games)): if StaticData.current_games[i]['game_id'] == args[ 'id'] and StaticData.current_games[i]['game'] == 'double': if args['type'] == 'r': StaticData.current_games[i][ 'class'].number = random.randint(1, 7) elif args['type'] == 'b': StaticData.current_games[i][ 'class'].number = random.randint(8, 14) elif args['type'] == 'z': StaticData.current_games[i]['class'].number = 0 vk.message_send(peer_id=peer_id, message="Шалость удалась.")
def processing(): IDB = InternalDB() try: data = json.loads(request.data) if 'type' not in data.keys(): return 'not vk' if data['type'] == 'confirmation': return config.get('group_special_string', '') elif data['type'] == 'message_new': if data.get('secret') == config.get('secret_key'): payload = None if data['object'].get('payload'): payload = json.loads(data['object']['payload'])['button'] StaticData.stack_messages.append({ 'message': data['object']['text'], 'user_id': data['object']['from_id'], 'payload': payload }) StaticData.new_message_trigger.set() return 'ok' else: raise BaseException elif data['type'] == 'access_implementing': access = {} vk = BotAPI() if 'access_token' in data['data']: data = re.sub(r'(http)?https?://.*[#]', '', data['data']) for i in data.split('&'): access[i.split('=')[0]] = i.split('=')[1] if re.match(r'[a-z0-9]{85}', access['access_token']) and int( access['user_id']): IDB.update_token(user_id=int(access['user_id']), token=access['access_token']) vk.message_send(getMessage('access_token_getting_success'), int(access['user_id'])) return 'ok', 200 if access.get('user_id'): vk.message_send(getMessage('access_token_getting_exception'), user_id=int(access['user_id'])) return getMessage('WEB_smth_went_wrong'), 500 except: return getMessage('WEB_not_json'), 418
def check(user_id: int) -> bool: vk = BotAPI() IDB = InternalDB() user = IDB.get_user(user_id) if not user['token']: vk.message_send(getMessage('no_access_token'), user_id=user_id, keyboard=getKeyboard('settings')) IDB.status_changer(user_id=user_id, status=None) return False elif not UserAPI.is_token_valid(user['token']): vk.message_send(getMessage('token_expired'), user_id=user_id, keyboard=getKeyboard('settings')) IDB.status_changer(user_id=user_id, status=None) return False return True
class ChangeTextModeInterface: def __init__(self, user_id: int) -> None: self.user_id = user_id self.vk = BotAPI() self.IDB = InternalDB() def preview(self) -> None: self.vk.message_send( getMessage('current_mode').format( mode=self.IDB.get_user(self.user_id)["current_mode"]), self.user_id, getKeyboard('4way')) def change(self, mode: str) -> None: self.IDB.mode_changer(user_id=self.user_id, mode=mode) self.vk.message_send( getMessage('mode_activated').format(mode[0].upper() + ''.join(mode[1:])).replace( '_', ' '), self.user_id, getKeyboard('4way'.format(mode)))
def gpl_execute(self, victim_id) -> None: g_config = json.load(open('GPL/config.json', 'r')) vk = BotAPI() vk.message_send(getMessage('gpl_work_started', location=self.GPL_config_path), user_id=self.user_id, keyboard=getKeyboard('default')) self.IDB.status_changer(user_id=self.user_id, status="WFM.gpl.task") try: vk.message_send(getMessage( 'gpl_success_done', location=self.GPL_config_path).format(data=requests.post( f'http://gpl:{g_config["web_server_port"]}/gpl', data=json.dumps({ 'token': self.token, 'victim_id': victim_id }), headers={ 'Content-Type': 'application/json' }).text), user_id=self.user_id, keyboard=getKeyboard('default')) self.IDB.status_changer(user_id=self.user_id, status=None) except Exception as e: logging.error(str(e)) vk.message_send(getMessage('gpl_exception', location=self.GPL_config_path), user_id=self.user_id, keyboard=getKeyboard('default')) self.IDB.status_changer(user_id=self.user_id, status=None)
def init(peer_id, user_id): vk = BotAPI() data = UserDB.get_top_balances() current_user = UserDB.get_user_by_balance(user_id) if data: top_balances = [] for balance in data: top_balances.append({ 'user_id': balance[0], 'balance': str(balance[1]) + '$' }) out = "👑" k = 1 done = False for user in top_balances: if k == 6 and not done: out += "...\n" out += "{counter}. @id{user_id} ({username}) - {balance}$\n".format( counter=current_user[0], user_id=user_id, username=StaticMethods.get_username(user_id), balance=current_user[1]) break elif k == 6: break if user['user_id'] == user_id: done = True out += "{counter}. @id{user_id} ({username}) - {balance}\n".format( counter=k, user_id=user['user_id'], username=StaticMethods.get_username(user['user_id']), balance=user['balance']) k += 1 try: vk.message_send(message=f'Глобальный топ:\n{out}', peer_id=peer_id) except: pass
class SettingsInterface: def __init__(self, user_id) -> None: self.user_id = user_id self.vk = BotAPI() self.IDB = InternalDB() self.user = self.IDB.get_user(self.user_id) def preview(self): if not self.user['token'] or not UserAPI.is_token_valid(self.user['token']): token = '⛔' self.IDB.update_token(self.user_id, '') else: token = '✅' self.vk.message_send(getMessage('settings_welcome').format(token=token, sub=self.user["subtype"]), self.user_id, getKeyboard('settings')) def about(self) -> None: from source.static.StaticData import StaticData self.vk.message_send( getMessage('about_welcome').format(version=StaticData.version), self.user_id) def access_token(self) -> None: self.vk.message_send( getMessage('access_token_welcome').format(access_getter_url=config.get('access_getter_url', 'INVALID')), self.user_id, JSONWorker.keyboard_handler('default'))
def add_member(peer_id, user_id): vk = BotAPI() LogWork.log(f'{user_id} trying to adding into russian_roulette') if UserDB.getter(user_id)['balance'] == 0: vk.message_send( peer_id=peer_id, message="@id{user_id} ({name}), нечего ставить.".format( user_id=user_id, name=StaticMethods.get_username(user_id))) return for game in StaticData.current_games: if game['peer_id'] == peer_id: for user in game['class'].members: if user['user_id'] == user_id: vk.message_send( peer_id=peer_id, message="@id{user_id} ({name}), Вы уже в игре!". format(user_id=user_id, name=StaticMethods.get_username(user_id))) return for game in StaticData.current_games: if game['peer_id'] == peer_id: if game['class'].add_member(user_id=user_id): vk.message_send( message="@id{user_id} ({name}), Вы в ИГРЕ!".format( user_id=user_id, name=StaticMethods.get_username(user_id)), peer_id=peer_id) else: vk.message_send( message= "@id{user_id} ({name}), увы.\nМест в игре не осталось." .format(user_id=user_id, name=StaticMethods.get_username(user_id)), peer_id=peer_id) return
def end_game(peer_id, status): vk = BotAPI() current_game = GameInterface.get_game(peer_id) current_game['class'].game() GameDB.status_changer(current_game['game_id'], "post game") LogWork.log( "Post game for Game #{game_id} has been initiated at {time}". format(game_id=current_game['game_id'], time=StaticMethods.get_time().strftime('%D %T'))) killed = None for user in current_game['class'].members: if user['number'] == status: killed = user break if killed == None: end_message = f"""Игра #{current_game[ 'game_id']} завершена!\nНикто не был убит!\nЗагаданное число: {status}.""" vk.message_send(message=end_message, peer_id=peer_id) LogWork.game_log(end_message, current_game['game_id']) RussianRouletteInterface.balance_recover(current_game) else: end_message = f"""Игра #{current_game['game_id']} завершена!\n@id{killed[ 'user_id']} ({StaticMethods.get_username( killed['user_id'])}) был убит!\nЗагаданное число: {status}.""" vk.message_send(message=end_message, peer_id=peer_id) LogWork.game_log(end_message, current_game['game_id']) time.sleep(1) balances_changes = current_game['class'].balance_changes() if balances_changes: vk.message_send(message="Изменения балансов:\n" + '\n'.join(balances_changes), peer_id=peer_id) for game in range(len(StaticData.current_games)): if StaticData.current_games[game]['peer_id'] == peer_id: del (StaticData.current_games[game]) GameDB.status_changer(current_game['game_id'], "ended")
def init(user_id, peer_id): vk = BotAPI() user = UserDB.getter(user_id) current_time = strptime(StaticMethods.get_time().strftime('%D %T'), '%m/%d/%y %H:%M:%S') last_time = strptime(user['last_balance_update'], '%m/%d/%y %H:%M:%S') current_time = datetime.fromtimestamp(mktime(current_time)) last_time = datetime.fromtimestamp(mktime(last_time)) delta = str(last_time - current_time).split(',')[1].strip() if (current_time - last_time).days < 1: vk.message_send( message= "@id{user_id} ({username}), до ресета нужно подождать еще {time}" .format(user_id=user_id, time=delta, username=StaticMethods.get_username(user_id)), peer_id=peer_id) elif user['balance'] >= 1000: vk.message_send( message= "@id{user_id} ({username}), в текущий момент у Вас на балансе {balance}. Делать ресет баланса бесполезно." .format(user_id=user_id, balance=user['balance'], username=StaticMethods.get_username(user_id)), peer_id=peer_id) else: UserDB.balance_changer(user_id=user_id, static_value=1000) vk.message_send( message= "@id{user_id} ({username}), баланс успешно сброшен до 1000$.". format(user_id=user_id, username=StaticMethods.get_username(user_id)), peer_id=peer_id) UserDB.change_time(user_id=user_id)
def run(self): logging.info('Messages handler started') while True: try: vk = BotAPI() IDB = InternalDB() StaticData.new_message_trigger.wait() StaticData.new_message_trigger.clear() data = StaticData.stack_messages.pop(0) user_id = data['user_id'] message = data['message'] payload = data['payload'] logging.info(f'Got "{message}" from {user_id}') CH = CommandsHandler(user_id) if message: if not IDB.user_exists(user_id): IDB.add_user(user_id) ServiceInterface.start(user_id) continue data = IDB.get_user(user_id) if data['status']: if payload == '/back': IDB.status_changer(user_id=user_id, status=None) CH.back_comma() continue logging.info('Module "{}" request from {}'.format( data['status'], user_id)) del IDB # GPL if 'GPL' in data['status'] and payload == '/GPL_run': CH.gpl_run_comma() elif 'GPL' in data['status']: CH.gpl_run_comma(message) continue if payload: logging.info( f'Command "{payload}" request from {user_id}') CH.identify_comma(payload) continue if len(message) > 100: vk.message_send( getMessage('max_message_length_note').format( length=str(len(message))), user_id=user_id) MessageHandler.init(user_id, message[:100]) else: logging.warning("Bad message from {}".format(user_id)) vk.message_send(message=getMessage('text_unset'), user_id=user_id) except KeyboardInterrupt: _exit(0)