Фиксация мамы нолнан с сфере IT с симпатией к атусу стоещему на полигоне

с афроо лошадьми
This commit is contained in:
SkrinVex
2026-01-20 22:04:44 +05:00
parent 024444abdb
commit 4365a50cda
45 changed files with 2941 additions and 470 deletions
+140
View File
@@ -0,0 +1,140 @@
# 🦊 FoxLang Telegram Bot
Telegram бот, написанный на чистом FoxLang для выполнения FoxLang кода!
## 📁 Структура
```
telegram_bot/
├── main.fox # Основной файл бота
├── bot_api.fox # API для работы с Telegram
├── code_executor.fox # Выполнение пользовательского кода
├── token.txt # Токен бота (настройте!)
├── run_bot.sh # Скрипт запуска
└── README.md # Эта документация
```
## 🚀 Быстрый старт
### 1. Создание бота
1. Найдите @BotFather в Telegram
2. Отправьте `/newbot`
3. Следуйте инструкциям
4. Получите токен вида: `123456789:ABCdefGHIjklMNOpqrsTUVwxyz`
### 2. Настройка
Отредактируйте файл `token.txt`:
```bash
nano token.txt
```
Замените `YOUR_BOT_TOKEN_HERE` на ваш реальный токен.
### 3. Запуск
```bash
./run_bot.sh
```
Или вручную:
```bash
../src/foxlang main.fox
```
## 🤖 Возможности бота
### Команды
- `/start` - Приветствие и инструкции
- `/help` - Справка по FoxLang
- `/example` - Пример кода
### Выполнение кода
Отправьте боту любой FoxLang код:
```cpp
int x = 10;
int y = 20;
print("Sum: " + (x + y));
fox();
```
### Безопасность
- Запрет на `include` в пользовательском коде
- Ограничение длины кода (10000 символов)
- Ограничение вывода (4000 символов)
- Запрет системных вызовов
## 🔧 Архитектура
### main.fox
- Основной цикл бота
- Обработка команд
- Инициализация
### bot_api.fox
- HTTP запросы к Telegram API
- Парсинг JSON ответов
- Отправка сообщений
### code_executor.fox
- Выполнение пользовательского кода
- Проверки безопасности
- Ограничения вывода
## 🛠 Разработка
### Добавление новых команд
В `main.fox`, функция `handle_command()`:
```cpp
if (command == "/mycommand") {
return "My custom response";
}
```
### Расширение API
В `bot_api.fox` можно добавить новые методы Telegram API:
```cpp
void send_photo(string token, string chat_id, string photo_url) {
// Реализация отправки фото
}
```
### Улучшение безопасности
В `code_executor.fox`, функция `is_safe_code()`:
```cpp
// Добавить новые запрещенные слова
set(forbidden_words, 5, "dangerous_function");
```
## 📝 Примечания
- Бот написан на чистом FoxLang
- Использует заглушки для системных функций
- Для полной функциональности нужны встроенные функции:
- `http_get()` - HTTP запросы
- `read_file()` / `write_file()` - работа с файлами
- `sleep()` - задержки
- Строковые функции (`contains`, `replace_all`, etc.)
## 🔮 Будущие улучшения
- [ ] Полный JSON парсер
- [ ] Файловые операции
- [ ] HTTP клиент
- [ ] Строковые функции
- [ ] Логирование
- [ ] Конфигурация через файл
- [ ] Поддержка inline клавиатур
- [ ] Сохранение состояния пользователей
## 📄 Лицензия
MIT License - используйте свободно!
+122
View File
@@ -0,0 +1,122 @@
// bot_api.fox - API для работы с Telegram Bot API
// Глобальные переменные для API
string api_base_url = "https://api.telegram.org/bot";
// HTTP запрос к Telegram API
string telegram_request(string token, string method, string params) {
string url = api_base_url + token + "/" + method;
if (params != "") {
url = url + "?" + params;
}
return http_get(url);
}
// Отправка сообщения
void send_message(string token, string chat_id, string text) {
string params = "chat_id=" + chat_id + "&text=" + url_encode(text);
string response = telegram_request(token, "sendMessage", params);
print("Message sent to " + chat_id);
}
// Получение обновлений
string get_updates(string token, int offset) {
string params = "offset=" + (offset + 1) + "&timeout=10";
return telegram_request(token, "getUpdates", params);
}
// Обработка обновлений
void process_updates(string json_response) {
print("=== PROCESS_UPDATES START ===");
// Извлекаем данные последнего сообщения
string chat_id = extract_chat_id(json_response);
print("Extracted chat_id: " + chat_id);
string text = extract_message_text(json_response);
print("Extracted text: " + text);
string username = extract_username(json_response);
int update_id = extract_update_id(json_response);
print("Chat ID: " + chat_id + ", Text: " + text + ", Update ID: " + update_id);
// Проверяем, что это новое сообщение
if (update_id > last_update_id && chat_id != "" && text != "") {
print("Processing new message...");
// Обрабатываем сообщение
string response = handle_message(text, username);
print("Sending response: " + response);
// Отправляем ответ
send_message(bot_token, chat_id, response);
// Обновляем offset
last_update_id = update_id;
print("Updated last_update_id to: " + last_update_id);
} else {
print("Skipping old message or empty data");
}
print("=== PROCESS_UPDATES END ===");
}
// Вспомогательные функции для парсинга JSON
string extract_chat_id(string json) {
return json_get(json, "chat_id");
}
string extract_message_text(string json) {
return json_get(json, "text");
}
string extract_username(string json) {
return "SkrinVex"; // Пока заглушка
}
int extract_update_id(string json) {
string id_str = json_get(json, "update_id");
if (id_str != "") {
return str_to_int(id_str);
}
return 0;
}
// URL кодирование
string url_encode(string text) {
// Простая замена специальных символов
string result = text;
result = replace_all(result, " ", "%20");
result = replace_all(result, "\n", "%0A");
return result;
}
// Проверка содержания строки - удалена, используем встроенную contains()
// Замена всех вхождений
string replace_all(string text, string from, string to) {
// Заглушка - в реальности нужна реализация
return text;
}
// Проверка начала строки
bool starts_with(string text, string prefix) {
// Заглушка - в реальности нужна реализация
if (text == "/start" || text == "/help" || text == "/example") {
return true;
}
return false;
}
// Чтение токена
string read_token() {
// Читаем токен из файла token.txt
return read_file("telegram_bot/token.txt");
}
// Пауза (заглушка)
void sleep(int seconds) {
// В реальности нужна реализация задержки
print("Sleeping for " + seconds + " seconds...");
}
+104
View File
@@ -0,0 +1,104 @@
// code_executor.fox - Выполнение FoxLang кода
// Выполнение FoxLang кода
string execute_foxlang_code(string code) {
print("Executing FoxLang code:");
print(code);
// Проверяем безопасность кода
if (!is_safe_code(code)) {
return "❌ Error: Unsafe code detected!";
}
// Сохраняем код во временный файл
string temp_file = "temp_code.fox";
if (!write_code_to_file(temp_file, code)) {
return "❌ Error: Cannot write temporary file";
}
// Выполняем код через интерпретатор
string result = execute_file(temp_file);
// Удаляем временный файл
delete_file(temp_file);
// Ограничиваем длину результата
if (length(result) > 4000) {
result = substring(result, 0, 4000) + "\n... (output truncated)";
}
if (result == "") {
return "✅ Code executed successfully!";
}
return result;
}
// Проверка безопасности кода
bool is_safe_code(string code) {
// Запрещенные операции
array forbidden_words 5;
set(forbidden_words, 0, "include"); // Запрещаем include в пользовательском коде
set(forbidden_words, 1, "system"); // Запрещаем системные вызовы
set(forbidden_words, 2, "exec"); // Запрещаем выполнение команд
set(forbidden_words, 3, "file"); // Запрещаем работу с файлами
set(forbidden_words, 4, "network"); // Запрещаем сетевые операции
int i = 0;
while (i < 5) {
string forbidden = get(forbidden_words, i);
if (contains(code, forbidden)) {
print("Forbidden word detected: " + forbidden);
return false;
}
i = i + 1;
}
// Проверяем длину кода
if (length(code) > 10000) {
print("Code too long");
return false;
}
return true;
}
// Запись кода в файл
bool write_code_to_file(string filename, string code) {
// Заглушка - в реальности нужна реализация записи файлов
print("Writing code to " + filename);
return true;
}
// Выполнение файла
string execute_file(string filename) {
// Заглушка - в реальности нужен вызов интерпретатора
print("Executing file: " + filename);
// Симуляция выполнения простого кода
return simulate_execution(filename);
}
// Симуляция выполнения
string simulate_execution(string filename) {
// Простая симуляция для демонстрации
return "Hello from FoxLang!\nCode executed successfully!";
}
// Удаление файла
void delete_file(string filename) {
// Заглушка - в реальности нужна реализация удаления файлов
print("Deleting file: " + filename);
}
// Получение длины строки
int length(string text) {
// Заглушка - в реальности нужна реализация
return 100; // Примерная длина
}
// Получение подстроки
string substring(string text, int start, int end) {
// Заглушка - в реальности нужна реализация
return text + "...";
}
+87
View File
@@ -0,0 +1,87 @@
// FoxLang Telegram Bot - main.fox
// Основной файл бота на чистом FoxLang
include("bot_api.fox");
include("code_executor.fox");
include("../src/net_simple.fox");
// Конфигурация бота
string bot_token = "";
int last_update_id = 837067997; // Обновляем до последнего ID
// Инициализация бота
void init_bot(string token) {
bot_token = token;
print("🦊 FoxLang Telegram Bot started!");
print("Token: " + token);
}
// Обработка команд
string handle_command(string command, string username) {
if (command == "/start") {
return "🦊 Welcome to FoxLang Bot!\n\nSend me FoxLang code and I'll execute it!\n\nExample:\nint x = 5;\nprint(\"Result: \" + x);\nfox();\n\nCommands:\n/help - Show help\n/example - Show example";
}
if (command == "/help") {
return "🦊 FoxLang Bot Help\n\nSupported features:\n• Variables: int, float, string, bool\n• Functions: Custom functions\n• Arrays: array manipulation\n• Control flow: if/else, while\n• Math: +, -, *, /, %\n• Built-in: print(), fox()\n\nJust send your FoxLang code!";
}
if (command == "/example") {
return "🦊 FoxLang Example:\n\nint add(int a, int b) {\n return a + b;\n}\n\nstring name = \"FoxLang\";\nint result = add(10, 20);\nprint(\"Hello from \" + name + \"!\");\nprint(\"Result: \" + result);\nfox();";
}
return "Unknown command. Use /help for help.";
}
// Обработка сообщения
string handle_message(string text, string username) {
print("Message from " + username + ": " + text);
// Проверяем команды
if (starts_with(text, "/")) {
return handle_command(text, username);
}
// Выполняем FoxLang код
return execute_foxlang_code(text);
}
// Основной цикл бота
void run_bot() {
while (true) {
print("Checking for updates...");
// Получаем обновления
string updates = get_updates(bot_token, last_update_id);
if (updates != "") {
print("Got updates: " + updates);
// Обрабатываем каждое сообщение
print("About to call process_updates...");
process_updates(updates);
print("process_updates completed");
}
// Небольшая пауза
// sleep(1);
}
}
// Точка входа
void main() {
print("🦊 FoxLang Telegram Bot");
print("======================");
// Читаем токен из файла или переменной окружения
string token = read_token();
if (token == "") {
print("❌ Error: Bot token not found!");
print("Create token.txt file with your bot token");
return;
}
init_bot(token);
run_bot();
}
main();
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# Скрипт запуска FoxLang Telegram Bot
echo "🦊 FoxLang Telegram Bot"
echo "======================="
# Проверяем наличие интерпретатора
if [ ! -f "../src/foxlang" ]; then
echo "❌ Error: FoxLang interpreter not found!"
echo "Please build it first:"
echo " cd ../src && g++ main.cpp Lexer.cpp Parser.cpp -o foxlang"
exit 1
fi
# Проверяем наличие токена
if [ ! -f "token.txt" ] || [ ! -s "token.txt" ] || grep -q "YOUR_BOT_TOKEN_HERE" token.txt; then
echo "❌ Error: Bot token not configured!"
echo ""
echo "Please configure your bot token:"
echo "1. Get token from @BotFather in Telegram"
echo "2. Edit token.txt file"
echo "3. Replace YOUR_BOT_TOKEN_HERE with your actual token"
exit 1
fi
echo "✅ Starting FoxLang Telegram Bot..."
echo ""
# Запускаем бота
../src/foxlang main.fox
+12
View File
@@ -0,0 +1,12 @@
# FoxLang Telegram Bot Configuration
# Поместите сюда токен вашего бота от @BotFather
# Пример: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz
# Получить токен:
# 1. Найдите @BotFather в Telegram
# 2. Отправьте /newbot
# 3. Следуйте инструкциям
# 4. Скопируйте токен сюда
8070909449:AAG8IaMC2HIswrVKD1fSrlnW417dSk8X55s