4 import pymumble.pymumble_py3 as pymumble
14 import variables as var
15 from librb import radiobrowser
16 from database import Database
19 def register_all_commands(bot):
20 bot.register_command(constants.commands('joinme'), cmd_joinme)
21 bot.register_command(constants.commands('user_ban'), cmd_user_ban)
22 bot.register_command(constants.commands('user_unban'), cmd_user_unban)
23 bot.register_command(constants.commands('url_ban'), cmd_url_ban)
24 bot.register_command(constants.commands('url_unban'), cmd_url_unban)
25 bot.register_command(constants.commands('play'), cmd_play)
26 bot.register_command(constants.commands('pause'), cmd_pause)
27 bot.register_command(constants.commands('play_file'), cmd_play_file)
28 bot.register_command(constants.commands('play_file_match'), cmd_play_file_match)
29 bot.register_command(constants.commands('play_url'), cmd_play_url)
30 bot.register_command(constants.commands('play_playlist'), cmd_play_playlist)
31 bot.register_command(constants.commands('play_radio'), cmd_play_radio)
32 bot.register_command(constants.commands('rb_query'), cmd_rb_query)
33 bot.register_command(constants.commands('rb_play'), cmd_rb_play)
34 bot.register_command(constants.commands('help'), cmd_help)
35 bot.register_command(constants.commands('stop'), cmd_stop)
36 bot.register_command(constants.commands('clear'), cmd_clear)
37 bot.register_command(constants.commands('kill'), cmd_kill)
38 bot.register_command(constants.commands('update'), cmd_update)
39 bot.register_command(constants.commands('stop_and_getout'), cmd_stop_and_getout)
40 bot.register_command(constants.commands('volume'), cmd_volume)
41 bot.register_command(constants.commands('ducking'), cmd_ducking)
42 bot.register_command(constants.commands('ducking_threshold'), cmd_ducking_threshold)
43 bot.register_command(constants.commands('ducking_volume'), cmd_ducking_volume)
44 bot.register_command(constants.commands('current_music'), cmd_current_music)
45 bot.register_command(constants.commands('skip'), cmd_skip)
46 bot.register_command(constants.commands('remove'), cmd_remove)
47 bot.register_command(constants.commands('list_file'), cmd_list_file)
48 bot.register_command(constants.commands('queue'), cmd_queue)
49 bot.register_command(constants.commands('random'), cmd_random)
50 bot.register_command(constants.commands('drop_database'), cmd_drop_database)
52 def send_multi_lines(bot, lines, text):
58 if len(msg) + len(newline) > 5000:
59 bot.send_msg(msg, text)
63 bot.send_msg(msg, text)
65 # ---------------- Commands ------------------
68 def cmd_joinme(bot, user, text, command, parameter):
69 bot.mumble.users.myself.move_in(
70 bot.mumble.users[text.actor]['channel_id'], token=parameter)
73 def cmd_user_ban(bot, user, text, command, parameter):
74 if bot.is_admin(user):
76 bot.mumble.users[text.actor].send_text_message(util.user_ban(parameter))
78 bot.mumble.users[text.actor].send_text_message(util.get_user_ban())
80 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
84 def cmd_user_unban(bot, user, text, command, parameter):
85 if bot.is_admin(user):
87 bot.mumble.users[text.actor].send_text_message(util.user_unban(parameter))
89 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
93 def cmd_url_ban(bot, user, text, command, parameter):
94 if bot.is_admin(user):
96 bot.mumble.users[text.actor].send_text_message(util.url_ban(util.get_url_from_input(parameter)))
98 bot.mumble.users[text.actor].send_text_message(util.get_url_ban())
100 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
104 def cmd_url_unban(bot, user, text, command, parameter):
105 if bot.is_admin(user):
107 bot.mumble.users[text.actor].send_text_message(util.url_unban(util.get_url_from_input(parameter)))
109 bot.mumble.users[text.actor].send_text_message(constants.strings('not_admin'))
113 def cmd_play(bot, user, text, command, parameter):
114 if var.playlist.length() > 0:
115 if parameter is not None and parameter.isdigit() and int(parameter) > 0 \
116 and int(parameter) <= len(var.playlist.playlist):
118 bot.launch_music(int(parameter) - 1)
122 bot.send_msg(util.format_current_playing(), text)
125 bot.send_msg(constants.strings('queue_empty'), text)
128 def cmd_pause(bot, user, text, command, parameter):
130 bot.send_msg(constants.strings('paused'))
133 def cmd_play_file(bot, user, text, command, parameter):
134 music_folder = var.config.get('bot', 'music_folder')
135 # if parameter is {index}
136 if parameter.isdigit():
137 files = util.get_recursive_filelist_sorted(music_folder)
138 if int(parameter) < len(files):
139 filename = files[int(parameter)].replace(music_folder, '')
140 music = {'type': 'file',
143 logging.info("cmd: add to playlist: " + filename)
144 music = var.playlist.append(music)
145 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
147 # if parameter is {path}
149 # sanitize "../" and so on
150 path = os.path.abspath(os.path.join(music_folder, parameter))
151 if not path.startswith(os.path.abspath(music_folder)):
152 bot.send_msg(constants.strings('no_file'), text)
155 if os.path.isfile(path):
156 music = {'type': 'file',
159 logging.info("cmd: add to playlist: " + parameter)
160 music = var.playlist.append(music)
161 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
164 # if parameter is {folder}
165 elif os.path.isdir(path):
166 if parameter != '.' and parameter != './':
167 if not parameter.endswith("/"):
172 files = util.get_recursive_filelist_sorted(music_folder)
173 music_library = util.Dir(music_folder)
175 music_library.add_file(file)
177 files = music_library.get_files(parameter)
178 msgs = [constants.strings('multiple_file_added')]
183 music = {'type': 'file',
186 logging.info("cmd: add to playlist: " + file)
187 music = var.playlist.append(music)
189 msgs.append("{} ({})".format(music['title'], music['path']))
192 send_multi_lines(bot, msgs, text)
194 bot.send_msg(constants.strings('no_file'), text)
197 # try to do a partial match
198 files = util.get_recursive_filelist_sorted(music_folder)
199 matches = [(index, file) for index, file in enumerate(files) if parameter.lower() in file.lower()]
200 if len(matches) == 0:
201 bot.send_msg(constants.strings('no_file'), text)
202 elif len(matches) == 1:
203 music = {'type': 'file',
204 'path': matches[0][1],
206 logging.info("cmd: add to playlist: " + matches[0][1])
207 music = var.playlist.append(music)
208 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
210 msgs = [ constants.strings('multiple_matches')]
211 for match in matches:
212 msgs.append("<b>{:0>3d}</b> - {:s}".format(match[0], match[1]))
213 send_multi_lines(bot, msgs, text)
216 def cmd_play_file_match(bot, user, text, command, parameter):
217 music_folder = var.config.get('bot', 'music_folder')
218 if parameter is not None:
219 files = util.get_recursive_filelist_sorted(music_folder)
220 msgs = [ constants.strings('file_added')]
224 match = re.search(parameter, file)
227 music = {'type': 'file',
230 logging.info("cmd: add to playlist: " + file)
231 music = var.playlist.append(music)
233 msgs.append("{} ({})".format(music['title'], music['path']))
236 send_multi_lines(bot, msgs, text)
238 bot.send_msg(constants.strings('no_file'), text)
240 except re.error as e:
241 msg = constants.strings('wrong_pattern', error=str(e))
242 bot.send_msg(msg, text)
244 bot.send_msg(constants.strings('bad_parameter', command))
247 def cmd_play_url(bot, user, text, command, parameter):
248 music = {'type': 'url',
250 'url': util.get_url_from_input(parameter),
252 'ready': 'validation'}
254 music = bot.validate_music(music)
256 var.playlist.append(music)
257 logging.info("cmd: add to playlist: " + music['url'])
258 bot.send_msg(constants.strings('file_added', item=util.format_song_string(music)), text)
259 if var.playlist.length() == 2:
260 # If I am the second item on the playlist. (I am the next one!)
261 bot.async_download_next()
263 bot.send_msg(constants.strings('unable_download'), text)
266 def cmd_play_playlist(bot, user, text, command, parameter):
267 offset = 0 # if you want to start the playlist at a specific index
269 offset = int(parameter.split(" ")[-1])
273 url = util.get_url_from_input(parameter)
274 logging.debug("cmd: fetching media info from playlist url %s" % url)
275 items = media.playlist.get_playlist_info(url=url, start_index=offset, user=user)
277 var.playlist.extend(items)
279 logging.info("cmd: add to playlist: " + util.format_debug_song_string(music))
282 def cmd_play_radio(bot, user, text, command, parameter):
284 all_radio = var.config.items('radio')
285 msg = constants.strings('preconfigurated_radio')
288 if len(i[1].split(maxsplit=1)) == 2:
289 comment = " - " + i[1].split(maxsplit=1)[1]
290 msg += "<br />" + i[0] + comment
291 bot.send_msg(msg, text)
293 if var.config.has_option('radio', parameter):
294 parameter = var.config.get('radio', parameter)
295 parameter = parameter.split()[0]
296 url = util.get_url_from_input(parameter)
298 music = {'type': 'radio',
301 var.playlist.append(music)
302 logging.info("cmd: add to playlist: " + music['url'])
303 bot.async_download_next()
305 bot.send_msg(constants.strings('bad_url'))
308 def cmd_rb_query(bot, user, text, command, parameter):
309 logging.info('cmd: Querying radio stations')
311 logging.debug('rbquery without parameter')
312 msg = constants.strings('rb_query_empty')
313 bot.send_msg(msg, text)
315 logging.debug('cmd: Found query parameter: ' + parameter)
316 # bot.send_msg('Searching for stations - this may take some seconds...', text)
317 rb_stations = radiobrowser.getstations_byname(parameter)
318 msg = constants.strings('rb_query_result')
319 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th></tr>'
321 logging.debug('cmd: No matches found for rbquery ' + parameter)
322 bot.send_msg('Radio-Browser found no matches for ' + parameter, text)
324 for s in rb_stations:
326 stationname = s['stationname']
327 country = s['country']
329 bitrate = s['bitrate']
331 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td></tr>'
332 msg += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td></tr>' % (
333 stationid, stationname, genre, codec, bitrate, country)
335 # Full message as html table
337 bot.send_msg(msg, text)
338 # Shorten message if message too long (stage I)
340 logging.debug('Result too long stage I')
341 msg = constants.strings('rb_query_result') + ' (shortened L1)'
342 msg += '\n<table><tr><th>!rbplay ID</th><th>Station Name</th></tr>'
343 for s in rb_stations:
345 stationname = s['stationname']
346 # msg += f'<tr><td>{stationid}</td><td>{stationname}</td>'
347 msg += '<tr><td>%s</td><td>%s</td>' % (stationid, stationname)
350 bot.send_msg(msg, text)
351 # Shorten message if message too long (stage II)
353 logging.debug('Result too long stage II')
354 msg = constants.strings('rb_query_result') + ' (shortened L2)'
355 msg += '!rbplay ID - Station Name'
356 for s in rb_stations:
358 stationname = s['stationname'][:12]
359 # msg += f'{stationid} - {stationname}'
360 msg += '%s - %s' % (stationid, stationname)
362 bot.send_msg(msg, text)
363 # Message still too long
365 bot.send_msg('Query result too long to post (> 5000 characters), please try another query.',
369 def cmd_rb_play(bot, user, text, command, parameter):
370 logging.debug('cmd: Play a station by ID')
372 logging.debug('rbplay without parameter')
373 msg = constants.strings('rb_play_empty')
374 bot.send_msg(msg, text)
376 logging.debug('cmd: Retreiving url for station ID ' + parameter)
377 rstation = radiobrowser.getstationname_byid(parameter)
378 stationname = rstation[0]['name']
379 country = rstation[0]['country']
380 codec = rstation[0]['codec']
381 bitrate = rstation[0]['bitrate']
382 genre = rstation[0]['tags']
383 homepage = rstation[0]['homepage']
384 msg = 'Radio station added to playlist:'
385 # msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
386 # f'<tr><td>{parameter}</td><td>{stationname}</td><td>{genre}</td><td>{codec}/{bitrate}</td><td>{country}</td><td>{homepage}</td></tr></table>'
387 msg += '<table><tr><th>ID</th><th>Station Name</th><th>Genre</th><th>Codec/Bitrate</th><th>Country</th><th>Homepage</th></tr>' + \
388 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s/%s</td><td>%s</td><td>%s</td></tr></table>' \
389 % (parameter, stationname, genre, codec, bitrate, country, homepage)
390 logging.debug('cmd: Added station to playlist %s' % stationname)
391 bot.send_msg(msg, text)
392 url = radiobrowser.geturl_byid(parameter)
394 logging.info('cmd: Found url: ' + url)
395 music = {'type': 'radio',
396 'title': stationname,
400 var.playlist.append(music)
401 logging.info("cmd: add to playlist: " + music['url'])
402 bot.async_download_next()
404 logging.info('cmd: No playable url found.')
405 msg += "No playable url found for this station, please try another station."
406 bot.send_msg(msg, text)
409 def cmd_help(bot, user, text, command, parameter):
410 bot.send_msg(constants.strings('help'), text)
411 if bot.is_admin(user):
412 bot.send_msg(constants.strings('admin_help'), text)
415 def cmd_stop(bot, user, text, command, parameter):
417 bot.send_msg(constants.strings('stopped'), text)
420 def cmd_clear(bot, user, text, command, parameter):
422 bot.send_msg(constants.strings('cleared'), text)
425 def cmd_kill(bot, user, text, command, parameter):
426 if bot.is_admin(user):
430 bot.mumble.users[text.actor].send_text_message(
431 constants.strings('not_admin'))
434 def cmd_update(bot, user, text, command, parameter):
435 if bot.is_admin(user):
436 bot.mumble.users[text.actor].send_text_message(
437 constants.strings('start_updating'))
438 msg = util.update(bot.version)
439 bot.mumble.users[text.actor].send_text_message(msg)
441 bot.mumble.users[text.actor].send_text_message(
442 constants.strings('not_admin'))
445 def cmd_stop_and_getout(bot, user, text, command, parameter):
448 bot.mumble.channels.find_by_name(bot.channel).move_in()
451 def cmd_volume(bot, user, text, command, parameter):
452 # The volume is a percentage
453 if parameter is not None and parameter.isdigit() and 0 <= int(parameter) <= 100:
454 bot.volume_set = float(float(parameter) / 100)
455 bot.send_msg(constants.strings('change_volume',
456 volume=int(bot.volume_set * 100), user=bot.mumble.users[text.actor]['name']), text)
457 var.db.set('bot', 'volume', str(bot.volume_set))
458 logging.info('cmd: volume set to %d' % (bot.volume_set * 100))
460 bot.send_msg(constants.strings('current_volume', volume=int(bot.volume_set * 100)), text)
463 def cmd_ducking(bot, user, text, command, parameter):
464 if parameter == "" or parameter == "on":
465 bot.is_ducking = True
466 var.db.set('bot', 'ducking', True)
467 bot.ducking_volume = var.config.getfloat("bot", "ducking_volume", fallback=0.05)
468 bot.ducking_threshold = var.config.getint("bot", "ducking_threshold", fallback=5000)
469 bot.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED,
470 bot.ducking_sound_received)
471 bot.mumble.set_receive_sound(True)
472 logging.info('cmd: ducking is on')
474 bot.send_msg(msg, text)
475 elif parameter == "off":
476 bot.is_ducking = False
477 bot.mumble.set_receive_sound(False)
478 var.db.set('bot', 'ducking', False)
480 logging.info('cmd: ducking is off')
481 bot.send_msg(msg, text)
484 def cmd_ducking_threshold(bot, user, text, command, parameter):
485 if parameter is not None and parameter.isdigit():
486 bot.ducking_threshold = int(parameter)
487 var.db.set('bot', 'ducking_threshold', str(bot.ducking_threshold))
488 msg = "Ducking threshold set to %d." % bot.ducking_threshold
489 bot.send_msg(msg, text)
491 msg = "Current ducking threshold is %d." % bot.ducking_threshold
492 bot.send_msg(msg, text)
495 def cmd_ducking_volume(bot, user, text, command, parameter):
496 # The volume is a percentage
497 if parameter is not None and parameter.isdigit() and 0 <= int(parameter) <= 100:
498 bot.ducking_volume = float(float(parameter) / 100)
499 bot.send_msg(constants.strings('change_ducking_volume',
500 volume=int(bot.ducking_volume * 100), user=bot.mumble.users[text.actor]['name']), text)
501 # var.db.set('bot', 'volume', str(bot.volume_set))
502 var.db.set('bot', 'ducking_volume', str(bot.ducking_volume))
503 logging.info('cmd: volume on ducking set to %d' % (bot.ducking_volume * 100))
505 bot.send_msg(constants.strings('current_ducking_volume', volume=int(bot.ducking_volume * 100)), text)
508 def cmd_current_music(bot, user, text, command, parameter):
510 if var.playlist.length() > 0:
511 bot.send_msg(util.format_current_playing())
513 reply = constants.strings('not_playing')
514 bot.send_msg(reply, text)
517 def cmd_skip(bot, user, text, command, parameter):
518 if var.playlist.length() > 0:
521 bot.async_download_next()
523 bot.send_msg(constants.strings('queue_empty'), text)
526 def cmd_remove(bot, user, text, command, parameter):
527 # Allow to remove specific music into the queue with a number
528 if parameter is not None and parameter.isdigit() and int(parameter) > 0 \
529 and int(parameter) <= var.playlist.length():
531 index = int(parameter) - 1
534 if index == var.playlist.current_index:
535 removed = var.playlist.remove(index)
536 if bot.is_playing and not bot.is_pause:
538 bot.launch_music(index)
540 removed = var.playlist.remove(index)
542 # the Title isn't here if the music wasn't downloaded
543 bot.send_msg(constants.strings('removing_item',
544 item=removed['title'] if 'title' in removed else removed['url']), text)
546 logging.info("cmd: delete from playlist: " + str(removed['path'] if 'path' in removed else removed['url']))
548 bot.send_msg(constants.strings('bad_parameter', command=command))
551 def cmd_list_file(bot, user, text, command, parameter):
552 folder_path = var.config.get('bot', 'music_folder')
554 files = util.get_recursive_filelist_sorted(folder_path)
555 msgs = [ "<br> <b>Files available:</b>" if not parameter else "<br> <b>Matched files:</b>" ]
558 for index, file in enumerate(files):
560 match = re.search(parameter, file)
565 msgs.append("<b>{:0>3d}</b> - {:s}".format(index, file))
568 send_multi_lines(bot, msgs, text)
570 bot.send_msg(constants.strings('no_file'), text)
572 except re.error as e:
573 msg = constants.strings('wrong_pattern', error=str(e))
574 bot.send_msg(msg, text)
577 def cmd_queue(bot, user, text, command, parameter):
578 if len(var.playlist.playlist) == 0:
579 msg = constants.strings('queue_empty')
580 bot.send_msg(msg, text)
582 msgs = [ constants.strings('queue_contents')]
583 for i, value in enumerate(var.playlist.playlist):
585 if i == var.playlist.current_index:
586 newline = '<b>{} ▶ ({}) {} ◀</b>'.format(i + 1, value['type'],
587 value['title'] if 'title' in value else value['url'])
589 newline = '<b>{}</b> ({}) {}'.format(i + 1, value['type'],
590 value['title'] if 'title' in value else value['url'])
594 send_multi_lines(bot, msgs, text)
597 def cmd_random(bot, user, text, command, parameter):
599 var.playlist.randomize()
602 def cmd_drop_database(bot, user, text, command, parameter):
604 var.db = Database(var.dbfile)
605 bot.send_msg(constants.strings('database_dropped'), text)