Discord机器人使用@bot.command注册指令后无响应故障求助
问题根因
- 重复实例化客户端:
commands.Bot是discord.Client的子类,本身就支持所有原生Client的事件监听功能。你当前代码同时创建了client、bot两个完全独立的客户端实例,事件回调都注册在client上,命令都注册在bot上,最后运行的是client.run(),bot实例根本没有启动,自然不会响应任何命令。 - 缺少消息内容权限:Discord API v10 及以上版本强制要求机器人显式开启
message_content意图才能读取服务器内的普通消息内容,未开启该权限时机器人无法识别消息中的指令前缀和命令,自然无法触发命令回调。同时你初始化bot实例时没有传入已经配置好的intents参数。
修正后的可运行代码
import discord from discord.ext import commands from dotenv import load_dotenv import os import json import random import requests # 配置权限 intents = discord.Intents.default() intents.members = True intents.message_content = True # 必须开启消息内容意图 # 直接用Bot实例,不需要额外创建Client bot = commands.Bot(command_prefix="<:givebanana:852295575772856400>", intents=intents) @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) global points try: with open('data.txt') as f: points = json.load(f) except FileNotFoundError: print("Could not load data.txt") points = {} @bot.event async def on_member_join(member): embed=discord.Embed(title="Welcome",description="Be sure to change your status. Once that is done, you will be assigned the monke intern role. Why don't you say hello to our new monke, <@&852658353678319656>. Viva la monke!", color=discord.Color.from_rgb(0,128,0)) embed.set_thumbnail(url=member.avatar_url) channel = bot.get_channel(852677413367709706) await channel.send(f"{member.mention}", embed=embed) @bot.command() async def roles(ctx): embed=discord.Embed(title="Monke Roles",description="The more people DM you 'monke', the more points you earn.", color=discord.Color.from_rgb(255,255,53)) embed.set_thumbnail(url="http://www.clker.com/cliparts/f/1/e/9/H/i/banana-md.png") embed.add_field(name="Points",value="Someone DMs you and joins the server= 2 points\n\nSomeone DMs you but doesn't join= 1 point\n",inline=False) embed.add_field(name="🐵 Monke Employee",value="1 Point", inline=True) embed.add_field(name="🪖 Monke Soldier",value="5 Points",inline=True) embed.add_field(name="🚨 Monke Officer",value="10 Points",inline=True) embed.add_field(name="🎖️ Monke General",value="20 Points",inline=True) embed.add_field(name="🎩 Monke Mayor",value="30 Points",inline=True) embed.add_field(name="🏙️ Monke Govenor",value="50 Points",inline=True) embed.add_field(name="🏛️ Monke President",value="100 Points",inline=True) await ctx.send(ctx.author.mention,embed=embed) print('Command Sucessful') @bot.command() async def ping(ctx): await ctx.send('_**AH AH**_ Here!') # 运行bot实例,不是client bot.run('censoredtoken')
注意:修改代码后需要先进入Discord开发者平台的对应机器人管理页,在「Privileged Gateway Intents」区域开启
Message Content Intent开关,否则权限不足依然无法读取消息内容。
内容的提问来源于stack exchange,提问作者DotMatrixProgrammer
相关产品推荐
相关产品推荐

