Issue Skipping Song by Requester

How do add a ratio?

Sure, you could do something like this

if control == 'skip':
skip = await channel.send(f':poop: **{user.name}** voted to skip **{source.title}**. **{react.count}/5** voted.', delete_after=8)
try:
ratio = react.count / len(ctx.author.voice.channel.members)
except ZeroDivisionError:
pass
if ratio >= .5: # bot counts as 1 reaction.
vc.stop()
await channel.send('**Skipping song...**', delete_after=5)

where it would only skip the song if more than or exactly half of the people in the voice channel voted to skip

You could adjust the ratio you want later on

playPause button not resetting upon track skip

Discrepancies

The term media tag is a generic name for <audio> and <video> tags.

  • OP lacked any event listeners or on-event properties so it's safe to assume that there are on-event attributes:

    <button onclick='lame()' type='button'>Click Me I'm Lame</button>

    Don't use them, they suck. Instead use:

    <button type='button'>Click Me</button>

    const btn = document.queryselector('button');

    btn.addEventListener('click', clickHandler);

    /* OR */

    btn.onclick = clickHandler;
  • There's a Boolean called isPlaying. Two problems:

    1. It shouldn't be true initially. Common sense dictates that song is not playing once the page loads (if it does, rethink that for the sake of UX).

    2. Instead of using a flag use the media properties that return a Boolean concerning the status of a media tag (ie song): song.paused, song.ended, and song.playing.

  • The first if conditional of nextSong() is wrong:

    if (songIndex === songs.length)  {...

    songs.length is 7. somgIndex range is 0 - 6. So it should be songs.length -1

  • Didn't include the <progress> tag and its handlers, it looks like it's copied correctly...almost. This looks as if it was added on later:

    setInterval (updateProgressValue, 500);

    function changeProgressBar() {
    song.currentTime = progressBar.value;
    };

    setInterval() is a poor substitute for the "timeupdate" event. A media tag triggers a "timeupedate" every 250ms while playing. Use the properties song.currentTime and song.duration to monitor elapsed time during playback.

    changeProgressBar() looks useless. There's already a handler called updateProgressValue(). In the only line that changeProgressBar() has is a reverse version of one of the lines in updateProgressValue():

    song.currentTime = progressBar.value;
    progressBar.value = song.currentTime;

Advice

The term form controls is a generic term for <input>, <output>, <textarea>, <button>, <select>, <fieldset>, and <object> tags.

The term ancestor tag is a term for a tag that shares the same branch on the DOM tree at a higher level than the targets -- a term for the descendant tags of the ancestor tags that the developer intends to imbue behavior triggered by an event.

  • If your layout has more than one form control, wrap everything in a <form> tag. Doing so allows you to use the HTMLFormElement interface and HTMLFormControlsCollection API. The syntax is terse and simplifies access to form controls.

     <form id='main'>
    <fieldset name='set'>
    <input>
    <button type='button'>
    [type='button'] is needed when nested within a <form>...
    </button>
    <button>
    ...otherwise it is a [type='submit'] by default.
    </button>
    </fieldset>
    <fieldset name='set'>
    <input id='input1'>
    <input id='input2'>
    </fieldset>
    </form>
    <script>
    /*
    - Referencing the <form> by #ID
    - Or bracket notation document.forms['main'];
    - Or by index document.forms[0];
    */
    const main = document.forms.main;

    /*
    - Once the <form> is referenced -- use the `.elements` property to collect
    all of its form controls into a **HTMLCollection** (Use an short and easy
    to remember identifier to reference it).
    */

    const ui = main.elements;
    /*
    - <form> tags and form controls can be referenced by [name] attribute as
    well. Keep in mind that if there is more than one tag with the same
    [name] -- then they will be collected into a **HTMLCollection**.
    - Note: There is another fieldset[name=set] -- so in this situation you can
    access them both: `sets[0]` and `sets[1]`
    */
    const sets = ui.set;

    /*
    - To reference a form control without a #ID or [name], its index is always
    available. There's an archaic way as well: `const input = ui.item(1)`
    - There's no need to reference the second <button> because its a
    [type='submit'] tag. They have default behavior built-in: *Sends data to
    server* and *Resets the <form>*
    */
    const input = ui[1];
    const button = ui[2];

    /*
    - Of the many ways to reference a form control -- #ID is the easiest.
    */
    const i1 = ui.input1;
    const i2 = ui.input2;
    </script>

  • Event Delegation is a programming pattern that leverages Event Bubbling so that we...

    • ...can listen for events triggered on not only an unknown and unlimited number of tags -- we are also able to listen for triggered events for tags that are dynamically created after page load.

    • Moreover, only one ancestor tag that all target tags have in common is needed to listen for events, (window, document, and body are always available, but only use if there is no other tag that's closer to all targets).

      document.forms[0].onclick = controlPlayer; 
    • The Event handler function must pass the Event Object so that the .target property can be used to determine the actual tag that interacted with the user (in this case what was clicked).

      function controlPlayer(event) {
      const clicked = event.target;
      ...
    • Once that is established we narrow the possibilities down further. Doing so allows us to exclude tags we don't need to deal with by explicitly excluding them:

      if (event.target.matches('[type=button]')) {...
  • Changing the appearance of tags to indicate state can be done by toggling .classes that have the styles unique to the state it represents. Common practice is to use the pseudo-elements ::before and ::after


Demo

const thumb = document.querySelector('.thumb');const song = document.querySelector('#song');
const form = document.forms.ui;const ui = form.elements;const artist = ui.artist;const title = ui.title;const play = ui.playBack;const prev = ui.prev;const next = ui.next;
const base = 'https://glpjt.s3.amazonaws.com/so/av';const songs = ['/mp3/righteous.mp3', '/mp3/jerky.mp3', '/mp3/nosegoblin.mp3', '/mp3/balls.mp3', '/mp3/behave.mp3'];const thumbs = ['/img/link.gif', '/img/sol.png', '/img/ren.gif', '/img/balls.gif', '/img/austin.gif'];const artists = ['Samuel L. Jackson', 'Sol Rosenberg', 'Ren', 'Al Pachino', 'Mike Myers'];const titles = ["Righteous", "Whatnot", "Magic Nose Goblins", "Balls", "Behave"];let index = 0;let quantity = songs.length;
const playMP3 = () => { play.classList.remove('play'); play.classList.add('pause'); song.play();}
const pauseMP3 = () => { play.classList.remove('pause'); play.classList.add('play'); song.pause();}
form.onclick = controlPlayer;
song.onended = function(event) { pauseMP3(); index++; if (index > quantity - 1) { index = 0; } song.src = base + songs[index]; thumb.src = base + thumbs[index]; artist.value = artists[index]; title.value = titles[index]; playMP3();}
function init() { song.src = base + songs[0]; thumb.src = base + thumbs[0]; artist.value = artists[0]; title.value = titles[0]; song.load();}
function controlPlayer(event) { const clicked = event.target;
if (clicked.matches('#playBack')) { if (song.paused || song.ended) { playMP3(); } else { pauseMP3(); } }
if (clicked.matches('#prev')) { pauseMP3(); index--; if (index < 0) { index = quantity - 1; } song.src = base + songs[index]; thumb.src = base + thumbs[index]; artist.value = artists[index]; title.value = titles[index]; playMP3(); }
if (clicked.matches('#next')) { pauseMP3(); index++; if (index > quantity - 1) { index = 0; } song.src = base + songs[index]; thumb.src = base + thumbs[index]; artist.value = artists[index]; title.value = titles[index]; playMP3(); }}
init();
:root,body {  font: 700 small-caps 2.5vw/1.5 Verdana;}
b { display: inline-block; width: 6ch; color: white;}
output { color: gold; text-shadow: 0 0 5px red;}
button { display: inline-block; width: 3vw; height: 11.25vw; line-height: 11.25vw; border: 0; font: inherit; font-size: 3rem; vertical-align: middle; color: lime; background: none; cursor: pointer;}
button:hover { color: cyan;}
#playBack.play::before { content: '\0025b6';}
#playBack.pause { height: 5.625vw; line-height: 5.625vw;}
#playBack.pause::before { content: '\00258e\a0\00258e'; height: 5.625vw; line-height: 5.625vw; font-size: 2rem; vertical-align: top;}
#prev::before { content: '\0023ee'; height: 5vw; line-height: 5vw; font-size: 3.25rem; vertical-align: top;}
#next,#prev { height: 5vw; line-height: 5vw;}
#next::before { content: '\0023ed'; height: 5vw; line-height: 5vw; font-size: 3.25rem; vertical-align: top;}
figure { position: relative; min-height: 150px; margin: 0px auto;}
figcaption { position: absolute; bottom: 0; left: 0; right: 0; z-index: 1; height: max-content; padding: 3px 5px; font-size: 1.2rem;}
figcaption label { background: rgba(0, 0, 0, 0.4);}
.thumb { display: block; max-width: 100%; height: auto; margin: 5px auto; object-fit: contain;}
.controls { display: flex; flex-flow: row nowrap; justify-content: space-evenly; align-items: center; height: 6vw;}
<main>  <form id='ui'>    <audio id='song'></audio>    <fieldset>      <figure>        <img class='thumb'>        <figcaption>          <label>          <b>Artist:</b> <output id='artist'></output>        </label>          <label><br>          <b>Title:</b> <output id='title'></output>        </label>        </figcaption>      </figure>      <fieldset class='controls'>        <button id='prev' type='button'></button>        <button id='playBack' class='play' type='button'></button>        <button id='next' type='button'></button>      </fieldset>    </fieldset>  </form></main>

Python Discord Music Bot - creating a queue - automatically playing the next song

I have some working code here that has a functioning queue system, along with clear and remove commands, that can clear the queue or remove a certain song from the queue. Keep in mind that this was written as a cog.

import discord
from discord.ext import commands
import random
import asyncio
import itertools
import sys
import traceback
from async_timeout import timeout
from functools import partial
import youtube_dl
from youtube_dl import YoutubeDL

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''

ytdlopts = {
'format': 'bestaudio/best',
'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # ipv6 addresses cause issues sometimes
}

ffmpegopts = {
'before_options': '-nostdin',
'options': '-vn'
}

ytdl = YoutubeDL(ytdlopts)


class VoiceConnectionError(commands.CommandError):
"""Custom Exception class for connection errors."""


class InvalidVoiceChannel(VoiceConnectionError):
"""Exception for cases of invalid Voice Channels."""


class YTDLSource(discord.PCMVolumeTransformer):

def __init__(self, source, *, data, requester):
super().__init__(source)
self.requester = requester

self.title = data.get('title')
self.web_url = data.get('webpage_url')
self.duration = data.get('duration')

# YTDL info dicts (data) have other useful information you might want
# https://github.com/rg3/youtube-dl/blob/master/README.md

def __getitem__(self, item: str):
"""Allows us to access attributes similar to a dict.
This is only useful when you are NOT downloading.
"""
return self.__getattribute__(item)

@classmethod
async def create_source(cls, ctx, search: str, *, loop, download=False):
loop = loop or asyncio.get_event_loop()

to_run = partial(ytdl.extract_info, url=search, download=download)
data = await loop.run_in_executor(None, to_run)

if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]

embed = discord.Embed(title="", description=f"Queued [{data['title']}]({data['webpage_url']}) [{ctx.author.mention}]", color=discord.Color.green())
await ctx.send(embed=embed)

if download:
source = ytdl.prepare_filename(data)
else:
return {'webpage_url': data['webpage_url'], 'requester': ctx.author, 'title': data['title']}

return cls(discord.FFmpegPCMAudio(source), data=data, requester=ctx.author)

@classmethod
async def regather_stream(cls, data, *, loop):
"""Used for preparing a stream, instead of downloading.
Since Youtube Streaming links expire."""
loop = loop or asyncio.get_event_loop()
requester = data['requester']

to_run = partial(ytdl.extract_info, url=data['webpage_url'], download=False)
data = await loop.run_in_executor(None, to_run)

return cls(discord.FFmpegPCMAudio(data['url']), data=data, requester=requester)


class MusicPlayer:
"""A class which is assigned to each guild using the bot for Music.
This class implements a queue and loop, which allows for different guilds to listen to different playlists
simultaneously.
When the bot disconnects from the Voice it's instance will be destroyed.
"""

__slots__ = ('bot', '_guild', '_channel', '_cog', 'queue', 'next', 'current', 'np', 'volume')

def __init__(self, ctx):
self.bot = ctx.bot
self._guild = ctx.guild
self._channel = ctx.channel
self._cog = ctx.cog

self.queue = asyncio.Queue()
self.next = asyncio.Event()

self.np = None # Now playing message
self.volume = .5
self.current = None

ctx.bot.loop.create_task(self.player_loop())

async def player_loop(self):
"""Our main player loop."""
await self.bot.wait_until_ready()

while not self.bot.is_closed():
self.next.clear()

try:
# Wait for the next song. If we timeout cancel the player and disconnect...
async with timeout(300): # 5 minutes...
source = await self.queue.get()
except asyncio.TimeoutError:
return self.destroy(self._guild)

if not isinstance(source, YTDLSource):
# Source was probably a stream (not downloaded)
# So we should regather to prevent stream expiration
try:
source = await YTDLSource.regather_stream(source, loop=self.bot.loop)
except Exception as e:
await self._channel.send(f'There was an error processing your song.\n'
f'```css\n[{e}]\n```')
continue

source.volume = self.volume
self.current = source

self._guild.voice_client.play(source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set))
embed = discord.Embed(title="Now playing", description=f"[{source.title}]({source.web_url}) [{source.requester.mention}]", color=discord.Color.green())
self.np = await self._channel.send(embed=embed)
await self.next.wait()

# Make sure the FFmpeg process is cleaned up.
source.cleanup()
self.current = None

def destroy(self, guild):
"""Disconnect and cleanup the player."""
return self.bot.loop.create_task(self._cog.cleanup(guild))


class Music(commands.Cog):
"""Music related commands."""

__slots__ = ('bot', 'players')

def __init__(self, bot):
self.bot = bot
self.players = {}

async def cleanup(self, guild):
try:
await guild.voice_client.disconnect()
except AttributeError:
pass

try:
del self.players[guild.id]
except KeyError:
pass

async def __local_check(self, ctx):
"""A local check which applies to all commands in this cog."""
if not ctx.guild:
raise commands.NoPrivateMessage
return True

async def __error(self, ctx, error):
"""A local error handler for all errors arising from commands in this cog."""
if isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.send('This command can not be used in Private Messages.')
except discord.HTTPException:
pass
elif isinstance(error, InvalidVoiceChannel):
await ctx.send('Error connecting to Voice Channel. '
'Please make sure you are in a valid channel or provide me with one')

print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)

def get_player(self, ctx):
"""Retrieve the guild player, or generate one."""
try:
player = self.players[ctx.guild.id]
except KeyError:
player = MusicPlayer(ctx)
self.players[ctx.guild.id] = player

return player

@commands.command(name='join', aliases=['connect', 'j'], description="connects to voice")
async def connect_(self, ctx, *, channel: discord.VoiceChannel=None):
"""Connect to voice.
Parameters
------------
channel: discord.VoiceChannel [Optional]
The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in
will be made.
This command also handles moving the bot to different channels.
"""
if not channel:
try:
channel = ctx.author.voice.channel
except AttributeError:
embed = discord.Embed(title="", description="No channel to join. Please call `,join` from a voice channel.", color=discord.Color.green())
await ctx.send(embed=embed)
raise InvalidVoiceChannel('No channel to join. Please either specify a valid channel or join one.')

vc = ctx.voice_client

if vc:
if vc.channel.id == channel.id:
return
try:
await vc.move_to(channel)
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Moving to channel: <{channel}> timed out.')
else:
try:
await channel.connect()
except asyncio.TimeoutError:
raise VoiceConnectionError(f'Connecting to channel: <{channel}> timed out.')
if (random.randint(0, 1) == 0):
await ctx.message.add_reaction('')
await ctx.send(f'**Joined `{channel}`**')

@commands.command(name='play', aliases=['sing','p'], description="streams music")
async def play_(self, ctx, *, search: str):
"""Request a song and add it to the queue.
This command attempts to join a valid voice channel if the bot is not already in one.
Uses YTDL to automatically search and retrieve a song.
Parameters
------------
search: str [Required]
The song to search and retrieve using YTDL. This could be a simple search, an ID or URL.
"""
await ctx.trigger_typing()

vc = ctx.voice_client

if not vc:
await ctx.invoke(self.connect_)

player = self.get_player(ctx)

# If download is False, source will be a dict which will be used later to regather the stream.
# If download is True, source will be a discord.FFmpegPCMAudio with a VolumeTransformer.
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop, download=False)

