如何制作对每条消息发送鸽子表情的Discord机器人?
实现Discord机器人自动回复鸽子表情
先修正你原代码里的问题
- 密钥导入语法错误:
from apikeys import Bot Token不符合Python变量命名规则,apikeys.py里的token变量名不能有空格,改成from apikeys import bot_token(对应apikeys.py里写bot_token = "你的机器人Token") - 循环和判断语句缺少冒号:
for filename in os.listdir("./cogs")和if filename.endswith(".py")末尾必须加: - 变量名拼写错误:
initial_extension.append应该是initial_extensions.append(复数形式) - 缩进混乱:
if __name__ == "__main__":块不能嵌套在文件遍历的if判断里,要和for循环同级 - 核心功能缺失:没加监听消息的事件函数,没法实现自动回复
完整可运行的代码
import discord from discord.ext import commands import os # 从apikeys.py导入机器人token(确保apikeys.py里变量名为bot_token) from apikeys import bot_token # 配置Intents,必须开启message_content才能读取消息 intents = discord.Intents.default() intents.message_content = True intents.members = True client = commands.Bot(command_prefix="!", intents=intents) @client.event async def on_ready(): print("Pigebot fliegt Los!") print("-------------------") # 监听所有消息,自动回复鸽子表情 @client.event async def on_message(message): # 忽略机器人自己发的消息,防止无限循环 if message.author == client.user: return # 发送鸽子表情,用默认emoji🐦或者自定义表情(格式:<:表情名:表情ID>) await message.channel.send("🐦") # 如果需要保留命令功能,必须加这行,否则命令会失效 await client.process_commands(message) # 加载cogs模块(如果有需要的话) initial_extensions = [] for filename in os.listdir("./cogs"): if filename.endswith(".py"): initial_extensions.append(f"cogs.{filename[:-3]}") if __name__ == "__main__": for extension in initial_extensions: try: client.load_extension(extension) print(f"加载扩展 {extension} 成功") except Exception as e: print(f"加载扩展 {extension} 失败: {e}") # 启动机器人 client.run(bot_token)
关键注意点
- Intents权限:除了代码里开启
message_content,还要去Discord开发者平台的机器人设置里,开启Privileged Gateway Intents下的Message Content Intent,否则机器人读不到消息。 - 避免无限循环:一定要判断
message.author == client.user,不然机器人会自己回复自己的消息,陷入死循环。 - 自定义表情:如果想用服务器里的自定义鸽子表情,把
"🐦"换成<:pigeon:123456789>(123456789替换成你的表情ID)。 - 命令兼容:如果你的机器人还要用
!开头的命令,必须保留await client.process_commands(message),否则on_message会拦截所有消息,命令无法触发。
内容的提问来源于stack exchange,提问作者Martunity
相关产品推荐
相关产品推荐

