i'm trying to make a user mute command and event i’ve got the command working but now the event is preventing any and all commands from working only events respond now even if user is not muted, but when user does have muted role their messages are properly deleted, please help
#bot.event
async def on_message(message):
user = message.author
channel = bot.get_channel(1060922421491793981)
role = discord.utils.get(user.guild.roles, id=1060693595964842165)
if role in message.author.roles:
await message.delete()
await channel.send(f"#{user.display_name} **You are muted, You cant do this right now**")
command arguments are always strings, except the first argument ctx which is the context. What you can do in this case is derive the user from the mention in the ctx which you can get from ctx.message.mentions, so in this case you can make something like this.
#bot.command()
async def mute(ctx, user: str, duration_arg: str = "0", unit: str = "m"):
duration = int(duration_arg)
role = discord.utils.get(ctx.message.guild.roles, id=1060693595964842165)
await ctx.send(f":white_check_mark: Muted {user} for {duration}{unit}")
await ctx.message.mentions[0].add_roles(role)
if unit == "s":
wait = 1 * duration
await asyncio.sleep(wait)
elif unit == "m":
wait = 60 * duration
await asyncio.sleep(wait)
await user.remove_roles(role)
await ctx.send(f":white_check_mark: {user} was unmuted")
#bot.event
#commands.has_role("Muted")
async def on_message(message):
role = discord.utils.get(message.guild.roles, name="Muted")
if role in message.author.roles:
await message.delete()
await ctx.send("You cant do this")
await bot.process_commands(message)
Also two notes:
try not to write the type in the variable name. We know that the roleobject is an object, as everything in python is an object. Using role is sufficient enough.
You might not want to wait during an async function for something like this. Instead I suggest you look into tasks, and have some sort of mechanism that stores who is currently muted, in case the bot gets turned off
found the error was missing a process line
await bot.process_commands(message)
event now works
Related
I need help making a afk command for my discord server. When the afk command is triggered, my bot doesn't respond with a reasoning when you ping the person whos afk. Also, when you return from being afk and type, the bot doesn't send a message saying "(user) is no longer afk". Please help me and tell me what i'm doing wrong and how can I fix this?
afkdict = {User: "their reason"} # somewhere in the code
#bot.command("afk")
async def afk(ctx, reason=None):
afkdict[ctx.user] = reason
await ctx.send("You are now afk. Beware of the real world!")
#bot.event
async def on_message(message):
afkdict = {user: "their reason"}
# some other checks here
for user, reason in afkdict.items():
if user in message.mentions:
if reason is None:
reason = ""
embed = discord.Embed(title=f"{user} is AFK", color=0xFF0000, description=reason[:2500])
await message.reply()
I was expecting this to work, the way dyno works. When i ran the command i got a message back saying user has no context. I dont know what to do anymore.
I think there's a couple of issues. Firstly, you are redefining afkdict in your on_message function it doesn't matter that you're adding users to it in the afk command. Secondly, when you're doing await message.reply(), you're not actually sending the created embed along with it.
I've resolved those problems and changed the logic slightly. Instead of iterating over the users in the afk_dict and checking if they're mentioned, we're iterating over the mentions and seeing if they're in the afk_dict. I'm also using user.id rather user objects as keys.
# defined somewhere
afk_dict = {}
#bot.command()
async def afk(ctx, reason=None):
afk_dict[ctx.user.id] = reason
await ctx.send("You are now afk. Beware of the real world!")
#bot.event
async def on_message(message):
# do whatever else you're doing here
for user in message.mentions:
if user.id not in afk_dict:
continue
# mentioned used is "afk"
reason = afk_dict[user.id] or ""
embed = discord.Embed(title=f"{user.mention} is AFK", color=0xFF0000, description=reason[:2500])
await message.reply(embed=embed)
It looks like you are missing some pieces in your code. Here is an updated version of the code:
afkdict = {}
#bot.command("afk")
async def afk(ctx, reason=None):
user = ctx.message.author
afkdict[user] = reason
await ctx.send(f"You are now AFK. {'Reason: ' + reason if reason else ''}")
#bot.event
async def on_message(message):
for user, reason in afkdict.items():
if user in message.mentions:
if reason is None:
reason = ""
embed = discord.Embed(title=f"{user} is AFK", color=0xFF0000, description=reason[:2500])
await message.channel.send(embed=embed)
if message.author in afkdict:
afkdict.pop(message.author)
await message.channel.send(f"{message.author} is no longer AFK")
In this code, the afk command will add the user who runs the command to the afkdict dictionary along with the reason for being AFK. The on_message event handler will then check if any of the mentioned users are in the afkdict and if so, it will send an embed with the AFK status and reason. Finally, if the author of the message is in the afkdict, it will remove them from the dictionary and send a message indicating that they are no longer AFK.
I am triying to develop a game using a discord bot. Im having trouble dealing with the onmessage routine.. I need it only to "listen" one specific channel, not all the server.. by now I did the following:
#client.event
async def on_message(message):
global rojo
global IDS
canal = IDS['C_Juego']
if message.author == client.user or str(message.channel) != IDS['C_Juego']:
return
else:
if(rojo == 1):
autor = message.author
await message.add_reaction("🔴")
await message.channel.send("Player: " + str(autor) + " removed!")
role = get(message.guild.roles, name="Jugador")
await message.author.remove_roles(role)
elif(str(message.channel) == IDS['C_Juego']):
await message.add_reaction("🟢")
print("verde")
What's going on? when I enable this function .. the rest of my commands stop having effect (in any channel of the server) in addition to the fact that this function is called by each message sent....
I explain the context: It is a game in which while listening to a song the players must place different words under a theme, when the music stops, if someone writes they are eliminated.
Commands definitios:
I have plenty command definitios... which works fine until I add this problematic function.. I add as example two of them:
#client.command()
#commands.has_role("Owner")
async def clear(ctx):
await ctx.channel.purge()
#client.command()
#commands.has_role("Owner")
async def swipe(ctx, role: discord.Role):
print(role.members)
for member in role.members:
await member.remove_roles(role)
await ctx.send(f"Successfully removed all members from {role.mention}.")
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message.
#client.event
async def on_message(message):
# do what you want to do here
await client.process_commands(message)
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working
So I'm trying to create a discord.py bot, I'm using on_reaction_add to run the bot but it isn't working. When I run the script nothing happens, no error messages no nothing and I'm confused about what to do.
This is the whole code:
from discord.ext import commands
from discord import utils
bot = commands.Bot(command_prefix='!"')
#bot.command(name = '!"Help Ban', help = 'Bans a user')
#bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching,
name='for !"help'))
print('We have logged in as {0.user}'.format(bot))
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message
if message.message_id == **CHANNEL NUMBER**:
member = utils.get(message.guild.members, id=message.user_id)
channel = bot.get_channel(**CHANNEL NUMBER**)
message.channel.send(f'#here, {member} wants to do parole')
#bot.event
async def on_message(message):
if '!"Ban' or '!"ban' in message.content:
run = True
if discord.utils.get(message.author.roles, name="Lord Jeebus") or discord.utils.get(message.author.roles, name="Supreme Lord Jeebus"):
messageTrue = message.content
messageTrue = messageTrue.split(' ')
Player = messageTrue[1]
Original = Player
Player = Player.replace('<', '')
Player = Player.replace('>', '')
Player = Player.replace(',', '')
userID = Player.replace('#', '')
userID = userID.replace('!', '')
member = await message.guild.fetch_member(userID)
banned_role = discord.utils.get(member.guild.roles, name="Death Row")
try:
reason = messageTrue[2]
await member.guild.ban(member, reason=reason)
await member.edit(roles=[])
await member.add_roles(banned_role)
await message.channel.send(f'{Original} now has 2 minutes before they are banned')
timer = 120
while timer != 0:
time.sleep(1)
timer -= 1
await message.channel.send(f'{Original} has been banned')
await member.ban(reason=reason)
except:
await message.channel.send(f'Could not ban user as no reason was given')
await bot.process_commands(message)
bot.run('TOKEN')
And this is the bit I'm stuck on:
#bot.event
async def on_reaction_add(reaction, user):
message = reaction.message
if message.message_id == **CHANNEL NUMBER**:
member = utils.get(message.guild.members, id=message.user_id)
channel = bot.get_channel(**CHANNEL NUMBER**)
message.channel.send(f'#here, {member} wants to do parole')
This code should be saying #here, Member wants to do parole it is supposed to do that in a private channel that is has access to but nothing is coming up, even in the command console.
Your code contains many errors and some wrong thinking. If you are new to Python/Reactions, then I would recommend tutorials or the Docs.
Many things in your code are also redundant.
First) message.message_id is wrong. You always query the ID of a channel, server etc. with .id and not with _id
Second) You don't need to query member at all. You have user as an argument and don't use it, that makes no sense. Accordingly, this line is also omitted.
Third) If you want to give the bot an instruction to send a message to the corresponding channel, you always have to do this with an await, this is completely missing in your code. You define channel but tell it to send the message in message.channel, so the bot has TWO specifications
The new code:
#bot.event
async def on_reaction_add(reaction, user):
if reaction.message.channel.id == PutYourChannelIDHere: # Check if the reaction is in the correct channel
channel = bot.get_channel(PutYourChannelIDHere) # Define your channel
await channel.send(f'#here, {user} wants to do parole') # Send it to the CHANNEL
The output:
I made a working AFK code, but i need it to slice (delete) '[AFK]' if the user sends a message. The code is:
#client.command()
async def afk(ctx, *, message="Dind't specify a message."):
global afk_dict
if ctx.author in afk_dict:
afkdict.pop(ctx.author)
await ctx.send('Welcome back! You are no longer afk.')
await ctx.author.edit(nick=ctx.author.display_name(slice[-6]))
else:
afk_dict[ctx.author] = message
await ctx.author.edit(nick=f'[AFK] {ctx.author.display_name}')
await ctx.send(f"{ctx.author.mention}, You're now AFK.")
I got no errors. i only need await ctx.author.edit(nick=ctx.author.display_name(slice[-6])) to be working and i'll be happy.
You need to have a on_message event. Something like this should work.
#client.event
async def on_message(message):
if message.author in afk_dict.keys():
afk_dict.pop(message.author.id, None)
nick = message.author.display_name.split('[AFK]')[1].strip()
await message.author.edit(nick=nick)
I also recomend you to store user id's instead of usernames.
To do that you just have to use member.id instead of member.
I am trying to add a role to someone but when I do the
client.add_roles(member, role)
I have tried everything I could think of with the code it just gives me that message, I have looked at several other questions around looking for the answer but everyone says to do that command that I have tried but it wont work.
#client.command(pass_context=True)
#commands.has_role('Unverified')
async def verify(ctx, nickname):
gmember = ctx.message.author #This is the looking for the memeber
role = discord.utils.get(gmember.server.roles, name='Guild Member')
channel = client.get_channel(401160140864094209)
await gmember.edit(nick=f"{nickname}")
await ctx.channel.purge(limit=1)
r = requests.get("This is the link to the API but it shows my key and everything so not going to put it here but it works in other commands")
#if nickname in role:
# await ctx.send(f"You have already verified your account.")
if nickname.encode() in r.content:
await channel.send(f'#here ``{nickname}`` is in the guild.')
await client.add_roles(gmember, role)
else:
await gmember.kick()
Instance of Bot has no add_roles member pylint (no-member)
await gmember.add_roles(role)
You can read more here