Compare commits
51 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
741abf7e18 | ||
|
|
c3f5a3a227 | ||
|
|
1eff7fd145 | ||
|
|
8f38cad96a | ||
|
|
38032706b9 | ||
|
|
167daebd7a | ||
|
|
b61929e4d0 | ||
|
|
ad1555e05d | ||
|
|
ba2822cbd0 | ||
|
|
fd29d2993b | ||
|
|
16e4dfbcb9 | ||
|
|
6e85b7f5d4 | ||
|
|
8d62e9789a | ||
|
|
689ced2212 | ||
|
|
fafaeaa72f | ||
|
|
bcf9380547 | ||
|
|
3d04f78929 | ||
|
|
ff261a5c5d | ||
|
|
ee3c9b7795 | ||
|
|
3c0fd592e8 | ||
|
|
b05fc4fceb | ||
|
|
156ceceb53 | ||
|
|
ebb9f40be5 | ||
|
|
006f6facf9 | ||
|
|
c49efa0c13 | ||
|
|
bae28fc0f5 | ||
|
|
e45c426618 | ||
|
|
53463f63f6 | ||
|
|
28aef4f2e1 | ||
|
|
f9846e5b6d | ||
|
|
aded3565e3 | ||
|
|
ed5485252c | ||
|
|
1d15c467f5 | ||
|
|
a80332f9af | ||
|
|
ce1db0b73d | ||
|
|
e800579801 | ||
|
|
77483804b1 | ||
|
|
b73d30e619 | ||
|
|
0619271bb1 | ||
|
|
9b63d6a62a | ||
|
|
16deac824b | ||
|
|
7ff015458f | ||
|
|
5a0106e084 | ||
|
|
0b4242e985 | ||
|
|
c01d6079a1 | ||
|
|
7e83482f8c | ||
|
|
71271ab53e | ||
|
|
56973ace6e | ||
|
|
01a566f4a0 | ||
|
|
b642cf0e0e | ||
|
|
6b7e4116d9 |
6
.vscode/settings.json
vendored
Normal file
6
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"python.formatting.provider": "none",
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
}
|
||||
}
|
||||
0
__init__.py
Normal file
0
__init__.py
Normal file
Binary file not shown.
289
api.py
Normal file
289
api.py
Normal file
@@ -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)
|
||||
264
app.py
264
app.py
@@ -1,35 +1,265 @@
|
||||
from typing import Union
|
||||
from fastapi import FastAPI,Header
|
||||
from fastapi import FastAPI, Header, BackgroundTasks
|
||||
from urllib.parse import unquote
|
||||
from flashSMS import sendFlash
|
||||
from tgMesaage import sendTg
|
||||
import re
|
||||
import pickle
|
||||
import os
|
||||
from fastapi.responses import JSONResponse
|
||||
import asyncio
|
||||
from pydantic import BaseModel
|
||||
import time
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class Item(BaseModel):
|
||||
query: Union[str, None] = None
|
||||
|
||||
|
||||
# 判断uid是否存在
|
||||
def findUid(uiddata, phoneNum):
|
||||
isFind = False
|
||||
newDict = {}
|
||||
if os.path.exists("data.txt"):
|
||||
# print('文件存在')
|
||||
with open("data.txt", "rb") as f:
|
||||
newDict = pickle.load(f)
|
||||
if newDict[uiddata] is not None:
|
||||
print("newDict[uid]", newDict[uiddata])
|
||||
isFind = True
|
||||
else:
|
||||
newDict[uiddata] = phoneNum
|
||||
with open("data.txt", "wb") as f:
|
||||
pickle.dump(newDict, f)
|
||||
isFind = False
|
||||
return isFind
|
||||
else:
|
||||
# print('文件不存在')
|
||||
isFind = False
|
||||
newDict[uiddata] = phoneNum
|
||||
with open("data.txt", "wb") as f:
|
||||
pickle.dump(newDict, f)
|
||||
return isFind
|
||||
|
||||
|
||||
# findUid('test','13243889782')
|
||||
|
||||
|
||||
# 正则查找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:
|
||||
return result[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def resData(inputArguments, uid):
|
||||
print("inputArguments", inputArguments)
|
||||
try:
|
||||
inputArguments = unquote(inputArguments, "utf-8")
|
||||
except:
|
||||
inputArguments = ""
|
||||
# 正则获取11位手机号
|
||||
phonenumber = findPhoneNum(inputArguments)
|
||||
print("phonenumber", phonenumber)
|
||||
# # phonenumber='13243889782'
|
||||
if phonenumber is not None and uid is not None:
|
||||
warntext = "[异度世界],微信加群验证码:3399"
|
||||
# sendTg(f"用户手机号{phonenumber},开始发送验证码")
|
||||
# 判断用户uid是都触发过短信,不允许触发第2次
|
||||
if findUid(uid, phonenumber) is True:
|
||||
print("用户uid已存在,不触发短信")
|
||||
# sendTg(f"用户{uid}已存在,不触发短信")
|
||||
else:
|
||||
# 发送闪信
|
||||
sendFlash(phonenumber, warntext)
|
||||
else:
|
||||
print(f"用户输入:{inputArguments},手机号不正确,或者uid参数异常")
|
||||
# sendTg(f"用户输入:{inputArguments},手机号不正确,或者uid参数异常")
|
||||
|
||||
|
||||
def urlSend(num):
|
||||
try:
|
||||
inputArguments = unquote(num, "utf-8")
|
||||
except:
|
||||
inputArguments = ""
|
||||
# 正则获取11位手机号
|
||||
phonenumber = findPhoneNum(inputArguments)
|
||||
print("phonenumber", phonenumber)
|
||||
# # phonenumber='13243889782'
|
||||
if phonenumber is not None:
|
||||
warntext = "[异度世界],微信加群验证码:3399"
|
||||
sendFlash(phonenumber, warntext)
|
||||
else:
|
||||
print(f"用户输入:{inputArguments},手机号不正确")
|
||||
sendTg(f"用户输入:{inputArguments},手机号不正确,或者uid参数异常")
|
||||
|
||||
|
||||
def returnRes(err_code, outputArguments):
|
||||
# 成功的响应 0成功 -1失败
|
||||
content = {
|
||||
"err_code": err_code,
|
||||
"data_list": [{"outputArguments": outputArguments}],
|
||||
}
|
||||
headers = {"Content-Type": "application/json"}
|
||||
return JSONResponse(content=content, headers=headers)
|
||||
|
||||
|
||||
@app.get("/")
|
||||
# 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)):
|
||||
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.get("/lili")
|
||||
# def read_root():
|
||||
# return {"Hello": "World"}
|
||||
def lili():
|
||||
# 直接返回字符串
|
||||
return "lili"
|
||||
|
||||
|
||||
# 通过网址发送闪信
|
||||
@app.get("/send")
|
||||
# def read_root():
|
||||
# return {"Hello": "World"}
|
||||
def read_items(
|
||||
background_tasks: BackgroundTasks,
|
||||
num: Union[str, None] = None,
|
||||
):
|
||||
print("num", num)
|
||||
background_tasks.add_task(urlSend, num)
|
||||
content = {"err_code": 0, "data_list": [{"outputArguments": "test"}]}
|
||||
headers = {"Content-Type": "application/json"}
|
||||
return JSONResponse(content=content, headers=headers)
|
||||
|
||||
|
||||
# 微信对话-用户输入
|
||||
@app.get("/input")
|
||||
async def getphonenum(inputArguments: Union[str, None] = 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('inputArguments',inputArguments)
|
||||
# 要处理url编码问题decode
|
||||
@app.get(
|
||||
"/input",
|
||||
)
|
||||
async def getphonenum(
|
||||
background_tasks: BackgroundTasks,
|
||||
inputArguments: Union[str, None] = 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),
|
||||
):
|
||||
err_code = 0
|
||||
outputArguments = "验证码发送成功,请留意短信"
|
||||
print("inputArguments", inputArguments)
|
||||
try:
|
||||
inputArguments = unquote(inputArguments, 'utf-8')
|
||||
inputArguments = unquote(inputArguments, "utf-8")
|
||||
except:
|
||||
inputArguments=''
|
||||
phonenumber='13243889782'
|
||||
phonenumber='13243889782'
|
||||
warntext='[异度世界],加群验证码:3399'
|
||||
sendTg(f'用户手机号{phonenumber},开始发送验证码')
|
||||
inputArguments = ""
|
||||
# 正则获取11位手机号
|
||||
phonenumber = findPhoneNum(inputArguments)
|
||||
print("phonenumber", phonenumber)
|
||||
# # phonenumber='13243889782'
|
||||
if phonenumber is not None and uid is not None:
|
||||
warntext = "[异度世界],微信加群验证码:3399"
|
||||
# sendTg(f"用户手机号{phonenumber},开始发送验证码")
|
||||
# 判断用户uid是都触发过短信,不允许触发第2次
|
||||
if findUid(uid, phonenumber) is True:
|
||||
err_code = -1
|
||||
outputArguments = "验证码已下发1次,不允许重复触发"
|
||||
print("用户uid已存在,不触发短信")
|
||||
# sendTg(f"用户{uid}已存在,不触发短信")
|
||||
else:
|
||||
# 发送闪信
|
||||
sendFlash(phonenumber,warntext)
|
||||
# uid:唯一标识用户的openid
|
||||
print("appid", appid,"bid",bid,"requestid", requestid,"uid", uid)
|
||||
# 存储uid和手机号
|
||||
return {"appid": appid,"bid": bid,"requestid": requestid,"uid": uid,'inputArguments':inputArguments}
|
||||
# sendFlash(phonenumber, warntext)
|
||||
# 后台发送
|
||||
background_tasks.add_task(sendFlash, phonenumber, warntext)
|
||||
|
||||
# 成功的响应 0成功 -1失败
|
||||
content = {
|
||||
"err_code": err_code,
|
||||
"data_list": [{"outputArguments": outputArguments}],
|
||||
}
|
||||
headers = {"Content-Type": "application/json"}
|
||||
return JSONResponse(content=content, headers=headers)
|
||||
|
||||
else:
|
||||
err_code = -1
|
||||
outputArguments = "验证码发送失败,请检查手机号格式,或其他异常"
|
||||
print(f"用户输入:{inputArguments},手机号不正确,或者uid参数异常")
|
||||
# sendTg(f"用户输入:{inputArguments},手机号不正确,或者uid参数异常")
|
||||
|
||||
# 成功的响应 0成功 -1失败
|
||||
content = {
|
||||
"err_code": err_code,
|
||||
"data_list": [{"outputArguments": outputArguments}],
|
||||
}
|
||||
headers = {"Content-Type": "application/json"}
|
||||
return JSONResponse(content=content, headers=headers)
|
||||
|
||||
# # 微信对话平台一定要选择: 随机回复
|
||||
|
||||
|
||||
# 通过网址发送闪信
|
||||
@app.post("/callback")
|
||||
# def read_root():
|
||||
# return {"Hello": "World"}
|
||||
async def callback(
|
||||
# item: Item,
|
||||
inputArguments: Union[str, None] = 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),
|
||||
):
|
||||
# time.sleep(10)
|
||||
# print("item", item)
|
||||
try:
|
||||
inputArguments = unquote(inputArguments, "utf-8")
|
||||
except:
|
||||
inputArguments = ""
|
||||
# 正则获取11位手机号
|
||||
phonenumber = findPhoneNum(inputArguments)
|
||||
print("phonenumber", phonenumber)
|
||||
|
||||
content = {
|
||||
# "ans_node_name": "小微闲聊",
|
||||
# "title": "小薇兄你好",
|
||||
"answer": "你好呀123!",
|
||||
"answer_type": "text",
|
||||
# "bid_stat": {
|
||||
# "curr_time": "20190515-18:07:37",
|
||||
# "err_msg": "微信通用意图.肯定.branches.s_Any@.arguments's element.slot slot does not exist!",
|
||||
# "latest_time": "20190523-16:06:33",
|
||||
# "latest_valid": False,
|
||||
# "up_ret": -1,
|
||||
# },
|
||||
# "confidence": 1,
|
||||
# "from_user_name": "o9U-85tEZToQxIF8ht6o-KkagxO0",
|
||||
# "status": "FAQ",
|
||||
# "to_user_name": "xalsjfasf1ljasjdf1",
|
||||
# "options": [
|
||||
# {
|
||||
# "ans_node_id": 12355896,
|
||||
# "ans_node_name": "自建应用",
|
||||
# "answer": "有详情入口的应用消息一般是通过api进行推送的入口不E_BREAKLINE_BREAK2、企业号或企业微信后台推送的图文消息,在微信PC侧会有“详情”入口,在企业微信手机端、PC端以及微信手机端则不会有“详情”入口。LINE_BREAKLINE_BREAK注意:微信电脑端侧仅会显示摘要和详情,不显示标题。企业微信电脑端、微信微信手机端、企业微信手机端则会显示标题和摘要。若未填写摘要,则不显示摘要。",
|
||||
# "confidence": 0.795230507850647,
|
||||
# "title": "自建应用消息没有详情入口",
|
||||
# }
|
||||
# ],
|
||||
}
|
||||
headers = {"Content-Type": "application/json"}
|
||||
return JSONResponse(content=content, headers=headers)
|
||||
|
||||
288
callback.py
Normal file
288
callback.py
Normal file
@@ -0,0 +1,288 @@
|
||||
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:
|
||||
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)
|
||||
175
dsxSms.py
Normal file
175
dsxSms.py
Normal file
@@ -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)
|
||||
@@ -22,7 +22,7 @@ def decode2HexStr(Unicde_Str):
|
||||
|
||||
|
||||
|
||||
def sendSMS(phonenumber,warntext):
|
||||
def sendSMS(phonenumber,warntext,modem):
|
||||
modem.write(("AT"+"\r\n").encode())
|
||||
print(modem.readline())
|
||||
time.sleep(0.5)
|
||||
@@ -69,7 +69,7 @@ def sendSMS(phonenumber,warntext):
|
||||
print(modem.readline())
|
||||
print('end---')
|
||||
# 触发tg消息提醒
|
||||
sendTg('4g模块短信发送成功,succsess')
|
||||
sendTg(f'4g模块短信-{phonenumber}发送成功,succsess')
|
||||
# if line.startswith("+CMGS"):
|
||||
# print ("已成功发送")
|
||||
# return True
|
||||
@@ -86,10 +86,10 @@ def sendFlash(phonenumber,warntext):
|
||||
print ("短信助手硬件USB接口已连接成功...正在启动")
|
||||
# phonenumber=input('请输入phonenumber: ')
|
||||
# warntext=input('warntext: ')
|
||||
sendSMS(phonenumber,warntext)
|
||||
sendSMS(phonenumber,warntext,modem)
|
||||
modem.close()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print ("请检查短信模块是否插上usb 或 确定端口号是否正确")
|
||||
# 触发tg消息提醒
|
||||
sendTg('4g模块短信发送失败,请检查错误')
|
||||
sendTg('4g模块短信-{phonenumber}发送失败,请检查错误')
|
||||
74
getCodeStatus.py
Normal file
74
getCodeStatus.py
Normal file
@@ -0,0 +1,74 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
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
|
||||
|
||||
# 导入可选配置类
|
||||
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" # 指定接入地域域名(默认就近接入)
|
||||
|
||||
# 非必要步骤:
|
||||
# 实例化一个客户端配置对象,可以指定超时时间等配置
|
||||
clientProfile = ClientProfile()
|
||||
clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法
|
||||
clientProfile.language = "en-US"
|
||||
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.PullSmsSendStatusRequest()
|
||||
|
||||
# 基本类型的设置:
|
||||
# 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
|
||||
req.SmsSdkAppId = "1400808237"
|
||||
# 拉取最大条数,最多100条
|
||||
req.Limit = 10
|
||||
# req.Action = 'PullSmsSendStatusByPhoneNumber'
|
||||
# req.Version = '2021-01-11'
|
||||
# req.Region = 10
|
||||
# req.LiRegionmit = 10
|
||||
# req.PhoneNumber = '+8613243889782'
|
||||
|
||||
# 通过client对象调用PullSmsSendStatus方法发起请求。注意请求方法名与请求对象是对应的。
|
||||
# 返回的resp是一个PullSmsSendStatusResponse类的实例,与请求对象对应。
|
||||
resp = client.PullSmsSendStatus(req)
|
||||
|
||||
# 输出json格式的字符串回包
|
||||
print(resp.to_json_string(indent=2))
|
||||
|
||||
|
||||
except TencentCloudSDKException as err:
|
||||
print(err)
|
||||
21
getapiPost.py
Normal file
21
getapiPost.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# pip install --upgrade tencentcloud-sdk-python
|
||||
import requests
|
||||
import time
|
||||
headers = {'content-type': 'application/json',"X-TC-Action": 'PullSmsSendStatusByPhoneNumber'}
|
||||
|
||||
payload = {
|
||||
"Action": "PullSmsSendStatusByPhoneNumber",
|
||||
"Version": "2021-01-11",
|
||||
"Region": "ap-beijing",
|
||||
"BeginTime":time.time(), #用户触发接口的时候
|
||||
# "BeginTime":1684724400, #用户触发接口的时候
|
||||
"Timestamp":1684724400,
|
||||
"Offset": 0,
|
||||
"Limit": 1,
|
||||
"PhoneNumber": "+8613243889782",
|
||||
"SmsSdkAppId": "1400808237",
|
||||
# "EndTime": 1684724400
|
||||
}
|
||||
r = requests.post("https://sms.tencentcloudapi.com", headers=headers,data=payload)
|
||||
|
||||
print('rjson',r.json())
|
||||
97
tentcentSMS.py
Normal file
97
tentcentSMS.py
Normal file
@@ -0,0 +1,97 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
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
|
||||
# pip install --upgrade tencentcloud-sdk-python
|
||||
|
||||
# 导入可选配置类
|
||||
from tencentcloud.common.profile.client_profile import ClientProfile
|
||||
from tencentcloud.common.profile.http_profile import HttpProfile
|
||||
|
||||
# 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("")
|
||||
# )
|
||||
|
||||
# 实例化一个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 = "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 = ""
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user