GE

How to write a simple program that can block a BOT from spamming a website

Recommended Posts

To block a bot that is spamming a website forum, we can implement several anti-bot mechanisms. Below is an example of Python code that could be used in a web framework like Flask, Django, or similar. The code outlines a method for detecting and blocking bots based on IP rate-limiting, checking for known bot user agents, and requiring a CAPTCHA challenge.

Here’s a basic implementation of a bot-blocking mechanism:

Requirements:

  1. Flask web framework for building a web server.
  2. Flask-Limiter for rate limiting.
  3. reCAPTCHA or similar challenge for bot prevention.
  4. User-Agent check for detecting known bots

Python Code:

pip install Flask Flask-Limiter requests

 

from flask import Flask, request, jsonify, render_template_string
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import re

# Initialize Flask app and Flask-Limiter for rate limiting
app = Flask(__name__)
limiter = Limiter(get_remote_address, app=app)

# Simple known bot user agents for blocking
KNOWN_BOTS = [
    "Googlebot", "Bingbot", "Slurp", "DuckDuckBot", "Baiduspider",
    "YandexBot", "Sogou", "Facebook", "Twitterbot", "WhatsApp"
]

# Helper function to check user-agent for bots
def is_bot(user_agent):
    for bot in KNOWN_BOTS:
        if bot.lower() in user_agent.lower():
            return True
    return False

# Rate limiting rule: limit to 5 requests per minute per IP address
@limiter.limit("5 per minute")
@app.route("/forum", methods=["POST"])
def forum_post():
    # Check for bot in user-agent header
    user_agent = request.headers.get('User-Agent', '')
    if is_bot(user_agent):
        return jsonify({"error": "Bot detected. Your request has been blocked."}), 403
    
    # If it's a legitimate post, proceed (add CAPTCHA validation in real scenarios)
    data = request.json
    if not data.get("captcha") == "valid_captcha_token":  # Replace with actual CAPTCHA verification
        return jsonify({"error": "Failed CAPTCHA verification."}), 403
    
    # Process the forum post
    # For simplicity, just echo back the message
    return jsonify({"message": f"Post received: {data.get('message')}"})

# Simple HTML page that users can visit to post to the forum
@app.route("/")
def index():
    return render_template_string("""
        <html>
            <body>
                <h1>Forum</h1>
                <form method="POST" action="/forum">
                    <textarea name="message"></textarea><br>
                    <!-- Add CAPTCHA here -->
                    <input type="text" name="captcha" placeholder="Enter CAPTCHA"><br>
                    <input type="submit" value="Post">
                </form>
            </body>
        </html>
    """)

if __name__ == "__main__":
    app.run(debug=True)

 

Share this post


Link to post
Share on other sites

[URL=https://en.casualdate.live] Dating for Sex. [/URL]

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
You are posting as a guest. If you have an account, please sign in.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.