Good afternoon! I am new to Python , and I am working on a discord bot. I keep suffering from this error: AttributeError: 'Client' object has no attribute 'command'. I tried everything to repair this, but I did not know. Any help would be fine. Please help me!
Here is the code:
import discord
import random
from discord.ext import commands
class MyClient(discord.Client):
client = commands.Bot(command_prefix = '?')
# Start
async def on_ready(self):
print('Logged on as', self.user)
# Latency
client = discord.Client()
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
# 8ball
#client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
responses = ['Biztosan.',
'Nagyon kétséges.']
await ctx.send(f'Kérdés: {question}\nVálasz: {random.choice(responses)}')
# Clear
#client.command()
async def clear(ctx, amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send(f'Kész!')
async def on_message(self, message):
word_list = ['fasz', 'kurva', 'anyad', 'anyád', 'f a s z', 'seggfej', 'buzi', 'f.a.s.z', 'fa sz', 'k U.rv# any#dat']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Ne használd ezt a szót!')
messageattachments = message.attachments
if len(messageattachments) > 0:
for attachment in messageattachments:
if attachment.filename.endswith(".dll"):
await message.delete()
await message.channel.send("Ne küldj DLL fájlokat!")
elif attachment.filename.endswith('.exe'):
await message.delete()
await message.channel.send("Ne csak parancsikont küldj!")
else:
break
client = MyClient()
client.run(token)
There are a multitude of ways to make your bot, and it seems you tried to mash 2 ways of making it together.
Option 1: using the pre-made commands bot class
client = commands.Bot(command_prefix = '?')
client.command()
async def command_name(ctx, argument):
#command function
client.run(token)
Option 2: making you own subclass of client
class MyClient(discord.Client):
async def on_message(self, message):
if message.content.startswith('command_name'):
#command functionality
client = MyClient()
client.run()
You can use either of the two options, but not both at the same time (you could actually do that, but not in the way you did)
Also I would advice staying away from discord.py to learn python as asyncio is pretty complex
Why don't you simply define client like this?
client = commands.Bot(...)
Also you have defined it a couple of times in the code, delete them all and define it only ONCE at the top of the code after the imports. This is a really bad question, you should learn a lot more python before diving deeper into discord.py.
Related
I want to receive information from the user from discord, but I don't know what to do.
I want to make a class to input data
if user write !make [name] [data], bot generate class A, A(name, data)
The following is the code I made. What should I do?
Ps. command_prefix is not working properly. What should I do with this?
`
import discord, asyncio
import char # class file
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("Game"))
#client.event
async def on_message(message):
if message.content == "test":
await message.channel.send ("{} | {}, Hello".format(message.author, message.author.mention))
await message.author.send ("{} | {}, User, Hello".format(message.author, message.author.mention))
if message.content =="!help":
await message.channel.send ("hello, I'm bot 0.0.1 Alpha")
async def new_class(ctx,user:discord.user,context1,context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.message.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
client.run('-')
`
I advice to not using on message for making commands
what I do advice:
import discord
from discord.ext import commands
#bot.command(name="name here if you want a different one than the function name", description="describe it here", hidden=False) #set hidden to True to hide it in the help
async def mycommand(ctx, argument1, argument2):
'''A longer description of the command
Usage example:
!mycommand hi 1
'''
await ctx.send(f"Got {argument1} and {argument2}")
if you will use the two ways together then add after this line
await message.channel.send ("hello, I'm bot 0.0.1 Alpha")
this:
else:
await bot.process_commands(message)
if you want to make help command u should first remove the default one
by editing this line bot = commands.Bot(command_prefix='!',intents=intents) to :
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
overall code should look like
import discord, asyncio
import char # class file
from discord.ext import commands
intents=discord.Intents.all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='!',intents=intents,help_command=None)
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("Game"))
#client.event
async def on_message(message):
async def new_class(ctx,user:discord.user,context1,context2):
global char_num
globals()['char_{}'.format(char_num)]=char(name=context1,Sffter=context2,username=ctx.message.author.name)
char_num+=1
await ctx.message.channel.send ("done", context1,"!")
#bot.command()
async def make(ctx,name,data):
#do whatever u want with the name and data premeter
pass
#bot.command()
async def help(ctx):
await ctx.send("hello, I'm bot 0.0.1 Alpha")
#bot.command()
async def test(ctx):
await ctx.send ("{} | {}, Hello".format(ctx.author, ctx.author.mention))
client.run('-')
and yeah if u want to know what is ctx
ctx is context which is default premeter and have some methods like send,author and more
i want to make a discord bot but i cant run it.
idk what to do
it just runs
and no log
idk REALLY what to do
import discord
from discord.ext import commands
import os
import keep_alive
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
async def on_ready():
print(f'{client.user} is connected')
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('massage', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
keep_alive.keep_alive()
client.run(token)
client.close()
i dont know what to do anymore
I tried everything i could i ran it in pycharm
vscode
nothing works
There's a lot of errors on your code. so I fixed it
First thing is your client events, keep_alive, client.run, also why did you put client.close()
import os, discord
import keep_alive
from discord.ext import commands
client = commands.Bot(command_prefix="!")
token = os.environ.get('Token')
GUILD = os.environ.get('Guild')
#client.event # You need this event
async def on_ready():
print(f'{client.user} is connected')
"""
client.wait_for('massage') is invalid. Changed it into 'message'. Guess it is a typo.
You can replace this command with the new one below.
"""
#client.command()
async def dm(ctx, member: discord.Member):
await ctx.send('what do u want to say bitch!')
def check(m):
return m.author.id == ctx.author.id
massage = await client.wait_for('message', check=check)
await ctx.send(f'send massage to {member} ')
await member.send(f'{ctx.member.mention} has a massage for you: \n {massage}')
"""
I also moved this on_member_join event outside because it blocks it.
"""
#client.event
async def on_member_join(member):
channel = discord.util.get(member.Guild, name='general')
await channel.send(f'Hey welcome to my server {member.mention}, hope you enjoy this server!')
"""
I put the keep_alive call outside because the function blocks it in your code.
And also removed client.close() to prevent your bot from closing
"""
keep_alive.keep_alive()
client.run(token)
For the dm command. Here it is:
#client.command()
async def dm(ctx, member:discord.Member=None):
if member is None:
return
await ctx.send('Input your message:')
def check(m):
return m.author.id == ctx.author.id and m.content
msg = await client.wait_for('message', check=check) # waits for message
if msg:
await member.create_dm().send(str(msg.content)) # sends message to user
await ctx.send(f'Message has been sent to {member}\nContent: `{msg.content}`')
Sorry, I'm kinda bad at explaining things, also for the delay. I'm also beginner so really I'm sorry
Code:
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
words = [] # List of words to look for
if message.author.id == self.user.id:
return
for i in words:
if i in message.content.lower():
await message.channel.send(f"Hey <#{message.author.id}>, i have noticed that in your message is a word on a list")
break
await message.add_reaction("✅")
await client.wait_for("reaction_add")
await message.delete()
client = MyClient()
client.run("TOKEN")
How Could i make the bot add reaction to its own message and if the user uses it delete its own message
i did look for the answer but god is discord.py messy, i have seen 6 answers that did not work and all of them seemed like they use different modules
i apologize if the answer was easy to find, but i just couldnt
First of all, you should always try to find your answer in the documentation (discord.py documentation). (Off-topic: it's not discord.py that's messy; it's likely the method you are using to find answers which is messy.)
The TextChannel.send() method returns the message which was sent. So, you could just assign that return value to a variable.
For the other issue, there is an event listener which detects message deletions, on_message_delete()
import discord
class MyClient(discord.Client):
async def on_ready(self):
...
async def on_message(self, message):
words = []
if message.author.id == self.user.id:
return
for i in words:
if i in message.content.lower():
sent_message = await message.channel.send(
f"Hey {message.author.mention}, I have noticed that in your message is a word on a list"
)
break
await sent_message.add_reaction("reaction")
await message.add_reaction("✅")
await client.wait_for("reaction_add")
await message.delete()
async def on_message_delete(self, message):
# Do stuff here
client = MyClient()
client.run("TOKEN")
(On a side note, you can use Member.mention to mention/ping a member, instead of "<#{message.author.id}>".)
In my opinion, it is preferable to use the #client.event method decorator above your event methods instead of putting them in their own class. You would declare the client object as client=discord.Client() at the top, then put #client.event above your event handling methods. The on_reaction_add method can have reaction and message parameters to respond.
I am coding a discord bot and i think there has got to be a much easier/ simpler way to detect messages using the prefix for commands (and easy to expand in future), my code at the moment just scans each message to see if it contains the exact command, maybe a class will help?
#client.event
async def on_message(message):
# print message content
print(message.content)
# if the message came from the bot ignore it
if message.author == client.user:
return
# if the message starts with "!repeat" then say the message in chat
if message.content.startswith("!repeat"):
sentmessage = message.content.replace("!repeat", "")
await message.channel.send(sentmessage)
if "hello" in message.content.lower():
await message.channel.send("Hello!")
if message.content.startswith("!cleanup"):
if not message.author.guild_permissions.administrator:
await message.channel.send("You do not have permission to run this command!")
else:
num2c = 0
num2c = int(message.content.replace("!cleanup", ""))+1
print(num2c)
await message.channel.purge(limit=num2c)
num2c = num2c-1
cleanmessage = str("Cleared "+str(num2c)+" Messages.")
await message.channel.send(cleanmessage, delete_after=5)
You can use commands.Bot, it has a built-in command system, here's an example:
import discord
from discord.ext import commands
# enabling intents
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command()
async def foo(ctx, *args):
await ctx.send('whatever')
# You also have all the functionality that `discord.Client` has
#bot.event
async def on_message(message):
# ...
# you always need to add this when using `commands.Bot`
await bot.process_commands(message)
bot.run('token')
Take a look at the introduction
I am trying to make a discord bot using Python and I want to make it so not everyone can mention #everyone or when they do the message will be deleted immediately, but then I have another code ($snipe) which doesn't work until I delete it, and after I do, it gives me the response! Any help would be appreciated!
#client.event
async def on_message(message):
xall = "#everyone"
role1 = discord.utils.get(message.guild.roles, name = "Owner")
role2 = discord.utils.get(message.guild.roles, name="Mod")
roles = role1 or role2
if xall in message.content:
if roles in message.author.roles:
pass
else:
await message.delete(message)
#Fun
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#client.command()
async def snipe(ctx):
await ctx.send("Aight, imma go snipe!")
#client.command()
async def slap(ctx, members: commands.Greedy[discord.Member], *, reason='no reason'):
slapped = ", ".join(x.mention for x in members)
await ctx.send('{} just got slapped for {}'.format(slapped, reason))
import discord
from discord.ext import commands
client = discord.Client()
#client.event
async def on_message(msg):
owner = discord.utils.get(msg.guild.roles, name="Owner")
mod = discord.utils.get(msg.guild.roles, name="Mod")
roles = (owner, mod)
if msg.mention_everyone:
if not any(r in msg.author.roles for r in roles):
await msg.delete()
client.run(TOKEN)
I have just ran this, and this works as expected. Removes the message if needed.