📜  如何使用Python和 MSG91 API 发送 SMS 警报

📅  最后修改于: 2022-05-13 01:54:45.753000             🧑  作者: Mango

如何使用Python和 MSG91 API 发送 SMS 警报

在我们的大学时代,我们经常忘记我们的日常课程,对吧?为了每天跟踪课程,我们可以使用Python向他们的手机发送通知(即)SMS Alert about their classes。

我们需要使用两个功能: http 模块和用于发送 SMS 的MSG91 API

import http.client as ht
  
conn = ht.HTTPSConnection("api.msg91.com")

这里我们在 http 模块中导入 http 客户端函数(因为我们使用我们的系统作为客户端,msg91 api 服务作为服务器)并使用 HTTPSConnection函数建立与 SMS API 服务(MSG91)的连接。

在建立连接时,我们需要在数据包中发送两个主要参数(即 Header 和 Payload)。

标头:在标头中,我们将发送我们的 MSG91 API 的身份验证密钥。当然,上下文文本只不过是上下文类型,它表示有效负载的类型。我们以 JSON 格式发送所有有效负载信息,因此上下文类型将为 JSON。

headers = {# Paste your MSG91 API Key
           'authkey' : "", 
           'content-type': "application/json"}

您需要在 MSG91 中创建一个帐户,并且您需要在 MSG91 中创建一个 API 密钥才能发送短信。

有效载荷:大家都知道有效载荷是发送或接收数据的重要部分。在这里,我们发送发送者 ID、路线、国家以及消息和接收者手机号码。发件人 ID 只不过是发件人姓名。它的长度必须为 6,并且只能包含字母字符。如果您想在国际上发送短信,则使用 0 作为国家代码,否则使用 91 进行印度通信。

payload = '''{"sender": "MSGAPI",
              "route": "4",
              "country": "91",
              "sms": [
                {
                  "message": "Welcome X, Today you have PC class",
                  "to": [
                    "9090XX8921"
                  ]
                },
                {
                  "message": "Welcome Y, Today you have WT Class",
                  "to": [
                    "901X83XX01"
                  ]
                }
              ]
            }'''

现在我们需要连同这个头和有效负载一起发送连接请求。这里我们使用 POST 方法来建立连接。发送请求后,API 会将消息发送给我们之前提到的 JSON 数组的接收者。然后 API 用状态码 200 和成功消息确认我们。

# importing the module
import http.client as ht
  
# establishing connection
conn = ht.HTTPSConnection("api.msg91.com")
  
# determining the payload
payload = '''{"sender": "MSGAPI",
              "route": "4",
              "country": "91",
              "sms": [
                {
                  "message": "Welcome GeeksForGeeks, Today you have PC class",
                  "to": [
                    "9090XX8921"
                  ]
                },
              ]
            }'''
  
# creating the header
headers = {
    'authkey': "", 
    'content-type': "application / json"
}
  
# sending the connection request
conn.request("POST", "/api / v2 / sendsms", payload, headers)
  
res = conn.getresponse()
data = res.read()
  
# printing the acknowledgement
print(data.decode("utf-8"))