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)
Related
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
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)
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.
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)
I've got a function to set up the server when the bot joins, but i'm talking with my friends at the same time and it is getting errors because i only want the bot to read messages from dm
async def on_guild_join(guild):
print("Bot added to server: " + guild.name)
gid = str(guild.id)
server = Server()
server.name = guild.name
server.discordId = guild.id
server.ownerId = guild.id
server.welcome_message = None
server.lang = "en"
# here goes another tons of values
if guild.id in db['guilds']:
pass
else:
servers_dic = db['guilds']
servers_dic[gid] = server.toJSON()
print(server.toJSON())
db['guilds'] = servers_dic
await guild.owner.send(f"Hi! Thanks for adding me to your server, {guild.name}! To start using me, we'll have to set up a few things. Do you want to do it now or later?\n\n(n/l)")
msg = await bot.wait_for('message', check=lambda message: message.author == guild.owner)
if msg.content.lower() in ['n', 'now']:
server = deencoder(db['guilds'][gid])
if isinstance(server, Server):
print("Class created successfully!")
print(server)
is there any way to do that?
You can simply use the isinstance function and check for a discord.DMChannel
def check(message):
return message.author == guild.owner and isinstance(message.channel, discord.DMChannel)
msg = await bot.wait_for('message', check=check)
# or if you still want to use lambda expressions
msg = await bot.wait_for('message', check=lambda message: message.author == guild.owner and isinstance(message.channel, discord.DMChannel))
You could add the #commands.dm_only() decorator for the command to only work in a DM channel:
import discord
from discord.ext import commands
#bot.command()
#commands.dm_only()
async def something(ctx):
#do something
Or you could change your check to check if the message was sent in a DM channel:
msg = await bot.wait_for('message', check=lambda message: message.author == guild.owner and isinstance(message.channel, discord.DMChannel))