Skip to main content
 首页 » 编程设计

python之SlackAPI之无法返回包含多个变量的消息

2024年11月01日15虾米姐

我的 Slack 机器人有以下代码:

    if command.startswith(COMMAND_FIVE): 
        owm = pyowm.OWM() 
 
        owm.set_API_key('') 
        observation = owm.weather_at_id(4744326) 
        w = observation.get_weather() 
        jsondata= w.get_temperature('fahrenheit') 
        RESPOND = ("The current temperature (Fahrenheit) is:",(jsondata["temp"]),"\nThe high is:",(jsondata["temp_max"]),"\nThe low is:",(jsondata["temp_min"]),"\n*Note: This can change*") 
        response = (RESPOND) 
        print("Someone got the weather.") 
 
    # Sends the response back to the channel 
    slack_client.api_call( 
        "chat.postMessage", 
        channel=channel, 
        text=response or default_response 
    ) 

当我调用这个命令时,我得到以下结果:

我如何格式化消息以便它返回所有内容,而不仅仅是底线?

请您参考如下方法:

您的代码未产生预期结果的原因是您将文本作为字符串元组传递给 API 方法。显然,API 方法在内部将其减少到只有一个元素(最后一个)。

要完成这项工作,您需要将文本作为一个完整的字符串传递给 API 方法的文本属性。

这是您的代码的新版本,应该可以更好地工作:

RESPOND = [ 
    "The current temperature (Fahrenheit) is: {0:.2f}".format(jsondata["temp"]), 
    "The high is: {0:.2f}".format(jsondata["temp_max"]), 
    "The low is: {0:.2f}".format(jsondata["temp_min"]), 
    "*Note: This can change*"] 
response = "\n".join(RESPOND)