How do I fix the error? discord.ext.commands.errors.CommandNotFound - discord.py

Whenever I do ?+"My question" in the discord, the error comes up
import discord
import openai
from discord.ext import commands
bot = commands.Bot(command_prefix="?", intents=discord.Intents.all())
token = "MTA2MzkxMzQ0NTcyNjEwNTYxMA.Gzwl09.Z7z5AFSoXSzqPl9qoNy1vkSOCL7sRvvNk_2WUk"
#bot.event
async def on_ready():
print("\033[32m\033[1m" + "Success: Bot is connected to Discord!")
#bot.command()
async def test(ctx, *, arg):
query = ctx.message.content
response = openai.Completion.create(
api_key='7bc82fafd22190d6e7e0dff98b662ab7169a7799386dbafe05de90b7f5e71335',
model="text-davinci-003",
prompt=query,
temperature=0.5,
max_tokens=60,
top_p=0.3,
frequency_penalty=0.5,
presence_penalty=0.0`your text`
)
await ctx.channel.send(content=response['choices'][0]['text'].replace(str(query), ""))
bot.run(token)
discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "hallo" is not found

First off, you leaked both your bot token and your OpenAI API key so you should go reset both of them.
Next, you're saying that the error appears when you send ?+"My question" in Discord. You don't have a command that matches this, as your error suggests. the only command you have is called test, so that is the only command you can use.
The error is telling you that someone tried to invoke a command that doesn't exist. If you don't care, you can create an error handler and ignore this exception. This Gist explains how to do so: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612

Related

Discord.py - How to run additional code after running client.run(token)?

Seemingly simple question but I'm stuck on how to solve it.
I use discord.py to login to my account and I want to DM a user by inputting his user_id .
import discord
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
client = MyClient()
client.run('token')
async def send_message(user_id):
user = client.get_user(user_id)
await user.send('My message')
When I run this python file in my python shell, it would print the "Logged in as ..." success message and it would hang up. It wouldn't let me type any other command.
I simply want to run the send_message function with a unique user_id, so I can DM a particular user.
How do I do this?
That's because client.run is blocking, so any code below it won't be executed while the bot is running. The best way to avoid this problem is by moving the function somewhere above it, like in the client subclass.
I don't know exactly where you want to execute this function from, so I would suggest that you run it from on_ready for now.
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
await self.send_message(123456) # DM a user with id "123456" as soon as the bot is ready
async def send_message(self, user_id):
user = self.get_user(user_id)
await user.send('My message')
client = MyClient()
...
If you want to execute this command from Discord, here is a good walkthrough.

Discord py anime character database

How to make Api anime character database function with my discord python bot? I am new add discord python bot. This sample api link for anime character database:
https://www.animecharactersdatabase.com/api_series_characters.php?character_q=naruto
I think this should work, try this! i commented out some stuff for it to be easy to understand
# Requrired modules
import discord
from discord.ext import commands
import requests
import random
import platform
# Creating the bot with the bot prefix as `?`
client = commands.Bot(command_prefix="?")
#client.event
async def on_ready():
print(f'Discord.py API version: {discord.__version__}')
print(f'Python version: {platform.python_version()}')
print(f'Logged in as {client.user.name}')
print('Bot is ready!')
# The commandsstarts here
#client.command()
async def anime(ctx, *, query="naruto"): # 'anime' is the name of the command
# This command can be used as `?anime character_name_here`
# The default value will be 'naruto' for the query
try:
reqcont = requests.get(f"https://www.animecharactersdatabase.com/api_series_characters.php?character_q={query}")
if reqcont.content==-1 or reqcont.content=='-1': # i found out that the website returns: -1 if there are no results, so here, we implement it
await ctx.send("[-] Unable to find results! - No such results exists!")
else:
# If the website doesnt return: -1 , this will happen
try:
reqcont = reqcont.json()
except Exception as e:
# Please enable this line only while you are developing and not when deplying
await ctx.send(reqcont.content)
await ctx.send(f"[-] Unable to turn the data to json format! {e}")
return # the function will end if an error happens in creating a json out of the request
# selecting a random item for the output
rand_val = len(reqcont["search_results"])-1
get_index = random.randint(0, rand_val)
curent_info = reqcont["search_results"][get_index]
# Creting the embed and sending it
embed=discord.Embed(title="Anime Info", description=":smiley: Anime Character Info result for {query}", color=0x00f549)
embed.set_author(name="YourBot", icon_url="https://cdn.discordapp.com/attachments/877796755234783273/879295069834850324/Avatar.png")
embed.set_thumbnail(url=f"{curent_info['anime_image']}")
embed.set_image(url=f"{curent_info['character_image']}")
embed.add_field(name="Anime Name", value=f"{curent_info['anime_name']}", inline=False)
embed.add_field(name="Name", value=f"{curent_info['name']}", inline=False)
embed.add_field(name="Gender", value=f"{curent_info['gender']}", inline=False)
embed.add_field(name="Description", value=f"{curent_info['desc']}", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.mention}")
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"[-] An error has occured: {e}")
client.run("NeverShareYourToken")

