我有一个代码
#!/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)
我打过一次你好,它发送了你好,重新打开后仍然发送你好有什么办法可以解决这个问题吗?
答案 0 :(得分:0)
您的机器人发送垃圾邮件“你好”的原因是它正在对自己做出回应。可以使用一种简单的方法来解决此问题,即检查用户是否是机器人,如果是,它只会返回,如果机器人说“你好”,则不会发生任何事情
@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
,这将检查用户是否是机器人,或者机器人是否正在响应自己并防止垃圾邮件。
答案 1 :(得分:0)
它发送了无数条消息,因为您的条件不正确。第一个比较是 message.content.startswith() == ‘hi’
,它将始终为 False
(将您的字符串放在括号中)。第二个是 ’Hi’
,它永远是 True
,因为它不是空字符串。
将您的条件更正为 if message.content.startswith(‘hi’) or message.content.startswith(‘Hi’):
,它应该可以工作。
答案 2 :(得分:0)
这是一个基本的 Python 问题。 if message.content.startswith == 'hi' or 'Hi':
并不意味着:
if(消息内容是 hi 或 Hi)
意思是:
<块引用>if(消息内容为hi)或(Hi)
在这种情况下,Hi 将始终返回 True
。这就是您的机器人发送垃圾邮件的原因。
您可以通过多种方式防止这种情况发生。但解决此问题的最佳方法是使用 str.lower()
此外,您不能像那样使用 str.startswith()
函数。您必须在括号内输入字符串。
@client.event
async def on_message(message):
if message.content.lower().startswith('hi'):
await message.channel.send('Hello!')
else:
await client.process_commands(message)