Discord not accessing message.content - python

I have encountered this problem where the discord api is not accessing my bot content after it has been sent. Down below is my code.
import discord
import random
TOKEN = 'SECRET'
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):
username = str(message.author).split("#")[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f' {username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == '🤖║bot':
if user_message.lower() == 'hello':
await message.channel.send(f'hello {username}!')
return
elif user_message.lower() == 'bye':
await message.channel.send(f'see you later {username}!')
elif user_message.lower() == "!random":
response = f'This is your random number: {random.randrange(100)}'
await message.channel.send(response)
return
client.run(TOKEN)
here is the output:
KaoGaming: (🤖║bot)
KaoGaming: (🤖║bot)
KaoGaming: (🤖║bot)
As you can see, the message is not identified.
I need the output to look sort of like this:
KaoGaming: hello (🤖║bot)
KaoGaming: bye (🤖║bot)
KaoGaming: !random (🤖║bot)

The problem could be related to missing the intents:
intents = discord.Intents.all()
client = discord.Client(intents=intents)

Related

How do i make my discord bot reply to a certain user always with the same string?

made my own discord bot using py and trying to solve the issue in the title.
This is my current code for responses
def get_response(message: str) -> str:
p_message = message.lower()
if p_message == 'hello':
return ''
if p_message == 'alex':
return ''
if p_message == 'benji':
return ''
if message == 'roll':
return str(random.randint(1, 6))
if p_message == '!help':
return '`This is a help message that you can modify.`'
if p_message == '-':
return ''
if p_message == 'aja':
return ''
if p_message == 'christian':
return ''
This is where i call my responses. And execute the code from above
import discord
import responses
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
async def send_message(message, user_message, is_private):
try:
response = responses.get_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
# #client.event
# async def on_message(message):
# if message.author.id == 195251214307426305:
# await message.channel.send("")
# #client.event
# async def on_message(message):
# if message.author.id == 305280287519145984:
# # Sending a message to the channel that the user is in.
# await message.channel.send("")
def run_discord_bot():
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(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})')
if user_message[0] == '?':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
TOKEN=""
with open("token.txt") as file:
TOKEN = file.read()
client.run(TOKEN)
Tried using msg.author.id and its unknown now. More then that i was sadly stunned by this issue and found no solutions online
I assume you use the discord libary, so this could be a solution to your problem
import discord #dependencies
client = discord.Client() #create a client object
#client.event #bind the function
async def on_message(message):
if message.author.id == 398238482382: #check for id
await message.channel.send("Hey") #send 'hey' to channel where the message was written
client.run(yout_token) #starts the bot

It keeps on saying IndexError: String Index out of range

I'm coding a discord bot and it works fine until I try and use one of the ! commands (Like !hello) and then It comes up with this
ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\vanti\PycharmProjects\discordbot4thtry\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\vanti\PycharmProjects\discordbot4thtry\bot.py", line 33, in on_message
if user_message[0] == '%':
~~~~~~~~~~~~^^^
IndexError: string index out of range
The % is supposed to make the bot send you the response in a DM e.g. if I do !hello it would reply in the channel with "Hello there!" but if I put %hello it would send "Hello There!" as a DM
import discord
import responses
async def send_message(message, user_message, is_private):
try:
response = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
def run_discord_bot():
TOKEN = 'This is where the bots token would go'
client = discord.Client(intents=discord.Intents.default())
#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})")
if user_message[0] == '%':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)
You must add the message_content intent.
intents.message_content = True
The class definition will look like
def run_discord_bot():
TOKEN = 'This is where the bots token would go'
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
You may want to add the following line to your code :
if len(user_message) > 0:
Like this:
#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})")
if len(user_message) > 0:
if user_message[0] == '%':
user_message = user_message[1:]
await send_message(message, user_message, is_private=True)
else:
await send_message(message, user_message, is_private=False)
client.run(TOKEN)

There is an empty message in terminal

