Python Discord Bot TypeError求助:__init__参数传入错误
问题分析
你报错的核心原因是错误地将interactions.Client实例作为位置参数传给了discord.Client的构造函数,同时command_prefix是discord.ext.commands.Bot类的参数,并非discord.Client的参数。
discord.Client的构造函数仅接收self作为位置参数(实例化时无需手动传递),你额外传入的interactions.Client(token="")属于多余的位置参数,直接触发了TypeError。
解决方案
要同时实现$前缀命令和斜杠命令,推荐使用discord.ext.commands.Bot(它继承自discord.Client,天然支持前缀命令,同时兼容discord.py的斜杠命令系统),无需混用interactions库(除非有特殊需求)。
修正后的核心代码
print("starting... ") import requests import discord from discord.ext.commands import Bot from discord.ext import commands from discord import app_commands import discord.ext.tasks import python_weather import asyncio from datetime import datetime import random import math import subprocess import time import os # 移除多余的interactions导入 print("imports successful") now = datetime.now() intents = discord.Intents.all() # 用commands.Bot替代discord.Client,传入正确参数 bot = commands.Bot(command_prefix='$', intents=intents) # 示例:斜杠命令 @bot.tree.command(name="hello", description="发送问候") async def hello_slash(interaction: discord.Interaction): await interaction.response.send_message(f"你好 {interaction.user.mention}!") # 同步斜杠命令到服务器(全局同步需等待1小时,测试可指定guild_id) async def setup_hook(): await bot.tree.sync() bot.setup_hook = setup_hook # 示例:前缀命令($hello) @bot.command(name="hello") async def hello_prefix(ctx): await ctx.send(f"你好 {ctx.author.mention}!") # on_message事件(必须调用process_commands,否则前缀命令不生效) @bot.event async def on_message(message): if message.author == bot.user: return # 让Bot处理前缀命令的关键步骤 await bot.process_commands(message) # 你的其他消息处理逻辑 if message.content == "测试": await message.channel.send("收到测试消息!") # 启动Bot(替换为你的真实token) bot.run("你的Bot Token")
关键说明
- 替换实例化类:用
commands.Bot替代discord.Client,它专门为前缀命令设计,支持command_prefix参数,同时保留discord.Client的所有事件功能。 - 斜杠命令实现:通过
bot.tree.command装饰器定义,调用bot.tree.sync()完成命令同步到服务器。 on_message事件注意:必须添加await bot.process_commands(message),否则前缀命令无法被Bot识别处理。
内容的提问来源于stack exchange,提问作者RegularCoder
相关产品推荐
相关产品推荐

