使用Pine Script的alert()发送TradingView警报至Discord失败求助
TradingView警报无法发送至Discord的排查与修复
问题情况
- TradingView的警报消息无法送达Discord频道,频道始终为空
- 已确认Discord相关设置(机器人/webhook)正确,曾怀疑消息末尾缺失
},但代码中已包含该符号
原代码
bullCondition_Label = "TF Period1: " + TF1 + " " + syminfo.ticker + '\n' + 'Background Change to Green \n' if barstate.islast for i = 0 to 19 LabelAdd = array.get(s_arr, i) + ' Price:' + str.tostring(array.get(price_arr, i), '#.#') + '\n' bullCondition_Label := array.get(bullCond_arr, i) ? bullCondition_Label + LabelAdd : bullCondition_Label if bullCondition alert_message1= "{\"content\":\"" + '\n'+ bullCondition_Label + "\"}" alert(alert_message1, alert.freq_once_per_bar_close)
问题根源
你的代码存在JSON格式转义错误:
bullCondition_Label中包含的\n换行符,在JSON字符串里需要转义为\\n,否则Discord的Webhook会解析失败,直接丢弃无效的JSON消息- 开头多余的
\n也会干扰JSON结构的正确性
修复后的代码
bullCondition_Label = "TF Period1: " + TF1 + " " + syminfo.ticker + '\n' + 'Background Change to Green \n' if barstate.islast for i = 0 to 19 LabelAdd = array.get(s_arr, i) + ' Price:' + str.tostring(array.get(price_arr, i), '#.#') + '\n' bullCondition_Label := array.get(bullCond_arr, i) ? bullCondition_Label + LabelAdd : bullCondition_Label if bullCondition // 将换行符转义为JSON支持的格式 escaped_label = str.replace_all(bullCondition_Label, '\n', '\\n') // 拼接正确的JSON字符串 alert_message1 = "{\"content\":\"" + escaped_label + "\"}" alert(alert_message1, alert.freq_once_per_bar_close)
额外排查步骤
- 验证Discord Webhook URL是否完全正确,无多余空格或字符
- 用最简JSON测试:
{"content":"测试消息"},确认Webhook能正常接收消息 - 检查
bullCondition触发逻辑:可以在图表上添加标签验证条件是否生效,比如if bullCondition => label.new(bar_index, high, "条件触发")
内容的提问来源于stack exchange,提问作者mgoblue33
相关产品推荐
相关产品推荐

