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)
CodePudding user response:
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)
CodePudding user response:
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)