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('help'), cmd_help)
36 bot.register_command(constants.commands('stop'), cmd_stop)
37 bot.register_command(constants.commands('clear'), cmd_clear)
38 bot.register_command(constants.commands('kill'), cmd_kill)
39 bot.register_command(constants.commands('update'), cmd_update)
40 bot.register_command(constants.commands('stop_and_getout'), cmd_stop_and_getout)
41 bot.register_command(constants.commands('volume'), cmd_volume)
42 bot.register_command(constants.commands('ducking'), cmd_ducking)
43 bot.register_command(constants.commands('ducking_threshold'), cmd_ducking_threshold)
44 bot.register_command(constants.commands('ducking_volume'), cmd_ducking_volume)
45 bot.register_command(constants.commands('current_music'), cmd_current_music)
46 bot.register_command(constants.commands('skip'), cmd_skip)
47 bot.register_command(constants.commands('remove'), cmd_remove)
48 bot.register_command(constants.commands('list_file'), cmd_list_file)
49 bot.register_command(constants.commands('queue'), cmd_queue)
50 bot.register_command(constants.commands('random'), cmd_random)
51 bot.register_command(constants.commands('repeat'), cmd_repeat)
52 bot.register_command(constants.commands('mode'), cmd_mode)
53 bot.register_command(constants.commands('drop_database'), cmd_drop_database)
55 def send_multi_lines(bot, lines, text):
63 if len(msg) + len(newline) > 5000:
64 bot.send_msg(msg, text)
68 bot.send_msg(msg, text)
70 # ---------------- Commands ------------------
73 def cmd_joinme(bot, user, text, command, parameter):
76 bot.mumble.users.myself.move_in(
77 bot.mumble.users[text.actor]['channel_id'], token=parameter)
80 def cmd_user_ban(bot, user, text, command, parameter):
83 if bot.is_admin(user):
85 bot.mumble.users[text.actor].send_text_message(util.user_ban(parameter))
87 bot.mumble.users[text.actor].send_text_message(util.get_user_ban())
89 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
93 def cmd_user_unban(bot, user, text, command, parameter):
96 if bot.is_admin(user):
98 bot.mumble.users[text.actor].send_text_message(util.user_unban(parameter))
100 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
104 def cmd_url_ban(bot, user, text, command, parameter):
107 if bot.is_admin(user):
109 bot.mumble.users[text.actor].send_text_message(util.url_ban(util.get_url_from_input(parameter)))
111 bot.mumble.users[text.actor].send_text_message(util.get_url_ban())
113 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
117 def cmd_url_unban(bot, user, text, command, parameter):
120 if bot.is_admin(user):
122 bot.mumble.users[text.actor].send_text_message(util.url_unban(util.get_url_from_input(parameter)))
124 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
128 def cmd_play(bot, user, text, command, parameter):
131 if var.playlist.length() > 0:
133 if parameter.isdigit() and int(parameter) > 0 and int(parameter) <= len(var.playlist):
134 bot.interrupt_playing()
135 bot.launch_music(int(parameter) - 1)
137 bot.send_msg(constants.strings('invalid_index', index=parameter), text)
142 bot.send_msg(util.format_current_playing(), text)
145 bot.send_msg(constants.strings('queue_empty'), text)
148 def cmd_pause(bot, user, text, command, parameter):
152 bot.send_msg(constants.strings('paused'))
155 def cmd_play_file(bot, user, text, command, parameter):
158 # if parameter is {index}
159 if parameter.isdigit():
160 files = util.get_recursive_file_list_sorted(var.music_folder)
161 if int(parameter) < len(files):
162 filename = files[int(parameter)].replace(var.music_folder, '')
163 music = {'type': 'file',
166 music = var.playlist.append(music)
167 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
168 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
170 # if parameter is {path}
172 # sanitize "../" and so on
173 path = os.path.abspath(os.path.join(var.music_folder, parameter))
174 if not path.startswith(os.path.abspath(var.music_folder)):
175 bot.send_msg(constants.strings('no_file'), text)
178 if os.path.isfile(path):
179 music = {'type': 'file',
182 music = var.playlist.append(music)
183 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
184 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
187 # if parameter is {folder}
188 elif os.path.isdir(path):
189 if parameter != '.' and parameter != './':
190 if not parameter.endswith("/"):
195 files = util.get_recursive_file_list_sorted(var.music_folder)
196 music_library = util.Dir(var.music_folder)
198 music_library.add_file(file)
200 files = music_library.get_files(parameter)
201 msgs = [constants.strings('multiple_file_added')]
206 music = {'type': 'file',
209 music = var.playlist.append(music)
210 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
211 msgs.append("{} ({})".format(music['title'], music['path']))
214 send_multi_lines(bot, msgs, text)
216 bot.send_msg(constants.strings('no_file'), text)
219 # try to do a partial match
220 files = util.get_recursive_file_list_sorted(var.music_folder)
221 matches = [(index, file) for index, file in enumerate(files) if parameter.lower() in file.lower()]
222 if len(matches) == 0:
223 bot.send_msg(constants.strings('no_file'), text)
224 elif len(matches) == 1:
225 music = {'type': 'file',
226 'path': matches[0][1],
228 music = var.playlist.append(music)
229 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
230 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
232 msgs = [ constants.strings('multiple_matches')]
233 for match in matches:
234 msgs.append("<b>{:0>3d}</b> - {:s}".format(match[0], match[1]))
235 send_multi_lines(bot, msgs, text)
238 def cmd_play_file_match(bot, user, text, command, parameter):
241 music_folder = var.music_folder
243 files = util.get_recursive_file_list_sorted(music_folder)
244 msgs = [ constants.strings('multiple_file_added')]
248 match = re.search(parameter, file)
251 music = {'type': 'file',
254 music = var.playlist.append(music)
255 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
257 msgs.append("{} ({})".format(music['title'], music['path']))
260 send_multi_lines(bot, msgs, text)
262 bot.send_msg(constants.strings('no_file'), text)
264 except re.error as e:
265 msg = constants.strings('wrong_pattern', error=str(e))
266 bot.send_msg(msg, text)
268 bot.send_msg(constants.strings('bad_parameter', command))
271 def cmd_play_url(bot, user, text, command, parameter):
274 music = {'type': 'url',
276 'url': util.get_url_from_input(parameter),
278 'ready': 'validation'}
280 music = bot.validate_music(music)
282 music = var.playlist.append(music)
283 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
284 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
285 if var.playlist.length() == 2:
286 # If I am the second item on the playlist. (I am the next one!)
287 bot.async_download_next()
289 bot.send_msg(constants.strings('unable_download'), text)
292 def cmd_play_playlist(bot, user, text, command, parameter):
295 offset = 0 # if you want to start the playlist at a specific index
297 offset = int(parameter.split(" ")[-1])
301 url = util.get_url_from_input(parameter)
302 log.debug("cmd: fetching media info from playlist url %s" % url)
303 items = media.playlist.get_playlist_info(url=url, start_index=offset, user=user)
305 var.playlist.extend(items)
307 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
310 def cmd_play_radio(bot, user, text, command, parameter):
314 all_radio = var.config.items('radio')
315 msg = constants.strings('preconfigurated_radio')
318 if len(i[1].split(maxsplit=1)) == 2:
319 comment = " - " + i[1].split(maxsplit=1)[1]
320 msg += "<br />" + i[0] + comment
321 bot.send_msg(msg, text)
323 if var.config.has_option('radio', parameter):
324 parameter = var.config.get('radio', parameter)
325 parameter = parameter.split()[0]
326 url = util.get_url_from_input(parameter)
328 music = {'type': 'radio',
331 var.playlist.append(music)
332 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
333 bot.async_download_next()
335 bot.send_msg(constants.strings('bad_url'))
338 def cmd_rb_query(bot, user, text, command, parameter):
341 log.info('cmd: Querying radio stations')
343 log.debug('rbquery without parameter')
344 msg = constants.strings('rb_query_empty')
345 bot.send_msg(msg, text)
347 log.debug('cmd: Found query parameter: ' + parameter)
348 # bot.send_msg('Searching for stations - this may take some seconds...', text)
349 rb_stations = radiobrowser.getstations_byname(parameter)
350 msg = constants.strings('rb_query_result')
351 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
353 log.debug('cmd: No matches found for rbquery ' + parameter)
354 bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
356 for s in rb_stations:
358 stationname = s['stationname']
359 country = s['country']
361 bitrate = s['bitrate']
363 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
364 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
365 stationid, stationname, genre, codec, bitrate, country)
367 # Full message as html table
369 bot.send_msg(msg, text)
370 # Shorten message if message too long (stage I)
372 log.debug('Result too long stage I')
373 msg = constants.strings('rb_query_result') + ' (shortened L1)'
374 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
375 for s in rb_stations:
377 stationname = s['stationname']
378 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
379 msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
382 bot.send_msg(msg, text)
383 # Shorten message if message too long (stage II)
385 log.debug('Result too long stage II')
386 msg = constants.strings('rb_query_result') + ' (shortened L2)'
387 msg += '!rbplay ID - Station Name'
388 for s in rb_stations:
390 stationname = s['stationname'][:12]
391 # msg += f'{stationid} - {stationname}'
392 msg += '%s - %s' % (stationid, stationname)
394 bot.send_msg(msg, text)
395 # Message still too long
397 bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
401 def cmd_rb_play(bot, user, text, command, parameter):
404 log.debug('cmd: Play a station by ID')
406 log.debug('rbplay without parameter')
407 msg = constants.strings('rb_play_empty')
408 bot.send_msg(msg, text)
410 log.debug('cmd: Retreiving url for station ID ' + parameter)
411 rstation = radiobrowser.getstationname_byid(parameter)
412 stationname = rstation[0]['name']
413 country = rstation[0]['country']
414 codec = rstation[0]['codec']
415 bitrate = rstation[0]['bitrate']
416 genre = rstation[0]['tags']
417 homepage = rstation[0]['homepage']
418 msg = 'Radio station added to playlist:'
419 # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
420 # f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
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 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
423 % (parameter, stationname, genre, codec, bitrate, country, homepage)
424 log.debug('cmd: Added station to playlist %s' % stationname)
425 bot.send_msg(msg, text)
426 url = radiobrowser.geturl_byid(parameter)
428 log.info('cmd: Found url: ' + url)
429 music = {'type': 'radio',
430 'title': stationname,
434 var.playlist.append(music)
435 log.info("cmd: add to playlist: " + util.format_debug_song_string(music))
436 bot.async_download_next()
438 log.info('cmd: No playable url found.')
439 msg += "No playable url found for this station, please try another station."
440 bot.send_msg(msg, text)
443 def cmd_help(bot, user, text, command, parameter):
446 bot.send_msg(constants.strings('help'), text)
447 if bot.is_admin(user):
448 bot.send_msg(constants.strings('admin_help'), text)
451 def cmd_stop(bot, user, text, command, parameter):
455 bot.send_msg(constants.strings('stopped'), text)
458 def cmd_clear(bot, user, text, command, parameter):
462 bot.send_msg(constants.strings('cleared'), text)
465 def cmd_kill(bot, user, text, command, parameter):
468 if bot.is_admin(user):
472 bot.mumble.users[text.actor].send_text_message(
473 constants.strings('not_admin'))
476 def cmd_update(bot, user, text, command, parameter):
479 if bot.is_admin(user):
480 bot.mumble.users[text.actor].send_text_message(
481 constants.strings('start_updating'))
482 msg = util.update(bot.version)
483 bot.mumble.users[text.actor].send_text_message(msg)
485 bot.mumble.users[text.actor].send_text_message(
486 constants.strings('not_admin'))
489 def cmd_stop_and_getout(bot, user, text, command, parameter):
494 bot.mumble.channels.find_by_name(bot.channel).move_in()
497 def cmd_volume(bot, user, text, command, parameter):
500 # The volume is a percentage
501 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
502 bot.volume_set = float(float(parameter) / 100)
503 bot.send_msg(constants.strings('change_volume',
504 volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
505 var.db.set('bot', 'volume', str(bot.volume_set))
506 log.info('cmd: volume set to %d' % (bot.volume_set * 100))
508 bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
511 def cmd_ducking(bot, user, text, command, parameter):
514 if parameter == "" or parameter == "on":
515 bot.is_ducking = True
516 var.db.set('bot', 'ducking', True)
517 bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
518 bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
519 bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
520 bot.ducking_sound_received)
521 bot.mumble.set_receive_sound(True)
522 log.info('cmd: ducking is on')
524 bot.send_msg(msg, text)
525 elif parameter == "off":
526 bot.is_ducking = False
527 bot.mumble.set_receive_sound(False)
528 var.db.set('bot', 'ducking', False)
530 log.info('cmd: ducking is off')
531 bot.send_msg(msg, text)
534 def cmd_ducking_threshold(bot, user, text, command, parameter):
537 if parameter and parameter.isdigit():
538 bot.ducking_threshold = int(parameter)
539 var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
540 msg = "Ducking threshold set to %d." % bot.ducking_threshold
541 bot.send_msg(msg, text)
543 msg = "Current ducking threshold is %d." % bot.ducking_threshold
544 bot.send_msg(msg, text)
547 def cmd_ducking_volume(bot, user, text, command, parameter):
550 # The volume is a percentage
551 if parameter and parameter.isdigit() and 0 <= int(parameter) <= 100:
552 bot.ducking_volume = float(float(parameter) / 100)
553 bot.send_msg(constants.strings('change_ducking_volume',
554 volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
555 # var.db.set('bot', 'volume', str(bot.volume_set))
556 var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
557 log.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
559 bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
562 def cmd_current_music(bot, user, text, command, parameter):
566 if var.playlist.length() > 0:
567 bot.send_msg(util.format_current_playing())
569 reply = constants.strings('not_playing')
570 bot.send_msg(reply, text)
573 def cmd_skip(bot, user, text, command, parameter):
576 if var.playlist.length() > 0:
579 bot.async_download_next()
581 bot.send_msg(constants.strings('queue_empty'), text)
584 def cmd_remove(bot, user, text, command, parameter):
587 # Allow to remove specific music into the queue with a number
588 if parameter and parameter.isdigit() and int(parameter) > 0 \
589 and int(parameter) <= var.playlist.length():
591 index = int(parameter) - 1
594 if index == var.playlist.current_index:
595 removed = var.playlist.remove(index)
597 if index < len(var.playlist):
599 bot.interrupt_playing()
600 var.playlist.current_index -= 1
601 # then the bot will move to next item
603 else: # if item deleted is the last item of the queue
604 var.playlist.current_index -= 1
606 bot.interrupt_playing()
608 removed = var.playlist.remove(index)
610 # the Title isn't here if the music wasn't downloaded
611 bot.send_msg(constants.strings('removing_item',
612 item=removed['title'] if 'title' in removed else removed['url']), text)
614 log.info("cmd: delete from playlist: " + str(removed['path'] if 'path' in removed else removed['url']))
616 bot.send_msg(constants.strings('bad_parameter', command=command))
619 def cmd_list_file(bot, user, text, command, parameter):
622 folder_path = var.music_folder
624 files = util.get_recursive_file_list_sorted(folder_path)
625 msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
628 for index, file in enumerate(files):
630 match = re.search(parameter, file)
635 msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
638 send_multi_lines(bot, msgs, text)
640 bot.send_msg(constants.strings('no_file'), text)
642 except re.error as e:
643 msg = constants.strings('wrong_pattern', error=str(e))
644 bot.send_msg(msg, text)
647 def cmd_queue(bot, user, text, command, parameter):
650 if len(var.playlist) == 0:
651 msg = constants.strings('queue_empty')
652 bot.send_msg(msg, text)
654 msgs = [ constants.strings('queue_contents')]
655 for i, value in enumerate(var.playlist):
657 if i == var.playlist.current_index:
658 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, value['type'],
659 value['title'] if 'title' in value else value['url'])
661 newline = '<b>{}</b> ({}) {}'.format(i + 1, value['type'],
662 value['title'] if 'title' in value else value['url'])
666 send_multi_lines(bot, msgs, text)
668 def cmd_random(bot, user, text, command, parameter):
671 bot.interrupt_playing()
672 var.playlist.randomize()
674 def cmd_repeat(bot, user, text, command, parameter):
678 if parameter and parameter.isdigit():
679 repeat = int(parameter)
681 music = var.playlist.current_item()
682 for _ in range(repeat):
684 var.playlist.current_index + 1,
687 log.info("bot: add to playlist: " + util.format_debug_song_string(music))
689 bot.send_msg(constants.strings("repeat", song=util.format_song_string(music), n=str(repeat)), text)
691 def cmd_mode(bot, user, text, command, parameter):
695 bot.send_msg(constants.strings("current_mode", mode=var.playlist.mode), text)
697 if not parameter in ["one-shot", "repeat", "random"]:
698 bot.send_msg(constants.strings('unknown_mode', mode=parameter), text)
700 var.db.set('playlist', 'playback_mode', parameter)
701 var.playlist.set_mode(parameter)
702 log.info("command: playback mode changed to %s." % parameter)
703 bot.send_msg(constants.strings("change_mode", mode=var.playlist.mode,
704 user=bot.mumble.users[text.actor]['name']), text)
705 if parameter == "random":
707 var.playlist.randomize()
711 def cmd_drop_database(bot, user, text, command, parameter):
715 var.db = Database(var.dbfile)
716 bot.send_msg(constants.strings('database_dropped'), text)