Rewrite my Python code to Rust please

import os
import asyncio
import aiohttp
import aiofiles
import zipfile
import shutil
import time
import json
from datetime import datetime
from colorama import init, Fore, Style

init()

print("""
 ▒█████   ██▓███    ███▄ ▄███▓ ▒█████  ▓██   ██▓ ▄▄▄     
▒██▒  ██▒▓██░  ██  ▓██▒▀█▀ ██▒▒██▒  ██▒ ▒██  ██▒▒████▄   
▒██░  ██▒▓██░ ██▓▒ ▓██    ▓██░▒██░  ██▒  ▒██ ██░▒██  ▀█▄ 
▒██   ██░▒██▄█▓▒ ▒ ▒██    ▒██ ▒██   ██░  ░ ▐██▓░░██▄▄▄▄██
░ ████▓▒░▒██▒ ░  ░▒▒██▒   ░██▒░ ████▓▒░  ░ ██▒▓░▒▓█   ▓██
░ ▒░▒░▒░ ▒▓▒░ ░  ░░░ ▒░   ░  ░░ ▒░▒░▒░    ██▒▒▒ ░▒▒   ▓▒█
  ░ ▒ ▒░ ░▒ ░     ░░  ░      ░  ░ ▒ ▒░  ▓██ ░▒░ ░ ░   ▒▒ 
░ ░ ░ ▒  ░░        ░      ░   ░ ░ ░ ▒   ▒ ▒ ░░    ░   ▒  
    ░ ░           ░       ░       ░ ░   ░ ░           ░  \n
    """)

config_file = 'config.json'

def load_config():
    if not os.path.exists(config_file):
        print(f"{Fore.RED}[!!!] Файл конфигурации {config_file} не найден, создаю.{Fore.RESET}")
        config_data = {
            "telegram_token": "TOKEN_TELEGRAM_BOT",
            "chat_id": "CHAT_ID"
        }
        with open(config_file, 'w') as f:
            json.dump(config_data, f, indent=4)
            print(f'{Fore.GREEN}[+] Конфиг создан, заполните его и запускайте программу!\n{Fore.RESET}')
            os.system('pause')
            exit()
    else:
        print(f'{Fore.CYAN}[+++] Конфиг существует, начинаю работу!{Fore.RESET}')
        #main()

    with open(config_file, 'r') as f:
        try:
            config = json.load(f)
            return config
        except json.JSONDecodeError:
            print(f"{Fore.RED}[!!!] Ошибка чтения конфигурационного файла {config_file}.{Fore.RESET}")
            return None
now = datetime.now()
fdt = now.strftime("%Y-%m-%d ! %H - %M - %S")

async def parse_file(filename, queries, result_folder):
    results = {}
    found_queries = 0
    not_found_queries = 0

    async with aiofiles.open(filename, 'r', errors='replace') as file:
        async for line_num, line in enumerate(file, start=1):
            line = line.strip()

            for query in queries:
                if query['domain'] in line.lower():
                    found_queries += 1
                    os.makedirs(result_folder, exist_ok=True)

                    folder_name = query['name'].replace('/', '_').replace(':', '_')
                    folder_path = os.path.join(result_folder, folder_name)

                    os.makedirs(folder_path, exist_ok=True)

                    file_name = f'{query["name"]}.txt'
                    file_name = file_name.replace('/', '_').replace(':', '_')
                    file_path = os.path.join(folder_path, file_name)

                    results[file_name] = results.get(file_name, 0) + 1

                    try:
                        async with aiofiles.open(file_path, 'a', encoding='utf-8') as result_file:
                            await result_file.write(f'{line}\n')
                    except Exception as e:
                        print(f'Ошибка при сохранении строки в файл: {e} (строка {line_num})')
                else:
                    not_found_queries += 1

    return results, found_queries, not_found_queries, line_num

async def archive_results(result_folder):
    zip_file_name = f'{result_folder}.zip'

    if os.path.exists(result_folder):
        try:
            with zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
                for root, _, files in os.walk(result_folder):
                    for file in files:
                        file_path = os.path.join(root, file)
                        zipf.write(file_path, os.path.relpath(file_path, result_folder))
        except Exception as e:
            print(f'{Fore.RED}[!!!] Ошибка при создании архива: {e}{Fore.RESET}')
            return None

        print(f'{Fore.GREEN}[+] {Fore.RESET}Результаты успешно запакованы в архив: {zip_file_name}{Fore.RESET}')
        return zip_file_name
    else:
        print(f'{Fore.RED}[!!!] Папка с результатами не найдена.{Fore.RESET}')
        return None