https://i.stack.imgur.com/VAgTp.png
it aint see my message. There is just empty message
I upload my bot to discord and copy the token, but there ni message just empty
import discord
import random
TOKEN = "token is here"
intents = discord.Intents(messages=True, guilds=True)
client = discord.Client(intents=intents)
#client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
#client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f"{username}: {user_message} ({channel})")
if message.author == client.user:
return
if message.channel.name == "discord-bot-tutorial":
if user_message.lower() == "hello":
await message.channel.send(f"Hello {username}!")
return
elif user_message.lower() == "bye":
await message.channel.send(f"See you next time!{username}!")
elif user_message.lower() == "!random":
response = f"This is your random number: {random.randrange(100000)}"
await message.channel.send(response)
return
if user_message.lower() == "!anywhere":
await message.channel.send(f"This can be anywhere")
client.run(TOKEN)
The most probable cause of this could be that the Message Content Intent is turned off. Without it Discord will not send you content of the messages.
You can enable it on Discord Developer Portal under "Bot" tab.
You will also need to add this intent in your code like this:
intents = discord.Intents.message_content
client = discord.Client(intents=intents)

Why doesn't my discord bot respond to any command that I give in the chat

The problem that I am facing is that my discord bot does not respond or read the messages that I am writing in the chat.
The out put of the code down bellow is the users name and nothing else.
import discord
import random
TOKEN ='example'
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):
username = str(message.author).split('#')[0]
user_message = (message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'example':
if user_message.lower() == 'Hello':
await message.channel.send(f'Hello {username}')
elif user_message.lower() == 'bye':
await message.channel.send(f'Hello {username}')
elif user_message.lower() == '!random':
response = f'This is your number: {random.randrange(1000000)}'
await message.channel.send(response)
client.run(TOKEN)
The .lower() method only searches for lower case letters in a string, hence the name, so typing "Hello" into the chat will not trigger the command, as "Hello" has a capital "H". To fix your code you can either:
Change your code to
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}')
Notice you can still keep the capital H for hello in
await message.channel.send(f'Hello {username}')
Or, you could compare 2 values like this:
string = 'Hello'
if user_message == string:
#the rest of your code goes here
Your full code should be:
import discord
import random
TOKEN ='exemple'
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):
username = str(message.author).split('#')[0]
user_message = (message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'example':
string = 'Hello'
if user_message.casefold() == string:
await message.channel.send(f'Hello {username}')
elif user_message.lower() == 'bye':
await message.channel.send(f'Hello {username}')
return
elif user_message.lower() == '!random':
response = f'This is your number: {random.randrange(1000000)}'
await message.channel.send(response)
return
client.run(TOKEN)
Intents.default() doesn't include the Message Content intent, which is now required. Without the intent, message.content will be empty.
More information in the docs:
https://discordpy.readthedocs.io/en/stable/intents.html#privileged-intents
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.

discord.py - Adding roles issue

I was trying to make an reaction menu to give roles, so far its working, but the problem is when I do the command !lol #[person here] and react to it, it adds the roles to the author (me) and not the user that I mentioned, please help
My Code is
import discord
#import secreto
import asyncio
from discord.utils import get
from discord.ext import commands
client = commands.Bot(command_prefix='!')
COR =0x690FC3
msg_id = None
msg_user = None
#client.event
async def on_ready():
print('BOT ONLINE!')
print(client.user.name)
print(client.user.id)
#client.command(pass_context=True)
async def lol(ctx, user = discord.Member):
message = ctx.message
embed1 =discord.Embed(title=f"Choose {user.name}'s rank", color=COR, description="🍍 - Pineapple\n🍎 - Apple\n🍉 - Watermellon")
botmsg = await client.send_message(message.channel, embed=embed1)
await client.add_reaction(botmsg, "🍍")
await client.add_reaction(botmsg, "🍎")
await client.add_reaction(botmsg, "🍉")
global msg_id
msg_id = botmsg.id
global msg_author
msg_author = message.author
global msg_user
msg_user = user
#client.event
async def on_reaction_add(reaction, user):
msg = reaction.message
if reaction.emoji == "🍍" and msg.id == msg_id: # and user == msg_user:
role = discord.utils.get(user.server.roles, name="Bronze")
await client.add_roles(user, role)
print("add" + user.name)
if reaction.emoji == "🍎" and msg.id == msg_id:
role = discord.utils.get(user.server.roles, name="Prata")
await client.add_roles(user, role)
print("add")
if reaction.emoji == "🍉" and msg.id == msg_id:
role = discord.utils.get(user.server.roles, name="Ouro")
await client.add_roles(user, role)
print("add")
user in on_reaction_add(reaction, user) is always the user who reacted to the message. What you need is mentioned_user = message.mentions[0] to get the user mentioned in your message and give him the according role.

Categories