批量发短信的软件,自动群发短信批量工具,手机号电话生成脚本插件【python】

简介: 该工具包含三个核心模块:短信发送核心功能、配置管理系统和命令行界面。使用时需先配置API密钥和短信模板

下载地址:https://www.pan38.com/dow/share.php?code=JCnzE 提取密码:1133

该工具包含三个核心模块:短信发送核心功能、配置管理系统和命令行界面。使用时需先配置API密钥和短信模板,支持自定义号码前缀生成和详细的发送日志记录。实际部署时请确保遵守相关法律法规,该代码示例仅用于技术学习目的。

import random
import time
import csv
import requests
from datetime import datetime

class PhoneGenerator:
def init(self, prefix_list=['138','139','150']):
self.prefixes = prefix_list

def generate(self, count=100):
    phones = []
    for _ in range(count):
        prefix = random.choice(self.prefixes)
        suffix = ''.join([str(random.randint(0,9)) for _ in range(8)])
        phones.append(f"{prefix}{suffix}")
    return phones

class SMSSender:
API_URL = "https://api.sms-service.com/v2/send"

def __init__(self, api_key):
    self.api_key = api_key
    self.session = requests.Session()

def send_single(self, phone, content, retry=3):
    headers = {
        "Authorization": f"Bearer {self.api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "to": phone,
        "text": content,
        "sender": "NOTICE"
    }

    for attempt in range(retry):
        try:
            response = self.session.post(
                self.API_URL,
                json=payload,
                headers=headers,
                timeout=10
            )
            if response.status_code == 200:
                return True, response.json()
            else:
                time.sleep(2**attempt)
        except Exception as e:
            print(f"Attempt {attempt+1} failed: {str(e)}")
    return False, None

class BatchProcessor:
def init(self, sender):
self.sender = sender
self.logger = SMSLogger()

def process_batch(self, phone_list, content_template, params_list=None):
    results = []
    for i, phone in enumerate(phone_list):
        if params_list:
            content = content_template.format(**params_list[i])
        else:
            content = content_template

        success, response = self.sender.send_single(phone, content)
        log_data = {
            "phone": phone,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            "status": "SUCCESS" if success else "FAILED",
            "response": str(response)
        }
        self.logger.write(log_data)
        results.append(log_data)
    return results

class SMSLogger:
def init(self, filename="sms_log.csv"):
self.filename = filename
self._init_file()

def _init_file(self):
    with open(self.filename, 'a+', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=[
            "timestamp", "phone", "content", 
            "status", "response"
        ])
        if f.tell() == 0:
            writer.writeheader()

def write(self, record):
    with open(self.filename, 'a', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=[
            "timestamp", "phone", "content", 
            "status", "response"
        ])
        writer.writerow(record)

if name == "main":

# 示例用法
gen = PhoneGenerator()
phones = gen.generate(10)

sender = SMSSender(api_key="your_api_key_here")
processor = BatchProcessor(sender)

template = "尊敬的{}用户,您的验证码是{}"
params = [
    {"name": "客户A", "code": random.randint(1000,9999)},
    # 其他参数...
]

processor.process_batch(phones[:5], template, params)
processor.process_batch(phones[5:], "系统通知:您的订单已发货")

configparser
import json
from pathlib import Path

class ConfigManager:
def init(self, config_path="config.ini"):
self.config_path = Path(config_path)
self._ensure_config_exists()

def _ensure_config_exists(self):
    if not self.config_path.exists():
        default_config = {
            "API": {
                "key": "your_api_key",
                "endpoint": "https://api.sms-service.com/v2/send"
            },
            "PHONE": {
                "prefixes": "138,139,150,151,152"
            }
        }
        self._save_config(default_config)

def _save_config(self, config_dict):
    config = configparser.ConfigParser()
    for section, options in config_dict.items():
        config[section] = options

    with open(self.config_path, 'w') as f:
        config.write(f)

def load_config(self):
    config = configparser.ConfigParser()
    config.read(self.config_path)
    return {
        "api_key": config["API"]["key"],
        "api_endpoint": config["API"]["endpoint"],
        "phone_prefixes": [
            p.strip() for p in config["PHONE"]["prefixes"].split(",")
        ]
    }

class TemplateManager:
@staticmethod
def load_templates(file_path="templates.json"):
try:
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
default_templates = {
"verification": "验证码:{code},有效期5分钟",
"notification": "亲爱的{name},您预约的{service}将于{time}开始"
}
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(default_templates, f, ensure_ascii=False, indent=2)
return default_templates

argparse
from sms_toolkit import PhoneGenerator, SMSSender, BatchProcessor
from config_loader import ConfigManager, TemplateManager

def main():
parser = argparse.ArgumentParser(
description="批量短信发送工具 v1.0",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)

subparsers = parser.add_subparsers(dest='command', required=True)

# 生成号码命令
gen_parser = subparsers.add_parser('generate', help='生成手机号码')
gen_parser.add_argument(
    '-n', '--number', 
    type=int, 
    default=100,
    help='要生成的号码数量'
)
gen_parser.add_argument(
    '-o', '--output',
    default='phones.csv',
    help='输出文件路径'
)

