Why won't Discord bot recognize commands? - python

I'm making a bot for a pokemon server, and I'm trying to make a command that will give the 'Gym Leader' role to another user. I try using the command, and using the test command, but there is no response in the server nor the shell.
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
from discord.utils import get
bot = commands.Bot(command_prefix='b!', case_insensitive=True)
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
#client.event #works
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
channel = client.get_channel(697500755766018098)
#client.event #works
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(
f'Hi {member.name}, welcome to Pokémon Beast Ball!\n\nThis server utilizes Pokecord and Mewbot.\n\nSay \'pkhelp\' in the server to learn about Pokecord commands.\nSay \';help\' in the server to learn about Mewbot commands.'
)
#bot.command() #doesn't work
async def test(ctx):
print("test recieved")
await ctx.send(ctx)
#bot.command(pass_context=True) #this is the command that really needs help
async def newleader(ctx: discord.User=None):
print("command recieved")
if not user:
await ctx.send("Invalid")
print("1")
else:
role = discord.utils.get(ctx.guild.roles, name="Gym Leader")
role2 = discord.utils.get(ctx.guild.roles, name="Purple UniTurtle Man")
if role in ctx.author.roles or role2 in ctx.author.roles:
print("2")
await ctx.send(f'A new Gym Leader has been appointed')
await user.add_roles(role)
await bot.remove_roles(ctx.author, role)
else:
print("3")
await ctx.send("You do not have permission to use this command")
client.run(TOKEN)

You are mixing bot and client and your client = discord.Client() is stepping on your bot = commands.Bot(...) statement. Since you want to do commands and events you only use the commands.Bot(...) statement.
Remove the client = discord.Client() statement and change your #client.event decorators to #bot.event.
Also if you want to reference the command context in your test command update it with the ctx parameter async def test(ctx):.
That will get you started using your commands and entering b1test will now work.
Please note that the case_insensitive=True on the commands declaration refers to the command name and not the prefix.

Did you check :
bot connection → make a "on_connect" event (not exactly the same as "on_ready") to see if your bot successfully connect to your server (before receiving data from discord). If not, try to add your bot again to your server and check if all tokens are goods.
bot permissions (if your bot have the right to write in channel, read messages from channels, manage roles) → if your bot cannot read messages, he can't read commands !
role priority (you can't manage roles highers thant yours) → go to "server settings" > "roles" > put your bot role above the 'Gym Leader' role (or at the top of the list if you don't care).

The problem isn't actually what the selected answer suggests. There is probably no reason to use both commands.Bot and discord.Client but using both won't lead to that issue.
The issue is because you are only running the client, not the bot. You need to also run the bot instance if you want it to function.
If you are not trying to do something specific, then just using either bot or client will suffice anyway, so that part of the selected answer was helpful in avoiding the issue at least.

Related

How can I get a discord bot to send a message if a command is said?

