I have a command which allows people to react to a message to enter into a "battle". Then with another command, 2 people are chosen. This is my code:
#client.command(aliases=['start', 'g'])
async def startbattle(ctx):
msg = await ctx.send("React to enter battle")
await msg.add_reaction("π")
await asyncio.sleep(10000000000000000)
message = await ctx.fetch_message(msg.id)
for reaction in message.reactions:
if str(reaction.emoji) == "π":
users = await reaction.users().flatten()
if len(users) == 1:
return await msg.edit(embed=discord.Embed(title="Nobody has won the giveaway."))
try:
user1 = random.choice(users)
user2 = random.choice(users)
except ValueError:
return await ctx.send("not enough participants")
await ctx.send(f'Battle will be against {user1} and {user2}')
#client.command()
async def pick(ctx):
async for message in ctx.channel.history(limit=100, oldest_first=False):
if message.author.id == client.user.id and message.embeds:
reroll = await ctx.fetch_message(message.id)
users = await reroll.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner1 = random.choice(users)
winner2 = random.choice(users)
await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
break
else:
await ctx.send("No giveaways going on in this channel.")
This is the error which I get while using the "pick" command,
users = await reroll.reactions[0].users().flatten()
IndexError: list index out of range
the error is in the for loop as it gets the msg and the msg doesnt have any reaction so it there is no list so list is out of range to fix this u have to add try and except there so it skips the msg with no reactions.
code :
#client.command()
async def pick(ctx):
async for message in ctx.channel.history(limit=100, oldest_first=False):
if message.author.id == client.user.id and message.embeds:
reroll = await ctx.fetch_message(message.id)
try:
users = await reroll.reactions[0].users().flatten()
except:
break
users.pop(users.index(client.user))
winner1 = random.choice(users)
winner2 = random.choice(users)
await ctx.send(f"The battle will be against {winner1.mention} and {winner2.mention}")
return # <--- was the break
else:
await ctx.send("No giveaways going on in this channel.")
and a suggestion dont add break in the if statement as it will continuously check for msg if already it got one
list(song_queue) = []
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}
def search(arg):
try: requests.get("".join(arg))
except: arg = " ".join(arg)
else: arg = "".join(arg)
with youtube_dl.YoutubeDL(YDL_OPTIONS ) as ydl:
info = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]
return {'source': info['formats'][0]['url'], 'title': info['title']}
def play_next(ctx):
voice = get(client.voice_clients, guild=ctx.guild)
if len(song_queue) > 1:
del song_queue[0]
voice.play(discord.FFmpegPCMAudio(song_queue[0][source], **FFMPEG_OPTIONS), after=lambda e: play_next(ctx))
voice.is_playing()
#client.command()
async def play(ctx, *arg):
channel = ctx.message.author.voice.channel
if channel:
voice = get(client.voice_clients, guild=ctx.guild)
song = search(arg)
song_queue.append(song)
if voice and voice.is_connected():
await voice.move_to(channel)
else:
voice = await channel.connect()
if not voice.is_playing():
voice.play(discord.FFmpegPCMAudio(song[0]['source'], **FFMPEG_OPTIONS), after=lambda e: play_next(ctx))
voice.is_playing()
else:
await ctx.send("Added to queue")
else:
await ctx.send("You're not connected to any channel!")
this code doesn't play the music and the song queue and idk how to fix it to help me please
I need it so that it can play music and preferably not have the queue ANd i need it so that it can
I have code for my music bot that will play the video using the title of the song. It also has a working queue feature. Try copy-pasting this code into your cog, and it should work for you without any issues.
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='leave', aliases=["stop", "dc", "disconnect", "bye"], description="stops music and disconnects from voice")
async def leave_(self, ctx):
"""Stop the currently playing song and destroy the player.
!Warning!
This will destroy the player assigned to your guild, also deleting any queued songs and settings.
"""
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 (random.randint(0, 1) == 0):
await ctx.message.add_reaction('π')
await ctx.send('**Successfully disconnected**')
await self.cleanup(ctx.guild)
def setup(bot):
bot.add_cog(Music(bot))
So far what I've got is this:
#Bot.command()
async def unpin(ctx, amount = None):
await ctx.message.delete()
channel = str(ctx.channel)
x = 0
amount = int(amount)
if amount == 0:
await ctx.send("How many messages do you want to unpin, max is 50.")
else:
pins = await channel.pins()
for message in pins:
await message.unpin()
x+=1
x1 = str(x)
await ctx.send(f"Unpinned {x} messages from #{channel}")
My problem is at pins = await channel.pins() - I don't know how to access the pinned messages in the channel. If someone could help that would be greatly appreciated.
The problem is this line:
channel = str(ctx.channel)
This line returns the string value of the channel object.
You use it in the following code:
pins = await channel.pins() # i.e. get string.pins()
Because strings dont have the pins() function. It throws an error, or wont function correctly.
In order to fix this you should assign the ctx.channel object to the channel variable. This way we dont convert it to a string by using str().
Now we have a channel object, we can correctly use the pins() function with, and do what you wanted it to do.
#Bot.command()
async def unpin(ctx, amount = None):
await ctx.message.delete()
channel = ctx.channel
x = 0
amount = int(amount)
if amount == 0:
await ctx.send("How many messages do you want to unpin, max is 50.")
else:
pins = await channel.pins()
for message in pins:
await message.unpin()
x+=1
x1 = str(x)
await ctx.send(f"Unpinned {x} messages from #{channel}")
You returned the ctx.channel in to a string. That's why you can't access the pins. If you change the line channel = str(ctx.channel) to channel = ctx.channel, your problem will be solved.
And also, you should change the parameter amount=None as amount=0.
Kind of new to Discordpy moderation commands and would like to know why this code doesn't work,
as I get no errors while trying to run it. it's supposed to temp mute a user for a specific amount of time depending on the unit and if no muted role was created it, creates one.
#commands.command()
async def mute(self , ctx, user : discord.Member, duration = 0,*, unit = None):
guild = ctx.guild
for role in guild.roles:
if role.name =="Muted":
await member.add_roles(role)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
return
overwrite = discord.PermissionsOverwrite(send_messages=False)
newRole = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(newRole,overwrite=overwrite)
await member.add_roles(newRole)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
```
All the code after your return statement is useless, as it will never be executed. Maybe you indented that part too far.
Make a list of the role names and check it through that instead of having a big loop
rolenames = {role.name: role for role in guild.roles}
if 'Muted' not in rolenames.keys():
# Make the new role
role = new_role_you_created
else:
role = rolenames['Muted']
# Add the role to the user
await member.add_roles(role)
All the code written after a return statement will NEVER be executed, so the last part of your code is unreachable.
You can use discord.utils.get to get a role based on the name, insted of looping over every role in the guild.
Then, if there isn't any role under that name, you create a new one (I'm guessing that's the behaviour you're looking for)
#commands.command()
async def mute(self , ctx, member : discord.Member, duration: int = 0, unit: str = None):
guild = ctx.guild
role = discord.utils.get(guild.roles, name="Muted")
if role is None:
overwrite = discord.PermissionsOverwrite(send_messages=False)
role = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(role, overwrite=overwrite)
await member.add_roles(role)
await ctx.send(f"{member.mention} Has been muted by {ctx.author.mention} for {duration}{unit} ")
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await member.remove_roles(role)
await ctx.send(f":white_check_mark: {member} was unmuted")
You should consider checking if the unit is valid before executing the command, because wait will not be defined if unit is not s or m, causing the command to raise an error, and the user will be muted forever.
Also, using asyncio.sleep in a tempmute command is not recommended. If the bot crashes or is turns off, the user will never be unmuted. Instead, store the tempmutes in a database and check them every X time.
As the others already stated, the code after the return statement won't be executed. So basically the whole command ends if there is a role called "Muted". Also you seem to create a new role called "Muted" if there is a role called Muted in which you disable sending messages. Also I am not sure, if you can't just set the global role permissions to send_messages=True
Do you maybe mean something like this?
#commands.command()
async def mute(self , ctx, user : discord.Member, duration = 0,*, unit = None):
guild = ctx.guild
muted_role = None
for role in guild.roles:
if role.name =="Muted":
muted_role = role
if muted_role == None:
overwrite = discord.PermissionsOverwrite(send_messages=False)
muted_role = await guild.create_role(name="Muted")
for channel in guild.text_channels:
await channel.set_permissions(muted_role,overwrite=overwrite)
await member.add_roles(muted_role)
await ctx.send("{} Has been muted by {} for {duration}{unit} " .format(member.mention,ctx.author.mention))
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(roleobject)
await ctx.send(f":white_check_mark: {user} was unmuted")
I hope I could help!