欢迎访问宙启技术站
智能推送

用Python编写一个可以自动发送短信的Bot()程序

发布时间:2023-12-28 05:23:05

以下是一个使用Python编写的自动发送短信的Bot程序:

import requests

class SMSBot:
    def __init__(self, api_key, api_secret):
        self.api_key = api_key
        self.api_secret = api_secret
        self.base_url = 'https://api.nexmo.com'

    def send_sms(self, from_number, to_number, message):
        url = f"{self.base_url}/sms/json"
        payload = {
            'api_key': self.api_key,
            'api_secret': self.api_secret,
            'from': from_number,
            'to': to_number,
            'text': message
        }
        response = requests.post(url, data=payload)
        if response.status_code == 200:
            print('SMS sent successfully!')
        else:
            print('Failed to send SMS.')

# 使用例子
if __name__ == '__main__':
    # 替换为你自己的API Key和API Secret
    api_key = 'YOUR_API_KEY'
    api_secret = 'YOUR_API_SECRET'
    
    # 创建一个SMSBot对象
    bot = SMSBot(api_key, api_secret)
    
    # 发送短信
    bot.send_sms('YOUR_PHONE_NUMBER', 'RECIPIENT_PHONE_NUMBER', 'Hello, this is a test message from SMSBot!')

在上述代码中,我们定义了一个SMSBot类,该类具有api_keyapi_secret属性,用于进行API身份验证。send_sms方法使用Nexmo API发送短信。我们传入发送者号码、接收者号码和要发送的消息作为参数。

在使用例子中,你需要将YOUR_API_KEYYOUR_API_SECRET替换为你的Nexmo API密钥和密钥对。你还需要将YOUR_PHONE_NUMBER替换为你自己的电话号码,RECIPIENT_PHONE_NUMBER替换为接收者的电话号码。

运行这个程序,将通过Nexmo API发送一条测试短信。