You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py使用print命令打印字符串时触发TypeError错误求助

Fixing "TypeError: unsupported operand type(s) for +: 'Member' and 'str'" in Discord.py

嘿,这个问题我熟!你碰到的错误根源很简单:message.author返回的是一个Member对象,不是字符串类型,Python当然没法直接把对象和字符串用+拼接在一起啦。

解决办法有这几种,挑你喜欢的用就行:

  1. 把Member对象转成字符串
    用str()函数把message.author转换成字符串后再拼接:

    @client.event
    async def on_message(message):
        print(str(message.author) + ' sent a message.')
    
  2. 用f-string(推荐!更简洁)
    Python的f-string会自动帮你把对象转换成字符串,写法清爽很多:

    @client.event
    async def on_message(message):
        print(f'{message.author} sent a message.')
    
  3. 获取特定的用户信息
    如果你不想显示带#后缀的完整用户名,还可以直接调用对象的属性:

    • 只拿纯用户名:message.author.name
    • 拿服务器内的昵称(如果用户设置了的话):message.author.display_name
      代码示例:
    @client.event
    async def on_message(message):
        # 显示纯用户名
        print(f'{message.author.name} sent a message.')
        # 显示服务器昵称
        # print(f'{message.author.display_name} sent a message.')
    

这样修改后,你的机器人就能正常在控制台打印消息提示啦~

内容的提问来源于stack exchange,提问作者user9818240

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:33