微信机器人搭建详细教程

确保已安装Python和pip。

在D盘上创建名为wxbot的文件夹,并将你的Python机器人项目文件放在这个目录中。

在D盘的wxbot文件夹中打开命令行工具,并创建一个新的Python虚拟环境(可选):

python -m venv venv

激活虚拟环境(如果有创建):

# Windows
venv\Scripts\activate

# macOS/Linux
source venv/bin/activate

安装Flask库:

pip install flask

在D盘的wxbot文件夹中创建一个名为app.py的后端代码文件,并添加以下代码:

from flask import Flask, render_template, send_file
import subprocess

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start_bot')
def start_bot():
    subprocess.Popen(['python', 'your_python_bot_script.py'])

    return 'Bot started'

@app.route('/qrcode.png')
def get_qrcode():
    return send_file('path/to/your/qrcode.png', mimetype='image/png')

if __name__ == '__main__':
    app.run()

请确保将上述代码中的your_python_bot_script.py替换为你自己的Python机器人项目文件路径,并将path/to/your/qrcode.png替换为后端生成的二维码图片路径。

在D盘的wxbot文件夹中创建一个名为templates的文件夹,并在该文件夹中创建一个名为index.html的前端代码文件,添加以下代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Wechaty Bot</title>
</head>
<body>
    <h1>Wechaty Bot</h1>
    <button onclick="startBot()">Start Bot</button>
    <div id="qrcode"></div>

    <script>
        function startBot() {
    
    
            fetch('/start_bot')
                .then(response => response.text())
                .then(result => {
    
    
                    console.log(result);
                    displayQRCode();
                })
                .catch(error => console.log(error));
        }

        function displayQRCode() {
    
    
            fetch('/qrcode.png')
                .then(response => response.blob())
                .then(blob => {
    
    
                    const url = URL.createObjectURL(blob);
                    const img = document.createElement('img');
                    img.src = url;
                    document.getElementById('qrcode').appendChild(img);
                })
                .catch(error => console.log(error));
        }
    </script>
</body>
</html>

在命令行中,确保已经进入到D盘的wxbot文件夹,然后运行以下命令启动后端服务器:

python app.py

打开浏览器并访问 http://localhost:5000 ,你将能够看到前端页面,并通过点击"Start Bot"按钮来启动微信机器人。后端会生成并返回二维码图片,在前端页面中显示。

请确保已经按照步骤正确配置了代码,并根据你的项目需求和具体路径做相应的调整。

要实现每个用户登录网站后都可以独立启动一个机器人,你需要为每个用户创建一个独立的机器人实例。目前你的代码中只创建了一个机器人实例并提供了一个按钮来启动该实例。

以下是一种可能的解决方案:

在后端代码中,使用诸如 Flask-Session 等会话管理工具来跟踪用户的会话。这样可以确保每个用户在登录后能够保持自己的会话状态。
对于每个用户,生成一个唯一的标识符,例如用户ID或随机生成的字符串,以便区分不同用户。此标识符将用于创建和跟踪用户特定的机器人实例。
使用一个数据结构(例如字典)来存储每个用户及其对应的机器人实例。键为用户标识符,值为相应用户的机器人实例。
下面是示例代码:

from flask import Flask, render_template, send_file, session
import subprocess

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 设置会话密钥,用于加密会话数据

# 字典用于存储每个用户的机器人实例
user_bots = {
    
    }

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start_bot')
def start_bot():
    user_id = session.get('user_id')
    if user_id not in user_bots:
        # 创建一个新的机器人实例
        bot = subprocess.Popen(['python', 'app.py'], stdout=None, stderr=None)
        # 存储用户和机器人实例的对应关系
        user_bots[user_id] = bot

    return 'Bot started'

@app.route('/QR.png')
def get_qrcode():
    user_id = session.get('user_id')
    if user_id in user_bots:
       return send_file('QR.png', mimetype='image/png')
    else:
       return 'No bot found for this user'

if __name__ == '__main__':
    app.run()

在这个示例中,会话标识符(session[‘user_id’])用于区分不同的用户。在启动机器人之前,首先检查该用户是否已有机器人实例。如果没有,则创建一个新的机器人实例,并将其与用户 ID 关联存储起来。避免多次启动相同的机器人实例。

你可以将这段代码引入你的项目中,确保会话管理工具已正确安装和配置。这样每个用户登录后都可以独立启动和操作他们自己的机器人。

请注意:以上只是一个简单的示例,实际情况根据你的需求可能需要做更多的处理和优化。

猜你喜欢

转载自blog.csdn.net/hbqjzx/article/details/131884781