I am trying to access the content of a message and print it using discord.py. The problem is, that the content is allways empty no matter what. The code works on my laptop but just refuses to work on this pc. The same has already happened when trying to run other, more complex, codes that worked on other devices. There are no errors showing up.
import nest_asyncio
nest_asyncio.apply()
import discord
TOKEN = "TOKEN"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("logged in as {0.user}".format(client))
#client.event
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = message.content
channel = str(message.channel.name)
print(f"{username}: {user_message} ({channel})")
client.run(TOKEN)
You need to enable the Guild Message Intent: https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guild_messages
Related
I am trying to set up a simple Discord bot for a server, but it only appears to be responding in DMs to commands and not in any server channels. The bot has admin permissions in the server I am trying to get it to respond in.
After doing some looking around I have found no fixes.
Here's the code:
import discord
token_file = open("bot_token.txt", "r+")
TOKEN = str(token_file.readlines()).strip("[]'")
token_file.close()
command_prefix = ">"
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
print("Logged in as: {0.user}".format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith(command_prefix):
if message.content == ">help":
await message.channel.send("What do you need help with?")
elif message.content == ">hello":
await message.channel.send("Hi there!")
else:
await message.channel.send("This command is not recognised by our bot, please use the help menu if required.")
else:
return
client.run(TOKEN)
Hope someone can help!
It‘s pretty simple…
For receiving message events in guilds (servers) you need the message intent (discord.Intents.message_content = True), you also have to enable it in the discord developer dashboard.
Discord added a message content intent that has to be used since the first September 2022. if you‘re doing a discord.py tutorial, be aware that it should be a 2.0 tutorial as many things have been updated since then.
Also, think of using the commands extension of discord.py as it is handling some annoying stuff and provides more easier interfaces to handle commands.
I‘ll help you with further questions if there are any
;-)
#kejax has given absolutely the right answer I just want to add how u
can make the use of 'intent' in your code:-
If you want to listen and have access to all available events and data
client = discord.Client(intents=discord.Intents.all())
Full Code :-
import discord
client = discord.Client(intents=discord.Intents.all())
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
You can also specify specific intents by creating a set of the desired discord.Intents constants.
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
Full Code:-
import discord
intents = {discord.Intents.guilds, discord.Intents.messages}
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('....................')
#client.event
async def on_message(message):
if message.content.startswith('!greet'):
await message.channel.send('Hello!')
client.run('YOUR_BOT_TOKEN')
well im making a discord bot for my server and it cant see when someone is typing something in general all tho everything seems to be fine the output stays 'mag_cecito#1080 said: '' (︱📫︱𝗴𝗲𝗻𝗲𝗿𝗮𝗹)'
from imaplib import Commands
import discord
import responces
async def send_message(message, user_message, is_private):
try:
responce = responces.handle_responce(user_message)
await message.author.send(responce) if is_private else await message.channel.send(responce)
except Exception as e:
print(e)
def run_disocrd_bot():
TOKEN = 'MTAxNzcxOTYxNjQzMDE2MTkyMA.G6gR5I.DyNWFqtwynSFYLr5MyKTaJ3gC47ZjGNAcR8-YY'
intents = discord.Intents(messages=True, guilds=True)
client = discord.Client(command_prefix="!", intents=intents)
#client.event
async def on_ready():
print(f'{client.user} is now running')
#client.event
async def on_message(message):
if message.author == client.user:
return
username = str(message.author)
user_message = str(message.content)
channel = str(message.channel)
print(f"{username} said: '{user_message}' ({channel})")
client.run(TOKEN)
thats pretty much the code pls help
If you are using a selfbot, then it's because you can't view messages in guilds using a selfbot as well as selfbots being unsupported in versions
bigger than 1.7.3. If not then I'm guessing you can't run your token from a function. Just run your token from main.
I'm playing around with the Discord API and noticed that I can't access the content of a message.
This is my code:
import discord
client = discord.Client()
#client.event
async def on_ready():
print(f'Logged in as {client.user}')
#client.event
async def on_message(message):
if 'My Name' in message.author.name:
print(f'Author: {message.author.name}')
print(f'Content: {message.content}')
print(f'Clean_Content: {message.clean_content}')
print(f'System_Content: {message.system_content}')
client.run(TOKEN, bot=False)
Note that the token and my username are kept private in this post for obvious reasons.
This is the output that I get, no matter the message:
Author: My Name
Content:
Clean_Content:
System_Content:
As you can see I have also tried the clean_content and system_content attributes. However, none of them show the actual message. I've also tried to use a bot account and that surprisingly worked, but I want this to work with my own account. Is the problem that Discord does not intent private clients to read messages or did I miss something fundamental?
As Matt mentioned, user bots are not supported. However, your problem may be related to intents instead. You might try using the following lines:
import discord
intents = discord.Intents.all()
client = discord.Client(intents=intents)
See also:
https://docs.pycord.dev/en/master/intents.html#privileged-intents
https://docs.pycord.dev/en/master/intents.html#message-content-intent
You can solve this by enabling the MESSAGE CONTENT INTENT for your bot in the Discord Developer Panel.
import os
TOKEN = os.environ['TOKEN']
import discord
# This example requires the 'message_content' privileged intent to function.
class MyClient(discord.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('!hello'):
await message.reply('Hello!', mention_author=True)
intents = discord.Intents.default()
intents.message_content = True
def main():
client = MyClient(intents=intents)
client.run(TOKEN)
if __name__ == '__main__':
main()
This is an example with reply in the documentation
Discord selfbots are no longer supported, you might have to use discord.ext which has support for them still. It seems using discord.py message.content will always be empty.
I tried making a secret in repl.it to put my bot's token in so i can code my bot but it doesn't recognize the variable TOKEN even though i made a System environment variable. I tried researching to see if someone has the same problem but I couldn't find anyone.
The code I written is in the following:
import discord
import os
client= discord.Client()
#client.event
async def on_read():
print('We Have Logged In As {0.user'.format(client))
#client.event
async def on_message(message):
if message.author == client:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
#client.event
async def on_reaction_add(reaction, user):
print('reaction added')
When I add a reaction it does not seem to print 'reaction added', I've added the reaction after the bot went online but still does not works.
full code:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('logged on!')
#client.event
async def on_reaction_add(reaction, user):
print('reaction added')
client.run('token_here')
I think your problem comes from because the message was sent before your bot started. As written in the documentation:
If the message is not found in the internal message cache, then this event will not be called.
You sould use on_raw_reaction_add, wich works even if the message wasn't in the internal cache (so sent before the bot started). This returns a payload that contains ids instead of objects (so convert them if necessary).
I hope it will solve your problem