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

Python3+Pyst2开发Asterisk FastAGI遇字节类型错误求助

解决Python3+pyst2开发Asterisk FastAGI的"bytes-like object is required"错误

这个错误的核心原因是Python3严格区分字符串(str)和字节(bytes)类型,而pyst2在Python3环境下的AGI交互需要使用字节对象传递数据,以下是针对性修复方案:

  • AGI命令及参数传递改为字节类型
    调用agi.execute()等方法时,将命令名和参数都加上b前缀转为字节,比如:

    # 错误写法
    agi.execute('PLAYBACK', 'welcome')
    # 正确写法
    agi.execute(b'PLAYBACK', b'welcome')
    
  • AGI返回结果转字符串处理
    调用agi.get_variable()等获取返回值的方法时,返回的是字节对象,需解码为字符串后再做拼接、判断等操作:

    caller_id_byte = agi.get_variable(b'CALLERID(num)')
    caller_id_str = caller_id_byte.decode('utf-8')
    
  • 自定义文本输出转为字节
    使用agi.send_text()发送文本时,同样要传递字节对象:

    # 错误写法
    agi.send_text('Hello caller')
    # 正确写法
    agi.send_text(b'Hello caller')
    
  • 升级pyst2到Python3兼容版本
    确保安装的是支持Python3的pyst2版本,执行以下命令升级:

    pip install --upgrade pyst2
    

修正后代码示例

from pyst2 import AGI

agi = AGI()
# 播放欢迎音
agi.execute(b'PLAYBACK', b'welcome')
# 获取主叫号码并转字符串
caller_id_byte = agi.get_variable(b'CALLERID(num)')
caller_id_str = caller_id_byte.decode('utf-8')
# 发送提示文本
agi.send_text(b'Your caller ID is: ' + caller_id_str.encode('utf-8'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:59:56