apparently I am creating a simple discord reply bot and I have an error with my code. Even if I say the correct word with $ in chat, it is still using and replying to me with the else statement. I do not have this problem on the replit, but I do on my home PC, what could be the problem?
import discord
import os
from dotenv import load_dotenv
client = discord.Client(intents=discord.Intents.default())
load_dotenv()
TOKEN = 'TOKEN'
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
#client.event
async def on_connect():
print("Bot Connected")
client.run(TOKEN)
enter image description here
Your bot does not have the Message Content Intents, so it will not be able to read messages sent by users.
In discord.py 2.0, a bot must have the Message intent in order to read messages' content.
To enable Message Intents for your bot, follow these steps:
Go to Discord's developer portal and click on your application's name.
Click on "Bot" in the sidebar.
Scroll down until you see "Privileged Gateway Intents".
You should see the option named "Message Content Intent". Enable it.
The next step:
At the start of your bot code, you should have a line of code that creates a Client or Bot object, for example:
client = discord.Client() or bot = discord.Bot(...)
First, you should define a variable intents:
intents = discord.Intents.all() # define intents
Now, add the parameter intents to the object, like this:
client = discord.Client(intents=intents)
or:
bot = discord.Bot(..., intents=intents)
And you are all set!
Hope this helped.
If I understood your question correctly. I suggest that you use the following code instead.
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.lower() == '$hello':
await message.channel.send("Hello World!")
else:
await message.channel.send("Hello World! BUT ERROR")
What I have changed here is using the string matching instead of startswith() function.
Related
I am trying to make a discord bot.
I have attached the code below. When I run it there are no errors, the bot says 'Hello, world!', but doesn't answer the 'hi' (as it should answer 'Hello!').
What can I do to make it work?
import discord
client = discord.Client(intents=discord.Intents.default())
#client.event
async def on_ready():
general_channel = client.get_channel('CHANNEL ID')
await general_channel.send('Hello, world!')
#client.event
async def on_message(message):
if message.content == 'hi':
general_channel = client.get_channel('CHANNEL ID')
await general_channel.send('Hello!')
client.run ('TOKEN')
The issue is that you put intents=discord.Intents.default() in your client. This only gives you the default intents, which do not include the message_content intent.
You need this intent because you are asking the bot if message.content == 'hi':.
First, you need to enable the message_content on your bot
After that, type
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents
Now if your run the code, it should work.
my code was running perfectly for some time but it stopped suddenly with an unexpected token error and also i tried adding an image to the rich presence of my bot but it doesn't seem to be working and also i did my whole in replit
The error!
import discord
from webserver import keep_alive
import os
intents = discord.Intents.all()
client = discord.Client(intents=intents)
welcome_channel = None
prefix = "&"
#client.event
async def on_ready():
print(f"Logged in as {client.user}!")
await client.change_presence(status= discord.Status.dnd,
activity = discord.Activity(type=discord.ActivityType.playing,
assets={
'large_text': 'details',
'large_image': 'https://cdn.discordapp.com/attachments/998612463492812822/1063409897871511602/welcome.png',
},
name = "Dynamically",
details = "Dreams of Desires",
))
#client.event
async def on_message(message):
if message.content.startswith(prefix):
command = message.content[len(prefix):]
# Set welcome channel command
if command.startswith("setwelcomechannel"):
# Check if the user is an admin
if not message.author.guild_permissions.administrator:
await message.channel.send("You have to be an admin to set the welcome channel.")
return
# Set the welcome channel
global welcome_channel
welcome_channel = message.channel
await message.channel.send(f"Welcome channel set to {welcome_channel.name}.")
# Get welcome channel command
if command.startswith("getwelcomechannel"):
# Check if the welcome channel has been set
if welcome_channel is None:
await message.channel.send("Welcome channel is not set.")
else:
await message.channel.send(f"Welcome channel is set to {welcome_channel.name}.")
# Add your new commands here
if command.startswith("hello"):
await message.channel.send("Hii!")
if command.startswith("dead"):
await message.channel.send("latom!")
#client.event
async def on_member_join(member):
# Send the welcome message
if welcome_channel:
embed = discord.Embed(title="Welcome!", description=f"Ara ara! {member.mention}, welcome to {member.guild.name}\nHope you find Peace here!", color=0x8438e8)
embed.set_image(url= 'https://cdn.discordapp.com/attachments/998612463492812822/1063409897871511602/welcome.png')
await welcome_channel.send(embed=embed)
keep_alive()
TOKEN = os.environ.get("DISCORD_BOT_SECRET")
client. Run(TOKEN)
to run properly and to show an image in the presence.
"discord.client logging in using static token" error
That says INFO, not ERROR, so it's not an error. The actual error is the red lines underneath, which is caused by you using Replit to run the bot.
Replit uses the same IP address for every bot, so all Replit bots combined will cause Discord to ratelimit you. The only solution is to use an actual VPS instead of abusing Replit's platform to host bots. There's nothing you can do about it.
I just started learning discord.py but my bot isn't responding even though I followed the documentation and no error messages. The bot is online but doesn't respond to my messages
I was attempting to do this from a tutorial
import os
import discord
client = discord.Client(intents=discord.Intents.default())
#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.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.environ['TOKEN'])
Please Someone Help me! :(
Your bot can't read the content of the messages sent in a guild because it is missing the message_content intent.
You gave your bot only the default intents, which doesn't include the message_content one.
client = discord.Client(intents=discord.Intents.default())
Here is how you fix it:
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
In case your bot isn't still able to read the content of the guild messages, you need also to turn on the message content intent in the Discord Developer Portal:
Select your app
Go to the "Bot" tab
Turn the "message content intent" on
Now your bot should be able to read the content of the messages sent in guilds.
Here you can read more about Intents
I started learning python today and made a Discord bot. I have a few problems:
If message.author == was used in the on_message, but the bot continued to reply to itself.
Afterwards, a new bot was created with a new token and the code didn't work.
I searched a lot on this site and Google. I didn't find any solution. It's okay to modify my code. Everything is from the internet, so it can be a mess. Please help me.
import discord
import asyncio
from discord.ext import commands
client = discord.Client()
bot = commands.Bot(command_prefix="!")
#bot.event
async def on_ready():
print('Loggend in Bot: ', bot.user.name)
print('Bot id: ', bot.user.id)
print('connection was succesful!')
print('=' * 30)
#client.event
async def on_message(message) :
if on_message.content.startswith('!의뢰'):
msg = on_message.channel.content[3:]
embed = discord.Embed(title = "브리핑", description = msg, color = 0x62c1cc)
embed.set_thumbnail(url="https://i.imgur.com/UDJYlV3.png")
embed.set_footer(text="C0de")
await on_message.channel.send("새로운 의뢰가 들어왔습니다", embed=embed)
await client.process_commands(message)
client.run("My bot's token.")
Your code was messy, but it should work now. I included comments to let you know how everything works. I think the good starting point to making your own bot is reading documentation. Especially Quickstart that shows you a simple example with explanation.
Write !example or hello to see how it works.
import discord
import asyncio
from discord.ext import commands
# you created 'client' and 'bot' and used them randomly. Create one and use it for everything:
client = commands.Bot(command_prefix="!") # you can change commands prefix here
#client.event
async def on_ready(): # this will run everytime bot is started
print('Logged as:', client.user)
print('ID:', client.user.id)
print('=' * 30)
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hello'): # you can change what your bot should react to
await message.channel.send("Hello! (This is not a command. It will run everytime a user sends a message and it starts with `hello`).")
await client.process_commands(message)
#client.command()
async def example(ctx): # you can run this command by sending command name and prefix before it, (e.g. !example)
await ctx.send("Hey! This is an example command.")
client.run("YOUR TOKEN HERE")
I am stumped on why my join message isn't working! I have the discord.py library installed, and I am really confused! I have other code below it, but it shouldn't effect the above.
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_member_join(member):
print("Player has joined")
channel = await client.fetch_channel(800395922764070942)
await channel.send(f'{member} has joined!')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!loser'):
await message.channel.send('Hello loser! Nice to meet you.')
elif message.content.startswith('!bruh'):
await message.channel.send('BRUHHHHHHHHHHHHHHH!!!!')
client.run("Where my token is")
Edited to show entire code. (Sorry for the stupid bruh things, they run perfectly but I just wanted to test some things..)
Due to recent changes in discord.py (1.5.0) you now need to use intents. Intents enable to track things that happen.
First you need to enable it on the developer portal (where you created your bot). When you're there, select your application, go to the bot section, scroll down and tick the box.
Then in your code you need to add this at the top :
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
You will now be able to receive events like on_member_join.
Have you tried changing the get_channel line from
channel = client.get_channel(800395922764070942)
to
channel = await client.fetch_channel(800395922764070942)