CommandNotFound issue with my discord bot in python - python

so i'm playing with discord bots a little bit.
My issue is that when I type one of my commands, it doesn't work and shows me this message: "discord.ext.commands.errors.CommandNotFound: Command "dadjoke" is not found" (this is an example but I have the same issue with all the commands I tried).
Here is my full code:
import discord
import requests
from discord.ext import commands
client = commands.Bot(command_prefix='.')
#Setup the client
#client.event
async def on_ready():
#connection
print(f'Ready and Logged in as {client.user}')
#Help
#commands.command(name='help')
async def help(ctx):
#Embed parameters
Help_Embed = discord.Embed(title=f"</{client.user}y Help>", description=f"{client.user} bot by Stan_#1423", color=0xfee010)
Help_Embed.add_field(name="Version code:", value="v0.1", inline=False)
Help_Embed.add_field(name="Day Released:", value="03/03/22", inline=False)
Help_Embed.add_field(name="Get a joke", value="type: '.dadjoke'", inline=True)
#Sending Embed
await ctx.send(embed=Help_Embed)
#Jokes
#commands.command(name='dadjoke')
async def dadjoke(ctx):
headers = {'Accept': 'text/plain',}
resp = requests.get('https://icanhazdadjoke.com/', headers=headers)
joke = resp.text
await ctx.send(joke)
#Run the client
client.run('TOKEN')
I have already looked it up on the internet and i didn't find anything that solved my problem, i also tried to copy some code i found on online courses and stuff, but i still had the same problem.
Thanks for helping and sorry for bothering you guys with my dumb problems.

If you are using prefixed commands, it should be
#client.command(name=‘whatever’)

I believe you should use #client.command() instead of commands.command().

Related

how can i make my discord bot do the !say command?

I've never coded before so I'm pretty new and I'm trying python on replit, I've searched a lot and this is what I did so far but it isn't working. (ignore the reverse part)
import os
import discord
from keep_alive import keep_alive
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.event
async def on_message(message):
if message.content.startswith("!reverse"):
await message.channel.send(message.content[::-1])
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
async def on_message(message):
echo = message.content.split(" ", 1)[1]
if message.content.startswith("!say"):
await message.channel.send(echo)
I want the bot to be like this:
me:!say blah blah blah
bot: blah blah blah
thanks to anyone that answers
There's a lot of problems here
Intents.default() doesn't include the message contents intent, so you won't be able to read messages. For more info on intents and how to enable them, read the docs: https://discordpy.readthedocs.io/en/stable/intents.html
You've got two on_message functions, which doesn't work. You can't have multiple functions with the same name. Combine them into one instead.
Never put any code underneath client.run() - it'll never get executed.
You've got two client.run()'s. Why?
The on_message at the bottom is missing the #client.event decorator, so even if you wouldn't have 2 of them it still wouldn't be invoked.
Why don't you use a Bot with commands instead of manually parsing everything in on_message? https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
Replit isn't made to run bots on and will cause you a lot of trouble. Consider hosting it on an actual VPS (or during the development phase - just locally).
Ok, there's some other changes to make first.
You're not using commands, and are instead looking for messages(technically nothing wrong with that, but it can cause unnecessary issues)
I'll modify the code, and hopefully, it works.
import os
import discord
from keep_alive import keep_alive
client= commands.Bot(command_prefix='!', intents=discord.Intents.default())
#client.event
async def on_ready():
print("I'm in")
print(client.user)
#client.command()
async def reverse(ctx,*,message):
await ctx.message.delete()
await ctx.channel.send(message[::-1])
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
keep_alive()
my_secret = os.environ['DISCORD_BOT_SECRET']
client.run(my_secret)
#client.command()
async def say(ctx, *, message):
await ctx.message.delete()
await ctx.channel.send(message)

How to fix this problem discord.py bot problem

