"commands" is not defined in discord.py - python

Code:
import os
import discord
import random
from discord.ext import commands
GUILD = os.getenv('DISCORD_GUILD')
client2 = commands.Bot(command_prefix = '')
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} has connected to '
f'{guild.name}'
)
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
bot = commands.Bot(command_prefix='$')
#client2.command(pass_context = True)
async def mute(ctx, member: discord.Member):
if ctx.message.author.server_permissions.administrator or ctx.message.author.id == '194151340090327041':
role = discord.utils.get(member.server.roles, name='Muted')
await bot.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await bot.say(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await bot.say(embed=embed)
client.run(os.getenv('TOKEN'))
I am trying to create a bot that mutes people. This is my 1st week in learning the discord API. I copied the mute function from a website so I didn't code everything myself. I'm having some trouble with the command. The error is:
NameError: name 'commands' is not defined
But I have seen other people do this and not get an error so I have no idea what the problem is.
Thanks a lot!

As mentioned before, you are going around with definitions that don't exist/that you shouldn't use.
First: Decide between client or bot and use the original handling, not somehow client2 etc.
Second: To use the commands, import from discord.ext import commands.
Third: Since you are now using client the commands have to be adapted. Also you don't use client.say or bot.say anymore, but ctx.send.
Fourth: You can't use multiple on_ready events, combine them or just use one.
Fifth: Please have a look at the mute command as yours contained many errors and requested things in the wrong way. You can take a look at other StackOverflow questions and answers as just copy and pasting another answer is not really useful...
Have a look at the full/final code:
from discord.utils import get # New import
import discord
from discord.ext import commands # New import
client = commands.Bot(command_prefix = 'YourPrefixHere') # Changes
TOKEN = "YourTokenHere" # Changes
#client.event
async def on_ready():
print(f'{client.user.name} has connected to Discord!')
#client.command()
async def mute(ctx, member: discord.Member):
if ctx.message.author.guild_permissions.administrator or ctx.message.author.id == 'Your_ID': # Changes
role = discord.utils.get(ctx.guild.roles, name='Muted') # Changes
await member.add_roles(role)
embed = discord.Embed(title="User Muted!",
description="**{}** was muted by **{}**!".format(member, ctx.message.author),
color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
client.run(TOKEN) # Changes

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

Can't run a join function because of a on_message event

i'm making a discord bot with python. I have some issues about running using #client.command and #client.event at the same time.
Here is the code:
when I comment the #client.event before the on message function, the join command run. This function cause a particular issue, do you know guys where it can come from? Thank you guys
import discord
import random
from discord.utils import get
from discord.ext import commands
#client.command(pass_context=True)
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
#client.command(pass_context=True)
async def leave(ctx):
await ctx.voice_client.disconnect()
#client.event
async def on_ready():
print("We have logged as {0.user}".format(client))
#client.event
async def on_message(message):
user = message.author.id
if message.content.lower() == "!poisson":
await message.delete()
with open('myimage.png', 'rb') as f:
picture = discord.File(f)
await message.channel.send(file=picture)
Put await client.process_commands(message) at the end of on_message()
If you're using on_message, then normal commands will be overridden unless you use process_commands.

How to I make a my discord bot join a voice channel *in a category*?

I'd like to write a bot with the ability to join; This is my code
import json
import discord
from discord.ext import commands
JSON_FILE = r"C:\JSON PATH"
bot = commands.Bot(command_prefix = "~")
with open(JSON_FILE, "r") as json_file:
TOKEN = json.load(json_file)["token"]
GUILD = json.load(json_file)["guild"]
bot = commands.Bot(command_prefix = "~")
#bot.event
async def on_ready():
print(f"{bot.user.name} launched and has arrived for further use")
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
await voice_channel.connect()
await ctx.send(f"I have joined: {voice_channel}")
#bot.command(name = "leave")
async def leave(ctx):
server = ctx.message.server
voice_client = bot.voice_client_int(server)
await voice_client.disconnect()
bot.run(TOKEN)
It can join usual channels but it cannot join channels in categories. Any advice on how to do that?
Thank you in advance
The problem is probably, that you are using an outdated version of discord.py since you are using server, which is deprecated since v1.0, and not guild. If you update it, it will probably work, because it worked for me too when I tried it.
To code it to automatically join the voice channel of the user executing the command, just use ctx.author.voice.channel:
#bot.command(name = "join")
async def join(ctx, voice_channel: commands.VoiceChannelConverter):
if not ctx.author.voice is None:
await ctx.author.voice.channel.connect()
await ctx.send(f"I have joined your voice channel.")
else:
await ctx.send("You are not in a voice channel!")
References:
discord.Member.voice
Server is deprecated

How to find users with a specific role in discord.py

I am trying to make a discord bot that finds users with a specific role so it can do something with this group of users. I have written code to list all of the members in a server but I don't think this will help.
import discord
#some code
client = discord.Client()
#some code
client.run("my token")
You can use the following, use it like this $get_members ROLENAME
ref for commands
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
#bot.event
async def on_ready():
print("Logged in as")
print(bot.user.name)
print("------")
#bot.command()
async def get_members(ctx,role_name):
role = discord.utils.find(
lambda r: r.name == role_name, ctx.guild.roles)
for user in ctx.guild.members:
if role in user.roles:
await ctx.send(f"{user.mention} has the role {role.mention}")
bot.run("TOKEN")

Discord.py - Previous function affects the next function

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.

Categories