discord py - message.mentions "else" makes nothing - python

I want to get the user that was mentioned in a message and send him a private message. That's working without problems, but now I want to add a message for the case, that the mentioned member is not on the same server.
I searched a lot and try now for over 3 hours to find a solution.
Showcase of the problem: https://youtu.be/PYZMVXYtxpE
Heres my code:
#bot.event
async def on_message(message):
if len(message.mentions) == 1:
membe1 = message.mentions[0].id
membe2 = bot.get_user(membe1)
guild = bot.get_guild(message.author.guild.id)
if guild.get_member(membe1) is not None:
await membe2.send(content=f"you was mentioned in the server chat")
else:
embed2 = discord.Embed(title=f"» :warning: | PING not possible", description=f"not possible")
await message.channel.send(content=f"{message.author.mention}", embed=embed)
await message.delete()
return
The first part is working without problems, but at the "else" part, does the bot nothing. He still posts the message with the "invalid" ping in the chat and just ignores it. What can I do to fix that?

There is an error of design in what you are trying to do.
In Discord, you are not able to mention a user if he is not on that same server, so what you are checking will never work at all, currently your code is pretty much checking if the mentioned user exists, which will always happen unless he leaves the guild at the same time the command is executed.
Say for example, to make your command work you want to mention the user user123, who is in your server, you do the following:
#user123 blablabla
And that works because Discord internal cache can find user123 in your server and it is mentioned, which means that clicking on "#user123" will show us a target with his avatar, his roles or whatsoever.
But if you try to do the same for an invalid user, let's say notuser321:
#notuser321 blablabla
This is not a mention, take for example that you know who notuser321 is but he is in the same server as the bot is. Discord cannot retrieve this user from the cache and it is not considered a mention, just a single string, so not a single part of your code will be triggered, because len(message.mentions) will be 0.
Something that you could try would be using regular expressions to find an attempt to tag within message.content. An example would be something like this:
import re
message = "I love #user1 and #user2"
mention_attempt = re.findall(r'[#]\S*', message) # ['#user1', '#user2']

Related

Disabling a discord bot for a set time using a command in Discord.py

I've been trying to figure this out for a little while, but given that I'm mostly just slapping other people's code together and trying to troubleshoot what goes wrong, I lack a lot of the knowledge needed to do this.
I'm trying to make a bot that, when someone in the server uses the word "the" in any context (even without the bot's prefix), it corrects them with "da" (this is a running joke, please don't roast me for it lmfao). With what it does, it can be annoying - so I'd like to have people be able to disable it for something like 5 minutes at a time, and have it not send messages. The problem is, I have so little experience with python that I'm basically just guessing here. How would I go about making a command that, when triggered, would keep the bot from sending messages for a set amount of time?
Right now, the way that it's sending messages is by checking if the message contains "the", so would it be possible to have it also check something like if a boolean is true before sending?
Here's the main block of code that's responsible for the sending. I am aware that it's probably suboptimal, and if you're so inclined, feel free to explain to me how I could make it better!
#client.event
async def on_message(message):
if message.author == client.user:
return
if ('the') in message.content:
await message.channel.send('i think you meant da :rolling_eyes:')
Thanks!
(Also, is there any way that I would be able to only have it respond if "the" is by itself, and not in a word? I tried just making it have spaces before and after, but that didn't work if a message started or ended with it. I figured this probably didn't warrant its own post, since I'm probably just stupid lmao)
You can use a global variable to store a value and edit it from different places
correct_the = True
#client.event
async def on_message(message):
global correct_the
if message.author == client.user:
return
words = message.content.lower().split(" ") # make a list of all words
# like this -> ["the", "dogs", "and", "cats"]
if 'the' in words:
if correct_the: # check if it should correct it
await message.channel.send('i think you meant da :rolling_eyes:')
if message.content.startswith("!disable"): # or make this as command if you use commands.Bot
if not correct_the:
print("already disabled")
else:
correct_the = False
await asyncio.sleep(5*60) # sleeps 5min
correct_the = True

Bot responding to channel mentions

I've been trying to develop a discord bot in python recently. I made it so that if a message contains a certain number, it will react and send a message. Here is the code in the cog file:
import discord
from discord.ext import commands
nice_numbers = ['69', '420']
class Auto(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_message(self, message):
msg = message.content
if message.author == self.client.user:
return
if any (word in msg for word in nice_numbers):
await message.add_reaction('👌')
await message.channel.send(f'lmao nice')
def setup(client):
client.add_cog(Auto(client))
The problem is, the bot also responds with the same message and reaction when a user mentions a certain channel (in this case #general, #super-private-testing, and #resources). I can't seem to fix it or figure out why it's happening. I'm still pretty new to python so can someone please tell me what I'm doing wrong?
Basically what is happening is that mentions have a special syntax within the Discord API where they are basically a bunch of numbers put together.
For example when you are mentioning another user like the following:
Hello #User1234!
The real syntax within the discord message is the following:
Hello <#125342019199458000>!
And in the case of mentioning channels, it works similar, as a channel mentioned like:
#general
Internally would be written as:
<#550012071928922144>
Of course, the problem is that within this big number there could be false positive of finding your nice_numbers. There could be different ways to avoid this, for example you could check if a channel or a user is being mentioned in the message and return in that case.
if message.channel_mentions or message.mentions:
return
I think a better solution would be to changing the way you are checking if the nice_numbers are within message.content.
Using if word in msg would return true if message.content also includes something like 'My favourite number is 45669'. To overcome this issue it is better to make use of regular expressions.
You can declare a new function like this answers explains, which would return a <match object> if what you pass as parameter is found.
It would be something like this:
import re
def findCoincidences(w):
return re.compile(r'\b({0})\b'.format(w)).search
findCoincidences('69')('I like 69') # -> return <match object>
findCoincidences('69')('My favourite number is 45669') # -> return None
Expanding on Shunya's answer, you can use message.clean_content instead of message.content:
A property that returns the content in a “cleaned up” manner. This basically means that mentions are transformed into the way the client shows it. e.g. <#id> will transform into #name.
This will also transform #everyone and #here mentions into non-mentions.
This will prevent you from inadvertently matching against the IDs of channels, users, roles, etc. Of course, if the actual name contains a nice_number, it'll still match.

Capturing user input as a string in Discord.py rewrite and returning said input in a message

I'm trying to capture a users input, what they say in a message, and have it returned to them in a message from the bot. More specifically, when they run a command, it'll return what ever text they have entered after that.
So far, I'm here:
async def on_message(message):
if message.content.startswith["=ok"]:
await client.send_message(message.channel, message.content[6:])
...unfortunately, I believe this was valid for the previous version of Discord.py before the rewrite. Essentially I want someone to be able to run the command =pressf and have the bot return the message "Everyone, lets pay respects to (string)!" An event probably isn't the best way to go about this but I'm stumped.
I've been struggling to find a specific answer online for my issue so I greatly appreciate anyone who could point me in the proper direction. Thanks!
I would recommend using the newer Commands Extension, it is much simpler to implement what you are wanting. See this bit specifically for passing everything a user types after the command into a variable.
There is an official example I would recommend looking at here: https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
You should use commands instead of on_message event. Here is a simple command:
#client.command()
async def test(ctx):
await ctx.send('A Simple Command')
ctx parameter is the parameter that all commands must have. So, when you type =test, it will send to that channel A Simple Command.
If we come to what you try to do, you can use more parameters than ctx. Here is how you can do it:
#client.command()
async def pressf(ctx, *, mess):
await ctx.send(mess)
In this code, you have 1 more parameter called mess and also there's a *. That means mess parameter includes every message after =pressf. So when a user type =pressf Hello, it will send the channel Hello.

How do I make a bot write a certain message when it first joins a server?

I want my Discord bot to send a certain message, For example: "Hello" when he joins a new server. The bot should search for the top channel to write to and then send the message there.
i saw this, but this isn't helpful to me
async def on_guild_join(guild):
general = find(lambda x: x.name == 'general', guild.text_channels)
if general and general.permissions_for(guild.me).send_messages:
await general.send('Hello {}!'.format(guild.name))```
The code you used is actually very helpful, as it contains all of the building blocks you need:
The on_guild_join event
The list of all channels in order from top to bottom (according to the official reference). If you want to get the "top channel" you can therefore just use guild.text_channels[0]
checking the permissions of said channel
async def on_guild_join(guild):
general = guild.text_channels[0]
if general and general.permissions_for(guild.me).send_messages:
await general.send('Hello {}!'.format(guild.name))
else:
# raise an error
Now one problem you might encounter is the fact that if the top channel is something like an announcement channel, you might not have permissions to message in it. So logically you would want to try the next channel and if that doesn't work, the next etc. You can do this in a normal for loop:
async def on_guild_join(guild):
for general in guild.text_channels:
if general and general.permissions_for(guild.me).send_messages:
await general.send('Hello {}!'.format(guild.name))
return
print('I could not send a message in any channel!')
So in actuality, the piece of code you said was "not useful" was actually the key to doing the thing you want. Next time please be concise and say what of it is not useful instead of just saying "This whole thing is not useful because it does not do the thing I want".

on_reaction_add not being run

I'm new to discord.py and trying to make a translator bot. When the user reacts with a certain flag, the bot translates it, but the event is never getting called hence I have no code to translate any messages yet. I know it's not getting called because the program isn't printing an 'x' to the console.
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
print('x')
await client.send_message(channel, '{} has added {} to the the message {}'.format(user.name, reaction.emoji, reaction.message.content))
await client.process_commands(reaction.message)
Probably a bit late to this thread but, the answer above is a valid answer. But you can also use on_raw_reaction_add which gets called even if the messages aren't in the Bot's cache.
Called when a message has a reaction added. Unlike on_reaction_add(), this is called regardless of the state of the internal message cache.
Documentation Link
Example:
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
channel = await self.bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
user = await self.bot.fetch_user(payload.user_id)
emoji = payload.emoji
await channel.send("Hello")
There isn't much valid reason for why the event isn't registered/called.
One of which is stated in the docs: http://discordpy.readthedocs.io/en/async/api.html#discord.on_reaction_add. Try adding a reaction immediately to a message that is sent after the bot is online. Since messages sent before the bot is online will not be recognized by the bot (not in Client.messages).
if the message is not found in the Client.messages cache, then this
event will not be called.
Another possible reason is that this function was never defined before the client loop commenced. Verify your indentation. And/Or try placing the function directly under client = Bot(...), to check if this is the problem.
If neither of the aforementioned solves your problem, please post a minimal, complete, verifiable example (a short runnable code from top to bottom that indicates your problem).

Categories