问题
I am very new to programming and just learning. I figured making a discord bot is a good way to learn and I'm enjoying it, I'm just a little stuck. So my bot is private and there's a running joke in our discord server that whenever a user sends "k" all bots respond with "k". ATM we have Dyno, my friend's private bot and hopefully mine. I got all my code working except because the command and the answer is the same my bot just spams the server with "k" until I shut down the bot, how do I stop it?
The code:
@client.event
async def on_message(message):
if message.content ==("k"):
await client.send_message(message.channel, "k")
await client.process_commands(message)
回答1:
You can simply run this on your message event:
if(!message.author.user.bot) return; //not the exact code
Because the message event can return
the user, and the user has a default bot check. message.author
returns a member, so you can call the user
object of member and then perform the check as I did above.
Pseudocode:
If the author of the message (user) is a bot: return;
This will prevent an infinite loop from occuring
回答2:
It is ok, I finally figured it out. To those having the same issue you have to add
if message.author == client.user:
return
if message.author.bot: return
to the code and it works so mine looks like this now:
@client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.author.bot: return
if message.content.startswith('k'):
msg = 'k'.format(message)
await client.send_message(message.channel, msg)
来源:https://stackoverflow.com/questions/48320766/how-to-stop-discord-bot-respond-to-itself-all-other-bots-discord-bot-in-python