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.
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 would like my bot to be able to reply to a mention of a specific user (ex.. one person mentions my personal account and the bot responds saying that I'm currently not here)
Is there a way to do this using a format similar to this?
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('#user_id'):
await message.channel.send('Im not here leave a message!')
You would need to use the specific format that discord bots receive mentions. The format is <#!user_id>.
#client.event
async def on_message(message):
if ("<#!put user id here>" in message.content):
await message.channel.send("Im not here leave a message!")
Example for how applied this and it worked for me
#client.event
async def on_message(message):
if ("<#!348256959671173120>" in message.content):
await message.channel.send("Im not here leave a message!")
Discord Member objects have a .mentioned_in(message) method.
WIZARD_ID = 123456 # <- replace with user ID you want
async def on_message(message):
wizard_of_oz = message.guild.get_member(WIZARD_ID)
if wizard_of_oz.mentioned_in(message):
await message.channel.send("Who dares summon the great Wizard of OZ?!")
If you also want to condition on if the user is mentioned by role you need to check the role_mentions in the message, too. So a more complete example is as follows:
def was_mentioned_in(message: discord.Message, member: discord.Member) -> bool:
"""
Whether or not the member (or a role the member has) was mentioned in a message.
"""
if member.mentioned_in(message):
return True
for role in message.role_mentions:
if role in member.roles:
return True
return False
#client.event
async def on_message(message):
wizard_of_oz = message.guild.get_member(WIZARD_ID)
if was_mentioned_in(message, wizard_of_oz):
await message.channel.send("Who dares summon the great Wizard of OZ?!")
I'm currently trying to make a bot in Discord using python (something almost brand new for me). I was trying to make an AFK function (similar to Dyno's). This is my code:
afkdict = {}
#client.command(name = "afk", brief = "Away From Keyboard",
description = "I'll give you the afk status and if someone pings you before you come back, I'll tell "
"them that you are not available. You can add your own afk message!")
async def afk(ctx, message = "They didn't leave a message!"):
global afkdict
if ctx.message.author in afkdict:
afkdict.pop(ctx.message.author)
await ctx.send('Welcome back! You are no longer afk.')
else:
afkdict[ctx.message.author] = message
await ctx.send("You are now afk. Beware of the real world!")
#client.event
async def on_message(message):
global afkdict
for member in message.mentions:
if member != message.author:
if member in afkdict:
afkmsg = afkdict[member]
await message.channel.send(f"Oh noes! {member} is afk. {afkmsg}")
await client.process_commands(message)
My issue here is that the user that uses this function will be AFK until they write again >afk. My intention was to make the bot able to remove the AFK status whenever the user talked again in the server, regardless they used a bot function or not. I know it's possible because other bots do so, but I'm lost and can't think of a way to do so.
Thanks in advance!
async def on_message(message):
global afkdict
if message.author in afkdict:
afkdict.pop(message.author)
for member in message.mentions:
if member != message.author:
if member in afkdict:
afkmsg = afkdict[member]
await message.channel.send(f"Oh noes! {member} is afk. {afkmsg}")
await client.process_commands(message)
I think that should do it, but you could as well pass the ctx again or save ctx as an parameter to access.
But this version does not notify the user, that they are not afk anymore
I am trying to code a command into my Discord Bot that when triggered will actively delete new messages from a specific user.
I have tried a couple variations of using ctx but I honestly I don't entirely understand how I could use it to accomplish this.
This block of code deletes the message that triggers it. Because of this, I think I am taking the wrong approach because it only deletes from whoever triggers it and only if they type the command. Obviously, I am new to this. I would appreciate any and all help. Thanks so much :)
#client.event
async def on_message(ctx):
message_author = ctx.author.id
if message_author == XXXXXXXXXXXXXXXXX:
await ctx.message.delete()
There is no more CTX in discord rewrite (DiscordPy 1.0+) instead you should do:
#client.event
async def on_message(message):
if message.author.id == XXXXXXXXXXXXXXXXX:
await message.delete()
Source: link
You can make a command to add the users to a list then use on_message to check if a user is in that list and then delete it if true
dels=[]
#bot.event
async def on_message(msg):
if msg.author.id in dels:
await bot.delete_message(msg)
await bot.process_commands(msg)
#bot.command(name='del_msg')
async def delete_message(con,*users:discord.Member):
for i in users:
dels.append(i.id)
await con.send("Users {} have been added to delete messages list".format(" ,".join(users)))
I have searched around a lot for this answer, and I haven't found it. I want to use a suggestion command, that whenever someone uses it to suggest an idea, it DMs me, and me only.
You'll have to use the send_message method. Prior to that, you have to find which User correspond to yourself.
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
# can be cached...
me = await client.get_user_info('MY_SNOWFLAKE_ID')
await client.send_message(me, "Hello!")
#client.event
async def on_message(message):
if message.content.startswith("#whatever you want it to be")
await client.send_message(message.author, "#The message")
Replace the hashtagged things with the words that you want it to be. eg.: #whatever you want it to be could be "!help". #The message could be "The commands are...".
discord.py v1.0.0+
Since v1.0.0 it's no longer client.send_message to send a message, instead you use send() of abc.Messageable which implements the following:
discord.TextChannel
discord.DMChannel
discord.GroupChannel
discord.User
discord.Member
commands.Context
Example
With bot.command() (recommended):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def suggest(ctx, *, text: str):
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here
With on_message:
from discord.ext import commands
bot = commands.Bot()
#bot.event
async def on_message(message: discord.Message):
if message.content.startswith("!suggest"):
text = message.content.replace("!suggest", "")
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here