I created a bot in discord.py which works perfectly before i add a block of code. Once i added the code it stops working. Then i removed the newly added code. But my bot is not working now and sometimes it sends reply after 5 minutes but it doesn't shows any error. Then i created a new bot and pasted the token to check whether there is any problem with my code but it works perfectly.
i am wondering what is the problem bcs it didn't show any error and even with token as it prints in terminal too and even it sends reply to commands sometimes after 5 minutes. I regenerated the token of my bot even but now too the same problem is there.
Can someone say how to make my old bot to work properly? I don't want to start with new bot since my old bot is already in 86 servers and struggled hard to join it in that much servers.
from discord.ext.commands import Bot
from discord.ext import commands
import os
import discord
from random import randint
import keep_alive
import DiscordUtils
import random
from discord_components import *
# intents = discord.Intents.all()
intents = discord.Intents(messages=True, guilds=True,members=True,typing=True,presences=True)
bot = Bot(command_prefix="?", case_insensitive=True,intents=intents)
bot.remove_command("help")
global music
music = DiscordUtils.Music()
DiscordComponents(bot)
#bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.idle, activity=discord.Game(f'on {len(bot.guilds)} servers | ?help'))
print(f"Logged in as {bot.user}")
#bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
title_error_one = 'You have not entered anything after the command'
desc_error_one = 'Use **?help** to see a list of all the commands available'
embed_var_one = discord.Embed(title=title_error_one,
description=desc_error_one,
colour=randint(0, 0xffffff))
await ctx.reply(embed=embed_var_one)
if isinstance(error, commands.MaxConcurrencyReached):
title_error_four = 'Someone is already playing'
desc_error_four = 'Please wait until the person currently playing is done with their turn'
embed_var_four = discord.Embed(title=title_error_four,
description=desc_error_four,
colour=randint(0, 0xffffff))
await ctx.reply(embed=embed_var_four)
if isinstance(error,commands.CommandOnCooldown):
embed = discord.Embed(
title="**Still on Cooldown!**",
description=f"Try again in {error.retry_after:.2f}s.",
colour=randint(0, 0xffffff)
)
await ctx.reply(embed=embed)
if isinstance(error, commands.CommandNotFound):
return
if __name__ == "__main__":
try:
for filename in os.listdir('./cogs'):
if(filename.endswith('.py')):
bot.load_extension(f'cogs.{filename[:-3]}')
except Exception as exc:
print(exc)
keep_alive.keep_alive()
token = os.environ.get("TOKEN")
bot.run(token)
This is the code on main.py file
I don't think other files have any errors. I only doubt with this file.
Thank you for help in advance
Atlast i found that it is due to on_member_update command. Once i commented it. My bot works fine(: and below is my on_member_update code. Is there anything Wrong or some way to make it fast. Below is the code
#commands.Cog.listener()
async def on_member_update(self,before, after):
try:
serverId=after.guild.id
channel_id=int(logs_info.find_one(
{'id': serverId})['action_logs'])
logchannel = self.bot.get_channel(channel_id)
except:
return
IST = pytz.timezone('Asia/Kolkata')
time_now = (datetime.now(IST))
time_now = str(time_now.strftime('%Y-%m-%d %H:%M:%S'))
if len(before.roles) < len(after.roles):
new_role = next(role for role in after.roles if role not in before.roles)
embed=discord.Embed(title=f"Roles given",description=f"{after.mention} has been given {new_role.mention} role",colour=randint(0, 0xffffff))
embed.add_field(name="Role added at",value=time_now)
elif(len(before.roles) > len(after.roles)):
new_role = next(role for role in before.roles if role not in after.roles)
embed=discord.Embed(title=f"Removed",description=f"{new_role.mention} role has been removed from {after.mention}",colour=randint(0, 0xffffff))
embed.add_field(name="Role removed at",value=time_now)
else:
return
embed.set_thumbnail(url=after.guild.icon_url)
embed.set_footer(text=self.bot.user.name,icon_url=self.bot.user.avatar_url)
embed.set_author(name=after.name, icon_url=after.avatar_url)
await logchannel.send(embed=embed)
Problem explanation
You use pymongo library to fetch some data in your on_member_update event:
channel_id=int(logs_info.find_one({'id': serverId})['action_logs'])
It's so bad because pymongo is a blocking library. It means that when you interact with your database this library blocks other code. Therefore your bot is so slow. It can't process command while it waits for pymongo request.
Solution
You can use motor instead of pymongo. It's an asynchronous wrapper for pymongo and it is related to this. But motor doesn't block your code execution.

How can I run my Discord bot that updates from an API without hitting Discord's 1,000 connection maximum?

I built a bot that updates the name of the bot to a price in Python. Likewise, the status of the bot updates to a different price as well. The bot works as intended for a bit of time, but then I receive the following message from Discord:
It appears your bot, "MY BOT NAME", has connected to Discord more than 1000 times within a short time period. Since this kind of behavior is usually a result of a bug we have gone ahead and reset your bot's token.
My bot runs every 15 seconds, from a shell script, on a linux server, that also kills the last process which was run before it. I kill the preceding process so they don't eat up my memory and crash my server.
Here is my code:
#!/usr/bin/python
import discord
from discord.ext import commands
import requests
import json
import emoji
import sys
import asyncio
client = commands.Bot(command_prefix = '.')
url = 'URL FOR THE API'
price = requests.get(url)
rapid_gprice = price.json()['data']['price1']
standardp = price.json()['data']['price2']
#client.event
async def on_ready():
guild = client.get_guild(MY GUILD ID)
me = guild.me
await me.edit(nick=standardp)
activity = discord.Game(name=rapid_gprice)
await client.change_presence(status=discord.Status.online, activity=activity)
client.run('MY TOKEN')
I'm fairly certain I need to use some sort of function inside my Python script that loops through the price api and updates the Discord bot accordingly, only having to run the Python script once.
I'm happy to provide any additional information you may need. Thanks in advance.
Running your script every 15 seconds is a really bad idea, there's an build-in discord.py extension called tasks, it lets you run background tasks, hence the name.
from discord.ext import tasks
#tasks.loop(seconds=15)
async def change_nick(guild):
nick = # Get the nick here
await guild.me.edit(nick=nick)
#client.event
async def on_ready():
await client.wait_until_ready()
guild = client.get_guild(MY GUILD ID)
change_nick.start(guild)
Also I see that you're using requests, which is a blocking library, I'd suggest you using aiohttp instead
Take a look at the tasks introduction
This is how I ended up solving my issue. It's probably code overkill but it works. Feel free to help me alter it to make it more efficient:
#!/usr/bin/python
from discord.ext import tasks, commands
import aiohttp
import json
import asyncio
import discord
client = commands.Bot(command_prefix = '.')
url = 'THE API LINK I''M USING'
async def getPrice1():
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
response = await resp.json()
price1 = response['data']['priceZYX']
return price1
async def getPrice2():
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
response = await resp.json()
price2 = response['data']['priceXYZ']
return price2
#tasks.loop(seconds=7)
async def change_nick(guild):
nick = await getPrice1()
await guild.me.edit(nick=nick)
activity = discord.Game(name=await getPrice2())
await client.change_presence(status=discord.Status.online, activity=activity)
#client.event
async def on_ready():
await client.wait_until_ready()
guild = client.get_guild(MY GUILD ID)
change_nick.start(guild)
I got an error trying to implement the pricedata (from url) to my bot's username.
The error: discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In nick: Could not interpret "(the live price)" as string.
If you have the same problem (and using discord rewrite), make sure to label (nick=nick) as a string:
#tasks.loop(seconds=15)
async def change_nick(guild):
nick = await getPrice1()
await guild.me.edit(nick=str(nick))
PS: Im fairly new to coding so please correct me if im wrong, it worked for me. Also thanks for this posts it helped me alot making my bot.

Changing discord.py bot using command

How would I go about changing my bots avatar with a command such as pfpchange or something similar?
Any help would be appreciated, I've tried the following code with zero luck.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='=')
client.remove_command('help')
pfp = 'https://cdn.discordapp.com/attachments/751402019046162494/774903321844645968/pinkbulba.jpg'
#client.command()
async def pfpchange(ctx):
await client.edit_profile(password=None, avatar=pfp)
client.run('super secret token')
Bot.edit_profile() was renamed to ClientUser.edit(), which is why it doesn't work. You're supposed to use Bot.user.edit().
More info in the relevant API documentation

I can't make commands in discord.py

So I'm having a problem with discord.py.
I'd like to make a command to kick/ban people.
I tried this at first and it didn't work, so I went to check if commands worked at all for me. Apparently it doesn't. I've tried everything and nothing works.
import discord
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix='!')
Token = 'TOKEN'
#bot.command(pass_context=True)
async def test(ctx):
await ctx.send('test')
client.run(Token)
I type !test on the channel but nothing happens.
I've tried basically everything.
I've changed the prefix, done: #bot.command(name='test), basically everything you could think of. Nothing works. I'd like to know if I'm missing something crucial. Like do I have to download something first or am I missing something in the code or are there permissions I need to enable. I've looked all over the discord py API reference. Anything would be helpful thanks.
Your problem is because of bot = commands.Bot(). You can use this code instead:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!")
#client.command()
async def test(ctx):
await ctx.send('test')
client.run(token)
So you just have to delete bot = commands.Bot() then replace the #bot.command() with #client.command.

Categories

Resources