I am trying to create a channel overwrite for my bot so it can send the message in the channel that the channel is locked for the #everyone role
#commands.command()
#has_permissions(manage_channels=True)
async def lock(self, ctx):
member = discord.Member.id(712885407993561169)
await ctx.channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ctx.channel.set_permissions(member, send_messages=True, read_messages=True)
await ctx.send(':greentick: Locked down ' + ctx.channel.name)
You can try:
#commands.command()
#commands.has_permissions(manage_channels=True)
async def lock(self, ctx: commands.Context):
overwrites = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrites.read_messages, overwrites.send_messages = False, False
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrites)
overwrites = ctx.channel.overwrites_for(ctx.me)
overwrites.send_messages, overwrites.read_messages = True, True
await ctx.channel.set_permissions(ctx.me, overwrite=overwrites)
Related
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ? Also seems like i need to post more details, don't pay attention to this : Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
I am having troubles gettimg my commands to work, it keeps telling me that they do not exist when they clearly do. I've been stumped on this for hours and can't figure out why its not working. I've tried doing commands.command() instead of #commands.command(), but no luck, i tried explicitly defining the name of the command #commands.command(name="play") but still no luck
import youtube_dl
import pafy
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.event
async def on_ready():
print(f"{bot.user.name} is ready.")
bot.run("....")
class Player(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.bot.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format" : "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0: return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel, please connect to the channel you want the bot to join.")
if ctx.voice_client is not None:
await ctx.voice_client.disconnect()
await ctx.author.voice.channel.connect()
#commands.command()
async def leave(self, ctx):
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
await ctx.send("I am not connected to a voice channel.")
#commands.command(name="play")
async def play(self, ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
# handle song where song isn't url
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for song, this may take a few seconds.")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I could not find the given song, try using my search command.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"I am currently playing a song, this song has been added to the queue at position: {queue_len+1}.")
else:
return await ctx.send("Sorry, I can only queue up to 10 songs, please wait for the current song to finish.")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
async def search(self, ctx, *, song=None):
if song is None: return await ctx.send("You forgot to include a song to search for.")
await ctx.send("Searching for song, this may take a few seconds.")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="*You can use these URL's to play an exact song if the one you want isn't the first result.*\n", colour=discord.Colour.red())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
async def queue(self, ctx): # display the current guilds queue
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("There are currently no songs in the queue.")
embed = discord.Embed(title="Song Queue", description="", colour=discord.Colour.dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
embed.set_footer(text="Thanks for using me!")
await ctx.send(embed=embed)
#commands.command()
async def skip(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not playing any song.")
if ctx.author.voice is None:
return await ctx.send("You are not connected to any voice channel.")
if ctx.author.voice.channel.id != ctx.voice_client.channel.id:
return await ctx.send("I am not currently playing any songs for you.")
poll = discord.Embed(title=f"Vote to Skip Song by - {ctx.author.name}#{ctx.author.discriminator}", description="**80% of the voice channel must vote to skip for it to pass.**", colour=discord.Colour.blue())
poll.add_field(name="Skip", value=":white_check_mark:")
poll.add_field(name="Stay", value=":no_entry_sign:")
poll.set_footer(text="Voting ends in 15 seconds.")
poll_msg = await ctx.send(embed=poll) # only returns temporary message, we need to get the cached message to get the reactions
poll_id = poll_msg.id
await poll_msg.add_reaction(u"\u2705") # yes
await poll_msg.add_reaction(u"\U0001F6AB") # no
await asyncio.sleep(15) # 15 seconds to vote
poll_msg = await ctx.channel.fetch_message(poll_id)
votes = {u"\u2705": 0, u"\U0001F6AB": 0}
reacted = []
for reaction in poll_msg.reactions:
if reaction.emoji in [u"\u2705", u"\U0001F6AB"]:
async for user in reaction.users():
if user.voice.channel.id == ctx.voice_client.channel.id and user.id not in reacted and not user.bot:
votes[reaction.emoji] += 1
reacted.append(user.id)
skip = False
if votes[u"\u2705"] > 0:
if votes[u"\U0001F6AB"] == 0 or votes[u"\u2705"] / (votes[u"\u2705"] + votes[u"\U0001F6AB"]) > 0.79: # 80% or higher
skip = True
embed = discord.Embed(title="Skip Successful", description="***Voting to skip the current song was succesful, skipping now.***", colour=discord.Colour.green())
if not skip:
embed = discord.Embed(title="Skip Failed", description="*Voting to skip the current song has failed.*\n\n**Voting failed, the vote requires at least 80% of the members to skip.**", colour=discord.Colour.red())
embed.set_footer(text="Voting has ended.")
await poll_msg.clear_reactions()
await poll_msg.edit(embed=embed)
if skip:
ctx.voice_client.stop()
#commands.command()
async def pause(self, ctx):
if ctx.voice_client.is_paused():
return await ctx.send("I am already paused.")
ctx.voice_client.pause()
await ctx.send("The current song has been paused.")
#commands.command()
async def resume(self, ctx):
if ctx.voice_client is None:
return await ctx.send("I am not connected to a voice channel.")
if not ctx.voice_client.is_paused():
return await ctx.send("I am already playing a song.")
ctx.voice_client.resume()
await ctx.send("The current song has been resumed.")
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
You can try replacing :
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.loop.create_task(setup())
With just :
bot.add_cog(Player(bot))
Moreover, put you run statement after all setup operations, so you have :
# Cog declaration
bot.add_cog(Player(bot))
bot.run('....')
run() should be executed as last function because it starts bot and it runs until you stop bot.
And all code which you have after run() is executed after you stop bot.
bot.loop.create_task(setup())
bot.run(TOKEN)
#commands.command()
Write this down where you wrote it down.
#bot.command()
Because:
bot = commands.Bot(command_prefix="!", intents=intents)
Since you have assigned a "bot" variable here, the name of the variable is added first, and then the "command" is added.
I made a lock command but when fl.lock #general test is used in #general channel it isn't locking the general channel but when fl.lock #general test is used in #staff-chat channel it is locking the #general channel
So my bot isn't locking a channel when that channel is mentioned in the lock commmand and it is used in the same channel
The code
#commands.command(case_insensitive = True)
#commands.has_any_role(885434191783788564, 856071314740740096, 856061783722426378, 856465667296985108)
async def lock(self, ctx, channel: discord.TextChannel, *, reason=None):
channel = channel or ctx.channel
overwrite = channel.overwrites_for(ctx.guild.default_role)
if overwrite.send_messages == True:
overwrite.send_messages = False
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
em_reason = discord.Embed(title="**Channel locked**", description=f":lock: {reason}",color=discord.Color.red())
embed = discord.Embed(description = f"<a:fl_check:874522235879186483> Locked channel <#{channel.id}>",color=discord.Color.green())
await ctx.send(embed=em_reason)
await ctx.send(embed=embed)
elif overwrite.send_messages == False:
em = discord.Embed(description="<a:fl_no:874522273984442420> That channel is already locked.", color=discord.Color.red())
await ctx.send(embed=em)```
I think channel = channel or ctx.channel is the issue here.
You should check directly if the channel argument is None and than use the ctx.channel.
#commands.command(case_insensitive = True)
#commands.has_any_role(885434191783788564, 856071314740740096, 856061783722426378, 856465667296985108)
async def lock(self, ctx, channel: discord.TextChannel=None, *, reason=None):
if channel is None:
channel = ctx.channel
overwrite = channel.overwrites_for(ctx.guild.default_role)
if overwrite.send_messages == True:
overwrite.send_messages = False
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
em_reason = discord.Embed(title="**Channel locked**", description=f":lock: {reason}",color=discord.Color.red())
embed = discord.Embed(description = f"<a:fl_check:874522235879186483> Locked channel <#{channel.id}>",color=discord.Color.green())
await ctx.send(embed=em_reason)
await ctx.send(embed=embed)
elif overwrite.send_messages == False:
em = discord.Embed(description="<a:fl_no:874522273984442420> That channel is already locked.", color=discord.Color.red())
await ctx.send(embed=em)
Iv been working on this bot which when you type "/court #user time" it will give them the role jail
and after the given amount of time it will remove it but when i run it it doesn't work and it says:
"discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined"
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#bot.event
async def on_ready():
print('Logged on as', bot.user)
channel = bot.get_channel(717005397655027805)
#await channel.send("I am now online")
activity = discord.Game(name="eb!help", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned, time):
messageContent = message.content
if len(messageContent) > 0:
if re.search("^send.*court$", messageContent):
user_id = message.mentions[0].id
user = message.mentions[0]
await message.channel.send(
f"sending <#{user_id}> to court!"
)
role = discord.utils.get(message.guild.roles, name="Jail")
await user.add_roles(role)
sleep(time)
await bot.remove_roles(user, role)
bot.run('TOKEN_GOES_HERE')
The error message is pretty clear,
messageContent = message.content.
message isn't defined in the scope here.
We can get the message with ctx.message
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned, time):
message = ctx.message
messageContent = message.content
Doing this will work fine, but you're entirely misusing ext.commands here.
You could do
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned: discord.Member, time: int):
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
time.sleep is blocking and bot doesn't have the attribute remove_roles, please refer to the docs for information.
#ceres here's the court command code:
bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned: discord.Member, time: int):
print("test")
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
You can get message's content by typing ctx.message.content but you don't need it. If you describe the parameter as discord.Member, it will return a member object if it founds else bot will raise commands.BadArgument. Also you should use asyncio.sleep for async sleep. This will not block your bot's other commands.
import asyncio
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user: discord.Member, time: int):
role = discord.utils.get(message.guild.roles, name="Jail")
if role is not None:
await ctx.send(
f"sending {user.mention} to court!"
)
await user.add_roles(role)
await asyncio.sleep(time)
await user.remove_roles(role)
else:
await ctx.send("Role `Jail` is not exist.")
bot.run('TOKEN')
How to use any certain commands without prefix in discord.py rewrite?
for example, i don't want to use the prefix in this command, what to do?
#bot.command(aliases=['2344',
'4324',
'3673',
'1325'])
async def _codes(ctx, amount=2):
user = ctx.message.author
role = discord.utils.get(ctx.guild.roles, name='testrole')
await user.add_roles(role)
embed = discord.Embed(title='Verification Successful',
colour= discord.Colour.green())
embed.set_thumbnail(url='https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/White_check_mark_in_dark_green_rounded_square.svg/600px-White_check_mark_in_dark_green_rounded_square.svg.png')
await ctx.send(embed=embed, delete_after=1 )
await ctx.channel.purge(limit=amount)```
Do this:
list = {'2344','4324','3673','1325'}
#bot.event
async def on_message(message):
if message.content in list:
user = message.author
role = discord.utils.get(ctx.guild.roles, name='testrole')
await user.add_roles(role)
embed = discord.Embed(title='Verification Successful', colour = discord.Colour.green())
embed.set_thumbnail(url='https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/White_check_mark_in_dark_green_rounded_square.svg/600px-White_check_mark_in_dark_green_rounded_square.svg.png')
await message.channel.send(embed=embed)
await message.channel.purge(limit=2)
#client.event
async def on_message(message):
message.content = message.content.lower()
if message.content.startwith("command_name"):
user = message.message.author
role = discord.utils.get(message.guild.roles, name='testrole')
await user.add_roles(role)
embed = discord.Embed(title='Verification Successful',
colour= discord.Colour.green())
await ctx.send(embed=embed, delete_after=1 )