Advertisement
Philipou

music bot code

Jul 16th, 2023
1,363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.64 KB | None | 0 0
  1. import discord
  2. from discord.ext import commands
  3. import time
  4. import yt_dlp
  5. import asyncio
  6. from requests import get
  7. import datetime
  8.  
  9. start_time = time.time()
  10. default_intents = discord.Intents.all()
  11. activity = discord.Activity(type=discord.ActivityType.listening, name="@philipou")
  12. bot = commands.Bot(command_prefix=".", intents=default_intents, activity=activity, status=discord.Status.online)
  13. musics = {}
  14. ytdl = yt_dlp.YoutubeDL()
  15. queue = []
  16.  
  17.  
  18. @bot.event
  19. async def on_ready():
  20.     print("The bot is ready !")
  21.  
  22.  
  23. class Video:
  24.     def __init__(self, arg):
  25.         try:
  26.             get(arg)
  27.         except:
  28.             video = ytdl.extract_info(f"ytsearch:{arg}", download=False)["entries"][0]
  29.         else:
  30.             video = ytdl.extract_info(arg, download=False)
  31.         video_format = video["requested_formats"][0]
  32.         self.url = video["webpage_url"]
  33.         self.stream_url = video_format["url"]
  34.  
  35.  
  36. @bot.command(name="stop", help="Stops the current track.", )
  37. async def stop(ctx):
  38.     global queue
  39.     client = ctx.guild.voice_client
  40.     musics[ctx.guild] = []
  41.     if client:
  42.         await client.disconnect()
  43.         await ctx.send("Disconnected from the voice channel.")
  44.     else:
  45.         await ctx.send("I'm not in a voice channel !")
  46.  
  47.  
  48. @bot.command(name="resume", help="Resume the current paused track.")
  49. async def resume(ctx):
  50.     client = ctx.guild.voice_client
  51.     if client.is_paused():
  52.         client.resume()
  53.         await ctx.send("Resuming the current track.")
  54.     else:
  55.         await ctx.send("I'm not paused !")
  56.  
  57.  
  58. @bot.command(name="pause", help="Pause the current playing track.")
  59. async def pause(ctx):
  60.     client = ctx.guild.voice_client
  61.     if not client.is_paused():
  62.         client.pause()
  63.         await ctx.send("Pausing the current playing track.")
  64.     else:
  65.         await ctx.send("I'm already paused !")
  66.  
  67.  
  68. async def play_song(client, queue, song):
  69.     source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(song.stream_url,
  70.                                                                  before_options="-reconnect 1 -reconnect_streamed 1 "
  71.                                                                                 "-reconnect_delay_max 5 "))
  72.  
  73.     # noinspection PyTypeChecker
  74.     def next(_):
  75.         global queue
  76.         if "loop" in queue:
  77.             asyncio.run_coroutine_threadsafe(play_song(client, queue, song), bot.loop)
  78.         elif len(queue) > 0:
  79.             new_song = queue[0]
  80.             del queue
  81.             queue = [0]
  82.             asyncio.run_coroutine_threadsafe(play_song(client, queue, new_song), bot.loop)
  83.         else:
  84.             asyncio.run_coroutine_threadsafe(client.disconnect(), bot.loop)
  85.  
  86.     client.play(source, after=next)
  87.  
  88.  
  89. @bot.command(name="play", help="Play a song from a search query or url.")
  90. async def play(ctx, *, url):
  91.     client = ctx.guild.voice_client
  92.     video = Video(url)
  93.     musics[ctx.guild] = []
  94.     channel = ctx.author.voice.channel
  95.     if client and client.channel:
  96.         await client.disconnect()
  97.         time.sleep(1)
  98.         client = await channel.connect()
  99.         await ctx.send(f"Playing : {video.url}")
  100.         await play_song(client, musics[ctx.guild], video)
  101.     else:
  102.         await ctx.send(f"Playing : {video.url}")
  103.         client = await channel.connect()
  104.         await play_song(client, musics[ctx.guild], video)
  105.  
  106.  
  107. @bot.command(name="ping", help="Check the bot's ping/latency.")
  108. async def bot_ping(ctx):
  109.     await ctx.channel.send(f"Bot have {round(bot.latency * 1000)} ms of ping")
  110.  
  111.  
  112. @bot.command(name="uptime", help="Check the bot's uptime")
  113. async def bot_uptime(ctx):
  114.     current_time = time.time()
  115.     difference = int(round(current_time - start_time))
  116.     text = str(datetime.timedelta(seconds=difference))
  117.     await ctx.channel.send("Bot have " + text + " of uptime")
  118.  
  119.  
  120. @bot.command(name="about", help="Give information about the bot.")
  121. async def about(ctx):
  122.     await ctx.send("Hey ! I'm a nice bot made to listen to music from youtube (and i also have some other "
  123.                    "funtionalities), for help type `.help`, for support contact `Philipou#6977`")
  124.  
  125.  
  126. @bot.command(name="loop", help="Toggle loop for the current track.")
  127. async def loop(ctx):
  128.     client = ctx.guild.voice_client
  129.     try:
  130.         if not client.is_playing():
  131.             return
  132.     except AttributeError:
  133.         await ctx.send("I'm not playing anything !")
  134.         return
  135.  
  136.     if "loop" in queue:
  137.         queue.remove("loop")
  138.         await ctx.send("Looping disabled for the current track.")
  139.     else:
  140.         queue.append("loop")
  141.         await ctx.send("Looping enabled for the current track.")
  142.  
  143.  
  144. bot.run("token :)")
  145.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement