Ping members with discord.py - python

I am making a command for my bot that will DM members when the command is used +ping #Member . Here is my code:
if message.content.startswith('+ping'):
ping = message.content.replace("+ping ","")
dm_member = ping
pinger = message.author
await dm_member.send('You got pinged by:')
await dm_member.send(pinger)
But in return I get:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 95, in on_message
await dm_member.send('You got pinged by:')
AttributeError: 'str' object has no attribute 'send'
How do I fix this AttributeError?
When I replace dm_member with message.author (therefore pinging the author) it works.
I think it doesn't work because str objects don't have discord attributes. But how can I fix this?

if message.content.startswith('+ping'):
ping = message.content.replace("+ping ","")
user_id = int(ping[2:-1]) # convert to int
dm_member = await message.guild.get_member(user_id) # this function accepts an int
pinger = message.author
await dm_member.send('You got pinged by:')
await dm_member.send(pinger)
You set dm_member equal to ping which is a string, a Python built-in. pinger is the user object of the author. To get the pinged user, extract the user id from ping and use it to find the user object using await message.guild.get_member(user_id).

Related

AttributeError: 'NoneType' object has no attribute 'send' when sending message

so I checked all over in stack overflow for answers and nothing.
Im trying to make it that when the bot fires up it will send a message in a channel, I have alr checked if the bot can see and talk in the channel and they can.
My code:
import discord
from discord.ext import commands
from datetime import datetime
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="!", intents=intents, case_insensitive=True)
client = discord.Client(intents=intents)
#bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
current_time = datetime.now().strftime("%H:%M:%S")
channel = bot.get_channel('1069075658979954700')
embed = discord.Embed(title="GAH Verification",
description="I have awoken",
color=discord.Color.green())
embed.set_footer(text=current_time)
await channel.send('Hi')
bot.run(
"MTA2OTI2NDQ0MTQwMjcyODU3MQ.GV353u.XXagXFsp3Ax4vRxvt3y5s6P9FPPDrOeMh2M7jI")
Error:
Traceback (most recent call last):
File "/home/runner/GAH-Bot/venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "main.py", line 19, in on_ready
await channel.send('Hi')
AttributeError: 'NoneType' object has no attribute 'send'
currently bot.get_channel() returns None,
either because it dont get it because 1069075658979954700 is in quotes
you should try using:
bot.get_channel(1069075658979954700)
and check if the bot has access to the channel
if this won't work you can always try to get the channel via the server this should work 100% because maybe the channel is not loaded to the cache directly idk
server = bot.get_guild(1234) # server id here
channel = await server.fetch_channel(12345) # channel id here

How can I fix, AttributeError: 'NoneType' object has no attribute 'send'

Aim of this is to try get a local image saved on your computer sent to a discord channel via a bot
# Create an Intents object with the `messages` attribute set to True
intents = discord.Intents(messages=True)
# Create the client with the specified intents
client = discord.Client(intents=intents)
#client.event
async def on_ready():
# When the bot is ready, send the image to the specified channel
channel = client.get_channel(CHANNEL_ID)
with open(r"file path", 'rb') as f:
file = discord.File(f)
await channel.send(file=file)
client.run(TOKEN)
Traceback (most recent call last):
File "C:\Python\Python39\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "path", line 39, in on_ready
await channel.send(file=file)
AttributeError: 'NoneType' object has no attribute 'send'
The offical documentation for Discord.py says
Parameters:
id (int) – The ID to search for.
Returns:
The returned channel or None if not found.
This means that the ID supplied does not match any server, so most likely you mistyped it or accidentally modified it in code somewhere
await channel.send(file=file)
AttributeError: 'NoneType' object has no attribute 'send'
So channel is None, so the error was caused by the following.
channel = client.get_channel(CHANNEL_ID)
I guess 99% that CHANNEL_ID is a string and not an integer...

Discord.py - How to get A's ID from B's message when B is sending a message that is replying to A's original message?

I'm trying to make a discord bot to automate playing my friend's bot's game. When my friend's bot sends a message replying to your message after you use a specific command. I want to be able to check if the message the bot sends is replying to my message specifically. This is what I've got so far:
#bot.event
async def on_message(message):
if message.author.id == botId:
content = str(message.content)
reference = message.reference
if reference.message_id.author.id == myId:
word = content.split('`')[1].split('`')[0]
await bot.send_message(message.channel, word)
I know reference.message_id.author.id will not work since author.id is incompatible with reference.message_id, but I cannot find something that will work with it.
The Error:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\OneDrive\Desktop\User\Projects\Programming\Python\Discord Bot\Waterhole Dryer\bot.py", line 30, in on_message
if reference.message_id.author.id == myId:
AttributeError: 'int' object has no attribute 'author'
Thanks!
Alrighty, so... I found a bit of a workaround to this...
#bot.event
async def on_message(message):
if message.author.id == botId:
guild = bot.get_guild(guildId)
channel = guild.get_channel(message.reference.channel_id)
msg = await channel.fetch_message(message.reference.message_id)
if msg.author.id == myId:
word = content.split('`')[1].split('`')[0]
await channel.send(word)
Basically, I made a new message object. I hope this helps anyone else with my problem.

Discord bot on_join_guild dm everyone

I am trying to dm everyone in the server when the bot is added to the server using the on_join_guild().
The code for it
#client.event
async def on_guild_join(guild):
for member in guild.members:
await member.create_dm()
embedVar = discord.Embed(title="Hi", description="Hello", color=0x00ff00)
await member.dm_channel.send(embed=embedVar)
But whenever I add the bot to server, it dms everyone in the server which is expected but a error also pops in the console.
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\Khusi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File ".\time-turner.py", line 42, in on_guild_join
await member.create_dm()
File "C:\Users\Khusi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 110, in general
return getattr(self._user, x)(*args, **kwargs)
AttributeError: 'ClientUser' object has no attribute 'create_dm'
What am I doing wrong?
After replicating your code, I found that your error only appears to happen if the bot tries to message itself. You would also get an error if your bot attempts to message another bot (Cannot send messages to this user). You can just use pass if your bot can't message a user or if it tries to message itself.
#client.event
async def on_guild_join(ctx):
for member in ctx.guild.members:
try:
await member.create_dm()
embedVar = discord.Embed(title="Hi", description="Hello", color=0x00ff00)
await member.dm_channel.send(embed=embedVar)
except:
pass
If the above still doesn't work, just as NerdGuyAhmad had said, you need to enable intents, at the very least member intents. View this link here: How do I get intents to work?

How to make the bot send a message with a invite link of the guild to a specific channel in my guild whenever it joins a new server?

So basically what I want is whenever my bot joins any guild it should send a message to a particular channel in my server stating that it is invited to a server with its name and if possible also the invite link of that server. I tried a few things but they never really worked.
#client.event
async def on_guild_join(guild):
channel = client.get_channel('736984092368830468')
await channel.send(f"Bot was added to {guild.name}")
It didn't work and throws the following error:
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\Rohit\AppData\Roaming\Python\Python37\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Rohit\Desktop\discord bots\test bot\main.py", line 70, in on_guild_join
await channel.send(f"Bot was added to {guild.name}")
AttributeError: 'NoneType' object has no attribute 'send'
And I really don't have any idea how to make the bot send invite link of the guild with the guild name.
The reason why you get the 'NoneType' object has no attribute 'send' exception is because your bot failed to find the channel provided.
This line:
channel = client.get_channel('736984092368830468')
Will not work, this is because the channel ID must be an integer, you can try this:
channel = client.get_channel(int(736984092368830468))
If this still does not work, make sure the bot has access to the channel, the channel exists and the ID provided is correct.
Here's how you would get an invite, name and guild icon assuming your bot has the required permissions.
#client.event
async def on_guild_join(guild):
channel = client.get_channel(745056821777006762)
invite = await guild.system_channel.create_invite()
e = discord.Embed(title="I've joined a server.")
e.add_field(name="Server Name", value=guild.name, inline=False)
e.add_field(name="Invite Link", value=invite, inline=False)
e.set_thumbnail(url=guild.icon_url)
await channel.send(embed=e)

Categories