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',
333 var.playlist.append(music)
334 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
335 bot.async_download_next()
337 bot.send_msg(constants.strings('bad_url'))
340 def cmd_rb_query(bot, user, text, command, parameter):
343 log.info('cmd: Querying radio stations')
345 log.debug('rbquery without parameter')
346 msg = constants.strings('rb_query_empty')
347 bot.send_msg(msg, text)
349 log.debug('cmd: Found query parameter: ' + parameter)
350 # bot.send_msg('Searching for stations - this may take some seconds...', text)
351 rb_stations = radiobrowser.getstations_byname(parameter)
352 msg = constants.strings('rb_query_result')
353 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
355 log.debug('cmd: No matches found for rbquery ' + parameter)
356 bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
358 for s in rb_stations:
360 stationname = s['stationname']
361 country = s['country']
363 bitrate = s['bitrate']
365 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
366 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
367 stationid, stationname, genre, codec, bitrate, country)
369 # Full message as html table
371 bot.send_msg(msg, text)
372 # Shorten message if message too long (stage I)
374 log.debug('Result too long stage I')
375 msg = constants.strings('rb_query_result') + ' (shortened L1)'
376 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
377 for s in rb_stations:
379 stationname = s['stationname']
380 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
381 msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
384 bot.send_msg(msg, text)
385 # Shorten message if message too long (stage II)
387 log.debug('Result too long stage II')
388 msg = constants.strings('rb_query_result') + ' (shortened L2)'
389 msg += '!rbplay ID - Station Name'
390 for s in rb_stations:
392 stationname = s['stationname'][:12]
393 # msg += f'{stationid} - {stationname}'
394 msg += '%s - %s' % (stationid, stationname)
396 bot.send_msg(msg, text)
397 # Message still too long
399 bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
403 def cmd_rb_play(bot, user, text, command, parameter):
406 log.debug('cmd: Play a station by ID')
408 log.debug('rbplay without parameter')
409 msg = constants.strings('rb_play_empty')
410 bot.send_msg(msg, text)
412 log.debug('cmd: Retreiving url for station ID ' + parameter)
413 rstation = radiobrowser.getstationname_byid(parameter)
414 stationname = rstation[0]['name']
415 country = rstation[0]['country']
416 codec = rstation[0]['codec']
417 bitrate = rstation[0]['bitrate']
418 genre = rstation[0]['tags']
419 homepage = rstation[0]['homepage']
420 msg = 'Radio station added to playlist:'
421 # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
422 # f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
423 msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
424 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
425 % (parameter, stationname, genre, codec, bitrate, country, homepage)
426 log.debug('cmd: Added station to playlist %s' % stationname)
427 bot.send_msg(msg, text)
428 url = radiobrowser.geturl_byid(parameter)
430 log.info('cmd: Found url: ' + url)
431 music = {'type': 'radio',
432 'title': stationname,
436 var.playlist.append(music)
437 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
438 bot.async_download_next()
440 log.info('cmd: No playable url found.')
441 msg += "No playable url found for this station, please try another station."
442 bot.send_msg(msg, text)
444 yt_last_result = None
445 yt_last_page = 0 # TODO: if we keep adding global variables, we need to consider sealing all commands up into classes.
447 def cmd_yt_query(bot, user, text, command, parameter):
448 global log, yt_last_result, yt_last_page
453 if parameter.startswith("-n"):
455 if len(yt_last_result) > yt_last_page * item_per_page:
456 msg = _yt_format_result(yt_last_result, yt_last_page * item_per_page, item_per_page)
457 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
459 bot.send_msg(constants.strings('yt_no_more'))
463 results = util.youtube_search(parameter)
465 yt_last_result = results
467 msg = _yt_format_result(results, 0, item_per_page)
468 bot.send_msg(constants.strings('yt_result', result_table=msg), text)
470 bot.send_msg(constants.strings('yt_query_error'))
472 bot.send_msg(constants.strings('bad_parameter', command=command), text)
474 def _yt_format_result(results, start, count):
475 msg = '<table><tr><th width="10%">Index</th><th>Title</th><th width="20%">Uploader</th></tr>'
476 for index, item in enumerate(results[start:start+count]):
477 msg += '<tr><td>{index:d}</td><td>{title}</td><td>{uploader}</td></tr>'.format(
478 index=index + 1 + start, title=item[1], uploader=item[2])
484 def cmd_yt_play(bot, user, text, command, parameter):
485 global log, yt_last_result
487 if parameter and parameter.isdigit() and 0 < int(parameter) - 1 < len(yt_last_result):
488 url = "https://www.youtube.com/watch?v=" + yt_last_result[int(parameter) - 1][0]
489 cmd_play_url(bot, user, text, command, url)
491 bot.send_msg(constants.strings('bad_parameter', command=command), text)
494 def cmd_help(bot, user, text, command, parameter):
497 bot.send_msg(constants.strings('help'), text)
498 if bot.is_admin(user):
499 bot.send_msg(constants.strings('admin_help'), text)
502 def cmd_stop(bot, user, text, command, parameter):
506 bot.send_msg(constants.strings('stopped'), text)
509 def cmd_clear(bot, user, text, command, parameter):
513 bot.send_msg(constants.strings('cleared'), text)
516 def cmd_kill(bot, user, text, command, parameter):
519 if bot.is_admin(user):
523 bot.mumble.users[text.actor].send_text_message(
524 constants.strings('not_admin'))
527 def cmd_update(bot, user, text, command, parameter):
530 if bot.is_admin(user):
531 bot.mumble.users[text.actor].send_text_message(
532 constants.strings('start_updating'))
533 msg = util.update(bot.version)
534 bot.mumble.users[text.actor].send_text_message(msg)
536 bot.mumble.users[text.actor].send_text_message(
537 constants.strings('not_admin'))
540 def cmd_stop_and_getout(bot, user, text, command, parameter):
545 bot.mumble.channels.find_by_name(bot.channel).move_in()
548 def cmd_volume(bot, user, text, command, parameter):
551 # The volume is a percentage
552 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
553 bot.volume_set = float(float(parameter) / 100)
554 bot.send_msg(constants.strings('change_volume',
555 volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
556 var.db.set('bot', 'volume', str(bot.volume_set))
557 log.info('cmd: volume set to %d' % (bot.volume_set * 100))
559 bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
562 def cmd_ducking(bot, user, text, command, parameter):
565 if parameter == "" or parameter == "on":
566 bot.is_ducking = True
567 var.db.set('bot', 'ducking', True)
568 bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
569 bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
570 bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
571 bot.ducking_sound_received)
572 bot.mumble.set_receive_sound(True)
573 log.info('cmd: ducking is on')
575 bot.send_msg(msg, text)
576 elif parameter == "off":
577 bot.is_ducking = False
578 bot.mumble.set_receive_sound(False)
579 var.db.set('bot', 'ducking', False)
581 log.info('cmd: ducking is off')
582 bot.send_msg(msg, text)
585 def cmd_ducking_threshold(bot, user, text, command, parameter):
588 if parameter and parameter.isdigit():
589 bot.ducking_threshold = int(parameter)
590 var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
591 msg = "Ducking threshold set to %d." % bot.ducking_threshold
592 bot.send_msg(msg, text)
594 msg = "Current ducking threshold is %d." % bot.ducking_threshold
595 bot.send_msg(msg, text)
598 def cmd_ducking_volume(bot, user, text, command, parameter):
601 # The volume is a percentage
602 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
603 bot.ducking_volume = float(float(parameter) / 100)
604 bot.send_msg(constants.strings('change_ducking_volume',
605 volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
606 # var.db.set('bot', 'volume', str(bot.volume_set))
607 var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
608 log.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
610 bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
613 def cmd_current_music(bot, user, text, command, parameter):
617 if var.playlist.length() > 0:
618 bot.send_msg(util.format_current_playing())
620 reply = constants.strings('not_playing')
621 bot.send_msg(reply, text)
624 def cmd_skip(bot, user, text, command, parameter):
627 if var.playlist.length() > 0:
630 bot.async_download_next()
632 bot.send_msg(constants.strings('queue_empty'), text)
635 def cmd_remove(bot, user, text, command, parameter):
638 # Allow to remove specific music into the queue with a number
639 if parameter and parameter.isdigit() and int(parameter) > 0 \
640 and int(parameter) <= var.playlist.length():
642 index = int(parameter) - 1
645 if index == var.playlist.current_index:
646 removed = var.playlist.remove(index)
648 if index < len(var.playlist):
650 bot.interrupt_playing()
651 var.playlist.current_index -= 1
652 # then the bot will move to next item
654 else: # if item deleted is the last item of the queue
655 var.playlist.current_index -= 1
657 bot.interrupt_playing()
659 removed = var.playlist.remove(index)
661 # the Title isn't here if the music wasn't downloaded
662 bot.send_msg(constants.strings('removing_item',
663 item=removed['title'] if 'title' in removed else removed['url']), text)
665 log.info("cmd: delete from playlist: " + str(removed['path'] if 'path' in removed else removed['url']))
667 bot.send_msg(constants.strings('bad_parameter', command=command))
670 def cmd_list_file(bot, user, text, command, parameter):
673 folder_path = var.music_folder
675 files = util.get_recursive_file_list_sorted(folder_path)
676 msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
679 for index, file in enumerate(files):
681 match = re.search(parameter, file)
686 msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
689 send_multi_lines(bot, msgs, text)
691 bot.send_msg(constants.strings('no_file'), text)
693 except re.error as e:
694 msg = constants.strings('wrong_pattern', error=str(e))
695 bot.send_msg(msg, text)
698 def cmd_queue(bot, user, text, command, parameter):
701 if len(var.playlist) == 0:
702 msg = constants.strings('queue_empty')
703 bot.send_msg(msg, text)
705 msgs = [ constants.strings('queue_contents')]
706 for i, value in enumerate(var.playlist):
708 if i == var.playlist.current_index:
709 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, value['type'],
710 value['title'] if 'title' in value else value['url'])
712 newline = '<b>{}</b> ({}) {}'.format(i + 1, value['type'],
713 value['title'] if 'title' in value else value['url'])
717 send_multi_lines(bot, msgs, text)
719 def cmd_random(bot, user, text, command, parameter):
722 bot.interrupt_playing()
723 var.playlist.randomize()
725 def cmd_repeat(bot, user, text, command, parameter):
729 if parameter and parameter.isdigit():
730 repeat = int(parameter)
732 music = var.playlist.current_item()
733 for _ in range(repeat):
735 var.playlist.current_index + 1,
738 log.info("bot: add to playlist: " + util.format_debug_song_string(music))
740 bot.send_msg(constants.strings("repeat", song=util.format_song_string(music), n=str(repeat)), text)
742 def cmd_mode(bot, user, text, command, parameter):
746 bot.send_msg(constants.strings("current_mode", mode=var.playlist.mode), text)
748 if not parameter in ["one-shot", "repeat", "random"]:
749 bot.send_msg(constants.strings('unknown_mode', mode=parameter), text)
751 var.db.set('playlist', 'playback_mode', parameter)
752 var.playlist.set_mode(parameter)
753 log.info("command: playback mode changed to %s." % parameter)
754 bot.send_msg(constants.strings("change_mode", mode=var.playlist.mode,
755 user=bot.mumble.users[text.actor]['name']), text)
756 if parameter == "random":
758 var.playlist.randomize()
762 def cmd_drop_database(bot, user, text, command, parameter):
766 var.db = Database(var.dbfile)
767 bot.send_msg(constants.strings('database_dropped'), text)