I'm making a discord bot using Python but none of the commands that should be running are running. I've traced it down to the if command below:
if message.content.startswith("$hello"): # <<<<<< This command is causing issues!
print("Command detected: $hello")
await message.channel.send('Hello there! I am a bot. Thats it.')
$hello is supposed to say in the chat "Hello there! I am a bot. Thats it."
However, the if command doesnt work, and even if $hello is said, it doesn't run what it is supposed to.
Here is the entire code itself:
import discord
import os
client = discord.Client(intents=discord.Intents(messages=True))
#client.event
async def on_ready():
print('Logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
print("Message detected.")
if message.author == client.user:
print("Returning...")
return
print("User message confirmed to not be a bot.")
if message.content.startswith("$hello"): #<<< This is causing issues!
print("Command detected: $hello")
await message.channel.send('Hello there! I am a bot. Thats it.')
# imagine there is a run command here, with the token
# im not putting it here since its a security risk
# the run bot command works
I've tried using different types of commands, like startswith and == contains but it doesn't print the hello message. Anyone got any idea how to get it working?
Intents.messages is not the same as Intents.message_content!
messages:
Whether guild and direct message related events are enabled.
This is a shortcut to set or get both guild_messages and dm_messages.
message_content:
Whether message content, attachments, embeds and components will be available in messages
You're missing message_content.
import discord
import os
#make sure to set up your command syntax and set your intents so the bot can read messages
client= commands.Bot(command_prefix='$', intents=discord.Intents.default())
client.remove_command("help")
#don't use on_message for commands, it's gonna cause problems.
#instead, use the command funtion here
#client.command()
async def command(ctx):
ctx.channel.send("command is working!")
client.run("token")
``` that should work

discord.py not responding to any commands

I followed a tutorial to make add a basic music function to a discord bot, but it doesnt respond to any commands. I get the "henlo frens i is alieving" message as to indicate that the bot is ready, and there are no errors showing up. But then when i try to use the ping command i get no response, and nothing shows up in the terminal unlike the other bots i've written.
from plznodie import plznodie
from discord.ext import commands
import music
import time
#vars
cogs=[music]
intents = discord.Intents()
intents.all()
client = commands.Bot(command_prefix = "!" , intents=intents)
intents.members = True
activvv = discord.Game("you guys complain")
#config
for i in range(len(cogs)):
cogs[i].setup(client)
#client.event
async def on_ready ():
await client.change_presence(status = discord.Status.online, activity = activvv)
print("Henlo frens i is alieving")
#client.command()
async def ping(ctx):
before = time.monotonic()
message = await ctx.send("Pong!")
ping = (time.monotonic() - before) * 1000
await message.edit(content=f"Pong! `{int(ping)}ms`")
client.run("TOKEN")```
Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
Instead set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
As noted in the docs, on_ready is also triggered multiple times, not just once.
I can further confirm this because running your code snippet (without on_ready defined) on my machine actually worked :
to process commands you need to add on_message function
#client.event
async def on_message(msg):
await client.process_commands(msg)

How can I make my Discord Bot delete all messages in a channel?

I am trying to make my bot delete all messages at once when a user asks the bot to do so, but my code isn't working.
import os
import discord
client = discord.Client()
client = commands.Bot(command_prefix='+')
#client.command(name='effacer')
async def purge(ctx):
async for msg in client.logs_from(ctx.message.channel):
await client.delete_messages(msg)
await ctx.send("Who am I? What is this place? And where the hell did the messages go?")
client.run(TOKEN)
How can I fix my code so that my bot can delete all messages? I believe my biggest problem is await client.delete_messages(msg), since Python continuously says that the client has no attribute to delete_messages.
By deleting every message would rate limit the bot, creating performance issues which would also slow down the bot. Instead it would be more efficient if the bot just deleted the channel and made a clone of it in the exact same place.
Here's the purge included in your command
#client.command(name='effacer')
async def purge(ctx):
await ctx.channel.delete()
new_channel = await ctx.channel.clone(reason="Channel was purged")
await new_channel.edit(position=ctx.channel.position)
await new_channel.send("Channel was purged")
So the way you would do that is with purge, not delete messages. This will delete all the messages in the channel AND keep the channel id the same, meaning you'll only need the manage_messages permission to run this command. The way it works is it counts all the messages in the channel and then purges that number of messages
import os
import discord
client = discord.Client()
client = commands.Bot(command_prefix='+')
#client.command(name='effacer')
async def purge(ctx):
limit = 0
async for msg in ctx.channel.history(limit=None):
limit += 1
await ctx.channel.purge(limit=limit)
client.run(TOKEN)

Discord bot to mute the voice of people Using Voice Chat with the help of Python

I am trying to make a Discord bot that mutes the voice of the participant using voice chat.
For this, I am using Python.
This is my code, but it is not working as expected.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=" !")
#client.event
async def on_ready():
print('BOT ACTIVATED')
#client.command()
async def mute(ctx):
voice_client = ctx.guild.voice_client
if not voice_client:
return
channel = voice_client.channel
await voice_client.voice_state(ctx.guild.id, channel.id, self_mute=True)
client.run(My Token)
The idea I have is:
Command I will enter: !muteall \
And the bot will mute all the participants in the voice chat
Command I will enter: !unmuteall \
And the bot will unmute all the participants in the voice chat.
Before we get to the crux of the question, a short word on your prefix:
Your command prefix is ! with a space beforehand. I do not know if this was intentional or not, but if it was, in my testing I found using this to be impossible. Discord strips beginning whitespace so all my messages !test come out as !test.
After fixing this, attempting to use the !mute command produces an error:
'VoiceClient' object has no attribute 'voice_state'
Indeed, I have been unable to find anything like this in the docs. It took me a lot of searching, but I may have found what you wanted.
client = commands.Bot(command_prefix="!")
#client.command()
async def mute(ctx):
voice_client = ctx.guild.voice_client #get bot's current voice connection in this guild
if not voice_client: #if no connection...
return #probably should add some kind of message for the users to know why nothing is happening here, like ctx.send("I'm not in any voice channel...")
channel = voice_client.channel #get the voice channel of the voice connection
people = channel.members #get the members in the channel
for person in people: #loop over those members
if person == client.user: #if the person being checked is the bot...
continue #skip this iteration, to avoid muting the bot
await person.edit(mute=True, reason="{} told me to mute everyone in this channel".format(ctx.author))
#edit the person to be muted, with a reason that shows in the audit log who invoked this command. Line is awaited because it involves sending commands ("mute this user") to the server then waiting for a response.
Your bot will need permissions to mute users.

Discord Python Bot: How to move specific users mentioned by the author of the message

I am looking for a way to allow a user to move him or her self and another user to a different voice channel. I already got the command to work for the author of the message, but I am having trouble finding out a way to move another user in the same message. The idea is that the user would be able to type "n!negotiate [Other User]" and it would move the author and the other user to the Negotiation channel.
I would love some help with how I might be able to do this. The code is provided below excluding the tokens and ids.
Code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client() #Initialise Client
client = commands.Bot(command_prefix = "n!") #Initialise client bot and prefix
#client.event
async def on_ready():
print("Logged in as:")
print(client.user.name)
print("ID:")
print(client.user.id)
print("Ready to use!")
#client.event
async def on_message(check): #Bot verification command.
if check.author == client.user:
return
elif check.content.startswith("n!check"):
await client.send_message(check.channel, "Nations Bot is online and well!")
async def on_message(negotiation): #Negotiate command. Allows users to move themselves and other users to the Negotiation voice channel.
if negotiation.author == client.user:
return
elif negotiation.content.startswith("n!negotiate"):
author = negotiation.author
voice_channel = client.get_channel('CHANNELID')
await client.move_member(author, voice_channel)
client.run("TOKEN")
You should use discord.ext.commands. You're importing it, but not actually using any of the features.
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix = "n!") #Initialize bot with prefix
#bot.command(pass_context=True)
async def check(ctx):
await bot.say("Nations Bot is online and well!")
#bot.command(pass_context=True)
async def negotiate(ctx, member: discord.Member):
voice_channel = bot.get_channel('channel_id')
author = ctx.message.author
await bot.move_member(author, voice_channel)
await bot.move_member(member, voice_channel)
bot.run('TOKEN')
Here we use a converter to accept a Member as input. Then we resolve the author of the message from the invocation context and move both Members to the voice channel.

Categories

Resources