From 741abf7e18585e3499b72e91a25a230ba2aff4f0 Mon Sep 17 00:00:00 2001 From: eric Date: Mon, 4 Mar 2024 21:10:20 +0800 Subject: [PATCH] update --- __init__.py | 0 api.py | 289 +++++++++++++++++++++++++++++++++++++++++++++++++ callback.py | 30 ++++- dsxSms.py | 175 ++++++++++++++++++++++++++++++ getapiPost.py | 7 +- tentcentSMS.py | 146 +++++++++++++------------ 6 files changed, 567 insertions(+), 80 deletions(-) create mode 100644 __init__.py create mode 100644 api.py create mode 100644 dsxSms.py diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api.py b/api.py new file mode 100644 index 0000000..b663f7a --- /dev/null +++ b/api.py @@ -0,0 +1,289 @@ +from typing import Union +from fastapi import FastAPI, Header, BackgroundTasks,Request,Body +from urllib.parse import unquote +import re +import pickle +import os +from fastapi.responses import JSONResponse +import asyncio +from pydantic import BaseModel +import time +from transformers import AutoTokenizer, AutoModel +import uvicorn, json, datetime +import torch +import json +import base64 +import requests +from tentcentSMS import sendSms + +#使用int8的量化模型 +tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b-int4", trust_remote_code=True) +#model = AutoModel.from_pretrained("THUDM/chatglm2-6b-int4", trust_remote_code=True).half().quantize(8).cuda() +model = AutoModel.from_pretrained("THUDM/chatglm2-6b-int4",trust_remote_code=True).cuda() +model.eval() + +#显存满配全开 +#tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) +#model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() +#model.eval() + +def submit_post(url: str, data: dict): + """ + Submit a POST request to the given URL with the given data. + """ + return requests.post(url, data=json.dumps(data)) + + +def save_encoded_image(b64_image: str, output_path: str): + """ + Save the given image to the given output path. + """ + with open(output_path, "wb") as image_file: + image_file.write(base64.b64decode(b64_image)) + +# 正则查找11位手机号 +def findPhoneNum(text): + pattern = re.compile(r"1[356789]\d{9}") + # strs = '小明的手机号是13987692110,你明天打给他' + result = pattern.findall(text) + print(result) + # ['13987692110'] + if len(result) > 0: + # 通过腾讯云-短信发送api + sendSms(result[0]) + return result[0] + else: + return None + + + +# bot发消息到tg群组 +def sendTg(message): + baseUrl="https://api.telegram.org/bot" + toekn="558659722:AAENA3v8gKq7R7_nsr8V58Iu-_Z6BWx2SCw" + chat_id="-861577609" + text=message + url=f'{baseUrl}{toekn}/sendMessage?chat_id={chat_id}&text={text}' + try: + r = requests.get(url) + except: + print('请检查网络代理') + # https://api.telegram.org/bot558659722:AAENA3v8gKq7R7_nsr8V58Iu-_Z6BWx2SCw/sendMessage?chat_id=-861577609&text=1234 + +DEVICE = "cuda" +DEVICE_ID = "0" +CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE + + +def torch_gc(): + if torch.cuda.is_available(): + with torch.cuda.device(CUDA_DEVICE): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + + + +app = FastAPI() + + +class Item(BaseModel): + query: Union[str, None] = None + + +@app.get("/") +def index(): + return "hello" + + + + +@app.get("/home") +# def read_root(): +# return {"Hello": "World"} +def read_items( + appid: Union[str, None] = Header(default=None), + bid: Union[str, None] = Header(default=None), + requestid: Union[str, None] = Header(default=None), + uid: Union[str, None] = Header(default=None), +): + print("console :,", "appid", appid, "bid", bid, "requestid", requestid, "uid", uid) + return {"appid": appid, "bid": bid, "requestid": requestid, "uid": uid} + + +@app.post("/glm") +async def create_item(request: Request): + # 获取请求参数 + global model, tokenizer + json_post_raw = await request.json() + json_post = json.dumps(json_post_raw) + json_post_list = json.loads(json_post) + prompt = json_post_list.get('prompt') #问题 + history = json_post_list.get('history') #默认空数组 + max_length = json_post_list.get('max_length') + top_p = json_post_list.get('top_p') + temperature = json_post_list.get('temperature') + + # 请求ai模型 + response, history = model.chat(tokenizer, + prompt, + history=history, + max_length=max_length if max_length else 2048, + top_p=top_p if top_p else 0.7, + temperature=temperature if temperature else 0.95) + now = datetime.datetime.now() + time = now.strftime("%Y-%m-%d %H:%M:%S") + answer = { + "response": response, + "history": history, + "status": 200, + "time": time + } + log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"' + print(log) + torch_gc() + return answer + + +# AI智能对话 +@app.post("/callback") +async def callback( + # item: Item, + # inputArguments: Union[str, None] = None, + query=Body(None), + appid: Union[str, None] = Header(default=None), + bid: Union[str, None] = Header(default=None), + requestid: Union[str, None] = Header(default=None), + uid: Union[str, None] = Header(default=None), +): + print('query',query) + print('query[query]',query["query"]) + + # 获取请求参数 + global model, tokenizer + # time.sleep(10) + # print("item", item) + history = [] #默认空数组 + prompt='' + try: + query = unquote(query["query"], "utf-8") + prompt = query #问题 + + except: + prompt = "" + + max_length=None + top_p=None + temperature=None + # 请求ai模型 + response, history = model.chat(tokenizer, + prompt, + history=history, + max_length=max_length if max_length else 2048, + top_p=top_p if top_p else 0.7, + temperature=temperature if temperature else 0.95) + # log日志 + now = datetime.datetime.now() + time = now.strftime("%Y-%m-%d %H:%M:%S") + log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"' + print(log) + torch_gc() + # return answer + content = { + "answer": response, + "answer_type": "text", + } + headers = {"Content-Type": "application/json"} + return JSONResponse(content=content, headers=headers) + + + +# AI生成图片 +@app.post("/img") +async def img( + # item: Item, + # inputArguments: Union[str, None] = None, + query=Body(None), + appid: Union[str, None] = Header(default=None), + bid: Union[str, None] = Header(default=None), + requestid: Union[str, None] = Header(default=None), + uid: Union[str, None] = Header(default=None), +): + # print("console :,", "appid", appid, "bid", bid, "requestid", requestid, "uid", uid) + print('query',query) + print('query[query]',query["query"]) + # sendTg(query["query"]) + # 获取请求参数 + global model, tokenizer + # time.sleep(10) + # print("item", item) + history = [] #默认空数组 + prompt='' + max_length=None + top_p=None + temperature=None + response=None + try: + query = unquote(query["query"], "utf-8") + # 判断有没有'/img'标识符 + if ('/img' in query) is True: + query=query.replace('/img', '') + prompt=query + + txt2img_url = 'http://127.0.0.1:7860/sdapi/v1/txt2img' + data = {'prompt': prompt} + res = submit_post(txt2img_url, data) + # 以时间戳命名 + now =str(time.time()) + save_encoded_image(res.json()['images'][0], f'img/{now}.png') + # 网络图片 + response=f'#web_img http://aiimg.hackrobot.cn/{now}.png' + print('response',response) + # return responseimg + # elif ('手机号' in query) is True or len(query)==11: + elif query.isdigit() and len(query)==11: + phonenumber=findPhoneNum(query) + if phonenumber is not None: + response="请查收短信,并在微信回复短信中的数字,自动邀请加群" + else: + response="手机号格式不正确,或其他错误" + + else: + prompt = query #问题 + # 请求ai模型 + response, history = model.chat(tokenizer, + prompt, + history=history, + max_length=max_length if max_length else 2048, + top_p=top_p if top_p else 0.7, + temperature=temperature if temperature else 0.95) + + except(ValueError, ArithmeticError): + print('ValueError',ValueError) + print('ArithmeticError',ArithmeticError) + prompt = "" + + # log日志 + # now = datetime.datetime.now() + # time = now.strftime("%Y-%m-%d %H:%M:%S") + # log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"' + # print(log) + content = { + "answer": response, + "answer_type": "text", + } + headers = {"Content-Type": "application/json"} + return JSONResponse(content=content, headers=headers) + + + +#if __name__ == '__main__': + #tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True) + #model = AutoModel.from_pretrained("THUDM/chatglm2-6b", trust_remote_code=True).cuda() + + # 多显卡支持,使用下面三行代替上面两行,将num_gpus改为你实际的显卡数量 + # model_path = "THUDM/chatglm2-6b" + # tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) + # model = load_model_on_gpus(model_path, num_gpus=2) + + # model.eval() + # uvicorn.run(app, host='0.0.0.0', port=8000, workers=1) \ No newline at end of file diff --git a/callback.py b/callback.py index 6df3f87..cde308c 100644 --- a/callback.py +++ b/callback.py @@ -14,6 +14,7 @@ import torch import json import base64 import requests +from tentcentSMS import sendSms #使用int8的量化模型 tokenizer = AutoTokenizer.from_pretrained("THUDM/chatglm2-6b-int4", trust_remote_code=True) @@ -40,6 +41,21 @@ def save_encoded_image(b64_image: str, output_path: str): with open(output_path, "wb") as image_file: image_file.write(base64.b64decode(b64_image)) +# 正则查找11位手机号 +def findPhoneNum(text): + pattern = re.compile(r"1[356789]\d{9}") + # strs = '小明的手机号是13987692110,你明天打给他' + result = pattern.findall(text) + print(result) + # ['13987692110'] + if len(result) > 0: + # 通过腾讯云-短信发送api + sendSms(result[0]) + return result[0] + else: + return None + + # bot发消息到tg群组 def sendTg(message): @@ -195,11 +211,7 @@ async def img( # print("console :,", "appid", appid, "bid", bid, "requestid", requestid, "uid", uid) print('query',query) print('query[query]',query["query"]) - try: - sendTg(query["query"]) - except: - print('发送tg失败') - + # sendTg(query["query"]) # 获取请求参数 global model, tokenizer # time.sleep(10) @@ -227,6 +239,12 @@ async def img( response=f'#web_img http://aiimg.hackrobot.cn/{now}.png' print('response',response) # return responseimg + elif ('手机号' in query) is True: + phonenumber=findPhoneNum(query) + if phonenumber is not None: + response="请查收短信,并在微信回复短信中的数字,自动邀请加群" + else: + response="手机号格式不正确,或其他错误" else: prompt = query #问题 @@ -267,4 +285,4 @@ async def img( # model = load_model_on_gpus(model_path, num_gpus=2) # model.eval() - # uvicorn.run(app, host='0.0.0.0', port=8000, workers=1 \ No newline at end of file + # uvicorn.run(app, host='0.0.0.0', port=8000, workers=1) \ No newline at end of file diff --git a/dsxSms.py b/dsxSms.py new file mode 100644 index 0000000..4540466 --- /dev/null +++ b/dsxSms.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- + +# pip install --upgrade tencentcloud-sdk-python + +from typing import Union +from fastapi import FastAPI, Header, BackgroundTasks,Request,Body +from fastapi.responses import JSONResponse +from urllib.parse import unquote +import re +from pydantic import BaseModel +import uvicorn, json, datetime +# from tentcentSMS import sendSms +from tencentcloud.common import credential +from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException +# 导入对应产品模块的client models。 +from tencentcloud.sms.v20210111 import sms_client, models + +# github地址 https://github.com/TencentCloud/tencentcloud-sdk-python + +# 导入可选配置类 +from tencentcloud.common.profile.client_profile import ClientProfile +from tencentcloud.common.profile.http_profile import HttpProfile + +app = FastAPI() + + +# 正则查找11位手机号 +def findPhoneNum(text): + pattern = re.compile(r"1[356789]\d{9}") + # strs = '小明的手机号是13987692110,你明天打给他' + result = pattern.findall(text) + print(result) + # ['13987692110'] + if len(result) > 0: + # 通过腾讯云-短信发送api + sendSms(result[0]) + return result[0] + else: + return None + + + +# phoneNum="+8613243889782" +def sendSms(phoneNum): + try: + # 必要步骤: + # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 + # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + # 以免泄露密钥对危及你的财产安全。 + # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi + cred = credential.Credential("AKIDIQTVDrJgrhQ5ngYJxXwISMFzXzMa6Udh", "3rjSxWwDKEwTzVsFcv10pZ7f8UhuxmP0") + # cred = credential.Credential( + # os.environ.get(""), + # os.environ.get("") + # ) + + # 实例化一个http选项,可选的,没有特殊需求可以跳过。 + httpProfile = HttpProfile() + # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略) + # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口") + httpProfile.reqMethod = "POST" # post请求(默认为post请求) + httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒) + httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默认就近接入) + + # 非必要步骤: + # 实例化一个客户端配置对象,可以指定超时时间等配置 + clientProfile = ClientProfile() + clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法 + clientProfile.language = "en-US" + # clientProfile.language = "en-ZH" + clientProfile.httpProfile = httpProfile + + # 实例化要请求产品(以sms为例)的client对象 + # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 + client = sms_client.SmsClient(cred, "ap-beijing", clientProfile) + + # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置 + # 属性可能是基本类型,也可能引用了另一个数据结构 + # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 + req = models.SendSmsRequest() + + # 基本类型的设置: + # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。 + # SDK提供对基本类型的指针引用封装函数 + # 帮助链接: + # 短信控制台: https://console.cloud.tencent.com/smsv2 + # 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 + + # 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 + # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看 + req.SmsSdkAppId = "1400866296" + # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 + # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看 + req.SignName = "小智云图小程序" + # 模板 ID: 必须填写已审核通过的模板 ID + # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看 + req.TemplateId = "1977541" + # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空 + req.TemplateParamSet = [] + # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号] + # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 + req.PhoneNumberSet = [phoneNum] + # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 + req.SessionContext = "" + # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] + req.ExtendCode = "" + # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 + req.SenderId = "" + + resp = client.SendSms(req) + + # 输出json格式的字符串回包` + print(resp.to_json_string(indent=2)) + + # 当出现以下错误码时,快速解决方案参考 + # - [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms) + + except TencentCloudSDKException as err: + print(err) + + +# AI生成图片 +@app.post("/sms") +async def sms( + # item: Item, + # inputArguments: Union[str, None] = None, + query=Body(None), + appid: Union[str, None] = Header(default=None), + bid: Union[str, None] = Header(default=None), + requestid: Union[str, None] = Header(default=None), + uid: Union[str, None] = Header(default=None), +): + # print("console :,", "appid", appid, "bid", bid, "requestid", requestid, "uid", uid) + print('query',query) + print('query[query]',query["query"]) + # sendTg(query["query"]) + response=None + try: + query = unquote(query["query"], "utf-8") + # return responseimg + if ('手机号' in query) is True: + phonenumber=findPhoneNum(query) + if phonenumber is not None: + sendSms(phonenumber) + response="请查收验证短信" + else: + response="手机号格式不正确,或其他错误" + + + else: + pass + + except(ValueError, ArithmeticError): + print('ValueError',ValueError) + print('ArithmeticError',ArithmeticError) + prompt = "" + + + content = { + "answer": response, + "answer_type": "text", + } + headers = {"Content-Type": "application/json"} + return JSONResponse(content=content, headers=headers) + + + +if __name__ == '__main__': + uvicorn.run(app, host='0.0.0.0', port=8000, workers=1) \ No newline at end of file diff --git a/getapiPost.py b/getapiPost.py index db5142b..36af715 100644 --- a/getapiPost.py +++ b/getapiPost.py @@ -1,3 +1,4 @@ +# pip install --upgrade tencentcloud-sdk-python import requests import time headers = {'content-type': 'application/json',"X-TC-Action": 'PullSmsSendStatusByPhoneNumber'} @@ -6,14 +7,14 @@ payload = { "Action": "PullSmsSendStatusByPhoneNumber", "Version": "2021-01-11", "Region": "ap-beijing", - # "BeginTime":time.time(), #用户触发接口的时候 - "BeginTime":1684724400, #用户触发接口的时候 + "BeginTime":time.time(), #用户触发接口的时候 + # "BeginTime":1684724400, #用户触发接口的时候 "Timestamp":1684724400, "Offset": 0, "Limit": 1, "PhoneNumber": "+8613243889782", "SmsSdkAppId": "1400808237", - "EndTime": 1684724400 + # "EndTime": 1684724400 } r = requests.post("https://sms.tencentcloudapi.com", headers=headers,data=payload) diff --git a/tentcentSMS.py b/tentcentSMS.py index 47db0d8..9242c89 100644 --- a/tentcentSMS.py +++ b/tentcentSMS.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- + from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException # 导入对应产品模块的client models。 @@ -10,84 +11,87 @@ from tencentcloud.sms.v20210111 import sms_client, models # 导入可选配置类 from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile -try: - # 必要步骤: - # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 - # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 - # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, - # 以免泄露密钥对危及你的财产安全。 - # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi - cred = credential.Credential("AKIDOaT6SZQ0JL7cqnTryoOhkW1FBqELAizz", "kDPKyMTJs99sKVP1NREkzxKQFo66pIUP") - # cred = credential.Credential( - # os.environ.get(""), - # os.environ.get("") - # ) - # 实例化一个http选项,可选的,没有特殊需求可以跳过。 - httpProfile = HttpProfile() - # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略) - # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口") - httpProfile.reqMethod = "POST" # post请求(默认为post请求) - httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒) - httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默认就近接入) +# phoneNum="+8613243889782" +def sendSms(phoneNum): + try: + # 必要步骤: + # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 + # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + # 以免泄露密钥对危及你的财产安全。 + # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi + cred = credential.Credential("AKIDOaT6SZQ0JL7cqnTryoOhkW1FBqELAizz", "kDPKyMTJs99sKVP1NREkzxKQFo66pIUP") + # cred = credential.Credential( + # os.environ.get(""), + # os.environ.get("") + # ) - # 非必要步骤: - # 实例化一个客户端配置对象,可以指定超时时间等配置 - clientProfile = ClientProfile() - clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法 - clientProfile.language = "en-US" - # clientProfile.language = "en-ZH" - clientProfile.httpProfile = httpProfile + # 实例化一个http选项,可选的,没有特殊需求可以跳过。 + httpProfile = HttpProfile() + # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略) + # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口") + httpProfile.reqMethod = "POST" # post请求(默认为post请求) + httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒) + httpProfile.endpoint = "sms.tencentcloudapi.com" # 指定接入地域域名(默认就近接入) - # 实例化要请求产品(以sms为例)的client对象 - # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 - client = sms_client.SmsClient(cred, "ap-beijing", clientProfile) + # 非必要步骤: + # 实例化一个客户端配置对象,可以指定超时时间等配置 + clientProfile = ClientProfile() + clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法 + clientProfile.language = "en-US" + # clientProfile.language = "en-ZH" + clientProfile.httpProfile = httpProfile - # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 - # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置 - # 属性可能是基本类型,也可能引用了另一个数据结构 - # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 - req = models.SendSmsRequest() + # 实例化要请求产品(以sms为例)的client对象 + # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 + client = sms_client.SmsClient(cred, "ap-beijing", clientProfile) - # 基本类型的设置: - # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。 - # SDK提供对基本类型的指针引用封装函数 - # 帮助链接: - # 短信控制台: https://console.cloud.tencent.com/smsv2 - # 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 + # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置 + # 属性可能是基本类型,也可能引用了另一个数据结构 + # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 + req = models.SendSmsRequest() - # 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 - # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看 - req.SmsSdkAppId = "1400808237" - # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 - # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看 - req.SignName = "异度世界公众号" - # 模板 ID: 必须填写已审核通过的模板 ID - # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看 - req.TemplateId = "1795459" - # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空 - req.TemplateParamSet = [] - # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号] - # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 - req.PhoneNumberSet = ["+8613243889782"] - # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 - req.SessionContext = "" - # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] - req.ExtendCode = "" - # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 - req.SenderId = "" + # 基本类型的设置: + # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。 + # SDK提供对基本类型的指针引用封装函数 + # 帮助链接: + # 短信控制台: https://console.cloud.tencent.com/smsv2 + # 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 - resp = client.SendSms(req) + # 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 + # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看 + req.SmsSdkAppId = "1400808237" + # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 + # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看 + req.SignName = "异度世界公众号" + # 模板 ID: 必须填写已审核通过的模板 ID + # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看 + req.TemplateId = "1976081" + # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空 + req.TemplateParamSet = [] + # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号] + # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 + req.PhoneNumberSet = [phoneNum] + # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 + req.SessionContext = "" + # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] + req.ExtendCode = "" + # 国内短信无需填写该项;国际/港澳台短信已申请独立 SenderId 需要填写该字段,默认使用公共 SenderId,无需填写该字段。注:月度使用量达到指定量级可申请独立 SenderId 使用,详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 + req.SenderId = "" - # 输出json格式的字符串回包` - print(resp.to_json_string(indent=2)) + resp = client.SendSms(req) - # 当出现以下错误码时,快速解决方案参考 - # - [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) - # - [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) - # - [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) - # - [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) - # - 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms) + # 输出json格式的字符串回包` + print(resp.to_json_string(indent=2)) -except TencentCloudSDKException as err: - print(err) \ No newline at end of file + # 当出现以下错误码时,快速解决方案参考 + # - [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F) + # - 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms) + + except TencentCloudSDKException as err: + print(err) \ No newline at end of file