Iv been working on this bot which when you type "/court #user time" it will give them the role jail
and after the given amount of time it will remove it but when i run it it doesn't work and it says:
"discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined"
import discord
from discord.ext import commands
import ctx
import re
import time
from time import sleep
PREFIX = "$"
bot = commands.Bot(command_prefix=PREFIX, description="Hi")
#bot.event
async def on_ready():
print('Logged on as', bot.user)
channel = bot.get_channel(717005397655027805)
#await channel.send("I am now online")
activity = discord.Game(name="eb!help", type=3)
await bot.change_presence(status=discord.Status.online, activity=activity)
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned, time):
messageContent = message.content
if len(messageContent) > 0:
if re.search("^send.*court$", messageContent):
user_id = message.mentions[0].id
user = message.mentions[0]
await message.channel.send(
f"sending <#{user_id}> to court!"
)
role = discord.utils.get(message.guild.roles, name="Jail")
await user.add_roles(role)
sleep(time)
await bot.remove_roles(user, role)
bot.run('TOKEN_GOES_HERE')
The error message is pretty clear,
messageContent = message.content.
message isn't defined in the scope here.
We can get the message with ctx.message
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned, time):
message = ctx.message
messageContent = message.content
Doing this will work fine, but you're entirely misusing ext.commands here.
You could do
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned: discord.Member, time: int):
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
time.sleep is blocking and bot doesn't have the attribute remove_roles, please refer to the docs for information.
#ceres here's the court command code:
bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user_mentioned: discord.Member, time: int):
print("test")
user_id = message.mentions[0].id
user = message.mentions[0]
role = discord.utils.get(message.guild.roles, name="Jail")
await user_mentioned.add_roles(role)
await ctx.send(
f"sending <#{user_id}> to court!"
)
await asyncio.sleep(time)
await user_mentioned.remove_roles(role)
You can get message's content by typing ctx.message.content but you don't need it. If you describe the parameter as discord.Member, it will return a member object if it founds else bot will raise commands.BadArgument. Also you should use asyncio.sleep for async sleep. This will not block your bot's other commands.
import asyncio
#bot.command(name='court')
#commands.has_role('Server Developer')
async def court(ctx, user: discord.Member, time: int):
role = discord.utils.get(message.guild.roles, name="Jail")
if role is not None:
await ctx.send(
f"sending {user.mention} to court!"
)
await user.add_roles(role)
await asyncio.sleep(time)
await user.remove_roles(role)
else:
await ctx.send("Role `Jail` is not exist.")
bot.run('TOKEN')
Related
So basically I have this problem, any command that I type does not work. There are no errors, and everything else is working fine. It's just that for some reasons #bot.command() isn't working, and that is kind of annoying.
import discord
from discord.utils import get
from discord.ext import commands
import time
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = '$', intents=intents)
TOKEN = 'hi'
ROLE = 'hi'
db1 = [hi, hi]
#bot.command()
async def test(ctx, arg):
await ctx.send(arg)
await bot.process_commands(arg)
#bot.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
await member.send('hi')
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Welcome <#{}> in {} ".format(str(member.id),str(member.guild)), description="hi", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_member_remove(member):
try:
channel = member.guild.system_channel
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
except:
channel = member.guild.get_channel(hi)
embedVar = discord.Embed(title="Bye {} from {} ".format(str(member.name),str(member.guild)), description="Come back when you want", color=0x00ff00)
await channel.send(embed=embedVar)
#bot.event
async def on_invite_create(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been created, {}, by <#{}> on {}".format(str(invite.url), str(invite.inviter.id), str(invite.created_at)))
#bot.event
async def on_invite_delete(invite):
channel = bot.get_channel(hi)
await channel.send("An invite has been deleted by{}".format(str(invite.inviter.id)))
#bot.event
async def on_member_ban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Ban", description="Ban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_member_unban(guild, member):
channel = bot.get_channel(hi)
embedVar = discord.Embed(title="Unban", description="Unban requested on<#{}>".format(str(member.id)))
await channel.send(embed=embedVar)
#bot.event
async def on_ready():
print(f'{bot.user} succesfully logged in')
return
#bot.event
async def on_message(message):
if message.content.startswith('purge requested by'):
time.sleep(1)
await message.delete()
if message.author == bot:
return
if message.content == 'hi':
await message.channel.send('hi')
if message.content.startswith('binvites'):
totalInvites = 0
for i in await message.guild.invites():
if i.inviter == message.author:
totalInvites += i.uses
await message.channel.send(f"You have invited {totalInvites} member{'' if totalInvites == 1 else 's'} to the Central Trade server")
if message.content == 'bpurge':
if message.author.id in db1:
await message.channel.purge(limit=10)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
else:
return
if message.content == 'block':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = False
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Lock", description="Channel lock request by <#{}>".format(str(message.author.id)), color= 0x00FFFF)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'bunlock':
if message.author.id in db1:
channel = message.channel
overwrite = channel.overwrites_for(message.guild.default_role)
overwrite.send_messages = True
await channel.set_permissions(message.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title="Unlock", description="Channel unlock request by <#{}>".format(str(message.author.id)), color=0xC0C0C0)
await message.channel.send(embed=embedVar)
else:
await message.author.send('You do not have the permission to use this command')
if message.content == 'test':
embedVar = discord.Embed(title="test", description="test", color=0x00ff00)
embedVar.add_field(name="test", value="test", inline=False)
embedVar.add_field(name="test", value="test", inline=False)
await message.channel.send(embed=embedVar)
if message.content == 'bpurges':
if message.author.id in db1:
await message.channel.purge(limit=10000)
await message.channel.send('purge requested by <#{}>'.format(str(message.author.id)))
embedVar = discord.Embed(title="Purge", description="Purge requested by<#{}>".format(str(message.author.id)))
await message.channel.send(embed=embedVar)
time.sleep(1)
await message.channel.delete()
bot.run(TOKEN)
Anyone has an idea why it's not working ? Also seems like i need to post more details, don't pay attention to this : Roméo et Juliette (Romeo and Juliet) est une tragédie de William Shakespeare.
I keep getting this error. Everything is imported right and everything is installed. The code was working in atom and then all of a sudden I get this error. Everything works in pycharm. Same error in vscode.
File "c:\Python\Python Tutorial\Discord Bot\Discord_Bot.py", line 5,
in client = commands.Bot(command_prefix = ",")
AttributeError: module 'discord.ext.commands' has no attribute 'Bot'
import discord
from discord.ext import commands
import random
client = commands.Bot(command_prefix = ",")
def bot():
print("hey im here")
#client.event
async def on_ready():
bot()
# Ping Command
#client.command(aliases=["p"])
async def ping(ctx):
await ctx.send("pong")
#8 Ball Game
#client.command(aliases=["8ball"])
async def eightball(ctx, *, question):
responses = ["It is certain.",
"It is decidedly so.",
"Without a doubt.",
"Yes - definitely.",
"You may rely on it.",
"As I see it, yes.",
"Most likely.",
"Outlook good.",
"Yes.",
"Signs point to yes.",
"Reply hazy, try again.",
"Ask again later.",
"Better not tell you now.",
"Cannot predict now.",
"Concentrate and ask again.",
"Don't count on it.",
"My reply is no.",
"My sources say no.",
"Outlook not so good.",
"Very doubtful."]
await ctx.send(f" :8ball: Question: {question} \n:8ball: Answer: {random.choice(responses)}")
#Kick Command
#client.command()
async def kick(ctx, member:discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f"{member.mention} Kicked! See You Later Alligator :knife: :dizzy_face: :skull: :ambulance: ")
#Ban Command
#client.command()
async def ban(ctx, member:discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f"{member.mention} Banned! Say Your Goodbyes :ghost: :skull: :coffin: :headstone:")
#Unban Command
#client.command()
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if(user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"{user.mention} Came Back To Life :zombie: ")
return
#Clear Messages Command
#client.command()
async def clear(ctx, amount = 11):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.send("ha ha you thought. need permissions baby")
return
amount+=1
if amount > 101:
await ctx.send("cant delete more than 100")
else:
await ctx.channel.purge(limit = amount)
await ctx.send("asta la vista messages")
#client.command()
async def mute(ctx, member: discord.Member, *, reason=None):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.send("ha ha you thought. need permissions baby")
return
guild=ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
if not muteRole:
muteRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(muteRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(muteRole, reason=reason)
await ctx.send(f"ive shut {member.mention} up")
await member.send(f"**The Great One** has muted you from: **{guild.name}** | Reason: **{reason}**")
#client.command()
async def unmute(ctx, member: discord.Member, *, reason=None):
if (not ctx.author.guild_permissions.manage_messages):
await ctx.send("ha ha you thought. need permissions baby")
return
guild = ctx.guild
muteRole = discord.utils.get(guild.roles, name="Muted")
if not muteRole:
await ctx.send(f"{member.mention} you may speak")
return
await member.remove_roles(muteRole, reason=reason)
await ctx.send(f"you may speak {member.mention} ")
await member.send(f"**The Great One** is sorry for muting you from **{guild.name}** | Reason: **{reason}**")
i had to reset my computer because of wifi troubles and reinstalled everything and that fixed it
at 4. and 5. lines i need help.it doesn't send embed.
#Bot.command()
#has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member=None, reason=None):
if member == None or member == ctx.message.author:
embed1 = discord.Embed(title="ERROR:", description="You can not ban yourself.", color=0x00ff00)
await ctx.send(embed=embed1)
return
if reason == None:
reason = 'Nothing.'
await ctx.guild.ban(member, reason=reason)
await ctx.channel.send(f"{ctx.message.author} banned {member} from server. Reason:{reason}")```
await ctx.guild.ban(member, reason=reason)
Expects a user to ban, not a member.
Try
await member.ban(reason=reason)
like documented here.
#Bot.command()
#has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member=None, reason=None):
if member == None or member == ctx.message.author:
embed1 = discord.Embed(title="ERROR:", description="You can not ban yourself.", color=0x00ff00)
await ctx.send(embed=embed1)
return
if reason == None:
reason = 'Nothing.'
await member.ban(reason=reason)
await ctx.channel.send(f"{ctx.message.author} banned {member} from server. Reason:{reason}")
I am trying to add roles in discord.py but I can't really make it work.
#bot.command(brief="Report member")
async def member(ctx):
if ctx.author.id != 783430063076147210:
await ctx.send("Mention the member you want to report")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
msg = message.content.replace("<","")
msg = msg.replace(">","")
msg = msg.replace("#","")
msg = msg.replace("!","")
#try:
msg = int(msg)
user = bot.get_user(msg)
await ctx.send('Are you sure you want to report ' + user.mention + "?")
message = await bot.wait_for('message', check=lambda message: ctx.author == ctx.author)
if message.content.lower() == "yes" or message.content.lower() == "y":
member = ctx.message.author
role = get(member.guild.roles, name="Reported")
user = ctx.guild.get_member(msg)
await bot.add_roles(user, role)
await ctx.send(user.mention + " was reported by " + member.mention + ".")
else:
await ctx.send("User was not reported!")
#except:
await ctx.send("Oops! That was not a user!")
I'm getting an AttributeError: 'Bot' object has no attribute 'add_roles', and the same with the other way
await user.add_roles(role)
returns AttributeError: 'NoneType' object has no attribute 'add_roles'
Is there something I'm missing?
Two ways of making this work:
1.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role:commands.RoleConverter):
await member.add_roles(role)
^^ This method uses a role converter that accepts role ID, name, or mention.
I also use commands.MemberConverter because it accepts more methods of referencing a user than discord.Member, and the same thing for discord.Role.
2.
#bot.command()
async def role(ctx, member:commands.MemberConverter, role):
role = discord.utils.get(ctx.guild.roles, name=role)
await member.add_roles(role)
^^ This method uses discord.utils.get to get a guild role. From my knowledge, it only accepts role names and not role IDs or mentions.
bot.get_user() will return a User object, to which you cannot add roles, as no guild is specified. You could do ctx.guild.get_member(id) to get the Member object then add roles to that, but you'd be better of getting the member from the mentions attribute of a Message. Docs: https://discordpy.readthedocs.io/en/latest/api.html?highlight=mentions#discord.Message.mentions
Try something like this:
#bot.command()
async def role(ctx):
test = ctx.author
role = discord.utils.get(test.guild.roles, name="Name")
if role in test.roles:
await ctx.send("you already have a role")
else:
await test.add_roles(role)
Your line
await bot.add_roles(user, role)
needs to be replaced by
await user.add_roles(role)
these are my addrole and remouverole commands:
#bot.command()
#commands.has_permissions(administrator=True)
async def addrole(ctx, member : discord.Member, role : discord.Role):
await member.add_roles(role)
await ctx.send(f"{role} is added to {member}.")
#bot.command()
#commands.has_permissions(administrator=True)
async def removerole(ctx, member : discord.Member, role : discord.Role):
await member.remove_roles(role)
await ctx.send(f"{role} is removed from {member}.")
okay I know for the past few days this is all I have been posting about but I am curious on why my on_message command works for a few times then it stops all of a sudden here I will show you my code:
import discord
from discord.ext import commands
from discord.utils import get
client = discord.Client()
client = commands.Bot(command_prefix=None)
#client.event
async def on_ready():
print("ready!")
#client.event
async def on_message(message):
if message.content.startswith('<:SF1:763564017456644116> sign'):
role = get(message.guild.roles, name='San Francisco 49ers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:SF1:763564017456644116>')
#client.event
async def on_message(message):
if message.content.startswith('<:ATL1:763564014344208414> sign'):
role = get(message.guild.roles, name='Atlanta Falcons')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:ATL1:763564014344208414>')
#client.event
async def on_message(message):
if message.content.startswith('<:CAR1:763564014478819378> sign'):
role = get(message.guild.roles, name='Carolina Panthers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:CAR1:763564014478819378>')
#client.event
async def on_message(message):
if message.content.startswith('<:DAL1:763564014843592714> sign'):
role = get(message.guild.roles, name='Dallas Cowboys')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DAL1:763564014843592714>')
#client.event
async def on_message(message):
if message.content.startswith('<:DET1:763564015057764362> sign'):
role = get(message.guild.roles, name='Detroit Lions')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DET1:763564015057764362>')
client.run('TOKEN')
so this is what is happening in picture form:
here is the first time I tested:
and the second time I test it:
can someone please help explain to me what I am doing incorrectly so I can fix it?
You can just put them all in 1 on_message instead of separating them like that.
#client.event
async def on_message(message):
if message.content.startswith('<:SF1:763564017456644116> sign'):
role = get(message.guild.roles, name='San Francisco 49ers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:SF1:763564017456644116>')
if message.content.startswith('<:ATL1:763564014344208414> sign'):
role = get(message.guild.roles, name='Atlanta Falcons')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:ATL1:763564014344208414>')
if message.content.startswith('<:CAR1:763564014478819378> sign'):
role = get(message.guild.roles, name='Carolina Panthers')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:CAR1:763564014478819378>')
if message.content.startswith('<:DAL1:763564014843592714> sign'):
role = get(message.guild.roles, name='Dallas Cowboys')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DAL1:763564014843592714>')
if message.content.startswith('<:DET1:763564015057764362> sign'):
role = get(message.guild.roles, name='Detroit Lions')
member = message.mentions[0]
await member.add_roles(role)
await message.channel.send(f'{member.mention} **Successfully signed to** <:DET1:763564015057764362>')
you could also put the await client.process_commands(message) at the end of each event
Docs: process_commands