How to stop discord bot respond to itself/all other bots [Discord Bot in Python 3.6]

爷,独闯天下 提交于 2019-12-11 18:19:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!