当前位置:   article > 正文

个人windows电脑在微信公众号创建聊天机器人_windows配置微信聊天机器人

windows配置微信聊天机器人

1.申请微信公众号;

2.申请大模型kpi;

3.使用内网穿透工具建立域名,并将域名映射到本地计算机上,选则端口;

4.利用python flask编写代码,建立ip端口连接,代码如下:

  1. import os
  2. import dashscope
  3. import hashlib
  4. from xml.etree.ElementTree import Element, SubElement, tostring
  5. import xml.etree.ElementTree as ET
  6. from flask import Flask, request, render_template, jsonify
  7. from flask import make_response
  8. import time
  9. urls = (
  10. '/wx'
  11. )
  12. # 创建Flask应用实例
  13. app = Flask(__name__)
  14. # 从环境变量读取API密钥
  15. dashscope.api_key = os.getenv('DASHSCOPE_API_KEY')
  16. def parse_request(xml_data):
  17. try:
  18. tree = ET.fromstring(xml_data)
  19. msg_type = tree.find('MsgType').text
  20. # 添加对 FromUserName 和 ToUserName 的解析
  21. from_user_name = tree.find('FromUserName').text
  22. to_user_name = tree.find('ToUserName').text
  23. if msg_type == 'text':
  24. content = tree.find('Content').text
  25. return {'type': 'text', 'content': content, 'from_user_name': from_user_name, 'to_user_name': to_user_name}
  26. elif msg_type == 'image':
  27. media_id = tree.find('MediaId').text
  28. return {'type': 'image', 'media_id': media_id, 'from_user_name': from_user_name, 'to_user_name': to_user_name}
  29. # 处理其它类型的消息...
  30. else:
  31. return None
  32. except Exception as e:
  33. print(f"Error parsing request: {e}")
  34. return None
  35. def generate_response_xml(answer, parsed_request):
  36. # 构建微信需要的XML格式响应
  37. root = Element('xml')
  38. to_user = SubElement(root, 'ToUserName')
  39. to_user.text = parsed_request['from_user_name']
  40. from_user = SubElement(root, 'FromUserName')
  41. from_user.text = parsed_request['to_user_name']
  42. create_time = SubElement(root, 'CreateTime')
  43. create_time.text = str(int(time.time()))
  44. msg_type = SubElement(root, 'MsgType')
  45. msg_type.text = 'text'
  46. content = SubElement(root, 'Content')
  47. content.text = answer
  48. return '<?xml version="1.0" encoding="UTF-8"?>' + tostring(root, encoding='unicode')
  49. def call_with_prompt(prompt):
  50. try:
  51. response = dashscope.Generation.call(
  52. model=dashscope.Generation.Models.qwen_turbo,
  53. prompt=prompt
  54. )
  55. if isinstance(response, dict) and 'output' in response:
  56. return response['output']["text"]
  57. else:
  58. # Log the unexpected response and return a default message
  59. app.logger.error("Unexpected response format from DashScope: %s", response)
  60. return "I'm sorry, but I couldn't process your request right now."
  61. except Exception as e:
  62. # Log the error and return a default message
  63. app.logger.error("Error calling DashScope: %s", str(e))
  64. return "An error occurred while processing your request."
  65. @app.route('/')
  66. def index():
  67. return render_template('index.html')
  68. @app.route('/ask', methods=['POST'])
  69. def ask_question():
  70. question = request.form['question']
  71. answer = call_with_prompt(question)
  72. return jsonify({'answer': answer})
  73. @app.route('/wechat', methods=['GET', 'POST'])
  74. def handle_wechat():
  75. if request.method == 'GET':
  76. signature = request.args.get('signature')
  77. timestamp = request.args.get('timestamp')
  78. nonce = request.args.get('nonce')
  79. echostr = request.args.get('echostr')
  80. token = "maluguang"
  81. # 使用列表推导式确保所有元素都不是None,然后再排序
  82. list = [x for x in [token, timestamp, nonce] if x is not None]
  83. list.sort()
  84. sha1 = hashlib.sha1()
  85. sha1.update(''.join(list).encode('utf-8'))
  86. hashcode = sha1.hexdigest()
  87. if hashcode == signature:
  88. # 使用make_response()并设置Content-Type
  89. response = make_response(echostr)
  90. response.headers['Content-Type'] = 'text/plain'
  91. return response
  92. else:
  93. return ""
  94. elif request.method == 'POST':
  95. xml_data = request.data.decode('utf-8')
  96. parsed_request = parse_request(xml_data)
  97. if parsed_request is not None:
  98. # Use only the content part of the parsed_request for generating the answer
  99. answer = call_with_prompt(parsed_request['content'])
  100. # Generate the response XML using the answer and parsed_request
  101. response_xml = generate_response_xml(answer, parsed_request)
  102. return response_xml
  103. else:
  104. # Return an error response in XML format
  105. return '<?xml version="1.0" encoding="UTF-8"?><xml><ToUserName><![CDATA[error]]></ToUserName><FromUserName><![CDATA[error]]></FromUserName><CreateTime>0</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Invalid request]]></Content></xml>', 400
  106. if __name__ == '__main__':
  107. app.run(host='0.0.0.0', port="8080")
  108. #app.run(debug=True)

4.下载nginx,并更改conf文件中的local地址和监听端口;

5.在微信公众平台上的基础设置中修改,将域名加子名称输入(此处需留意,应与上述的local地址相互对应),进行token验证,该token和代码中token一致

6.enjoy。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/1010104
推荐阅读
相关标签
  

闽ICP备14008679号