Why is my bot.command function not working? - python

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.

Related

discord.ext.commands.errors.CommandNotFound: Command "play" is not found

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.

Getting error on discord bot discord.py for typing in role

I get this error on my bot when mentioning a role,here is the error,
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unhashable type: 'set'
my code:
import os
import discord
from discord.ext import commands
from discord import Intents
from apikeys import *
intents = Intents.all()
client = commands.Bot(intents = intents, command_prefix="-", case_insensitive=True)
#client.event
async def on_ready():
for emoji in client.emojis:
print("Name:", emoji.name + ",", "ID:", emoji.id)
print('Bot is Online {0.user}'.format(client))
print("--------------------------------------------------------------------------------------------------------------------------------------------------------")
client.remove_command('help')
emojigood = '\N{THUMBS UP SIGN}'
emojibad="\N{THUMBS DOWN SIGN}"
#client.command()
async def war(ctx):
await client.wait_until_ready()
embed = discord.Embed(title='War', description='You are starting a war, do you want to continue?', color=0x00000)
msg = await ctx.send(embed=embed)
await msg.add_reaction(emojigood)
await msg.add_reaction(emojibad)
def check(r, user):
return (r.emoji == emojigood or r.emoji == emojibad) and r.message == msg and user != client.user
r, user = await client.wait_for('reaction_add',check=check)
if r.emoji == emojigood:
embed = discord.Embed(title='War', description='Please now choose a country', color=0x00000)
await ctx.send(embed=embed)
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
msg = await client.wait_for('message', check=check)
if len(msg.role_mentions) > 0:
role = msg.role_mentions[0]
channel = client.get_channel({849549009038344262})
await channel.send(f"{role.mention} {ctx.author} has declared war on you.")
else:
await ctx.send("Invalid role mentioned")
else:
await ctx.send("Cancelled")
client.run(token)
What's meant to happen:
Me:-war
Bot:Are you sure
Me:reacts
Bot:Type in role
Me:(role name)
Bot:....
{849549009038344262}
is a set literal for a set containing a number. discord.py is using hashing under the hood to look up channels, which is failing because it is not possible to hash sets. You should be passing a regular int instead of a set:
channel = client.get_channel(849549009038344262)

getting error code message is not defined

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')

Command Without Prefix Discord.py Rewrite

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 )

Why is the on message event working for a few minutes then it stops working?

okay I know for the past few days this is all I have been posting about but I am curious on why my on_message command works for a few times then it stops all of a sudden here I will show you my code:
import discord
from discord.ext import commands
from discord.utils import get
client = discord.Client()
client = commands.Bot(command_prefix=None)
#client.event
async def on_ready():
print("ready!")
#client.event
async def on_message(message):
if message.content.startswith('<:SF1:763564017456644116> sign'):
role = get(message.guild.roles, name='San Francisco 49ers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:SF1:763564017456644116>')
#client.event
async def on_message(message):
if message.content.startswith('<:ATL1:763564014344208414> sign'):
role = get(message.guild.roles, name='Atlanta Falcons')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:ATL1:763564014344208414>')
#client.event
async def on_message(message):
if message.content.startswith('<:CAR1:763564014478819378> sign'):
role = get(message.guild.roles, name='Carolina Panthers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:CAR1:763564014478819378>')
#client.event
async def on_message(message):
if message.content.startswith('<:DAL1:763564014843592714> sign'):
role = get(message.guild.roles, name='Dallas Cowboys')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DAL1:763564014843592714>')
#client.event
async def on_message(message):
if message.content.startswith('<:DET1:763564015057764362> sign'):
role = get(message.guild.roles, name='Detroit Lions')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DET1:763564015057764362>')
client.run('TOKEN')
so this is what is happening in picture form:
here is the first time I tested:
and the second time I test it:
can someone please help explain to me what I am doing incorrectly so I can fix it?
You can just put them all in 1 on_message instead of separating them like that.
#client.event
async def on_message(message):
if message.content.startswith('<:SF1:763564017456644116> sign'):
role = get(message.guild.roles, name='San Francisco 49ers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:SF1:763564017456644116>')
if message.content.startswith('<:ATL1:763564014344208414> sign'):
role = get(message.guild.roles, name='Atlanta Falcons')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:ATL1:763564014344208414>')
if message.content.startswith('<:CAR1:763564014478819378> sign'):
role = get(message.guild.roles, name='Carolina Panthers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:CAR1:763564014478819378>')
if message.content.startswith('<:DAL1:763564014843592714> sign'):
role = get(message.guild.roles, name='Dallas Cowboys')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DAL1:763564014843592714>')
if message.content.startswith('<:DET1:763564015057764362> sign'):
role = get(message.guild.roles, name='Detroit Lions')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DET1:763564015057764362>')
you could also put the await client.process_commands(message) at the end of each event
Docs: process_commands

Categories

Resources