Discord.py Bot is not online, but still works

i have a problem with my discord bot, whenever i run the code below using apraw to get the titles of the recent submissions on a subreddit the bot doesn't appear online anymore but still returns the titles in CMD :
Bot is not online when i execute this but still asks for subreddit name & prints the titles of the new posts of the subreddit in CMD:
import asyncio
import apraw
from discord.ext import commands
bot = commands.Bot(command_prefix = '?')
#bot.event
async def on_ready():
print('Bot is ready')
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))
#bot.command()
async def online (ctx):
await ctx.send('Bot is online !')
reddit = apraw.Reddit(client_id = "CLIENT_ID",
client_secret = "CLIENT_SECRET",
password = "PASSWORD",
user_agent = "pythonpraw",
username = "LittleBigOwl")
#bot.event
async def scan_posts():
xsub = str(input('Enter subreddit name : '))
subreddit = await reddit.subreddit(xsub)
async for submission in subreddit.new.stream():
print(submission.title)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(scan_posts())
bot.run('TOKEN')
But is online when i execute this but obviously doesn't ask for sub name... :
import asyncio
import apraw
from discord.ext import commands
bot = commands.Bot(command_prefix = '?')
#bot.event
async def on_ready():
print('Bot is ready')
await bot.change_presence(status=discord.Status.online, activity=discord.Game('?'))
#bot.command()
async def online (ctx):
await ctx.send('Bot is online !')
bot.run('TOKEN')
So reddit is the problem here. But what exaclty do i ahve to change in order to make my bot apear online whilst still being able to retreive the titles of new submissions on a given subreddit? The code doesn't return any error:/
the #bot.event that you put above async def scan_posts(): should be changed to #bot.command(). It triggers by itself because you have this in your code:
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(scan_posts())
this is what causes the scan_posts to run automatically. You should remove this as you want scan_posts to be a bot command and not something that happens automatically. The bot also doesn't come online because of this code. What this does is check if this file has been run and then runs scan_posts. The rest of the code won't be triggered.
Also, you shouldn't change presence in on_ready as Discord has a high chance to completely disconnect you during the on_ready event and there is nothing you can do to prevent it. Instead you can use the activity and status kwargs in commands.Bot like:
bot = commands.Bot(command_prefix = '?', status=discord.Status.online, activity=discord.Game('?'))

How To count total number of members on my Discord server by python

i'm trying this code but it is not working
from discord.ext import commands
#commands.command(pass_context=True)
async def myid(ctx):
print(ctx.guild.member_count)
client.run(my token)
can you provide me right code
I found a solution for the problem statement, if we need to find name of total members of our servers. then use this code.
import discord
client = discord.Client()
token = 'your token'
#client.event
async def on_ready():
users = client.users
print(users)
#or
guilds = client.get_guild
for guild in client.guilds:
print(guild.name)
for member in guild.members:
print(member)
client.run(token)
As what Patrick Haugh said, you did not define your client yet. Also, pass_context is no longer needed in discord rewrite.
The most basic code would look something like this:
from discord.ext import commands
client = commands.Bot(command_prefix = 'PREFIX')
#client.command()
async def myid(ctx):
print(ctx.guild.member_count)
client.run('TOKEN')
Where PREFIX is whatever command prefix you want and TOKEN is your bot token
I suggest reading the discord.py documentation for more information
#bot.command()
async def members(ctx):
embedVar = discord.Embed(title=f'There Are {ctx.guild.member_count} Members In This Server', color=0xFF0000)
await ctx.send(embed=embedVar)
This also works but sends in server, not console.

How do I set a in Discord.py a command without Prefix only with certain word to which bot replies and also bot replies to thaat only in dm with bot

Discord.py, how to set a command, without Prefix, only with certain word to which bot replies, and also bot replies to that command while Dm with the bot.
Remember about the errors for example, bot object has no attribute on_message, etc, errors.
You can write a function to pass to command_prefix that will check for one prefix in servers and another (or none) in private messages:
from discord.ext import commands
def command_prefix(bot, message):
if message.guild is None:
return ''
else:
return '$'
bot = commands.Bot(command_prefix=command_prefix)
#bot.command(name='hello')
async def hello(ctx):
await ctx.send("Hello")
bot.run("TOKEN")
If you are using this in a cog.
#commands.Cog.listener()
async def on_message(self,message):
await message.send("Hello!")
or in the main.py
#bot.event
async def on_message(message):
await message.send("Hello!")
Please reply back if you have an error with this.
message.guild will return None if the message is in dms.

Resources