How do i make a discord bot answer? - python

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.

Related

inside on_message in discord.py, if statements to check content doesn't work

#client.event
async def on_message(message):
if message.author.bot:
return
if message.content == 'hi':
await message.channel.send("hi")
Why doesn't this work? The code runs without errors but it doesn't detect the message "hi"
I wanted the bot to send a message when I send a certain message.
You have to have 'message content intent' enabled in your Discord Developer Portal (https://i.stack.imgur.com/jD6zh.png) and your program:
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

Simple Discord Python Bot Err0r

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.

My discord bot will not send a welcome message, but is reading other messages. I am using discord.py

I am trying to create a basic discord bot and am currently trying to implement a welcome message. I am not getting an error message, it just doesn't do anything, and if I try and print a message to the console when a member joins, nothing happens. The on_message function works just fine, along with the on_ready.
#bot
import discord
TOKEN = ('top secret token')
client = discord.Client()
intents = discord.Intents.default()
intents.members = True
#client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
#client.event
async def on_member_join(member):
await message.channel.send('Welcome!')
print('New User Detected')
client.run(TOKEN)
Let's see... hmm
does the bot know what message and channel are in the on_member_join event which has kwarg member. Nope, it doesn't!
message and channel aren't defined in an on_member_join. First, get the channel
channel = client.get_channel(ChannelID)
this will get you the channel you want to send your message to.
after that, we will simply use channel.send("message") to send the message.
The final code will look like this:
#client.event
async def on_member_join(member):
channel = client.get_channel(ChannelID)
await channel.send('Welcome!')
print('New User Detected')

discord.py: Why isn't my join message working?

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)

Disocrd.py command

I am coding a discord bot and i think there has got to be a much easier/ simpler way to detect messages using the prefix for commands (and easy to expand in future), my code at the moment just scans each message to see if it contains the exact command, maybe a class will help?
#client.event
async def on_message(message):
# print message content
print(message.content)
# if the message came from the bot ignore it
if message.author == client.user:
return
# if the message starts with "!repeat" then say the message in chat
if message.content.startswith("!repeat"):
sentmessage = message.content.replace("!repeat", "")
await message.channel.send(sentmessage)
if "hello" in message.content.lower():
await message.channel.send("Hello!")
if message.content.startswith("!cleanup"):
if not message.author.guild_permissions.administrator:
await message.channel.send("You do not have permission to run this command!")
else:
num2c = 0
num2c = int(message.content.replace("!cleanup", ""))+1
print(num2c)
await message.channel.purge(limit=num2c)
num2c = num2c-1
cleanmessage = str("Cleared "+str(num2c)+" Messages.")
await message.channel.send(cleanmessage, delete_after=5)
You can use commands.Bot, it has a built-in command system, here's an example:
import discord
from discord.ext import commands
# enabling intents
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command()
async def foo(ctx, *args):
await ctx.send('whatever')
# You also have all the functionality that `discord.Client` has
#bot.event
async def on_message(message):
# ...
# you always need to add this when using `commands.Bot`
await bot.process_commands(message)
bot.run('token')
Take a look at the introduction

Categories