[英]Discord.py On Message Sending Infinite Messages
我有一个代码
#!/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)
我曾经输入过你好,它发送垃圾邮件你好,重新打开后仍然发送垃圾邮件你好有什么办法可以解决这个问题吗?
您的机器人发送“你好”的垃圾邮件的原因是它在响应自己。 可以使用一种简单的方法来解决这个问题,它检查用户是否是机器人,如果是,它就会返回,如果机器人说“你好”,什么都不会发生
@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)
在这里我添加了message.author.bot
,这将检查用户是否是机器人,或者机器人是否正在响应自己并防止垃圾邮件。
由于您的条件不正确,它会发送无限数量的消息。 第一个比较是message.content.startswith() == 'hi'
,它总是False
(把你的字符串放在括号里)。 第二个是'Hi'
,它总是True
,因为它不是一个空字符串。
将您的条件更正为if message.content.startswith('hi') or message.content.startswith('Hi'):
它应该可以工作。
这是一个基本的 Python 问题。 if message.content.startswith == 'hi' or 'Hi':
并不意味着:
if(消息内容是 hi 或 Hi)
它的意思是:
if (message content is hi) or (Hi)
在这种情况下, Hi将始终返回True
。 这就是您的机器人发送垃圾邮件的原因。
您可以通过不同的方式来防止这种情况。 但解决此问题的最佳方法是使用str.lower()
此外,您不能像这样使用str.startswith()
function 。 您必须在括号内键入字符串。
@client.event
async def on_message(message):
if message.content.lower().startswith('hi'):
await message.channel.send('Hello!')
else:
await client.process_commands(message)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.