What does redefinition of unused 'on_message' mean - python

This bot that I am making on Discord is just a hangman game. I've been able to do the most basic part of the bot and now am trying to add a 2nd command. But there is an error on line 24 that pops up saying "redefinition of unused 'on_message' from line 13".
The 2nd command is supposed to print something once a person sends "$start". However, it does not work when I do so.
This is my current code:
import discord
import random
import os
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):
if message.author == client.user:
return
if message.content.startswith("$help"):
await message.channel.send("To start your game, type '$start'")
client.run(os.getenv("TOKEN"))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")
This is where the problem lies:
#client.event
async def on_message(message): #this is line 24
if message.author == client.user:
return
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")

Issue:
You have redefined the on_message function. This means, there are 2 functions with the same name on_message.
Solution:
Since you have been using some if statements to decide which function to execute on which command, you can group all if statements into one function, so your code would look like:
import discord
import random
import os
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):
if message.author == client.user:
return
if message.content.startswith("$help"):
await message.channel.send("To start your game, type '$start'")
if message.content.startswith("$start"):
await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")
client.run(os.getenv("TOKEN"))

The error states what it means literally: you are redefining the on_message event for the same Client.
Typically you would use the commands.Bot client from discord.ext branch instead of the native Client when implementing bots with commands.
So this piece of code:
client = discord.Client()
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$help"):
await message.channel.send("To start your game, type '$start'")
would be replaced with this:
client = commands.Bot("$")
#client.command()
async def help(ctx):
if ctx.author == client.user:
return
await message.channel.send("To start your game, type '$start'")
However FYI, you can have multiple on_message listeners in your code through the Bot.listen() decorator.

Related

Discord bot not responding (python)

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_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('token is here')
I'm trying to create a discord bot and I'm trying to use this simple code to get started but whenever I type the command ($hello) in a server that the bot is in it doesn't respond. Any solutions?
I'm assuming you're new to discord.py which is fine, though writing code like this is a little counter-intuitive. Instead of registering it as an event, why not just register it as an actual command?
This is how it should be done:
from discord.ext import commands
client = commands.Bot(command_prefix='$') # This can always be changed
#client.event()
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.command()
async def hello():
await ctx.send('Hello')
client.run('token is here')

Commands don't work. They used to work but they don't any more

I added the bot status and after that the
Commands don't work. Added a answerers answer but it still no work ( help works not but not hello ;-;)
import discord
from KeepAlive import keep_alive
client=discord.Client()
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online,activity=discord.Game('Hey There! Do €help to start!'))
print('We have logged in as {0.user}'.format(discord.Client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$help'):
await message.channel.send('no help here!')
await bot.process_commands(message)
keep_alive()
client.run('wont say token :)')
If you are talking about commands and not "commands" that you run with on_message then you have to add await client.process_commands(message) (check this issue in documentation). If your on_message event is not working then it's probably only because of missing _ in on_message event.
#client.event
async def on_message(message): # your forgot "_"
if message.author == client.user: # discord.Client won't work. Use client.user instead
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
if message.content.startswith('$help'):
await message.channel.send('no help here!')
await client.process_commands(message) # add this line at the end of your on_message event
the problem is your message function, it has async def onmessage(message): but the correct one is:
#client.event
async def on_message(message):
And I recommend defining the prefix and then separating it from the message so you don't have to keep typing $ in every if, and save the elements written after the command for future functions:
PREFIX = "$"
#client.event
async def on_message(message):
msg = message.content[1:].split(' ')
command = msg[0]
if command == "hello":
await message.channel.send('Hello!')

event message is not recognized

i'm trying to make a discord bot and I want to add functionality that handles events like ?help, ?creator etc. I want to send a message if the command after ? is not recognised. This is my code:
import os
import discord
client = discord.Client()
unrecogcommand = "I don't recognize this command do **?help** for the list of the available
commands :3"
#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('?'):
if message.content.startswith('?ownerfavOP'):
await message.channel.send("The server Owner really love Kaikai Kitan
https://www.youtube.com/watch?v=i1P-9IspBus :3")
if message.content.startswith('?creator'):
await message.channel.send("PashPash#7668 is the username of the creator and have a yt
channel https://www.youtube.com/channel/UCxJXY07JAsmJBaYf67KKk7Q")
if message.content.startswith('?help'):
await message.channel.send("Command available ```?help``` ```ownerfavOP```")
client.run(os.getenv('TOKEN'))
I would approach your command like that:
#client.event
async def on_message(message):
if message.author != client.user:
if message.content.startswith('?'):
if message.content.startswith('?ownerfavOP'):
# do something
elif message.content.startswith('?creator'):
# do something
elif message.content.startswith('?help'):
# do something
else:
print("Couldn't found that command.")
Note that I removed the return statment, since the command will automatically return if the message author equals the client user.
I hope this helps you, sheers!

kick is undefined in discord bot

I made a bot that kicks people when pinging #everyone on discord but the problem is that I get this error
NameError: name 'kick' is not defined
Here is the code:
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_message(message):
if message.author == client.user:
return
if message.content.startswith('#everyone'):
await kick(message.author,reason = "spam")
client.run('censored for obvious reasons')
I think the comments were already quite informative, but here is a possible solution anyway, in case others stumble across this "error".
Your information is not correct, but you have already provided all the information we need, only these must be changed in the arrangement.
Have a look at the following code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('#everyone'):
await message.author.kick(reason="Spam")
Here we get the message.author and kick him for the reason="Spam"
An await kick does not work here, because the bot does not know who to kick, even if you have already specified message.author as the person to be kicked. It's just the wrong arrangement.

On message delete message Discord.py

import discord
import asyncio
client = discord.Client()
#client.event
async def on_ready():
print ("I’m Now Online")
#client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith("deletethis"):
I’m wonder how I could be able to add to this to delete the above command when the author of the message sends the command above.
May someone help create one? I’ve tried my self by brain and didn’t find anything online so I’m looking for some help maybe.
for async just do
await client.delete_message(message)
otherwise for rewrite just do
await message.delete()
Finished code:
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("deletethis"):
await asyncio.sleep(1)
await message.delete()

Categories