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

mIRC脚本调用LastFM API求助:实现!lfm触发显示艺人信息

mIRC脚本:修复!lfm指令调用LastFM API的问题

原脚本的核心问题

  • 触发指令不匹配:需求是!lfm,但原代码监听的是.lfm,导致指令无法触发。
  • 参数传递失败:艺人名称和API密钥未传递到sockopen事件,请求里硬写了无效的API_KEY,且艺人名未做URL编码,特殊字符会导致请求无效。
  • 响应处理错误:仅读取一行响应就输出固定文本,未解析LastFM返回的JSON数据,无法获取实际信息。
  • 错误处理逻辑失效:sockError别名调用方式错误,无法正确捕获套接字错误。

修复后的完整代码

; 设置你的Last.fm API密钥
alias SetAPIKey {
  return 你的有效API密钥 ; 替换成你自己的API密钥
}

; 监听频道中的!lfm指令
on *:TEXT:!lfm *:#: {
  ; 提取完整艺人名称(支持带空格的名字)
  var %artist = $2-
  if (%artist == $null) {
    msg $chan 请输入艺人名称,格式:!lfm 艺人名
    return
  }

  ; 获取API密钥并校验
  var %apiKey = $SetAPIKey()
  if (%apiKey == $null || %apiKey == "你的有效API密钥") {
    notice $nick 请先在SetAPIKey别名中设置有效的LastFM API密钥
    return
  }

  ; 打开套接字,用sockmark传递参数
  sockclose LastFmSock
  sockopen -ea LastFmSock ws.audioscrobbler.com 443
  sockmark LastFmSock %artist %apiKey
}

; 套接字打开事件
on *:sockopen:LastFmSock:{
  ; 处理连接错误
  if ($sockerr) {
    notice $nick 连接LastFM失败:$sock($sockname).wsmsg
    sockclose $sockname
    return
  }

  ; 从sockmark取出参数
  var %artist = $sock($sockname).mark(1)
  var %apiKey = $sock($sockname).mark(2)
  ; 对艺人名称做URL编码,处理特殊字符
  var %encodedArtist = $urlencode(%artist)

  ; 发送标准HTTP请求
  sockwrite -n $sockname GET /2.0/?method=artist.getinfo&artist=%encodedArtist&api_key=%apiKey&format=json HTTP/1.1
  sockwrite -n $sockname Host: ws.audioscrobbler.com
  sockwrite -n $sockname Connection: close
  sockwrite -n $sockname
}

; 读取套接字响应
on *:sockread:LastFmSock:{
  var %response = $null
  ; 读取完整响应内容
  while ($sock($sockname).r) {
    sockread %line
    var %response = %response %line
  }

  ; 处理API返回的错误
  if ($pos(%response, "error") != $null) {
    var %errorMsg = $json(%response, message)
    msg $chan 查询失败:%errorMsg
    sockclose $sockname
    return
  }

  ; 解析JSON数据
  var %artistName = $json(%response, artist, name)
  var %genre = $iif($json(%response, artist, tags, tag, 0, name) != $null, $json(%response, artist, tags, tag, 0, name), "未知流派")
  var %playCount = $json(%response, artist, stats, playcount)

  ; 输出结果到频道
  msg $chan [艺人名称: %artistName] | [流派: %genre] | [播放量: %playCount]

  sockclose $sockname
}

关键修改说明

  1. 触发指令修正:把.lfm改成!lfm,用$2-获取完整艺人名称,支持带空格的名字(比如!lfm Linkin Park)。
  2. 参数传递优化:用sockmark将艺人名称和API密钥传递到套接字事件,解决局部变量无法跨事件访问的问题。
  3. URL编码处理:用$urlencode处理艺人名称,确保空格、特殊字符不会破坏请求URL的有效性。
  4. 完整响应读取:循环读取所有响应内容,保证拿到完整的JSON数据,避免因分段返回导致解析失败。
  5. JSON解析实现:使用mIRC内置的$json标识符解析返回数据,提取艺人名称、流派(取第一个标签)、播放量字段。
  6. 错误处理完善:增加API密钥校验、连接错误提示,以及LastFM返回的业务错误信息展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:06:23