这是我尝试过的代码:
@client.event
async def on_message(message):
if client.user.mention in message.content.split():
await client.say("You can type `!vx help` for more info.")
但它似乎不起作用。
使用命令修饰器时,您可以执行以下操作:
from discord.ext import commands # necessary for this task
client = commands.Bot(command_prefix=commands.when_mentioned_or("!"))
或者使用on_message()
事件,这是您可以检查提及的众多方法之一:
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("You can type `!vx help` for more info")
另外,我注意到您向频道发送消息的方法不太正确。
在 d.py 重写 (v1.x( 中,您有一个abc.Messageable
对象,顾名思义,它类似于服务器的文本通道、DM 或群聊。
这个对象有一个名为send()
的方法,它允许你发送内容。您会发现这种情况的一些常见情况是;ctx.send()
当您使用命令修饰器时 - 它们将Context
作为第一个参数 - 当您像您一样使用on_message()
事件时message.channel.send()
。它也会出现在其他一些地方,但这些将是最常见的。
您已经正确了解它是协程,因此需要对其进行await
。在文档中,它将说明某些内容是否是协程。
引用:
commands.when_mentioned_or()
ClientUser.mentioned_in()
abc.Messageable
- 查看可以将消息send()
的内容。commands.Context
- 这继承自abc.Messageable
。Messageable.send()
@client.event async def on_message(message):
if client.user.mention in message.content.split():
await client.say("You can type `!vx help` for more info.")
代替 content.split(( 使用内容: 而不是client.say使用message.channel.send(( 所以我们会得到
@client.event
async def on_message(message):
if client.user.mention in message.content:
await message.channel.send("You can type `!vx help` for more info.")
@bot.event#ping reply
async def on_message(message):
if message.author.bot == False and bot.user.mentioned_in(message) and len(message.content) == len(bot.user.mention)+1:
await message.channel.send(f'Hello! I am the {bot.user.mention}!nMy Prefix is $')
else:
await bot.process_commands(message)
该方法非常简单,在 bot.event 中机器人将读取每条消息,请检查以下内容
- ping 不是来自不同的机器人,而是仅来自用户
- 消息中提到了机器人
- 仅提到了机器人,它避免了在 convo 中意外提及/ping。 长度为 +1 表示换行符。
bot.process_commands(message)
在那里,如果它不是 ping,那么机器人可以进一步处理消息/命令。
这是一个使用类的类似解决方案。我对确切的情况有问题,最终设法解决了它,但找不到任何这样的例子。关键是if self.user in message.mentions:
线。
message.mentions
是指用户列表,以便您可以自己或其他任何人进行检查。
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# Don't respond to ourselves
if message.author == self.user:
return
# If bot is mentioned, reply with a message
if self.user in message.mentions:
await message.channel.send("You can type `!vx help` for more info.")
return
def main():
client = MyClient()
client.run(DISCORD_TOKEN)
if __name__ == "__main__":
main()