编辑:我终于使代码正常工作,但仅适用于一个通道。有没有办法使它成为2个频道?尝试做“或”,但不起作用。它只接受一个频道,或者有时它忽略所有内容。
例如一般删除所有用户消息,然后进行测试,除了“ ask”或“!question”以及“测试中!test”
@commands.Cog.listener()
async def on_message(self, message):
if not message.guild:
return
if not message.channel.name == 'general':
return
if message.channel.name == 'general' and message.content != '!ask' or '!question':
if message.author.bot:
pass
else:
await message.delete()
答案 0 :(得分:0)
您可以通过探索message author is a bot来检查是否command name(响应命令)或消息是否包含every commands:
@commands.Cog.listener()
async def on_message(self, ctx):
if not message.guild:
return
for command in self.client.commands:
if command.name in message or message.author.bot:
return
await message.delete()
要使其在特定渠道上运作,您有多种选择:
bot_channels = {}
@commands.command()
async def bot_channel(self, ctx):
try:
temp = bot_channels[ctx.guild.id]
except:
bot_channels[ctx.guild.id] = [ctx.channel.id]
print(f"Set {ctx.channel} as a bot channel")
else:
if ctx.channel.id in bot_channels[ctx.guild.id]:
bot_channels[ctx.guild.id].pop(ctx.channel.id)
print(f"{ctx.channel} is no longer a bot channel")
else:
bot_channels[ctx.guild.id].append(ctx.channel.id)
print(f"Set {ctx.channel} as a bot channel")
@commands.Cog.listener()
async def on_message(self, ctx):
try:
temp = bot_channels[ctx.guild.id]
except:
return
else:
if not message.guild:
return
for command in self.client.commands:
if (command.name in message or message.author.bot) and message.channel.id in bot_channels[ctx.guild.id]:
return
await message.delete()
json
library和json文件(数据量适中时效率更高):{}
您的python代码
from json import loads, dumps
@commands.command()
async def bot_channel(self, ctx):
with open('file directory', 'r') as file:
data = file.read()
bot_channels = loads(data)
try:
temp = bot_channels[str(ctx.guild.id)]
except:
bot_channels[str(ctx.guild.id)] = [ctx.channel.id]
print(f"Set {ctx.channel} as a bot channel")
else:
if ctx.channel.id in bot_channels[str(ctx.guild.id)]:
bot_channels[ctx.guild.id].pop(ctx.channel.id)
print(f"{ctx.channel} is no longer a bot channel"
else:
bot_channels[str(ctx.guild.id)].append(ctx.channel.id)
print(f"Set {ctx.channel} as a bot channel")
with open("filename.json", "w") as file:
bot_channels = file.write(dumps(bot_channels))
@commands.Cog.listener()
async def on_message(self, ctx):
with open('file directory', 'r') as file:
data = file.read()
bot_channels = loads(data)
try:
temp = bot_channels[ctx.guild.id]
except:
return
else:
if not message.guild:
return
for command in self.client.commands:
if (command.name in message or message.author.bot) and message.channel.id in bot_channels[ctx.guild.id]:
return
await message.delete()