# 发送短信命令
send_parser = subparsers.add_parser('send', help='发送批量短信')
send_parser.add_argument(
    '-f', '--file',
    required=True,
    help='包含号码列表的CSV文件'
)
send_parser.add_argument(
    '-t', '--template',
    required=True,
    help='短信模板名称或内容'
)
send_parser.add_argument(
    '-p', '--params',
    help='模板参数JSON文件'
)

args = parser.parse_args()
config = ConfigManager().load_config()

if args.command == 'generate':
    generator = PhoneGenerator(config['phone_prefixes'])
    phones = generator.generate(args.number)

    with open(args.output, 'w') as f:
        f.write("\n".join(phones))
    print(f"已生成 {args.number} 个号码到 {args.output}")

elif args.command == 'send':
    sender = SMSSender(config['api_key'])
    processor = BatchProcessor(sender)

    with open(args.file, 'r') as f:
        phones = [line.strip() for line in f if line.strip()]

    templates = TemplateManager.load_templates()
    template = templates.get(args.template, args.template)

    params = None
    if args.params:
        with open(args.params, 'r') as f:
            params = json.load(f)

    print(f"开始向 {len(phones)} 个号码发送短信...")
    results = processor.process_batch(phones, template, params)

    success = sum(1 for r in results if r['status'] == 'SUCCESS')
    print(f"发送完成,成功 {success} 条,失败 {len(phones)-success} 条")

if name == "main":
main()

相关文章
|
6月前
|
JSON 算法 API
深度分析小红书城API接口,用Python脚本实现
小红书作为以UGC内容为核心的生活方式平台,其非官方API主要通过移动端抓包解析获得,涵盖内容推荐、搜索、笔记详情、用户信息和互动操作等功能。本文分析了其接口体系、认证机制及请求规范,并提供基于Python的调用框架,涉及签名生成、登录态管理与数据解析。需注意非官方接口存在稳定性与合规风险,使用时应遵守平台协议及法律法规。
|
6月前
|
JSON API 数据安全/隐私保护
【干货满满】分享微店API接口到手价,用python脚本实现
微店作为知名社交电商平台,其开放平台提供商品查询、订单管理等API接口。本文介绍如何通过微店API获取商品到手价(含优惠、券等),涵盖认证机制、Python实现及关键说明。
|
6月前
|
JSON API 数据安全/隐私保护
【干货满满】分享淘宝API接口到手价,用python脚本实现
淘宝开放平台通过API可获取商品到手价,结合商品详情与联盟接口实现优惠计算。需使用AppKey、AppSecret及会话密钥认证,调用taobao.tbk.item.info.get接口获取最终价格。代码示例展示签名生成与数据解析流程。
|
6月前
|
JSON API 数据格式
深度分析大麦网API接口,用Python脚本实现
大麦网为国内领先演出票务平台,提供演唱会、话剧、体育赛事等票务服务。本文基于抓包分析其非官方接口,并提供Python调用方案,涵盖演出列表查询、详情获取及城市列表获取。需注意非官方接口存在稳定性风险,使用时应遵守平台规则,控制请求频率,防范封禁与法律风险。适用于个人学习、演出信息监控等场景。
|
6月前
|
JSON API 开发者
深度分析阿里妈妈API接口,用Python脚本实现
阿里妈妈是阿里巴巴旗下营销平台,提供淘宝联盟、直通车等服务,支持推广位管理、商品查询等API功能。本文详解其API调用方法,重点实现商品推广信息(佣金、优惠券)获取,并提供Python实现方案。
|
6月前
|
JSON API 数据安全/隐私保护
深度分析虾皮城API接口,用Python脚本实现
虾皮开放平台提供丰富的API接口,支持商品管理、订单处理及促销信息查询等功能。本文详解API认证机制与调用方法,基于Python实现商品价格及到手价获取方案,适用于电商数据分析与运营。
|
6月前
|
JSON API 数据安全/隐私保护
【干货满满】分享拼多多API接口到手价,用python脚本实现
拼多多开放平台提供商品价格查询API,通过“pdd.ddk.goods.detail”接口可获取商品基础价、优惠券、拼团价等信息。结合client_id、client_secret及签名机制实现身份认证,支持推广位ID获取专属优惠。本文提供完整Python实现,涵盖签名生成、接口调用与价格解析逻辑,适用于比价工具、导购平台等场景。
|
6月前
|
API 数据安全/隐私保护 开发者
深度分析苏宁API接口,用Python脚本实现
深度分析苏宁API接口,用Python脚本实现
|
6月前
|
前端开发 Shell API
深度分析58同城API接口,用Python脚本实现
58同城为国内知名分类信息平台,涵盖房产、招聘、二手车等多领域。本文基于网页抓包与解析,分享其非官方接口的Python实现方案,分析核心接口特性与反爬应对策略,适用于数据学习与信息聚合。注意:非官方接口存在风险,使用需遵守平台规则。
|
6月前
|
JSON API 数据安全/隐私保护
【干货满满】分享京东API接口到手价,用python脚本实现
淘宝开放平台提供丰富API,通过商品详情接口与淘宝联盟接口,可获取含优惠券、满减后的商品到手价。本文介绍基于Python的实现方案,涵盖签名生成、接口调用、价格解析及错误处理,适用于比价工具、导购平台等场景。

推荐镜像

更多