简体   繁体   中英

Discord.py On Message Sending Infinite Messages

I have a code

#!/usr/bin/env python3
import discord
import json
from discord.ext import commands

with open('config.json', 'r') as config:
    config = json.load(config)

token = config['token']
prefix = config['prefix']

client = commands.Bot(command_prefix=prefix)

@client.event
async def on_ready():
    print('Bot is ready!')

@client.event
async def on_message(message):
    if message.content.startswith == 'hi' or 'Hi':
        await message.channel.send('Hello!')
    else:
        await client.process_commands(message)

client.run(token)

And I Had Typed hi Once And It Spammed Hello And After Reopening It Still Spammed Hello Is There Any Way To Fix This?

The reason your bot is spamming "hello" is it's responding to itself. A simple way can be used to fix this which checks if the user is a bot, if so it would just return and simply nothing would happen if a bot said "hello"

@client.event
async def on_message(message):
    if message.author.bot:
        return
    if message.content.startswith == 'hi' or 'Hi':
        await message.channel.send('Hello!')
    else:
        await client.process_commands(message)

Here I have added message.author.bot , this would check if the user is a bot or not, or if the bot is responding to itself and prevent spamming.

It's sending an infinite number of messages because your conditional is incorrect. The first comparison is message.content.startswith() == 'hi' , which will always be False (stick your string in the parentheses). The second is 'Hi' which will always be True , since it is not an empty string.

Correct your condition to if message.content.startswith('hi') or message.content.startswith('Hi'): and it should work.

This is a basic Python problem. if message.content.startswith == 'hi' or 'Hi': doesn't means:

if (message content is either hi or Hi)

It means:

if (message content is hi) or (Hi)

In this case, Hi will always return True . That's why your bot is spamming messages.

You can prevent this by variant ways. But the best way to fix this is using str.lower()

Also, you cannot use str.startswith() function like that. You have to type the string inside the parentheses.

@client.event
async def on_message(message):
    if message.content.lower().startswith('hi'):
        await message.channel.send('Hello!')
    else:
        await client.process_commands(message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM