4 import pymumble.pymumble_py3 as pymumble
14 import variables as var
15 from librb import radiobrowser
16 from database import Database
18 log = logging.getLogger("bot")
20 def register_all_commands(bot):
21 bot.register_command(constants.commands('joinme'), cmd_joinme)
22 bot.register_command(constants.commands('user_ban'), cmd_user_ban)
23 bot.register_command(constants.commands('user_unban'), cmd_user_unban)
24 bot.register_command(constants.commands('url_ban'), cmd_url_ban)
25 bot.register_command(constants.commands('url_unban'), cmd_url_unban)
26 bot.register_command(constants.commands('play'), cmd_play)
27 bot.register_command(constants.commands('pause'), cmd_pause)
28 bot.register_command(constants.commands('play_file'), cmd_play_file)
29 bot.register_command(constants.commands('play_file_match'), cmd_play_file_match)
30 bot.register_command(constants.commands('play_url'), cmd_play_url)
31 bot.register_command(constants.commands('play_playlist'), cmd_play_playlist)
32 bot.register_command(constants.commands('play_radio'), cmd_play_radio)
33 bot.register_command(constants.commands('rb_query'), cmd_rb_query)
34 bot.register_command(constants.commands('rb_play'), cmd_rb_play)
35 bot.register_command(constants.commands('yt_query'), cmd_yt_query)
36 bot.register_command(constants.commands('yt_play'), cmd_yt_play)
37 bot.register_command(constants.commands('help'), cmd_help)
38 bot.register_command(constants.commands('stop'), cmd_stop)
39 bot.register_command(constants.commands('clear'), cmd_clear)
40 bot.register_command(constants.commands('kill'), cmd_kill)
41 bot.register_command(constants.commands('update'), cmd_update)
42 bot.register_command(constants.commands('stop_and_getout'), cmd_stop_and_getout)
43 bot.register_command(constants.commands('volume'), cmd_volume)
44 bot.register_command(constants.commands('ducking'), cmd_ducking)
45 bot.register_command(constants.commands('ducking_threshold'), cmd_ducking_threshold)
46 bot.register_command(constants.commands('ducking_volume'), cmd_ducking_volume)
47 bot.register_command(constants.commands('current_music'), cmd_current_music)
48 bot.register_command(constants.commands('skip'), cmd_skip)
49 bot.register_command(constants.commands('remove'), cmd_remove)
50 bot.register_command(constants.commands('list_file'), cmd_list_file)
51 bot.register_command(constants.commands('queue'), cmd_queue)
52 bot.register_command(constants.commands('random'), cmd_random)
53 bot.register_command(constants.commands('repeat'), cmd_repeat)
54 bot.register_command(constants.commands('mode'), cmd_mode)
55 bot.register_command(constants.commands('drop_database'), cmd_drop_database)
58 bot.register_command('rtrms', cmd_real_time_rms)
60 def send_multi_lines(bot, lines, text):
68 if len(msg) + len(newline) > 5000:
69 bot.send_msg(msg, text)
73 bot.send_msg(msg, text)
75 # ---------------- Commands ------------------
78 def cmd_joinme(bot, user, text, command, parameter):
81 bot.mumble.users.myself.move_in(
82 bot.mumble.users[text.actor]['channel_id'], token=parameter)
85 def cmd_user_ban(bot, user, text, command, parameter):
88 if bot.is_admin(user):
90 bot.mumble.users[text.actor].send_text_message(util.user_ban(parameter))
92 bot.mumble.users[text.actor].send_text_message(util.get_user_ban())
94 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
98 def cmd_user_unban(bot, user, text, command, parameter):
101 if bot.is_admin(user):
103 bot.mumble.users[text.actor].send_text_message(util.user_unban(parameter))
105 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
109 def cmd_url_ban(bot, user, text, command, parameter):
112 if bot.is_admin(user):
114 bot.mumble.users[text.actor].send_text_message(util.url_ban(util.get_url_from_input(parameter)))
116 bot.mumble.users[text.actor].send_text_message(util.get_url_ban())
118 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
122 def cmd_url_unban(bot, user, text, command, parameter):
125 if bot.is_admin(user):
127 bot.mumble.users[text.actor].send_text_message(util.url_unban(util.get_url_from_input(parameter)))
129 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
133 def cmd_play(bot, user, text, command, parameter):
136 if var.playlist.length() > 0:
138 if parameter.isdigit() and int(parameter) > 0 and int(parameter) <= len(var.playlist):
139 bot.interrupt_playing()
140 bot.launch_music(int(parameter) - 1)
142 bot.send_msg(constants.strings('invalid_index', index=parameter), text)
147 bot.send_msg(util.format_current_playing(), text)
150 bot.send_msg(constants.strings('queue_empty'), text)
153 def cmd_pause(bot, user, text, command, parameter):
157 bot.send_msg(constants.strings('paused'))
160 def cmd_play_file(bot, user, text, command, parameter):
163 # if parameter is {index}
164 if parameter.isdigit():
165 files = util.get_recursive_file_list_sorted(var.music_folder)
166 if int(parameter) < len(files):
167 filename = files[int(parameter)].replace(var.music_folder, '')
168 music = {'type': 'file',
171 music = var.playlist.append(music)
172 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
173 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
175 # if parameter is {path}
177 # sanitize "../" and so on
178 path = os.path.abspath(os.path.join(var.music_folder, parameter))
179 if not path.startswith(os.path.abspath(var.music_folder)):
180 bot.send_msg(constants.strings('no_file'), text)
183 if os.path.isfile(path):
184 music = {'type': 'file',
187 music = var.playlist.append(music)
188 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
189 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
192 # if parameter is {folder}
193 elif os.path.isdir(path):
194 if parameter != '.' and parameter != './':
195 if not parameter.endswith("/"):
200 files = util.get_recursive_file_list_sorted(var.music_folder)
201 music_library = util.Dir(var.music_folder)
203 music_library.add_file(file)
205 files = music_library.get_files(parameter)
206 msgs = [constants.strings('multiple_file_added')]
211 music = {'type': 'file',
214 music = var.playlist.append(music)
215 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
216 msgs.append("{} ({})".format(music['title'], music['path']))
219 send_multi_lines(bot, msgs, text)
221 bot.send_msg(constants.strings('no_file'), text)
224 # try to do a partial match
225 files = util.get_recursive_file_list_sorted(var.music_folder)
226 matches = [(index, file) for index, file in enumerate(files) if parameter.lower() in file.lower()]
227 if len(matches) == 0:
228 bot.send_msg(constants.strings('no_file'), text)
229 elif len(matches) == 1:
230 music = {'type': 'file',
231 'path': matches[0][1],
233 music = var.playlist.append(music)
234 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
235 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
237 msgs = [ constants.strings('multiple_matches')]
238 for match in matches:
239 msgs.append("<b>{:0>3d}</b> - {:s}".format(match[0], match[1]))
240 send_multi_lines(bot, msgs, text)
243 def cmd_play_file_match(bot, user, text, command, parameter):
246 music_folder = var.music_folder
248 files = util.get_recursive_file_list_sorted(music_folder)
249 msgs = [ constants.strings('multiple_file_added')]
253 match = re.search(parameter, file)
256 music = {'type': 'file',
259 music = var.playlist.append(music)
260 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
262 msgs.append("{} ({})".format(music['title'], music['path']))
265 send_multi_lines(bot, msgs, text)
267 bot.send_msg(constants.strings('no_file'), text)
269 except re.error as e:
270 msg = constants.strings('wrong_pattern', error=str(e))
271 bot.send_msg(msg, text)
273 bot.send_msg(constants.strings('bad_parameter', command))
276 def cmd_play_url(bot, user, text, command, parameter):
279 music = {'type': 'url',
281 'url': util.get_url_from_input(parameter),
283 'ready': 'validation'}
285 music = bot.validate_music(music)
287 music = var.playlist.append(music)
288 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
289 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
290 if var.playlist.length() == 2:
291 # If I am the second item on the playlist. (I am the next one!)
292 bot.async_download_next()
294 bot.send_msg(constants.strings('unable_download'), text)
297 def cmd_play_playlist(bot, user, text, command, parameter):
300 offset = 0 # if you want to start the playlist at a specific index
302 offset = int(parameter.split(" ")[-1])
306 url = util.get_url_from_input(parameter)
307 log.debug("cmd: fetching media info from playlist url %s" % url)
308 items = media.playlist.get_playlist_info(url=url, start_index=offset, user=user)
310 var.playlist.extend(items)
312 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
315 def cmd_play_radio(bot, user, text, command, parameter):
319 all_radio = var.config.items('radio')
320 msg = constants.strings('preconfigurated_radio')
323 if len(i[1].split(maxsplit=1)) == 2:
324 comment = " - " + i[1].split(maxsplit=1)[1]
325 msg += "<br />" + i[0] + comment
326 bot.send_msg(msg, text)
328 if var.config.has_option('radio', parameter):
329 parameter = var.config.get('radio', parameter)
330 parameter = parameter.split()[0]
331 url = util.get_url_from_input(parameter)
333 music = {'type': 'radio',
337 log.info("bot: fetching radio server description")
338 music["name"] = media.radio.get_radio_server_description(url)
340 var.playlist.append(music)
341 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
342 bot.async_download_next()
344 bot.send_msg(constants.strings('bad_url'))
347 def cmd_rb_query(bot, user, text, command, parameter):
350 log.info('cmd: Querying radio stations')
352 log.debug('rbquery without parameter')
353 msg = constants.strings('rb_query_empty')
354 bot.send_msg(msg, text)
356 log.debug('cmd: Found query parameter: ' + parameter)
357 # bot.send_msg('Searching for stations - this may take some seconds...', text)
358 rb_stations = radiobrowser.getstations_byname(parameter)
359 msg = constants.strings('rb_query_result')
360 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
362 log.debug('cmd: No matches found for rbquery ' + parameter)
363 bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
365 for s in rb_stations:
367 stationname = s['stationname']
368 country = s['country']
370 bitrate = s['bitrate']
372 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
373 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
374 stationid, stationname, genre, codec, bitrate, country)
376 # Full message as html table
378 bot.send_msg(msg, text)
379 # Shorten message if message too long (stage I)
381 log.debug('Result too long stage I')
382 msg = constants.strings('rb_query_result') + ' (shortened L1)'
383 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
384 for s in rb_stations:
386 stationname = s['stationname']
387 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
388 msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
391 bot.send_msg(msg, text)
392 # Shorten message if message too long (stage II)
394 log.debug('Result too long stage II')
395 msg = constants.strings('rb_query_result') + ' (shortened L2)'
396 msg += '!rbplay ID - Station Name'
397 for s in rb_stations:
399 stationname = s['stationname'][:12]
400 # msg += f'{stationid} - {stationname}'
401 msg += '%s - %s' % (stationid, stationname)
403 bot.send_msg(msg, text)
404 # Message still too long
406 bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
410 def cmd_rb_play(bot, user, text, command, parameter):
413 log.debug('cmd: Play a station by ID')
415 log.debug('rbplay without parameter')
416 msg = constants.strings('rb_play_empty')
417 bot.send_msg(msg, text)
419 log.debug('cmd: Retreiving url for station ID ' + parameter)
420 rstation = radiobrowser.getstationname_byid(parameter)
421 stationname = rstation[0]['name']
422 country = rstation[0]['country']
423 codec = rstation[0]['codec']
424 bitrate = rstation[0]['bitrate']
425 genre = rstation[0]['tags']
426 homepage = rstation[0]['homepage']
427 msg = 'Radio station added to playlist:'
428 # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
429 # f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
430 msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
431 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
432 % (parameter, stationname, genre, codec, bitrate, country, homepage)
433 log.debug('cmd: Added station to playlist %s' % stationname)
434 bot.send_msg(msg, text)
435 url = radiobrowser.geturl_byid(parameter)
437 log.info('cmd: Found url: ' + url)
438 music = {'type': 'radio',
443 var.playlist.append(music)
444 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
445 bot.async_download_next()
447 log.info('cmd: No playable url found.')
448 msg += "No playable url found for this station, please try another station."
449 bot.send_msg(msg, text)
452 yt_last_page = 0 # TODO: if we keep adding global variables, we need to consider sealing all commands up into classes.
454 def cmd_yt_query(bot, user, text, command, parameter):
455 global log, yt_last_result, yt_last_page
460 if parameter.startswith("-n"):
462 if len(yt_last_result) > yt_last_page * item_per_page:
463 msg = _yt_format_result(yt_last_result, yt_last_page * item_per_page, item_per_page)
464 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
466 bot.send_msg(constants.strings('yt_no_more'))
470 results = util.youtube_search(parameter)
472 yt_last_result = results
474 msg = _yt_format_result(results, 0, item_per_page)
475 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
477 bot.send_msg(constants.strings('yt_query_error'))
479 bot.send_msg(constants.strings('bad_parameter', command=command), text)
481 def _yt_format_result(results, start, count):
482 msg = '<table><tr><th width="10%">Index</th><th>Title</th><th width="20%">Uploader</th></tr>'
483 for index, item in enumerate(results[start:start+count]):
484 msg += '<tr><td>{index:d}</td><td>{title}</td><td>{uploader}</td></tr>'.format(
485 index=index + 1 + start, title=item[1], uploader=item[2])
491 def cmd_yt_play(bot, user, text, command, parameter):
492 global log, yt_last_result
494 if parameter and parameter.isdigit() and 0 <= int(parameter) - 1 < len(yt_last_result):
495 url = "https://www.youtube.com/watch?v=" + yt_last_result[int(parameter) - 1][0]
496 cmd_play_url(bot, user, text, command, url)
498 bot.send_msg(constants.strings('bad_parameter', command=command), text)
501 def cmd_help(bot, user, text, command, parameter):
504 bot.send_msg(constants.strings('help'), text)
505 if bot.is_admin(user):
506 bot.send_msg(constants.strings('admin_help'), text)
509 def cmd_stop(bot, user, text, command, parameter):
513 bot.send_msg(constants.strings('stopped'), text)
516 def cmd_clear(bot, user, text, command, parameter):
520 bot.send_msg(constants.strings('cleared'), text)
523 def cmd_kill(bot, user, text, command, parameter):
526 if bot.is_admin(user):
530 bot.mumble.users[text.actor].send_text_message(
531 constants.strings('not_admin'))
534 def cmd_update(bot, user, text, command, parameter):
537 if bot.is_admin(user):
538 bot.mumble.users[text.actor].send_text_message(
539 constants.strings('start_updating'))
540 msg = util.update(bot.version)
541 bot.mumble.users[text.actor].send_text_message(msg)
543 bot.mumble.users[text.actor].send_text_message(
544 constants.strings('not_admin'))
547 def cmd_stop_and_getout(bot, user, text, command, parameter):
552 bot.mumble.channels.find_by_name(bot.channel).move_in()
555 def cmd_volume(bot, user, text, command, parameter):
558 # The volume is a percentage
559 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
560 bot.volume_set = float(float(parameter) / 100)
561 bot.send_msg(constants.strings('change_volume',
562 volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
563 var.db.set('bot', 'volume', str(bot.volume_set))
564 log.info('cmd: volume set to %d' % (bot.volume_set * 100))
566 bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
569 def cmd_ducking(bot, user, text, command, parameter):
572 if parameter == "" or parameter == "on":
573 bot.is_ducking = True
574 var.db.set('bot', 'ducking', True)
575 bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
576 bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
577 bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
578 bot.ducking_sound_received)
579 bot.mumble.set_receive_sound(True)
580 log.info('cmd: ducking is on')
582 bot.send_msg(msg, text)
583 elif parameter == "off":
584 bot.is_ducking = False
585 bot.mumble.set_receive_sound(False)
586 var.db.set('bot', 'ducking', False)
588 log.info('cmd: ducking is off')
589 bot.send_msg(msg, text)
592 def cmd_ducking_threshold(bot, user, text, command, parameter):
595 if parameter and parameter.isdigit():
596 bot.ducking_threshold = int(parameter)
597 var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
598 msg = "Ducking threshold set to %d." % bot.ducking_threshold
599 bot.send_msg(msg, text)
601 msg = "Current ducking threshold is %d." % bot.ducking_threshold
602 bot.send_msg(msg, text)
605 def cmd_ducking_volume(bot, user, text, command, parameter):
608 # The volume is a percentage
609 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
610 bot.ducking_volume = float(float(parameter) / 100)
611 bot.send_msg(constants.strings('change_ducking_volume',
612 volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
613 # var.db.set('bot', 'volume', str(bot.volume_set))
614 var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
615 log.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
617 bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
620 def cmd_current_music(bot, user, text, command, parameter):
624 if var.playlist.length() > 0:
625 bot.send_msg(util.format_current_playing())
627 reply = constants.strings('not_playing')
628 bot.send_msg(reply, text)
631 def cmd_skip(bot, user, text, command, parameter):
634 if var.playlist.length() > 0:
637 bot.async_download_next()
639 bot.send_msg(constants.strings('queue_empty'), text)
642 def cmd_remove(bot, user, text, command, parameter):
645 # Allow to remove specific music into the queue with a number
646 if parameter and parameter.isdigit() and int(parameter) > 0 \
647 and int(parameter) <= var.playlist.length():
649 index = int(parameter) - 1
652 if index == var.playlist.current_index:
653 removed = var.playlist.remove(index)
655 if index < len(var.playlist):
657 bot.interrupt_playing()
658 var.playlist.current_index -= 1
659 # then the bot will move to next item
661 else: # if item deleted is the last item of the queue
662 var.playlist.current_index -= 1
664 bot.interrupt_playing()
666 removed = var.playlist.remove(index)
668 # the Title isn't here if the music wasn't downloaded
669 bot.send_msg(constants.strings('removing_item',
670 item=removed['title'] if 'title' in removed else removed['url']), text)
672 log.info("cmd: delete from playlist: " + str(removed['path'] if 'path' in removed else removed['url']))
674 bot.send_msg(constants.strings('bad_parameter', command=command))
677 def cmd_list_file(bot, user, text, command, parameter):
680 folder_path = var.music_folder
682 files = util.get_recursive_file_list_sorted(folder_path)
683 msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
686 for index, file in enumerate(files):
688 match = re.search(parameter, file)
693 msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
696 send_multi_lines(bot, msgs, text)
698 bot.send_msg(constants.strings('no_file'), text)
700 except re.error as e:
701 msg = constants.strings('wrong_pattern', error=str(e))
702 bot.send_msg(msg, text)
705 def cmd_queue(bot, user, text, command, parameter):
708 if len(var.playlist) == 0:
709 msg = constants.strings('queue_empty')
710 bot.send_msg(msg, text)
712 msgs = [ constants.strings('queue_contents')]
713 for i, value in enumerate(var.playlist):
715 if i == var.playlist.current_index:
716 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, value['type'],
717 value['title'] if 'title' in value else value['url'])
719 newline = '<b>{}</b> ({}) {}'.format(i + 1, value['type'],
720 value['title'] if 'title' in value else value['url'])
724 send_multi_lines(bot, msgs, text)
726 def cmd_random(bot, user, text, command, parameter):
729 bot.interrupt_playing()
730 var.playlist.randomize()
732 def cmd_repeat(bot, user, text, command, parameter):
736 if parameter and parameter.isdigit():
737 repeat = int(parameter)
739 music = var.playlist.current_item()
740 for _ in range(repeat):
742 var.playlist.current_index + 1,
745 log.info("bot: add to playlist: " + util.format_debug_song_string(music))
747 bot.send_msg(constants.strings("repeat", song=util.format_song_string(music), n=str(repeat)), text)
749 def cmd_mode(bot, user, text, command, parameter):
753 bot.send_msg(constants.strings("current_mode", mode=var.playlist.mode), text)
755 if not parameter in ["one-shot", "repeat", "random"]:
756 bot.send_msg(constants.strings('unknown_mode', mode=parameter), text)
758 var.db.set('playlist', 'playback_mode', parameter)
759 var.playlist.set_mode(parameter)
760 log.info("command: playback mode changed to %s." % parameter)
761 bot.send_msg(constants.strings("change_mode", mode=var.playlist.mode,
762 user=bot.mumble.users[text.actor]['name']), text)
763 if parameter == "random":
765 var.playlist.randomize()
768 def cmd_drop_database(bot, user, text, command, parameter):
772 var.db = Database(var.dbfile)
773 bot.send_msg(constants.strings('database_dropped'), text)
776 def cmd_real_time_rms(bot, user, text, command, parameter):
777 bot._display_rms = not bot._display_rms