def set_privileges(username, val, sender): if username in users.keys(): if username == sender['name']: debug_print( f"This user: [{username}] tried to modify their own user privileges. Modification denied." ) logging.warning( f"This user: [{username}] tried to modify their own user privileges. Modification denied." ) return with open(f"{utils.get_main_dir()}/privileges/privileges.csv", mode='r') as csvf: csvr = csv.reader(csvf) content = list(csvr) ind = [(i, j.index(username)) for i, j in enumerate(content) if username in j] if int(content[ind[0][0]][1]) >= privileges_check(sender): if privileges_check(sender) == 4: debug_print( f"This administrator: [{sender['name']}] tried to modify privileges for a user with equal/higher privileges: [{username}]" ) logging.warning( f"This administrator: [{sender['name']}] tried to modify privileges for a user with equal/higher privileges: [{username}]" ) return content[ind[0][0]][1] = val users[username] = val return overwrite_privileges(content) else: return False
def clear_audio_thread(): if YoutubeHelper.music_thread is not None: debug_print("Stopping audio thread.") YoutubeHelper.music_thread.terminate() YoutubeHelper.music_thread.kill() YoutubeHelper.music_thread = None YoutubeHelper.is_playing = False
def clear_audio_thread(self): if SBH.audio_thread is not None: debug_print("Clearing sound_board audio thread...") SBH.audio_thread.terminate() SBH.audio_thread.kill() SBH.audio_thread = None return True return False
def stop_audio(): if YoutubeHelper.music_thread is not None: debug_print("Stopping audio thread.") YoutubeHelper.music_thread.terminate() YoutubeHelper.music_thread.kill() YoutubeHelper.music_thread = None YoutubeHelper.current_song_info = None YoutubeHelper.current_song = None YoutubeHelper.is_playing = False
def __init__(self): debug_print("Music Plugin Initialized...") super().__init__() warnings.filterwarnings("ignore", category=UserWarning, module='bs4') YH.volume = float(GM.cfg['Plugin_Settings']['Youtube_DefaultVolume']) YH.max_queue_size = int(GM.cfg['Plugin_Settings']['Youtube_MaxQueueLength']) YH.max_track_duration = int(GM.cfg['Plugin_Settings']['Youtube_MaxVideoLength']) YH.autoplay = GM.cfg.getboolean('Plugin_Settings', 'Youtube_AutoPlay') YH.queue_instance = qh.QueueHandler(YH.max_queue_size)
def stop_audio(): if SoundBoardHelper.audio_thread is not None: debug_print("Stopping sound_board audio thread...") SoundBoardHelper.audio_thread.terminate() SoundBoardHelper.audio_thread.kill() SoundBoardHelper.audio_thread = None SoundBoardHelper.current_song = None return True return False
def add_to_privileges(username, level): with open(f"{utils.get_main_dir()}/privileges/privileges.csv", mode='a', newline='') as csvf: headers = ['user', 'level'] csvw = csv.DictWriter(csvf, fieldnames=headers) csvw.writerow({'user': username, 'level': level}) users[username] = level debug_print(f"Added [{username}-{level}] to the user list.") return True
def setup_privileges(): with open(f"{utils.get_main_dir()}/privileges/privileges.csv", mode='r') as csvf: csvr = csv.DictReader(csvf) debug_print("Setting up user privileges...") for i, row in enumerate(csvr): users[row['user']] = int(row['level']) logging.info( f"Added [{row['user']}-{row['level']}] to the user privilege list." )
def download_image_stream(img_url): utils.clear_directory(utils.get_temporary_img_dir()) img_ext = img_url.rsplit('.', 1)[1] with open(f"{utils.get_temporary_img_dir()}image.{img_ext}", 'wb') as img_file: resp = requests.get(img_url, stream=True) for block in resp.iter_content(1024): if not block: break img_file.write(block) debug_print(f"Downloaded image from: {img_url}")
def download_image_requests(img_url): utils.clear_directory(utils.get_temporary_img_dir()) img_ext = img_url.rsplit('.', 1)[1] s = requests.Session() r = s.get(img_url, headers={'User-Agent': 'Mozilla/5.0'}) if r.status_code == 200: with open(f"image.{img_ext}", 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) debug_print(f"Downloaded image from: {img_url}") else: debug_print(f"403 Error! - {img_url}")
def overwrite_privileges(content): try: with open(f"{utils.get_main_dir()}/privileges/privileges.csv", mode='w', newline='') as csvf: csvr = csv.writer(csvf) csvr.writerows(content) return True except Exception: debug_print("There was a problem overwriting the privileges csv file.") logging.critical( "There was a problem overwriting the privileges csv file.") return False
def privileges_check(user): if user['name'] in users.keys(): return int(users[user['name']]) priv_path = "privileges/privileges.csv" with open(f"{utils.get_main_dir()}/{priv_path}", mode='r') as csvf: csvr = csv.DictReader(csvf) for i, row in enumerate(csvr): if row['user'] == user['name']: users[user['name']] = int(row['level']) return int(users[user['name']]) with open(f"{utils.get_main_dir()}/{priv_path}", mode='a', newline='') as csvf: headers = ['user', 'level'] csvw = csv.DictWriter(csvf, fieldnames=headers) csvw.writerow({'user': user['name'], 'level': 1}) users[user['name']] = 1 debug_print( f"Added [{user['name']}-{user['level']}] to the user list.") return int(users[user['name']])
def add_to_blacklist(username, sender): if username in users.keys(): if users[username] == 0: return False with open(f"{utils.get_main_dir()}/privileges/privileges.csv", mode='r') as csvf: csvr = csv.reader(csvf) content = list(csvr) ind = [(i, j.index(username)) for i, j in enumerate(content) if username in j] if int(content[ind[0][0]][1]) >= 4: if privileges_check(sender) == 4: debug_print( f"This administrator: [{sender['name']}] tried to blacklist another administrator: [{username}]" ) logging.warning( f"This administrator: [{sender['name']}] tried to blacklist another administrator: [{username}]" ) return content[ind[0][0]][1] = 0 users[username] = 0 return overwrite_privileges(content) return False
def plugin_test(self): debug_print("Randomizer Plugin self-test callback.")
def process_core_commands(self, command, text): if command == "alias": if not pv.plugin_privilege_checker(text, command, self.priv_path): return message = text.message.strip() message_parse = message[1:].split(' ', 2) alias_name = message_parse[1] if alias_name in aliases.aliases.keys(): aliases.set_alias(alias_name, message_parse[2]) debug_print(f"Registered alias: [{alias_name}] - [{message_parse[2]}]") GM.gui.quick_gui( f"Registered alias: [{alias_name}] - [{message_parse[2]}]", text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name']) else: aliases.add_to_aliases(alias_name, message_parse[2]) debug_print(f"Registered new alias: [{alias_name}] - [{message_parse[2]}]") GM.gui.quick_gui( f"Registered alias: [{alias_name}] - [{message_parse[2]}]", text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name']) return elif command == "aliases": if not pv.plugin_privilege_checker(text, command, self.priv_path): return cur_text = f"<font color='{GM.cfg['PGUI_Settings']['HeaderTextColor']}'>Registered Aliases:</font>" for i, alias in enumerate(aliases.aliases): cur_text += f"<br><font color={GM.cfg['PGUI_Settings']['IndexTextColor']}>[{alias}]</font> - " \ f"[{BeautifulSoup(aliases.aliases[alias], 'html.parser').get_text()}] " if i % 50 == 0 and i != 0: GM.gui.quick_gui( cur_text, text_type='header', box_align='left', text_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) cur_text = "" GM.gui.quick_gui( cur_text, text_type='header', box_align='left', text_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) return elif command == "removealias": if not pv.plugin_privilege_checker(text, command, self.priv_path): return message = text.message.strip() message_parse = message[1:].split(' ', 2) alias_name = message_parse[1] if aliases.remove_from_aliases(alias_name): debug_print(f'Removed [{alias_name}] from registered aliases.') GM.gui.quick_gui( f'Removed [{alias_name}] from registered aliases.', text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) else: debug_print(f'Could not remove [{alias_name}] from registered aliases.') GM.gui.quick_gui( f'Could not remove [{alias_name}] from registered aliases.', text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) return elif command == "clearaliases": if not pv.plugin_privilege_checker(text, command, self.priv_path): return if aliases.clear_aliases(): debug_print('Cleared all registered aliases.') GM.gui.quick_gui( 'Cleared all registered aliases.', text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) else: debug_print('The registered aliases could not be cleared.') GM.gui.quick_gui( 'The registered aliases could not be cleared.', text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) return elif command == "refresh": if not pv.plugin_privilege_checker(text, command, self.priv_path): return self.refresh_plugins() return elif command == "sleep": if not pv.plugin_privilege_checker(text, command, self.priv_path): return sleep_time = float(text.message[1:].split(' ', 1)[1].strip()) self.tick_rate = sleep_time time.sleep(sleep_time) self.tick_rate = float(GM.cfg['Main_Settings']['CommandTickRate']) return elif command == "exit": if not pv.plugin_privilege_checker(text, command, self.priv_path): return debug_print("Stopping all threads...") self.exit() GM.logger.info("JJ Mumble Bot is being shut down.") GM.logger.info("######################################") return elif command == "status": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui( f"{utils.get_bot_name()} is {self.status()}.", text_type='header', box_align='left' ) return elif command == "version": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui( f"{utils.get_bot_name()} is on version {utils.get_version()}", text_type='header', box_align='left' ) return elif command == "system_test": if not pv.plugin_privilege_checker(text, command, self.priv_path): return self.plugin_callback_test() debug_print("A system self-test was run.") GM.logger.info("A system self-test was run.") return elif command == "about": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui( f"{utils.get_about()}<br>{utils.get_bot_name()} is on version {utils.get_version()}", text_type='header', box_align='left' ) return elif command == "history": if not pv.plugin_privilege_checker(text, command, self.priv_path): return cur_text = f"<font color='{GM.cfg['PGUI_Settings']['HeaderTextColor']}'>Command History:</font>" for i, item in enumerate(GM.cmd_history.queue_storage): cur_text += f"<br><font color={GM.cfg['PGUI_Settings']['IndexTextColor']}>[{i}]</font> - {item}" if i % 50 == 0 and i != 0: GM.gui.quick_gui( cur_text, text_type='header', box_align='left', text_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) cur_text = "" GM.gui.quick_gui( cur_text, text_type='header', box_align='left', text_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) elif command == "uptime": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui( check_time(), text_type='header', box_align='left', ignore_whisper=True, user=GM.mumble.users[text.actor]['name'] ) return elif command == "reboot": if not pv.plugin_privilege_checker(text, command, self.priv_path): return self.exit() GM.logger.info("JJ Mumble Bot is being rebooted.") os.execv(sys.executable, ['python3'] + sys.argv) return
def process_command(self, text): message = text.message.strip() message_parse = message[1:].split(' ', 1) all_messages = message[1:].split() command = message_parse[0] if command == "echo": if not pv.plugin_privilege_checker(text, command, self.priv_path): return parameter = message_parse[1] GM.gui.quick_gui(parameter, text_type='header', box_align='left', ignore_whisper=True) GM.logger.info(f"Echo:[{parameter}]") return elif command == "log": if not pv.plugin_privilege_checker(text, command, self.priv_path): return debug_print(f"Manually Logged: [{message_parse[1]}]") GM.logger.info(f"Manually Logged: [{message_parse[1]}]") return elif command == "spam_test": if not pv.plugin_privilege_checker(text, command, self.priv_path): return for i in range(10): GM.gui.quick_gui("This is a spam test message...", text_type='header', box_align='left', ignore_whisper=True) GM.logger.info( f"A spam_test was conducted by: {GM.mumble.users[text.actor]['name']}." ) return elif command == "msg": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui(message[1:].split(' ', 2)[2], text_type='header', box_align='left', user=all_messages[1], ignore_whisper=True) GM.logger.info( f"Msg:[{all_messages[1]}]->[{message[1:].split(' ', 2)[2]}]") return elif command == "move": if not pv.plugin_privilege_checker(text, command, self.priv_path): return parameter = message_parse[1] channel_name = parameter if channel_name == "default" or channel_name == "Default": channel_name = utils.get_default_channel() channel_search = utils.get_channel(channel_name) if channel_search is None: return else: channel_search.move_in() GM.gui.quick_gui( f"{utils.get_bot_name()} was moved by {GM.mumble.users[text.actor]['name']}", text_type='header', box_align='left', ignore_whisper=True) GM.logger.info( f"Moved to channel: {channel_name} by {GM.mumble.users[text.actor]['name']}" ) return elif command == "make": if not pv.plugin_privilege_checker(text, command, self.priv_path): return parameter = message_parse[1] channel_name = parameter utils.make_channel(utils.get_my_channel(), channel_name) GM.logger.info( f"Made a channel: {channel_name} by {GM.mumble.users[text.actor]['name']}" ) return elif command == "leave": if not pv.plugin_privilege_checker(text, command, self.priv_path): return utils.leave() GM.logger.info("Returned to default channel.") return elif command == "joinme": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui( f"Joining user: {GM.mumble.users[text.actor]['name']}", text_type='header', box_align='left', ignore_whisper=True) GM.mumble.channels[GM.mumble.users[text.actor] ['channel_id']].move_in() GM.logger.info( f"Joined user: {GM.mumble.users[text.actor]['name']}") return elif command == "privileges": if not pv.plugin_privilege_checker(text, command, self.priv_path): return GM.gui.quick_gui(f"{pv.get_all_privileges()}", text_type='header', box_align='left', text_align='left', user=GM.mumble.users[text.actor]['name'], ignore_whisper=True) return elif command == "setprivileges": if not pv.plugin_privilege_checker(text, command, self.priv_path): return try: username = all_messages[1] level = int(all_messages[2]) result = pv.set_privileges(username, level, GM.mumble.users[text.actor]) if result: GM.gui.quick_gui( f"User: {username} privileges have been modified.", text_type='header', box_align='left', user=GM.mumble.users[text.actor]['name'], ignore_whisper=True) GM.logger.info(f"Modified user privileges for: {username}") except Exception: reg_print( "Incorrect format! Format: !setprivileges 'username' 'level'" ) GM.gui.quick_gui( "Incorrect format! Format: !setprivileges 'username' 'level'", text_type='header', box_align='left', user=GM.mumble.users[text.actor]['name'], ignore_whisper=True) return return elif command == "addprivileges": if not pv.plugin_privilege_checker(text, command, self.priv_path): return try: username = all_messages[1] level = int(all_messages[2]) result = pv.add_to_privileges(username, level) if result: GM.gui.quick_gui( f"Added a new user: {username} to the user privileges.", text_type='header', box_align='left', user=GM.mumble.users[text.actor]['name'], ignore_whisper=True) GM.logger.info( f"Added a new user: {username} to the user privileges." ) except Exception: reg_print( "Incorrect format! Format: !addprivileges 'username' 'level'" ) GM.gui.quick_gui( "Incorrect format! Format: !addprivileges 'username' 'level'", text_type='header', box_align='left', user=GM.mumble.users[text.actor]['name'], ignore_whisper=True) return return elif command == "blacklist": if not pv.plugin_privilege_checker(text, command, self.priv_path): return try: parameter = all_messages[1] reason = "No reason provided." print(len(message[1:].split())) if len(message[1:].split()) >= 3: reason = message[1:].split(' ', 2)[2] result = pv.add_to_blacklist(parameter, GM.mumble.users[text.actor]) if result: GM.gui.quick_gui( f"User: {parameter} added to the blacklist.<br>Reason: {reason}", text_type='header', box_align='left', text_align='left') GM.logger.info( f"Blacklisted user: {parameter} <br>Reason: {reason}") except IndexError: GM.gui.quick_gui(pv.get_blacklist(), text_type='header', box_align='left', text_align='left') return elif command == "whitelist": if not pv.plugin_privilege_checker(text, command, self.priv_path): return try: parameter = message_parse[1] result = pv.remove_from_blacklist(parameter) if result: GM.gui.quick_gui( f"User: {parameter} removed from the blacklist.", text_type='header', box_align='left') GM.logger.info( f"User: {parameter} removed from the blacklist.") except IndexError: GM.gui.quick_gui("Command format: !whitelist username", text_type='header', box_align='left') return return
def __init__(self): debug_print("Bot_Commands Plugin Initialized.") super().__init__()
def download_playlist(url): ydl_opts = { 'quiet': True, 'format': 'bestaudio/best', 'noplaylist': False, 'extract_flat': True, 'logger': GM.logger, 'outtmpl': f'{utils.get_temporary_img_dir()}%(id)s.jpg', 'skip_download': True, 'writethumbnail': True, 'ignoreerrors': True } if GM.cfg.getboolean('Plugin_Settings', 'Youtube_AllowPlaylistMax'): ydl_opts = { 'quiet': True, 'format': 'bestaudio/best', 'noplaylist': False, 'extract_flat': True, 'logger': GM.logger, 'outtmpl': f'{utils.get_temporary_img_dir()}%(id)s.jpg', 'skip_download': True, 'writethumbnail': True, 'ignoreerrors': True, 'playlistend': int(GM.cfg['Plugin_Settings']['Youtube_MaxPlaylistLength']) } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.cache.remove() playlist_dict_check = ydl.extract_info(url, download=False, process=False) if playlist_dict_check is None: GM.gui.quick_gui( f"ERROR: This playlist is private. Only unlisted/public playlists can be played.", text_type='header', box_align='left') return None if 'entries' in playlist_dict_check: count = 0 for entry in playlist_dict_check['entries']: count += 1 # print(f"Playlist length: {count}") if count > int( GM.cfg['Plugin_Settings']['Youtube_MaxPlaylistLength']): if not GM.cfg.getboolean('Plugin_Settings', 'Youtube_AllowPlaylistMax'): GM.gui.quick_gui( f"ERROR: This playlist is longer than the limit set in the config.<br>The current limit is {GM.cfg['Plugin_Settings']['Youtube_MaxPlaylistLength']}.", text_type='header', box_align='left') return None with youtube_dl.YoutubeDL(ydl_opts) as ydl: GM.gui.quick_gui("The playlist is being generated...", text_type='header', box_align='left') playlist_dict = ydl.extract_info(url, download=True) all_videos = [] if not playlist_dict['entries']: GM.gui.quick_gui("ERROR: Unable to get playlist information.", text_type='header', box_align='left') return None for video in playlist_dict['entries']: if not video: debug_print("Unable to get video information...skipping.") continue # print(video) prep_struct = { 'main_url': f"https://www.youtube.com/watch?v={video['id']}", 'main_title': video['title'], 'img_id': video['id'] } all_videos.append(prep_struct) return all_videos
def quit(self): debug_print("Exiting Help Plugin")
def plugin_test(self): debug_print("Help Plugin self-test callback.")
def __init__(self, bot_plugins): debug_print("Help Plugin Initialized.") super().__init__() self.bot_plugins = bot_plugins
def quit(self): debug_print("Exiting Randomizer Plugin")
def __init__(self): debug_print("Randomizer Plugin Initialized.") super().__init__()
def plugin_test(self): debug_print("Sound_Board Plugin self-test callback.")
def quit(self): self.clear_audio_thread() SBM.stop_audio() SBH.exit_flag = True debug_print("Exiting Sound_Board Plugin...")
def quit(self): YM.stop_audio() YH.exit_flag = True debug_print("Exiting Youtube Plugin...")
def plugin_test(self): debug_print("Youtube Plugin self-test callback.")
def plugin_test(self): debug_print("Bot_Commands Plugin self-test callback.")
def quit(self): debug_print("Exiting Bot_Commands Plugin...")
def __init__(self): debug_print("Sound_Board Plugin Initialized...") super().__init__() SBH.volume = float( GM.cfg['Plugin_Settings']['SoundBoard_DefaultVolume'])