push_user_app.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import json
  2. import random
  3. import threading
  4. import time
  5. import requests
  6. import uvicorn
  7. from fastapi import FastAPI
  8. from fastapi import Request
  9. from fastapi.exceptions import RequestValidationError
  10. from fastapi.middleware.cors import CORSMiddleware
  11. from fastapi.responses import PlainTextResponse
  12. from starlette.exceptions import HTTPException as StarletteHTTPException
  13. from starlette.middleware.sessions import SessionMiddleware
  14. from starlette.responses import JSONResponse
  15. app = FastAPI(title="push_user_app ", description="通用系统 ", version="v 0.0.0")
  16. # 添加 session 中间键,使项目中可以使用session
  17. app.add_middleware(SessionMiddleware, secret_key='123456hh112312h')
  18. app.add_middleware(
  19. CORSMiddleware,
  20. allow_origins=["*", ],
  21. allow_credentials=True,
  22. allow_methods=["*"],
  23. allow_headers=["*"],
  24. )
  25. @app.exception_handler(StarletteHTTPException)
  26. async def http_exception_handler(request, exc):
  27. """接口服务异常捕获; text/plain"""
  28. return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
  29. @app.exception_handler(RequestValidationError)
  30. async def validation_exception_handler(request, exc):
  31. """请求校验异常捕获; application/json """
  32. json_response = JSONResponse({'message': '【 {} 】接口触发了 RequestValidationError 错误.'
  33. .format(request.scope.get("endpoint").__name__, exc.errors()), 'status_code': 999,
  34. "error_message": exc.errors(), "queryParasm": exc.body})
  35. return json_response
  36. @app.exception_handler(Exception)
  37. async def validation_exception_handler(request, exc):
  38. """请求校验异常捕获; application/json """
  39. return JSONResponse({'message': "服务器内部错误", 'status_code': 500})
  40. @app.middleware("http")
  41. async def add_process_time_header(request: Request, call_next):
  42. """接口响应中间键; 当前只支持 http 请求"""
  43. start_time = time.time()
  44. response = await call_next(request)
  45. process_time = time.time() - start_time
  46. response.headers["API-Process-Time"] = f"{process_time} seconds"
  47. return response
  48. # http://localhost:8000/query?uid=1
  49. @app.get("/query")
  50. def query(uid):
  51. msg = f'uid为{uid}'
  52. return {'success': True, 'msg': msg}
  53. token = None
  54. def delete_token():
  55. global token
  56. time.sleep(60 * 60)
  57. token = None
  58. notes = [
  59. """我们曾如此渴望命运的波澜,到最后才发现,人生最曼妙的风景,竟是内心的淡定与从容;
  60. 我们曾如此期盼外界的认可,到最后才知道,世界是自己的,与他人毫无关系。""",
  61. """做一个浪漫的人,对世界保持永远的好奇,但别让他轻易改变你。""",
  62. """我们终其一生都是为了获得选择的权利和拒绝的底气。""",
  63. """无聊是非常有必要的,一个人在空白时间所做的事,决定了这个人和他人根本的不同。""",
  64. """当爱支配一切时,权力就不存在了;
  65. 当权力主宰一切时,爱就消失了。两者互为对方的影子。""",
  66. """没有一个人是住在客观的世界里, 我们都居住在一个各自赋予其意义的主观的世界。""",
  67. """每天安静地坐十五分钟,倾听你的气息,感觉它,感觉你自己,并且试着什么都不想。"""
  68. ]
  69. def get_des():
  70. li = random.choice(notes).split("\n")
  71. li.append("点击进行复习。")
  72. res = ''
  73. for line in li:
  74. res += "<div>" + line.strip() + "</div>"
  75. return res
  76. def send_message(corp_id, agent_id, secret, userid_list=None, title=None):
  77. global token
  78. if userid_list is None:
  79. userid_list = []
  80. userid_str = "|".join(userid_list)
  81. if token is None:
  82. print("获取一次 token")
  83. response = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corp_id}&corpsecret={secret}")
  84. data = json.loads(response.text)
  85. access_token = data['access_token']
  86. token = access_token
  87. threading.Thread(target=delete_token).start()
  88. else:
  89. access_token = token
  90. json_dict = {
  91. "touser": userid_str,
  92. "msgtype": "textcard",
  93. "agentid": agent_id,
  94. "textcard": {
  95. "title": title,
  96. "description": get_des(),
  97. "url": "https://memory.tianyunperfect.cn/",
  98. "btntxt": "更多"
  99. },
  100. "safe": 0,
  101. "enable_id_trans": 0,
  102. "enable_duplicate_check": 0,
  103. "duplicate_check_interval": 1800
  104. }
  105. json_str = json.dumps(json_dict)
  106. response_send = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}",
  107. data=json_str)
  108. return json.loads(response_send.text)['errmsg'] == 'ok'
  109. @app.get("/push_user")
  110. def push_user(user_id):
  111. return {
  112. 'success': send_message("ww582505d35b886cde", "1000002", "yDCwvVOHSvb_43Y3e17mZi4E7hEZ2Z3UDyDpuKxzPsQ",
  113. [str(user_id)], "念念不忘,必有回响")}
  114. @app.get("/push_msg")
  115. def push_msg(user_id, title):
  116. return {
  117. 'success': send_message("ww582505d35b886cde", "1000002", "yDCwvVOHSvb_43Y3e17mZi4E7hEZ2Z3UDyDpuKxzPsQ",
  118. [str(user_id)], title)}
  119. if __name__ == '__main__':
  120. uvicorn.run(app='push_user_app:app', host="0.0.0.0", port=8087, reload=True, debug=True)
  121. # uvicorn push_user_app:app --reload --host 0.0.0.0 --port 9100