Python Discord机器人报错:缺少keko和msg两个必要位置参数求助
解决Discord机器人TypeError: send_message_from_webhook()缺失参数问题
你的错误源于调用send_message_from_webhook时仅传入了message参数,但函数定义明确要求keko和msg两个必填参数。要修复问题,需从用户发送的命令文本中提取这两个参数,再传递给函数。
修改步骤:
- 拆分用户输入的命令内容,分离出
keko(目标用户名)和msg(待发送消息) - 在调用
send_message_from_webhook时传入提取到的两个参数 - 添加参数校验与异常处理,避免因用户输入格式错误或API请求失败导致崩溃
修改后的完整代码:
from discord_webhook import DiscordWebhook import discord from discord.ext import commands import requests bot = commands.Bot(command_prefix='!', description="") bot.remove_command("help") @bot.event async def on_message(message : discord.Message): if message.author == bot.user: return content_parts = message.content.split() # 校验命令格式是否正确:!prueba 用户名 消息内容 if len(content_parts) >= 3 and content_parts[0] == '!prueba': keko = content_parts[1] msg = ' '.join(content_parts[2:]) await send_message_from_webhook(message, keko, msg) await message.delete() async def send_message_from_webhook(message : discord.Message, keko, msg): webhook = None try: webhook = await message.channel.create_webhook(name='haboo') response = requests.get(f"https://www.habbo.es/api/public/users?name={keko}") # 检查API请求是否成功 if response.status_code != 200: await message.channel.send(f"无法获取用户{keko}的信息") return skinhabbo = response.json()['figureString'] await webhook.send( content=msg, username=keko, avatar_url=f"https://www.habbo.com/habbo-imaging/avatarimage?size=m&figure={skinhabbo}&action=sit&direction=4&head_direction=4&gesture=std&size=m" ) except Exception as e: await message.channel.send(f"消息发送失败: {str(e)}") finally: # 确保webhook被删除,避免频道残留无效webhook if webhook: await webhook.delete() @bot.event async def on_ready(): print("BOT ready") bot.run("你的Bot Token")
关键修改说明:
- 在
on_message中拆分命令内容,从!prueba sefos hi里提取出keko=sefos和msg=hi - 增加API请求状态码检查,避免因用户不存在导致的KeyError
- 使用try-except-finally结构,确保无论是否出错都能删除创建的webhook
- 添加命令格式校验,防止用户输入不完整命令引发异常
内容的提问来源于stack exchange,提问作者paulita
相关产品推荐
相关产品推荐

