how to define "#client.command"? - python

So basically I have this code:
import discord
import os
bot = commands.Bot(command_prefix = "!")
TOKEN = (os.getenv("TOKEN"))
client = discord.Client()
#client.event
async def on_message(message):
if message.content.startswith('!help'):
embedVar = discord.Embed(
title="Help Page", description="Under development", color=0x00ff00)
await message.channel.send(embed=embedVar)
#client.command()
#commands.has_any_role("Owner")
async def ban (ctx, member:discord.User=None, reason =None):
if member == None or member == ctx.message.author:
await ctx.channel.send("You cannot ban yourself")
return
if reason == None:
reason = "Breaking Rules"
message = f"You have been banned from {ctx.guild.name} for {reason}"
await member.send(message)
# await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{member} is banned!")
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
When I run this I get the sequent error:
Traceback (most recent call last):
File "main.py", line 4, in <module>
bot = commands.Bot(command_prefix = "!")
NameError: name 'commands' is not defined
Can someone please help me?

In the documentation for commands, it states to add this to your imports:
from discord.ext import commands

commands isn't defined because it isn't imported in your code put from discord.ext import commands at the top of your code. And, you don't need discord.Client() bc commands.Bot() is a subclass of it so please remove it for it is redundant. and finally, change client.command to bot.command to make the code work.

Related

No error but it is not running HELP Discord.py

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

Python Discord bot give roles on join

I'm trying to make a simple bot that will give out a role to a person who just joined the server.
The code:
import discord
import os
from discord.utils import get
bot_acces_token = os.environ['token']
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, id="123456789")
await client.add_roles(member, role)
#client.event
async def on_ready():
print('Bot is ready')
client.run(bot_acces_token)
but unfortunately I get this error:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 17, in on_member_join
role = discord.utils.get(member.server.roles, id="123456789")
AttributeError: 'Member' object has no attribute 'server'
The way your are trying to get the result is old and have changed.
You need to change the way you are defining your bot. You need to change this piece of code:
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
You have to use Command API to use event. Change these lines to:
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
Add an import statement as well on the top of the script:
from discord.ext import commands
Remove this as well:
from discord.utils import get
Try this instead:
#client.event
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, id="123456789")
await member.add_roles(role)
You need to use member.guild.roles instead of the one you have actually used. Also you need to use await member.add_roles(role) instead of the one you used. It would work for you. If you still have an error, ask away!
Thank You! :D
Thats the solution:
import discord
from discord.ext import commands
import os
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
#client.event
async def on_member_join(member):
channel = client.get_channel(1234567)
role = discord.utils.get(member.guild.roles, id=1234567)
await member.add_roles(role)

How to add role to person after saying smth

from discord.ext import commands
from discord.utils import get
client = discord.Client()
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
bot = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
print(f"{member} was given {role}")
client.run('NzY0MjA1MzA1MjQwMjIzNzQ0.X4C3pw.5RmXn1XswHCTWwOQ5i1v5lH5B6I')
when i run it and type something it gives me this:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\jpbay\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
TypeError: on_message() missing 1 required positional argument: 'member'
any help?
on_message event has only 1 argument, which is message. You cannot use 2 parameters in this event but you can access every attribute that member object has with using message.author.
Also, I don't recommend you to use discord.Client and discord.Bot at the same time. discord.Bot can do everything that discord.Client does.
ROLE = 'SPECIAL'
BOT_PREFIX = '/'
client = commands.Bot(command_prefix=BOT_PREFIX)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message, member):
if message.author == client.user:
return
if message.author.name == "Pawlu_il_Fenku":
await message.channel.send('Hello!')
role = get(message.guild.roles, name=ROLE)
await message.author.add_roles(role)
print(f"{message.author} was given {role}")
client.run('TOKEN')
NOTE:
You should change your token if you haven't changed yet.

Discord bot commands not working (Python)

