Discord py anime character database - discord.py

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

Related

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

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

Discord bot repeating the command but not an event in discord.py

I want to ask something.I got stuck on something.I wanted to add some new features to my bot such as swear words so that making cleaner server.I finished my code and tried to give command which is !dc greetings(!dc is my command_prefix btw).My bot sent 'Hi everyone' message for 7 times.That 7 times is same number as the number of swear words in "Badwords.txt".By looking these,that repeating issue is related to this file handling codes(or not idk).Interesting thins is when I write swear word into server's chatbox,bot send only one "Please do not use this word ever" message.So How can i prevent bot not to repeat for many times?Thank you
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)
client = commands.Bot(command_prefix="!dc ", intents=intents)
#Below command gets repeated 7 times everytime.That number is same as the number of swear words in "Badwords.txt"
#client.command(aliases=["sayHi"])
async def greetings(ctx):
await ctx.send('Hi everyone')
#My purpose in the below codes is countering profanity
with open("Badwords.txt", "r", encoding="utf-8") as f:
word = f.read()
badwords = word.split(",")
#In the below event,bot sends message only 1 time for 1 message
#client.event
async def on_message(message):
msg = message.content
for x in badwords:
if x in msg:
await message.delete()
await message.channel.send("Please do not use this word ever")
else:
await client.process_commands(message)
client.run(Token)
I would take the await client.process_commands(message) out of the else statement. I have also moved the with open inside the on message event so everything a message is sent, it will open the file to check if the message contained a bad word.
import discord
from discord.ext import commands
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True,presences=True)
client = commands.Bot(command_prefix="!dc ", intents=intents)
#client.command(aliases=["sayHi"])
async def greetings(ctx):
await ctx.send('Hi everyone')
#client.event
async def on_message(message):
msg = message.content
with open("Badwords.txt", "r", encoding="utf-8") as f:
word = f.read()
badwords = word.split(",")
for x in badwords:
if x in msg:
await message.delete()
await message.channel.send("Please do not use this word ever")
else:
return
await client.process_commands(message)
client.run(Token)
await client.process_commands(message) was taken out of the else statement because, with your current code, the bot would only process the commands if the message did NOT contain a bad word. But we need it to process the commands every time a message is sent.

How to make bot reply to a mention discord.py

I'm making a discord bot and a problem that has come up for me is that the bot won't reply to the user, here is the code
#Code Imports
import discord
import random
from discord import message
from discord import channel
from discord.embeds import Embed
from discord.ext import commands
from discord.ext.commands.bot import Bot
from discord.message import Message
from apikeys import *
from discord import guild
from discord import emoji
from discord import *
from discord import ContentFilter
from discord import channel
from discord import client
#intents
intents=discord.Intents.default()
intents.members=True
#prefix
client=commands.Bot(command_prefix='!',intents=intents)
#Start
#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')
#Commands
#client.command()
async def work(ctx):
await ctx.send('use !war to get up the war menu')
emojigood = '\N{THUMBS UP SIGN}'
emojibad="\N{THUMBS DOWN SIGN}"
#client.command()
async def help(ctx):
embed=discord.Embed(title='Help', description='!war is currently under testing please do not complain about it', color=0x00000)
await ctx.send(embed=embed)
#client.command()
async def war(ctx):
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
#Checks whether the message is the same, and the emoji is one of the accepted ones, and returns either True or False
r, user = await client.wait_for('reaction_add',timeout=10 ,check=check)
#this is equivalent to a event listener within your command, it will stop there until a reaction that meets the requirements has been found
#(This won't block other commands and functions)
if r.emoji == emojigood:
embed = discord.Embed(title='War', description='Please now choose a country', color=0x00000)
await ctx.send(embed=embed)
prefix = "!" #insert your prefix
async def on_message(message):
if message.author == client.user:
return
if message.content == f'{prefix}war': #dont need to use this string, just illustrating the point
await message.channel.send("What country do you want to start a war with?")
def check(msg):
return msg.author == message.author and len(msg.role_mentions) > 0
msg = await client.wait_for('message', check=check)
role = msg.role_mentions[0]
channel = client.get_channel(849230881994047508)
await channel.send(f"{role.mention} {message.author} has declared war on you.")
client.run(token)
What's meant to happen:
Bot: Which role would you like to start a war with
User:#something
Bot:Send information to UN, 'War on #something'
I don't know how to make it see the role mention
You have a couple of issues, the way to make the code you're using function decently is to replace message.content with message.clean_content, however, 1. That will react to any message starting with # or a mention, which is probably not what you want, and 2. any message not beginning with the mention wouldn't work.
You say in your description that you're looking for role mentions, which is a different attribute, and you're looking to send a message, and wait for a response, so here's a piece of sample code that would solve those issues, assuming I'm interpreting your question correctly:
def check(msg):
return msg.author == message.author and len(msg.role_mentions) > 0
msg = await client.wait_for('message', check=check)
role = msg.role_mentions[0]
channel = client.get_channel(ID of the channel)
await channel.send(f"{role.mention} {message.author} has declared war on you."
If I misinterpreted any of what you wanted or you're not sure how some of it works, shoot me a comment and I'll do my best to explain!
Docs reference for slightly more complex objects used:
role_mentions,
wait_for(),

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.

Resources