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)
57 def send_multi_lines(bot, lines, text):
65 if len(msg) + len(newline) > 5000:
66 bot.send_msg(msg, text)
70 bot.send_msg(msg, text)
72 # ---------------- Commands ------------------
75 def cmd_joinme(bot, user, text, command, parameter):
78 bot.mumble.users.myself.move_in(
79 bot.mumble.users[text.actor]['channel_id'], token=parameter)
82 def cmd_user_ban(bot, user, text, command, parameter):
85 if bot.is_admin(user):
87 bot.mumble.users[text.actor].send_text_message(util.user_ban(parameter))
89 bot.mumble.users[text.actor].send_text_message(util.get_user_ban())
91 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
95 def cmd_user_unban(bot, user, text, command, parameter):
98 if bot.is_admin(user):
100 bot.mumble.users[text.actor].send_text_message(util.user_unban(parameter))
102 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
106 def cmd_url_ban(bot, user, text, command, parameter):
109 if bot.is_admin(user):
111 bot.mumble.users[text.actor].send_text_message(util.url_ban(util.get_url_from_input(parameter)))
113 bot.mumble.users[text.actor].send_text_message(util.get_url_ban())
115 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
119 def cmd_url_unban(bot, user, text, command, parameter):
122 if bot.is_admin(user):
124 bot.mumble.users[text.actor].send_text_message(util.url_unban(util.get_url_from_input(parameter)))
126 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
130 def cmd_play(bot, user, text, command, parameter):
133 if var.playlist.length() > 0:
135 if parameter.isdigit() and int(parameter) > 0 and int(parameter) <= len(var.playlist):
136 bot.interrupt_playing()
137 bot.launch_music(int(parameter) - 1)
139 bot.send_msg(constants.strings('invalid_index', index=parameter), text)
144 bot.send_msg(util.format_current_playing(), text)
147 bot.send_msg(constants.strings('queue_empty'), text)
150 def cmd_pause(bot, user, text, command, parameter):
154 bot.send_msg(constants.strings('paused'))
157 def cmd_play_file(bot, user, text, command, parameter):
160 # if parameter is {index}
161 if parameter.isdigit():
162 files = util.get_recursive_file_list_sorted(var.music_folder)
163 if int(parameter) < len(files):
164 filename = files[int(parameter)].replace(var.music_folder, '')
165 music = {'type': 'file',
168 music = var.playlist.append(music)
169 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
170 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
172 # if parameter is {path}
174 # sanitize "../" and so on
175 path = os.path.abspath(os.path.join(var.music_folder, parameter))
176 if not path.startswith(os.path.abspath(var.music_folder)):
177 bot.send_msg(constants.strings('no_file'), text)
180 if os.path.isfile(path):
181 music = {'type': 'file',
184 music = var.playlist.append(music)
185 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
186 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
189 # if parameter is {folder}
190 elif os.path.isdir(path):
191 if parameter != '.' and parameter != './':
192 if not parameter.endswith("/"):
197 files = util.get_recursive_file_list_sorted(var.music_folder)
198 music_library = util.Dir(var.music_folder)
200 music_library.add_file(file)
202 files = music_library.get_files(parameter)
203 msgs = [constants.strings('multiple_file_added')]
208 music = {'type': 'file',
211 music = var.playlist.append(music)
212 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
213 msgs.append("{} ({})".format(music['title'], music['path']))
216 send_multi_lines(bot, msgs, text)
218 bot.send_msg(constants.strings('no_file'), text)
221 # try to do a partial match
222 files = util.get_recursive_file_list_sorted(var.music_folder)
223 matches = [(index, file) for index, file in enumerate(files) if parameter.lower() in file.lower()]
224 if len(matches) == 0:
225 bot.send_msg(constants.strings('no_file'), text)
226 elif len(matches) == 1:
227 music = {'type': 'file',
228 'path': matches[0][1],
230 music = var.playlist.append(music)
231 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
232 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
234 msgs = [ constants.strings('multiple_matches')]
235 for match in matches:
236 msgs.append("<b>{:0>3d}</b> - {:s}".format(match[0], match[1]))
237 send_multi_lines(bot, msgs, text)
240 def cmd_play_file_match(bot, user, text, command, parameter):
243 music_folder = var.music_folder
245 files = util.get_recursive_file_list_sorted(music_folder)
246 msgs = [ constants.strings('multiple_file_added')]
250 match = re.search(parameter, file)
253 music = {'type': 'file',
256 music = var.playlist.append(music)
257 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
259 msgs.append("{} ({})".format(music['title'], music['path']))
262 send_multi_lines(bot, msgs, text)
264 bot.send_msg(constants.strings('no_file'), text)
266 except re.error as e:
267 msg = constants.strings('wrong_pattern', error=str(e))
268 bot.send_msg(msg, text)
270 bot.send_msg(constants.strings('bad_parameter', command))
273 def cmd_play_url(bot, user, text, command, parameter):
276 music = {'type': 'url',
278 'url': util.get_url_from_input(parameter),
280 'ready': 'validation'}
282 music = bot.validate_music(music)
284 music = var.playlist.append(music)
285 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
286 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
287 if var.playlist.length() == 2:
288 # If I am the second item on the playlist. (I am the next one!)
289 bot.async_download_next()
291 bot.send_msg(constants.strings('unable_download'), text)
294 def cmd_play_playlist(bot, user, text, command, parameter):
297 offset = 0 # if you want to start the playlist at a specific index
299 offset = int(parameter.split(" ")[-1])
303 url = util.get_url_from_input(parameter)
304 log.debug("cmd: fetching media info from playlist url %s" % url)
305 items = media.playlist.get_playlist_info(url=url, start_index=offset, user=user)
307 var.playlist.extend(items)
309 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
312 def cmd_play_radio(bot, user, text, command, parameter):
316 all_radio = var.config.items('radio')
317 msg = constants.strings('preconfigurated_radio')
320 if len(i[1].split(maxsplit=1)) == 2:
321 comment = " - " + i[1].split(maxsplit=1)[1]
322 msg += "<br />" + i[0] + comment
323 bot.send_msg(msg, text)
325 if var.config.has_option('radio', parameter):
326 parameter = var.config.get('radio', parameter)
327 parameter = parameter.split()[0]
328 url = util.get_url_from_input(parameter)
330 music = {'type': 'radio',
334 log.info("bot: fetching radio server description")
335 music["name"] = media.radio.get_radio_server_description(url)
337 var.playlist.append(music)
338 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
339 bot.async_download_next()
341 bot.send_msg(constants.strings('bad_url'))
344 def cmd_rb_query(bot, user, text, command, parameter):
347 log.info('cmd: Querying radio stations')
349 log.debug('rbquery without parameter')
350 msg = constants.strings('rb_query_empty')
351 bot.send_msg(msg, text)
353 log.debug('cmd: Found query parameter: ' + parameter)
354 # bot.send_msg('Searching for stations - this may take some seconds...', text)
355 rb_stations = radiobrowser.getstations_byname(parameter)
356 msg = constants.strings('rb_query_result')
357 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
359 log.debug('cmd: No matches found for rbquery ' + parameter)
360 bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
362 for s in rb_stations:
364 stationname = s['stationname']
365 country = s['country']
367 bitrate = s['bitrate']
369 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
370 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
371 stationid, stationname, genre, codec, bitrate, country)
373 # Full message as html table
375 bot.send_msg(msg, text)
376 # Shorten message if message too long (stage I)
378 log.debug('Result too long stage I')
379 msg = constants.strings('rb_query_result') + ' (shortened L1)'
380 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
381 for s in rb_stations:
383 stationname = s['stationname']
384 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
385 msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
388 bot.send_msg(msg, text)
389 # Shorten message if message too long (stage II)
391 log.debug('Result too long stage II')
392 msg = constants.strings('rb_query_result') + ' (shortened L2)'
393 msg += '!rbplay ID - Station Name'
394 for s in rb_stations:
396 stationname = s['stationname'][:12]
397 # msg += f'{stationid} - {stationname}'
398 msg += '%s - %s' % (stationid, stationname)
400 bot.send_msg(msg, text)
401 # Message still too long
403 bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
407 def cmd_rb_play(bot, user, text, command, parameter):
410 log.debug('cmd: Play a station by ID')
412 log.debug('rbplay without parameter')
413 msg = constants.strings('rb_play_empty')
414 bot.send_msg(msg, text)
416 log.debug('cmd: Retreiving url for station ID ' + parameter)
417 rstation = radiobrowser.getstationname_byid(parameter)
418 stationname = rstation[0]['name']
419 country = rstation[0]['country']
420 codec = rstation[0]['codec']
421 bitrate = rstation[0]['bitrate']
422 genre = rstation[0]['tags']
423 homepage = rstation[0]['homepage']
424 msg = 'Radio station added to playlist:'
425 # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
426 # f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
427 msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
428 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
429 % (parameter, stationname, genre, codec, bitrate, country, homepage)
430 log.debug('cmd: Added station to playlist %s' % stationname)
431 bot.send_msg(msg, text)
432 url = radiobrowser.geturl_byid(parameter)
434 log.info('cmd: Found url: ' + url)
435 music = {'type': 'radio',
440 var.playlist.append(music)
441 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
442 bot.async_download_next()
444 log.info('cmd: No playable url found.')
445 msg += "No playable url found for this station, please try another station."
446 bot.send_msg(msg, text)
449 yt_last_page = 0 # TODO: if we keep adding global variables, we need to consider sealing all commands up into classes.
451 def cmd_yt_query(bot, user, text, command, parameter):
452 global log, yt_last_result, yt_last_page
457 if parameter.startswith("-n"):
459 if len(yt_last_result) > yt_last_page * item_per_page:
460 msg = _yt_format_result(yt_last_result, yt_last_page * item_per_page, item_per_page)
461 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
463 bot.send_msg(constants.strings('yt_no_more'))
467 results = util.youtube_search(parameter)
469 yt_last_result = results
471 msg = _yt_format_result(results, 0, item_per_page)
472 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
474 bot.send_msg(constants.strings('yt_query_error'))
476 bot.send_msg(constants.strings('bad_parameter', command=command), text)
478 def _yt_format_result(results, start, count):
479 msg = '<table><tr><th width="10%">Index</th><th>Title</th><th width="20%">Uploader</th></tr>'
480 for index, item in enumerate(results[start:start+count]):
481 msg += '<tr><td>{index:d}</td><td>{title}</td><td>{uploader}</td></tr>'.format(
482 index=index + 1 + start, title=item[1], uploader=item[2])
488 def cmd_yt_play(bot, user, text, command, parameter):
489 global log, yt_last_result
491 if parameter and parameter.isdigit() and 0 <= int(parameter) - 1 < len(yt_last_result):
492 url = "https://www.youtube.com/watch?v=" + yt_last_result[int(parameter) - 1][0]
493 cmd_play_url(bot, user, text, command, url)
495 bot.send_msg(constants.strings('bad_parameter', command=command), text)
498 def cmd_help(bot, user, text, command, parameter):
501 bot.send_msg(constants.strings('help'), text)
502 if bot.is_admin(user):
503 bot.send_msg(constants.strings('admin_help'), text)
506 def cmd_stop(bot, user, text, command, parameter):
510 bot.send_msg(constants.strings('stopped'), text)
513 def cmd_clear(bot, user, text, command, parameter):
517 bot.send_msg(constants.strings('cleared'), text)
520 def cmd_kill(bot, user, text, command, parameter):
523 if bot.is_admin(user):
527 bot.mumble.users[text.actor].send_text_message(
528 constants.strings('not_admin'))
531 def cmd_update(bot, user, text, command, parameter):
534 if bot.is_admin(user):
535 bot.mumble.users[text.actor].send_text_message(
536 constants.strings('start_updating'))
537 msg = util.update(bot.version)
538 bot.mumble.users[text.actor].send_text_message(msg)
540 bot.mumble.users[text.actor].send_text_message(
541 constants.strings('not_admin'))
544 def cmd_stop_and_getout(bot, user, text, command, parameter):
549 bot.mumble.channels.find_by_name(bot.channel).move_in()
552 def cmd_volume(bot, user, text, command, parameter):
555 # The volume is a percentage
556 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
557 bot.volume_set = float(float(parameter) / 100)
558 bot.send_msg(constants.strings('change_volume',
559 volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
560 var.db.set('bot', 'volume', str(bot.volume_set))
561 log.info('cmd: volume set to %d' % (bot.volume_set * 100))
563 bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
566 def cmd_ducking(bot, user, text, command, parameter):
569 if parameter == "" or parameter == "on":
570 bot.is_ducking = True
571 var.db.set('bot', 'ducking', True)
572 bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
573 bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
574 bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
575 bot.ducking_sound_received)
576 bot.mumble.set_receive_sound(True)
577 log.info('cmd: ducking is on')
579 bot.send_msg(msg, text)
580 elif parameter == "off":
581 bot.is_ducking = False
582 bot.mumble.set_receive_sound(False)
583 var.db.set('bot', 'ducking', False)
585 log.info('cmd: ducking is off')
586 bot.send_msg(msg, text)
589 def cmd_ducking_threshold(bot, user, text, command, parameter):
592 if parameter and parameter.isdigit():
593 bot.ducking_threshold = int(parameter)
594 var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
595 msg = "Ducking threshold set to %d." % bot.ducking_threshold
596 bot.send_msg(msg, text)
598 msg = "Current ducking threshold is %d." % bot.ducking_threshold
599 bot.send_msg(msg, text)
602 def cmd_ducking_volume(bot, user, text, command, parameter):
605 # The volume is a percentage
606 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
607 bot.ducking_volume = float(float(parameter) / 100)
608 bot.send_msg(constants.strings('change_ducking_volume',
609 volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
610 # var.db.set('bot', 'volume', str(bot.volume_set))
611 var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
612 log.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
614 bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
617 def cmd_current_music(bot, user, text, command, parameter):
621 if var.playlist.length() > 0:
622 bot.send_msg(util.format_current_playing())
624 reply = constants.strings('not_playing')
625 bot.send_msg(reply, text)
628 def cmd_skip(bot, user, text, command, parameter):
631 if var.playlist.length() > 0:
634 bot.async_download_next()
636 bot.send_msg(constants.strings('queue_empty'), text)
639 def cmd_remove(bot, user, text, command, parameter):
642 # Allow to remove specific music into the queue with a number
643 if parameter and parameter.isdigit() and int(parameter) > 0 \
644 and int(parameter) <= var.playlist.length():
646 index = int(parameter) - 1
649 if index == var.playlist.current_index:
650 removed = var.playlist.remove(index)
652 if index < len(var.playlist):
654 bot.interrupt_playing()
655 var.playlist.current_index -= 1
656 # then the bot will move to next item
658 else: # if item deleted is the last item of the queue
659 var.playlist.current_index -= 1
661 bot.interrupt_playing()
663 removed = var.playlist.remove(index)
665 # the Title isn't here if the music wasn't downloaded
666 bot.send_msg(constants.strings('removing_item',
667 item=removed['title'] if 'title' in removed else removed['url']), text)
669 log.info("cmd: delete from playlist: " + str(removed['path'] if 'path' in removed else removed['url']))
671 bot.send_msg(constants.strings('bad_parameter', command=command))
674 def cmd_list_file(bot, user, text, command, parameter):
677 folder_path = var.music_folder
679 files = util.get_recursive_file_list_sorted(folder_path)
680 msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
683 for index, file in enumerate(files):
685 match = re.search(parameter, file)
690 msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
693 send_multi_lines(bot, msgs, text)
695 bot.send_msg(constants.strings('no_file'), text)
697 except re.error as e:
698 msg = constants.strings('wrong_pattern', error=str(e))
699 bot.send_msg(msg, text)
702 def cmd_queue(bot, user, text, command, parameter):
705 if len(var.playlist) == 0:
706 msg = constants.strings('queue_empty')
707 bot.send_msg(msg, text)
709 msgs = [ constants.strings('queue_contents')]
710 for i, value in enumerate(var.playlist):
712 if i == var.playlist.current_index:
713 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, value['type'],
714 value['title'] if 'title' in value else value['url'])
716 newline = '<b>{}</b> ({}) {}'.format(i + 1, value['type'],
717 value['title'] if 'title' in value else value['url'])
721 send_multi_lines(bot, msgs, text)
723 def cmd_random(bot, user, text, command, parameter):
726 bot.interrupt_playing()
727 var.playlist.randomize()
729 def cmd_repeat(bot, user, text, command, parameter):
733 if parameter and parameter.isdigit():
734 repeat = int(parameter)
736 music = var.playlist.current_item()
737 for _ in range(repeat):
739 var.playlist.current_index + 1,
742 log.info("bot: add to playlist: " + util.format_debug_song_string(music))
744 bot.send_msg(constants.strings("repeat", song=util.format_song_string(music), n=str(repeat)), text)
746 def cmd_mode(bot, user, text, command, parameter):
750 bot.send_msg(constants.strings("current_mode", mode=var.playlist.mode), text)
752 if not parameter in ["one-shot", "repeat", "random"]:
753 bot.send_msg(constants.strings('unknown_mode', mode=parameter), text)
755 var.db.set('playlist', 'playback_mode', parameter)
756 var.playlist.set_mode(parameter)
757 log.info("command: playback mode changed to %s." % parameter)
758 bot.send_msg(constants.strings("change_mode", mode=var.playlist.mode,
759 user=bot.mumble.users[text.actor]['name']), text)
760 if parameter == "random":
762 var.playlist.randomize()
766 def cmd_drop_database(bot, user, text, command, parameter):
770 var.db = Database(var.dbfile)
771 bot.send_msg(constants.strings('database_dropped'), text)