async def send_to_telegram(token, chat_id, file_path):
    if not file_path:
        return

    api_url = f'https://api.telegram.org/bot{token}/sendDocument'

    try:
        async with aiohttp.ClientSession() as session:
            form_data = aiohttp.FormData()
            form_data.add_field('chat_id', str(chat_id))
            form_data.add_field('document', open(file_path, 'rb'))

            async with session.post(api_url, data=form_data) as response:
                if response.status == 200:
                    print(f'{Fore.GREEN}[+] {Fore.RESET}Результаты успешно отправлены в Telegram бота.{Fore.RESET}')
                else:
                    print(f'{Fore.RED}[!!!] Ошибка при отправке результатов в Telegram. \n{response.text}{Fore.RESET}')
    except Exception as e:
        print(f'{Fore.RED}[!!!] Ошибка при отправке результатов в Telegram: {e}{Fore.RESET}')

    # Удаляем архив после отправки
    if os.path.exists(file_path):
        os.remove(file_path)

def process_file_line(line):
    for query in queries:
        if query['domain'] in line.lower():
            return query['name'], line
    return None

if __name__ == '__main__':
    config = load_config()
    if config is None:
        os.system('pause')
        exit()

    filename = 'req.txt'
    queries = []

    with open('qr.txt', 'r', encoding='utf-8') as qr_file:
        lines = qr_file.readlines()

        for line in lines:
            line = line.strip()
            if line:
                query = {
                    'name': line,
                    'domain': line.lower()
                }
                queries.append(query)

    result_folder = str("Results ") + str(datetime.now().strftime("%Y-%m-%d %H-%M-%S"))

    found_queries = 0
    total_lines = 0
    results = {}

    os.makedirs(result_folder, exist_ok=True)

    start_time = time.time()

    with open(filename, 'r', encoding='utf-8') as file:
        for line in file:
            line = line.strip()
            total_lines += 1

            result = process_file_line(line)
            if result:
                query_name, result_line = result
                found_queries += 1

                folder_name = query_name.replace('/', '_').replace(':', '_')
                folder_path = os.path.join(os.getcwd(), result_folder, folder_name)
                os.makedirs(folder_path, exist_ok=True)

                file_name = f'{query_name}.txt'
                file_name = file_name.replace('/', '_').replace(':', '_')
                file_path = os.path.join(folder_path, file_name)

                if file_name in results:
                    results[file_name] += 1
                else:
                    results[file_name] = 1

                try:
                    with open(file_path, 'a', encoding='utf-8') as result_file:
                        result_file.write(f'{result_line}\n')
                except Exception as e:
                    print(f'Ошибка при сохранении строки в файл: {e}')

    for file_name, count in results.items():
        if count > 0:
            file_path = os.path.join(result_folder, file_name)
            if os.path.exists(file_path):
                try:
                    with open(file_path, 'r', encoding='utf-8') as result_file:
                        for line in result_file:
                            print(line.strip())
                except Exception as e:
                    print(f'Ошибка при чтении файла: {e}')
        else:
            print(f'Файл не существует: {file_name}')

    end_time = time.time()
    elapsed_time = end_time - start_time

    print(f'Найдено: {Fore.GREEN}{found_queries}{Fore.RESET} | Не найдено: {Fore.RED}{total_lines - found_queries}{Fore.RESET} | Всего строк: {Fore.YELLOW}{total_lines}{Fore.RESET}')
    print(f'Затраченное время: {Fore.CYAN}{elapsed_time // 60} {Fore.RESET}минут {Fore.BLUE}{elapsed_time % 60:.2f} {Fore.RESET}секунд\n')
    print(f'\n{Fore.CYAN}[!] Результаты сохранены в: {Fore.WHITE}{Style.BRIGHT}{str("Results ") + str(fdt)}{Fore.RESET}')

    # Архивация папки и отправка в Telegram
    zip_file_name = asyncio.run(archive_results(result_folder))
    if zip_file_name is not None:
        telegram_token = config.get('telegram_token', '')
        chat_id = config.get('chat_id', '')
        asyncio.run(send_to_telegram(telegram_token, chat_id, zip_file_name))

        # Получение полного пути для удаления архива
        zip_file_path = os.path.abspath(zip_file_name)

    # Удаление папки с результатами и архива после отправки в Telegram
    #if os.path.exists(result_folder):
    #    shutil.rmtree(result_folder)

    # Удаление архива
    if os.path.exists(zip_file_path):
        os.remove(zip_file_path)

    os.system('pause')