I am currently using python to code my first discord bot. While trying to write a command, I saw that I was unable to do this. This code:
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = 'NzQxMjA2OTQzMDc4ODA5NjEy.Xy0Mwg.Shkr9hHvkn-y4l5ye1yTHYM3rQo'
client = discord.Client()
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
is not outputting anything in the discord application when I type !swear. The bot is online, and working normally for other codes such as:
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
Here is the full code:
import discord
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = (##my token spelled out)
client = discord.Client()
#client.event
async def on_ready():
print('im in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#client.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
pp = commands.Bot(command_prefix='!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
client.run(TOKEN)
Does anyone know how I can fix my problem?
Client() and Bot() are two methods to create bot and using both at the same time is wrong.
Using Client() and Bot() you create two bots but they would need client.run(TOKEN) and pp.run(TOKEN) to run together - but it makes problem to start them at the same time and it can make conflict which one should get user message.
Bot() is extended version of Client() so you need only Bot() and use
#pp.event instead of #client.event
pp.run(TOKEN) instead of client.run(TOKEN)
pp.user instead of client.user
EDIT:
And you have to define pp before all functions. Like this
import random
from discord.ext import commands
TOKEN = 'TOKEN'
pp = commands.Bot(command_prefix='!')
#pp.event
async def on_ready():
print('im in as {}'.format(pp.user))
#pp.event
async def on_message(message):
if message.author == pp.user:
return
if message.content.startswith('hello'):
await message.channel.send('Hi there!')
elif message.content.startswith("Is Ethan's mum gay?"):
await message.channel.send("Yep, 100%!")
elif message.content.startswith("What are you doing?"):
await message.channel.send(f"Step {message.author}")
elif 'happy birthday' in message.content.lower():
await message.channel.send('Happy Birthday! 🎈🎉')
#pp.event
async def on_member_join(member):
await member.create_dm()
await member.dm_channel.send(f'Hi {member.name}, welcome to my Discord server!')
messages = ["hello", "hi", "how are you?"]
#pp.command(name = "swear")
async def swear(ctx):
await ctx.send(rand.choice(messages))
pp.run(TOKEN)

Command raised an exception: NameError: name 'challenge_player' is not defined

Me and my friend are trying to make a minigame kind of discord bot. I am trying to make a challenge command that takes the id of the user-specified and asks whether they want to accept or not.
#imports
import discord
from discord.ext import commands
#DISCORD PART#
client = commands.Bot(command_prefix = '-')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def challenge(ctx, member: discord.Member = None):
if not member:
await ctx.send("Please specify a member!")
elif member.bot:
await ctx.send("Bot detected!")
else:
await ctx.send(f"**{member.mention} please respond with -accept to accept the challenge!**")
challenge_player_mention = member.mention
challenge_player = member.id
#client.command()
async def accept(ctx):
if ctx.message.author.id == challenge_player:
await ctx.send(f"{challenge_player_mention} has accepted!")
else:
await ctx.send("No one has challenged you!")
#client.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
await client.process_commands(message)
client.run("token")
Everything is working fine except for the accept command.
Here is the error:
Traceback (most recent call last):
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
ret = await coro(*args, **kwargs)
File "c:/Users/impec/Downloads/bots/epic gamer bot/epic_gamer.py", line 30, in accept
if ctx.message.author.id == challenge_player:
NameError: name 'challenge_player' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\impec\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'challenge_player' is not defined
I cannot understand what I am doing wrong.
challenge_player is defined locally, in the challenge function so you can access it from the accept function.
You need to declare challenge_player outside of your function and add global challenge_player inside your functions, same thing with challenge_player_mention:
import discord
from discord.ext import commands
challenge_player, challenge_player_mention = "", ""
client = commands.Bot(command_prefix = '-')
#client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#client.command()
async def challenge(ctx, member: discord.Member = None):
global challenge_player, challenge_player_mention
if not member:
await ctx.send("Please specify a member!")
elif member.bot:
await ctx.send("Bot detected!")
else:
await ctx.send(f"**{member.mention} please respond with -accept to accept the challenge!**")
challenge_player_mention = member.mention
challenge_player = member.id
#client.command()
async def accept(ctx):
global challenge_player, challenge_player_mention
if ctx.message.author.id == challenge_player:
await ctx.send(f"{challenge_player_mention} has accepted!")
else:
await ctx.send("No one has challenged you!")
#client.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
await client.process_commands(message)
client.run("token")
PS: Don't share your bot token on internet! Anyone could access your bot with it and do whatever they want with it. You should generate another one and use it.

Categories