你好,我正在尝试做一个反垃圾邮件机器人,以工作捕捉垃圾邮件发送者和踢出服务器。但我的问题是,代码忽略了行会中的所有通道,而不是json文件中的通道。这是我的代码,请您看一看,并更新我做错了什么。谢谢
@client.listen()
async def on_message(message):
counter = 0
with open("spam-bank.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
try:
with open("channels.json", "r") as r:
j = json.load(r)
all_channels = j["channels"]
return all_channels
if counter > 3:
await message.channel.send(f'{message.author} has been kicked for spamming')
await message.guild.kick(message.author,reason="Caught by Anti-Spam for Spamming")
print(f'{message.author} was kicked')
await asyncio.sleep(2)
except:
return
@client.command()
async def ignore(ctx, channel_):
def add_channel(channel, file="channels.json"):
with open(file, "r+") as fw:
j = json.load(fw)
j["channels"].append(channel)
with open(file, "w+") as wp:
wp.write(json.dumps(j))
try:
with open("channels.json", "r"):
pass
except:
with open("channels.json", "w+") as wp:
wp.write('{"channels" : []}')
finally:
add_channel(channel_)
await ctx.send("Done!")发布于 2022-09-02 18:22:14
问题是:
with open("channels.json", "r") as r:
j = json.load(r)
all_channels = j["channels"]
return all_channels当执行命中return all_channels时,函数结束,并返回all_channels。在此之后将不会有任何代码。
相反,您需要编写代码来检查消息被发送到的通道是否包含在all_channels中,并且只在这种情况下返回/跳过。
将来解决这个问题的一个简单方法是添加许多临时的print语句,并通过跟随print语句来跟踪这个函数。
with open("channels.json", "r") as r:
j = json.load(r)
print("loaded json from file")
all_channels = j["channels"]
print(f"extracted channels from json: {all_channels}")
return all_channels
print(f"checking counter: {counter}")
if counter > 3:
print("user has sent more than 3 messages. Kicking..")
await message.channel.send(f'{message.author} has been kicked for spamming')
await message.guild.kick(message.author,reason="Caught by Anti-Spam for Spamming")
print(f'{message.author} was kicked')
await asyncio.sleep(2)你会得到像这样的输出
loaded json from file
extracted channels from json: [list]从这一点,您可以很容易地看出,在打印语句和下一个语句之间出现了问题,因为checking counter: [number]没有被打印出来。
https://stackoverflow.com/questions/73586380
复制相似问题