Why can't I use command prefixes? - python

Every I try to use the commands.Bot(command_prefix=''), the program reads it as an error. For example, with the code below, it comes out with
Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "-ping" is not
found Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not
found
and is repeated a few times before what i wanted the bot to say (Pong!), is sent 2 or more times in the server...
\I think it might be looping? I'm not sure, but I got it to work once, but the longer I waited, every time used the command it sent more responses? -it sent 16 'Pong's last time I tried... Is there anything I can do about this?\
How can i fix this?
from discord.ext import commands
client = commands.Bot(command_prefix='-')
#client.event
async def on_ready():
print("Bot is ready for use...")
#client.command()
async def ping(ctx):
await ctx.send('Pong')
client.run('TOKEN')

The problem doesn't come from you prefix, you just forgot parentheses after your client.command decorator:
from discord.ext import commands
client = commands.Bot(command_prefix='-')
#client.event
async def on_ready():
print("Bot is ready for use...")
#client.command()
async def ping(ctx):
await ctx.send('Pong')
client.run('TOKEN')
The client.event decorator doesn't have any arguments so you don't need parentheses but client.command() can have arguments like name=, brief=, description=, aliases, ... so you need parentheses. ^^

Related

discord.ext.commands.bot Ignoring exception in command None discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

so i was trying to create my first discord bot, with no experience in Python whatsoever just to learn stuff by doing so and stumbled on an Error (Title) which was answered quiet a lot, but didn't really help me.
Im just gonna share my code:
import discord
from discord.ext import commands
import random
client = commands.Bot(command_prefix="=", intents=discord.Intents.all())
#client.event
async def on_ready():
print("Bot is connected to Discord")
#commands.command()
async def ping(ctx):
await ctx.send("pong")
client.add_command(ping)
#client.command()
async def magic8ball(ctx, *, question):
with open("Discordbot_rank\magicball.txt", "r") as f:
random_responses = f.readlines()
response = random.choice(random_responses)
await ctx.send(response)
client.add_command(magic8ball)
client.run(Token)
I tried to run this multiple times, first without the client.add_command line, but both methods for registering a command didn't work for me. I also turned all options for privileged gateway intents in the discord developer portal on. What am i doing wrong?
Because you have an incorrect decorator for your command ping. It should be #client.command() in your case.
Also, in most of the cases, you don't need to call client.add_command(...) since you use the command() decorator shortcut already.
Only when you have cogs, you will use #commands.command() decorator. Otherwise, all commands in your main py file should have decorator #client.command() in your case.
A little bit of suggestion, since you already uses commands.Bot, you could rename your client variable to bot since it is a little bit ambiguous.
You have to use Slash commands cause user commands are no longer available
Example code using Pycord library
import discord
bot = discord.Bot()
#bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")
bot.run("token")

Bot stopped working even though code is fine

This is my first time coding a discord bot and I have been following tutorials mainly but I wanted to make a unique game so I tried to make it myself. But after messing around with it for a while I realized that the only part of my code that works is the mcguccy is an idiot part none of the client. Command parts work.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.command()
async def ping1(ctx):
await ctx.send("pong!")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("cranking 90s on shitters"))
print("bot is ready!")
#client.event
async def on_member_join(member):
print(f'{member} has joined :weary:.')
#client.event
async def on_member_remove(member):
print(f'{member} has left :weary:')
#client.command()
async def helb(ctx):
await ctx.send('#everyone look at this idiot')
#client.command()
async def ping(ctx):
await ctx.send(f'here you go: {round(client.latency * 1000)}ms')
#client.command()
async def commands(ctx):
await ctx.send('1. helb it will help you. 2. ping it will tell you the bots ping. ')
#client.command()
async def overlord(ctx):
await ctx.send("muah hah hah YOUR SERVER IS MINE")
keywords = ["mcguccy is an idiot", "kick mcguccy", "i want to nuke the server"]
#client.event
async def on_message(message):
for i in range(len(keywords)):
if keywords[i] in message.content:
for j in range(20):
await message.channel.send(f"#everyone someone has spammed :weary:")
There are a few things to look at here:
Your client variable is a Bot type, not a Client type.
client = commands.Bot(command_prefix='!')
This means you need to use #bot decorators instead of #client decorators:
#client.command()
async def helb(ctx):
...
# Becomes
#bot.command()
async def helb(ctx):
...
The .run() method is never called.
Because of this, the bot's event loop doesn't start. You need to initialize the Client event loop so the bot can listen for commands to pass:
if __name__=='__main__':
client.run(TOKEN)
That code needs to be the very last statement run in the file, as it's blocking.
The .run() command requires an API token.
You can acquire said token by creating a bot account if you don't have one already. If you do have one, you'll need to pass it as the first paramater to the .run() method.

!help [command_name] discord.py

I’m creating a discord bot using python. I did a custom help command (don’t worry, for this part I’m ok), and I want to do a !help [command_name]. Let me explain. If we do !help, the bot will send the basic help command, but if I do !help [command_name], like !help ping, it will send informations a bout the ping command. I tried to do this
#bot.command()
async def help ping(ctx):
…
await ctx.send(embed=embed)
#bot.command()
async def help(ctx):
…
await ctx.send(embed=embed)
It didn’t worked, so I did this:
#bot.event
async def on_message(message):
if message.content.startswith(+help ping):
…
await message.channel.send(embed=embed)
#bot.command()
async def help(ctx):
…
await ctx.send(embed=embed)
There, the !help ping worked, but not the !help. And now, I’m there. Can you tell me a simple solution using #bot.command() or #bot.event?
You can also do Grouping on the commands.
Example :
#client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
await ctx.send("Help! Categories : Moderation, Utils, Fun")
#help.command() #For this command (.help Moderation)
async def Moderation(ctx):
await ctx.send("Moderation commands : kick, ban, mute, unban")
#help.command() #And for this command (.help Utils)
async def Uitls(ctx):
await ctx.send("Utils : ping, prefix")
#help.command() #And lastly this command (.help Fun)
async def Fun(ctx):
await ctx.send("Fun : 8ball, poll, headsortails")
Thank me later :D
...
from discord.ext.commands import Cog, Group, Command, HelpCommand
... # bot and bot commands
class MyCustomHelpCommand(HelpCommand):
async def send_bot_help(self, mapping): # Mapping[Optional[Cog], List[Command]]
... # write you'r help message here
self.get_destination().send(message)
async def send_cog_help(self, cog: Cog):
... # write you'r help message here
self.get_destination().send(message)
async def send_group_help(self, group: Group):
... # write you'r help message here
self.get_destination().send(message)
async def command_not_find(self):
... # write you'r help message here
self.get_destination().send(message)
bot.help_command = MyCustomHelpCommand()
docs: HelpCommand
also see: DefaultHelpCommand, MinimalHelpCommand
try it:
...
from discord.ext.commands import Command
... # bot and bot commands
# command example 1
#client.command(help='I am an example')
async def ex1(ctx):
await ctx.send('I am working')
# command example 2
#client.command()
async def ex2(ctx):
'''I am an example too'''
await ctx.send('I am working too')
#client.command(name='help')
async def my_help_command(ctx, command_name: str = 'help')
await ctx.send(client.get_command(command_name) or 'Command Not Find')
Output with '!' command_perfix:
me: !help ex1
bot: I am an example
me: !help ex2
bot: I am an example too
me: !help i_an_not_command
bot: Command Not Find
You can do this:
#bot.commands()
async def help(ctx, cmd=None):#if the user doesn't give any arguments for "cmd" then it will count it as None
if not cmd:#checks if the user gave arguments for "cmd"
await ctx.send("Help is here!")#the message the bot should send
elif cmd.lower()=="ping":#checks if the arguments given for "cmd" is ping and I set "cmd.lower()" so that the argument is not case sensitive
await ctx.send("Help for command `ping` is here!")
else:#if the arguments doesn't match any of the if statements it will show an error
await ctx.send(f"No command named `{cmd.lower()}`")#you can set anything for the error message
Hope you find it helpful
And sorry for answering this late

Discord.py: Why do the welcome and goodbye messages repeat?

Problem: I am trying to have it so that the bot sends a single message in general, but the messages continuously repeat, seemingly increasing each time this occurs. Also, if I switch the message to something else, the repeated parts are of the old message.
Code:
import discord
from discord.ext import commands
client=commands.Bot(command_prefix = '.')
#client.event
async def on_ready():
print('ok')
#client.event
async def on_member_join(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Hi {}".format(member))
#client.event
async def on_member_remove(member):
channel=discord.utils.get(member.guild.channels, name="general")
await channel.send("Bye")
client.run(token)
Since the code is under the function variable then you have to end each function.
It might be due to multiple instances of the application are running. Check your task manager and search for python process, End it if there are multiple and re-run the script.

Discord bot commands execute multiple times

It worked at first, but then somewhy it started to give the answers 4-5 times at once, any idea why?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
#client.event
async def once_ready():
print('Bot is ready.')
#client.event
async def on_member_join(member):
print(f'{member} has joined the server.')
#client.event
async def on_member_remove(member):
print(f'{member} has left the server.')
#client.command()
async def ping(ctx):
await ctx.send('Pong!')
client.run('my token here')
So, the problem was that I couldn't shut down the already running bots in Atom.
If you add the code that I wrote down there (that only the owner can
use) will shut down the already running bots (write /shutdown in
discord server or whatever your prefix is).
However, you may need a PC restart after saving the bot with this code.
#client.command()
#commands.is_owner()
async def shutdown(ctx):
await ctx.bot.logout()
So every time if you want to edit your command, you write /shutdown
and edit it, after that, you can start it again.
I hope this works for you and that I could help if you had the same problem.

Categories