await player.queue.put(source)

@commands.command(name='pause', description="pauses music")
async def pause_(self, ctx):
"""Pause the currently playing song."""
vc = ctx.voice_client

if not vc or not vc.is_playing():
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)
elif vc.is_paused():
return

vc.pause()
await ctx.send("Paused ⏸️")

@commands.command(name='resume', description="resumes music")
async def resume_(self, ctx):
"""Resume the currently paused song."""
vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)
elif not vc.is_paused():
return

vc.resume()
await ctx.send("Resuming ⏯️")

@commands.command(name='skip', description="skips to next song in queue")
async def skip_(self, ctx):
"""Skip the song."""
vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)

if vc.is_paused():
pass
elif not vc.is_playing():
return

vc.stop()

@commands.command(name='remove', aliases=['rm', 'rem'], description="removes specified song from queue")
async def remove_(self, ctx, pos : int=None):
"""Removes specified song from queue"""

vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)

player = self.get_player(ctx)
if pos == None:
player.queue._queue.pop()
else:
try:
s = player.queue._queue[pos-1]
del player.queue._queue[pos-1]
embed = discord.Embed(title="", description=f"Removed [{s['title']}]({s['webpage_url']}) [{s['requester'].mention}]", color=discord.Color.green())
await ctx.send(embed=embed)
except:
embed = discord.Embed(title="", description=f'Could not find a track for "{pos}"', color=discord.Color.green())
await ctx.send(embed=embed)

