Matrix bot to download audio from youtube links, ID3 tag them, and move them to a correct directory

musicbot.py 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from matrix_bot_api.matrix_bot_api import MatrixBotAPI
  2. from matrix_bot_api.mhandler import MHandler
  3. from matrix_bot_api.mregex_handler import MRegexHandler
  4. from matrix_bot_api.mcommand_handler import MCommandHandler
  5. import configparser
  6. import youtube_dl
  7. import eyed3
  8. import os
  9. from pathlib import Path
  10. #tempdir, final dir required
  11. def addsong_callback(room, event):
  12. args = event['content']['body'].split(',')
  13. args.pop(0)
  14. ydl_options = {
  15. 'format': 'bestaudio/best','postprocessors': [{
  16. 'key': 'FFmpegExtractAudio',
  17. 'preferredcodec': 'mp3',
  18. 'preferredquality': '192',
  19. },
  20. ],
  21. }
  22. room.send_notice("Downloading and converting...")
  23. with youtube_dl.YoutubeDL(ydl_options) as ydl:
  24. ydl.download([args[0]])
  25. room.send_notice("Moving and renaming...")
  26. for filename in os.listdir("."):
  27. if filename.endswith(".mp3"):
  28. p = Path(filename)
  29. song = eyed3.load(filename)
  30. song.tag.artist = args[2]
  31. song.tag.title = args[1]
  32. song.tag.save()
  33. p.rename('/home/whoishex/Music/'+args[1]+"-"+args[2]+".mp3")
  34. room.send_notice("Done!")
  35. def songhelp_callback(room,event):
  36. help_str = "!addsong - Add a song, in the form URL, Title, Artist. Don't put extra spaces and delimit with commas. \n"
  37. help_str += "!songhelp - Print this\n"
  38. help_str += "example: !addsong,https://youtu.be/yzdZj_9DxVs,Zero Machine,Le Castle Vania"
  39. room.send_notice(help_str)
  40. def main():
  41. config = configparser.ConfigParser()
  42. config.read("config.ini")
  43. username = config.get("Matrix","Username")
  44. password = config.get("Matrix","Password")
  45. server = config.get("Matrix", "Homeserver")
  46. global url
  47. global title
  48. global artist
  49. bot = MatrixBotAPI(username, password, server)
  50. m_addsong_handler = MCommandHandler('addsong', addsong_callback)
  51. bot.add_handler(m_addsong_handler)
  52. m_songhelp_handler = MCommandHandler('songhelp', songhelp_callback)
  53. bot.add_handler(m_songhelp_handler)
  54. bot.start_polling()
  55. while True:
  56. input()
  57. if __name__ == "__main__":
  58. main()