Here is my code, rewrite it to Rust please, i'm very need. Be helpful

How much are you offering?

6 Likes

0, I'm waiting on free help, if anyone can. My pleasure if you do it, bro :slight_smile:

I'm going to be honest here: you'll have a tough time getting someone to rewrite 200 lines of your code for free, especially if it's uncommented with no description of what it's supposed to do.

You'll likely have better luck if you try rewriting it yourself, and then ask questions about the parts that you don't know how to do. Are you familiar with the Rust programming language? If not, I suggest you get started with the Rust book.

10 Likes

Thank you for good answer, good luck. +rep

I made a start for you:

use colored::Colorize;

fn main() {
    let banner = r#"
    ▒█████   ██▓███    ███▄ ▄███▓ ▒█████  ▓██   ██▓ ▄▄▄     
    ▒██▒  ██▒▓██░  ██  ▓██▒▀█▀ ██▒▒██▒  ██▒ ▒██  ██▒▒████▄   
    ▒██░  ██▒▓██░ ██▓▒ ▓██    ▓██░▒██░  ██▒  ▒██ ██░▒██  ▀█▄ 
    ▒██   ██░▒██▄█▓▒ ▒ ▒██    ▒██ ▒██   ██░  ░ ▐██▓░░██▄▄▄▄██
    ░ ████▓▒░▒██▒ ░  ░▒▒██▒   ░██▒░ ████▓▒░  ░ ██▒▓░▒▓█   ▓██
    ░ ▒░▒░▒░ ▒▓▒░ ░  ░░░ ▒░   ░  ░░ ▒░▒░▒░    ██▒▒▒ ░▒▒   ▓▒█
      ░ ▒ ▒░ ░▒ ░     ░░  ░      ░  ░ ▒ ▒░  ▓██ ░▒░ ░ ░   ▒▒ 
    ░ ░ ░ ▒  ░░        ░      ░   ░ ░ ░ ▒   ▒ ▒ ░░    ░   ▒  
        ░ ░           ░       ░       ░ ░   ░ ░           ░
"#;
    println!("{}", banner.red());
}

just for inspiration.

No renumeration required, you got me curious as to how one might do that. Now I know.

9 Likes

I glanced through the code and don't like what I see. I'm an admin on several tg channels; this code is my enemy.

4 Likes

I have to say that the mention of "telegram" in the code triggered an alert for me too. The fact that the comments appear to be in Russian is also, shall we say, curious.

2 Likes

OT: tg has the most spammer-friendly API I've ever seen. It even lets spammers place custom keyboards on victim channels without any kind of mod approval. We have to use bots to battle bots in an ever-escalating landscape.

1 Like

Just ask ChatGPT, man. It can translate easily.
Edit: spelling error

2 Likes

Hi and welcome to our forum. Of course, you may ask for it, but be advised that it's quite unlikely that someone will just do a full translation of your python program into Rust for you here.

More commonly, people in this forum will help with specific issues (the more specific the question, the easier), or help with reviewing code – Rust code :wink: These kinds of things would require less effort on the person answering, and are also generally more useful to other people who have similar problems, or try similar things, and read this topic as well, now or in the future.

In that context, if you tried a translation yourself, feel free to ask for any issues you encounter, or general questions you might have.

For your post, it also isn't clear what the motivation is anyways. For once, what does the program even do, why are there no English comments / descriptions? And then, if you have a complete working Python program, why use Rust? Hopes of significantly optimizing performance? Do you want to improve the behavior of the program? (In which, for improving the behavior, a Python forum might be more appropriate..) Don you want to learn Rust? (In which case, trying to approach the translation yourself might be more instructive; and you should probably share your current level of Rust knowledge.) Or something else?

9 Likes

Thank you. My program haven't English description because I'm from Ukraine, and speaking Russian, and that program maked for peoples from CIS regions. Analyze that code and after you can understand logic of this code. Thank you again, bro :slight_smile:

Are you the same OpMoya that is signed up for all kind of crack/hack/cheat sites all over the internet? Some Russia?

3 Likes

Yes, I'm. But I'm from Ukraine, no russia )))

How do you import red()? I think something is missing.

You probably need to add colored to your list of dependencies in Cargo.toml:

[dependencies]
colored = "2.0.4"
1 Like

ah yes thanks such a basic mistake.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.