@commands.command(name='clear', aliases=['clr', 'cl', 'cr'], description="clears entire queue")
async def clear_(self, ctx):
"""Deletes entire queue of upcoming songs."""

vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)

player = self.get_player(ctx)
player.queue._queue.clear()
await ctx.send(' **Cleared**')

@commands.command(name='queue', aliases=['q', 'playlist', 'que'], description="shows the queue")
async def queue_info(self, ctx):
"""Retrieve a basic queue of upcoming songs."""
vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)

player = self.get_player(ctx)
if player.queue.empty():
embed = discord.Embed(title="", description="queue is empty", color=discord.Color.green())
return await ctx.send(embed=embed)

seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)

# Grabs the songs in the queue...
upcoming = list(itertools.islice(player.queue._queue, 0, int(len(player.queue._queue))))
fmt = '\n'.join(f"`{(upcoming.index(_)) + 1}.` [{_['title']}]({_['webpage_url']}) | ` {duration} Requested by: {_['requester']}`\n" for _ in upcoming)
fmt = f"\n__Now Playing__:\n[{vc.source.title}]({vc.source.web_url}) | ` {duration} Requested by: {vc.source.requester}`\n\n__Up Next:__\n" + fmt + f"\n**{len(upcoming)} songs in queue**"
embed = discord.Embed(title=f'Queue for {ctx.guild.name}', description=fmt, color=discord.Color.green())
embed.set_footer(text=f"{ctx.author.display_name}", icon_url=ctx.author.avatar_url)

