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.
Related
I came back to creating bots on discord, but this time with Python, it seems I am doing something wrong, and I don't know what it is.
I placed a simple code, which is (command-reply), but the bot does not answer and does nothing about it.
My bot is online, I don't get errors in my terminal, and I am using the correct token.
Here is my code:
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
#client.event
async def on_message(message):
if message.content == "hello":
await message.channel.send("Hello there!")
client.run('BOT TOKEN')
You didn't enable the message_content intent.
Docs about intents: https://discordpy.readthedocs.io/en/stable/intents.html
So I was used to use this bot about one year ago, now I wanted to launch it again but after discord.py 2.0 update it seems doesn't work propery
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['ffs','gdsgds']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
client = discord.Client(intents=discord.Intents.default())
client.run('OTkxfsa9WC5G34')
from flask import Flask
from threading import Thread
app = Flask('')
#app.route('/')
def home():
return 'dont forget uptime robot monitor'
def run():
app.run(host='0.0.0.0',port=8000)
def keep_alive():
t = Thread(target=run)
t.start()
I tried to fix it by my own by changing this line
client = discord.Client(intents=discord.Intents.default())
It has to be some trivial syntax mistake, but I cannot locate it
Edit1: so i turned on intents in bot developer portal and made my code to looks like this but still seems something doesn't work
import discord
from keep_alive import keep_alive
class MyClient(discord.Client):
async def on_ready(self):
print('bot is online now', self.user)
async def on_message(self, message):
word_list = ['fdsfds','fsa']
if message.author == self.user:
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
# keep_alive()
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents = intents)
client.run('OTkxMDcxMTUx')
If it would be a syntax mistake you'd get a syntax error. The real issue is that you didn't enable the message_content intent, so you can't read the content of messages. Intents.default() doesn't include privileged intents.
intents = discord.Intents.default()
intents.message_content = True
Don't forget to enable it on your bot's developer portal as well.
Also all of that keep alive & flask stuff hints that you're abusing an online host to run a bot on. This brings loads of issues along with it that you can't fix so you should really consider moving away from that. There's posts on a daily basis of people with problems caused by this.
Your code should be:
import discord
from discord.ext import commands # you need to import this to be able to use commands and events
from keep_alive import keep_alive
client = commands.Bot(intents=discord.Intents.default())
#bot.event
async def on_ready(): # you don't need self in here
print('bot is online now', client.user) # you can just use client.user
#bot.event
async def on_message(message): # again, you do not need self
word_list = ['ffs','gdsgds']
if message.author == client.user: # you can use client.user here too
return
messageContent = message.content
if len(messageContent) > 0:
for word in word_list:
if word in messageContent:
await message.delete()
await message.channel.send('Do not say that!')
keep_alive()
client.run('OTkxfsa9WC5G34') #if this is your real token/you have been using this token since you made the bot, you should definitely generate a new one
To help you, I added some comments to help show you what I have changed and why. As one of the comments in the code says, you should regenerate your bot token at the Discord Developer Portal.
For more info about migrating to 2.0, read the Discord.Py docs
This is my first time using the Discord.py library. I have the following code:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
bot = commands.Bot(intents=intents, command_prefix='$')
#client.event
async def on_ready():
print(f'Logged in as {client.user}!')
#bot.command()
async def say(ctx, arg):
await ctx.send(arg)
client.run('MY_TOKEN')
When I say "$say "hello world"" I don't get any error message, but I also don't get any response from the bot. Can someone tell me what the issue is, I'm sure it's a simple mistake. Thanks.
I figured out what I did wrong. I didn't need to include client and bot as separate things. I simply removed client = discord.Client(intents=intents) and the code ran fine (obviously I replaced every instance of 'client' with 'bot').
Im using the discord.py library and using replit for the bot, but my code doesnt work.
my code:
import os
import discord
from discord.utils import get
client = discord.Client()
#client.event
async def on_ready():
print ("We have logged in as {0.user}".format(client))
#client.event
async def on_message(message):
if message.content == ";":
member = message.author
role = get(member.guild.roles, name="Recruiter")
await member.add_roles(role)
client.run(os.getenv("TOKEN"))
First of all, you're using client object and it is not a bot.
This is the way to create a proper bot (not client):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
You can't code reactions roles without reading the discord.py docs. It involves lots of stuff.
If you want to code it yourself, the only way is to learn and do.
I am looking for a way to allow a user to move him or her self and another user to a different voice channel. I already got the command to work for the author of the message, but I am having trouble finding out a way to move another user in the same message. The idea is that the user would be able to type "n!negotiate [Other User]" and it would move the author and the other user to the Negotiation channel.
I would love some help with how I might be able to do this. The code is provided below excluding the tokens and ids.
Code:
import discord
from discord.ext.commands import Bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client() #Initialise Client
client = commands.Bot(command_prefix = "n!") #Initialise client bot and prefix
#client.event
async def on_ready():
print("Logged in as:")
print(client.user.name)
print("ID:")
print(client.user.id)
print("Ready to use!")
#client.event
async def on_message(check): #Bot verification command.
if check.author == client.user:
return
elif check.content.startswith("n!check"):
await client.send_message(check.channel, "Nations Bot is online and well!")
async def on_message(negotiation): #Negotiate command. Allows users to move themselves and other users to the Negotiation voice channel.
if negotiation.author == client.user:
return
elif negotiation.content.startswith("n!negotiate"):
author = negotiation.author
voice_channel = client.get_channel('CHANNELID')
await client.move_member(author, voice_channel)
client.run("TOKEN")
You should use discord.ext.commands. You're importing it, but not actually using any of the features.
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix = "n!") #Initialize bot with prefix
#bot.command(pass_context=True)
async def check(ctx):
await bot.say("Nations Bot is online and well!")
#bot.command(pass_context=True)
async def negotiate(ctx, member: discord.Member):
voice_channel = bot.get_channel('channel_id')
author = ctx.message.author
await bot.move_member(author, voice_channel)
await bot.move_member(member, voice_channel)
bot.run('TOKEN')
Here we use a converter to accept a Member as input. Then we resolve the author of the message from the invocation context and move both Members to the voice channel.