await ctx.send(embed=embed)

@commands.command(name='np', aliases=['song', 'current', 'currentsong', 'playing'], description="shows the current playing song")
async def now_playing_(self, ctx):
"""Display information about the currently playing song."""
vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I'm not connected to a voice channel", color=discord.Color.green())
return await ctx.send(embed=embed)

player = self.get_player(ctx)
if not player.current:
embed = discord.Embed(title="", description="I am currently not playing anything", color=discord.Color.green())
return await ctx.send(embed=embed)

seconds = vc.source.duration % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
duration = "%dh %02dm %02ds" % (hour, minutes, seconds)
else:
duration = "%02dm %02ds" % (minutes, seconds)

embed = discord.Embed(title="", description=f"[{vc.source.title}]({vc.source.web_url}) [{vc.source.requester.mention}] | `{duration}`", color=discord.Color.green())
embed.set_author(icon_url=self.bot.user.avatar_url, name=f"Now Playing quot;)
await ctx.send(embed=embed)

@commands.command(name='volume', aliases=['vol', 'v'], description="changes Kermit's volume")
async def change_volume(self, ctx, *, vol: float=None):
"""Change the player volume.
Parameters
------------
volume: float or int [Required]
The volume to set the player to in percentage. This must be between 1 and 100.
"""
vc = ctx.voice_client

if not vc or not vc.is_connected():
embed = discord.Embed(title="", description="I am not currently connected to voice", color=discord.Color.green())
return await ctx.send(embed=embed)

if not vol:
embed = discord.Embed(title="", description=f" **{(vc.source.volume)*100}%**", color=discord.Color.green())
return await ctx.send(embed=embed)

if not 0 < vol < 101:
embed = discord.Embed(title="", description="Please enter a value between 1 and 100", color=discord.Color.green())
return await ctx.send(embed=embed)

player = self.get_player(ctx)

if vc.source:


Related Topics



Leave a reply



Submit