Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions apps/eliza-chatbot/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Cortensor Community

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
9 changes: 9 additions & 0 deletions apps/eliza-chatbot/PROJECTS.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
- name: eliza-chatbot
category: apps
owner: "@cortensor-ryuma"
collaborators:
- "@beranalpa"
status: active
created: 2025-06-23
version: v1.0.0
tags: [telegram, python, bot, cortensor, llm]
114 changes: 114 additions & 0 deletions apps/eliza-chatbot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<div align="center">

<img src="https://github.com/ghavatar/u/174224856?s=200&v=4" alt="Project Logo" width="150">

# **Cortensor Eliza ChatBot**

*Your Conversational Gateway to the Cortensor API*

<p>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"></a>
<a href="./STATUS.md"><img src="https://img.shields.io/badge/status-active-success.svg" alt="Status"></a>
<a href="#"><img src="https://img.shields.io/badge/python-3.9+-blue.svg" alt="Python Version"></a>
<a href="#"><img src="https://img.shields.io/badge/Telegram-%232CA5E0.svg?logo=telegram&logoColor=white" alt="Telegram"></a>
</p>

<p align="center">
<a href="#-features">Features</a> •
<a href="#-prerequisites">Prerequisites</a> •
<a href="#-installation--setup">Installation</a> •
<a href="#-usage">Usage</a>
</p>
</div>

Cortensor Eliza ChatBot provides a seamless bridge between your Telegram messenger and the powerful Cortensor AI. Ask questions, get instant responses, and interact with the AI backend through a simple and familiar chat interface. This project is designed for easy deployment and robust performance.

## ✨ Features

* **Seamless Integration**: Directly connects to the Cortensor API for natural language processing.
* **Conversational Interface**: Leverages Telegram as a user-friendly platform to interact with the AI backend.
* **Asynchronous Handling**: Provides a "typing..." indicator to the user while requests are being processed for a better user experience.
* **Easy Configuration**: Quick and secure setup using a `.env` file to manage all API keys and tokens.
* **Lightweight**: Built with efficient Python libraries like `python-telegram-bot` and `requests`.

## 📋 Prerequisites

Before running this bot, it is crucial to understand that it acts as a client for the Cortensor network. Therefore, you must have access to a fully operational Cortensor backend infrastructure.

The core requirements for the backend are:

* A configured **Cortensor Node**
* **cortensord**: The Cortensor daemon service.
* A running **Router Node** that the bot can connect to.

For complete, step-by-step instructions on setting up this backend infrastructure, please follow the official **[Router Node Setup Guide](https://docs.cortensor.network/getting-started/installation-and-setup/router-node-setup)**.

## 🔧 Installation & Setup

This project is located within the `Cortensor Community Projects` monorepo. Follow these steps to set it up.

1. **Clone the Main Repository**
Clone the central hub where all community projects reside.
```bash
git clone https://github.com/cortensor/community-projects.git
cd community-projects
```

2. **Navigate to the Project Directory**
This bot is located in the `apps/` directory.
```bash
cd apps/eliza-chatbot
```

3. **Create and Activate a Virtual Environment**
```bash
# For MacOS/Linux
python3 -m venv venv
source venv/bin/activate

# For Windows
python -m venv venv
.\venv\Scripts\activate
```

4. **Install Dependencies**
The required packages are listed in `requirements.txt`.
```bash
pip install -r requirements.txt
```

5. **Configure Environment Variables**
Create a file named `.env` inside the `apps/eliza-chatbot` directory and populate it with your credentials.
```ini
TELEGRAM_BOT_TOKEN="YOUR_TELEGRAM_BOT_TOKEN_HERE"
CORTENSOR_API_URL="YOUR_CORTENSOR_API_ENDPOINT_URL_HERE"
CORTENSOR_API_KEY="YOUR_CORTENSOR_API_KEY_HERE"
CORTENSOR_SESSION_ID="YOUR_SESSION_ID_HERE"
```

## 🚀 Usage

Once the configuration is complete, run the bot from within the `apps/eliza-chatbot` directory:

```bash
python src/main.py
````

The bot is now running. Open your Telegram app, find your bot, and start a conversation. You can begin by sending the `/start` command.

## ⚙️ Configuration

The following variables must be set in your `.env` file for the bot to function correctly:

* `TELEGRAM_BOT_TOKEN`: The unique token you received from BotFather on Telegram.
* `CORTENSOR_API_URL`: The full URL to the `/completions` endpoint of the Cortensor API.
* `CORTENSOR_API_KEY`: The authorization key (Bearer Token) to access the Cortensor API.
* `CORTENSOR_SESSION_ID`: The session ID required by the API payload to maintain conversation context.

## 👤 Maintainer

* **@beranalpa** (Discord)

## 📄 License

This project is licensed under the MIT License. See the `LICENSE` file for more details.
11 changes: 11 additions & 0 deletions apps/eliza-chatbot/RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Release History

## v1.0.0 (2025-06-23)

This marks the first public release of the Eliza ChatBot project within the Cortensor community.

### ✨ Features

* **Initial Bot Implementation**: The bot can receive text messages from a user on Telegram, submit them as a prompt to the Cortensor API, and reply with the generated response.
* **Secure Configuration**: Loads all necessary credentials (Telegram Token, Cortensor API Key, etc.) from a `.env` file for easy and secure setup.
* **Core Dependencies**: The project is built on Python and includes key libraries such as `python-telegram-bot` and `requests`.
28 changes: 28 additions & 0 deletions apps/eliza-chatbot/STATUS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
## 🗺️ Roadmap

This roadmap outlines our future goals, organized by priority and complexity. It is subject to change.

### Version 1.1 (Core Improvements)
*Easy*
- [ ] **Add More Commands**: Implement essential user commands for better usability.
- [ ] `/help`: To provide usage instructions.
- [ ] `/status`: To check the bot's connection to the Cortensor API.
- [ ] **Enhanced Error Handling**: Provide more specific and helpful feedback to users when the API fails or returns unexpected data.
- [ ] **Code Refactoring**: Separate the API communication logic from the main bot logic (`main.py`) for better maintainability and future expansion.

### Version 1.2 (Stateful Application)
*Medium*
- [ ] **Implement User-Specific Sessions**: This is a high-priority feature to make the bot truly conversational.
- **Goal**: Transition from a single, shared `SESSION_ID` to a system where each user has their own unique session.
- **Outcome**: The bot will have "memory" for each user's conversation (`1 user = 1 session`), addressing the current limitation of it being stateless.

### Version 1.3 (DevOps & Deployment)
*Medium*
- [ ] **Support for Docker**: Create a `Dockerfile` and `docker-compose.yml` for easier, consistent, and isolated deployment.
- [ ] **Add Basic CI/CD**: Implement GitHub Actions to automate code linting and testing on every push to maintain code quality.

### Future (Major Features)
*Hard*
- [ ] **Web3 Integration**: Explore and implement Web3 capabilities to evolve the project.
- **Goal**: Integrate wallet connections or smart contract interactions to create a hybrid or fully decentralized application with more user control.
- **Status**: This is a long-term research and development goal that will require significant architectural changes.
3 changes: 3 additions & 0 deletions apps/eliza-chatbot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
python-telegram-bot==13.15
requests
python-dotenv
102 changes: 102 additions & 0 deletions apps/eliza-chatbot/src/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import os
import logging
import requests
from dotenv import load_dotenv
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext

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

load_dotenv()

TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
CORTENSOR_API_URL = os.getenv("CORTENSOR_API_URL")
CORTENSOR_API_KEY = os.getenv("CORTENSOR_API_KEY")
CORTENSOR_SESSION_ID = os.getenv("CORTENSOR_SESSION_ID")

def submit_cortensor_task(update: Update, context: CallbackContext):
user_prompt = update.message.text
logger.info(f"Submitting task for prompt: '{user_prompt}'")

context.bot.send_chat_action(chat_id=update.effective_chat.id, action='typing')

headers = {
"Authorization": f"Bearer {CORTENSOR_API_KEY}",
"Content-Type": "application/json"
}

payload = {
"session_id": int(CORTENSOR_SESSION_ID),
"prompt": user_prompt,
"prompt_type": 0,
"stream": False,
"timeout": 180
}

try:
logger.info(f"Sending request to {CORTENSOR_API_URL} with payload: {payload}")
response = requests.post(CORTENSOR_API_URL, headers=headers, json=payload, timeout=320)
response.raise_for_status()

response_data = response.json()
logger.info(f"Received response from Cortensor: {response_data}")

answer = response_data['choices'][0]['text']

if answer and answer.strip():
update.message.reply_text(answer.strip())
else:
logger.warning("Received an empty 'text' field from Cortensor API.")
update.message.reply_text("I'm sorry, I did not receive any valid content from the server. Please try a different prompt.")

except requests.exceptions.ReadTimeout:
logger.error("Request timed out while waiting for a response from the server.")
update.message.reply_text("I'm sorry, the server did not respond in time. It might be having issues or under maintenance. Please try again later.")

except requests.exceptions.HTTPError as e:
if e.response.status_code == 408:
logger.warning("Request timed out on the Cortensor server side (408).")
update.message.reply_text("I'm sorry, the server is busy or your request is taking too long to process. Please try again in a moment.")
else:
logger.error(f"HTTP Error occurred: {e.response.status_code} - {e.response.text}")
update.message.reply_text(f"Sorry, an API error occurred (Status: {e.response.status_code}).")

except (KeyError, IndexError):
logger.error(f"Failed to parse the response JSON. Data: {response_data}", exc_info=True)
update.message.reply_text("Sorry, I received a response, but could not understand its format.")

except Exception as e:
logger.error("An unexpected error occurred", exc_info=True)
update.message.reply_text(f"Sorry, an unexpected error occurred.")


def start_command(update: Update, context: CallbackContext):
update.message.reply_text("Hello! I am a Cortensor bot. Please ask me a question.")

def main():
if not all([TELEGRAM_BOT_TOKEN, CORTENSOR_API_URL, CORTENSOR_API_KEY, CORTENSOR_SESSION_ID]):
logger.critical("FATAL: One or more configurations in .env are missing! Bot cannot start.")
return

logger.info("Starting bot...")

updater = Updater(token=TELEGRAM_BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler("start", start_command))
dispatcher.add_handler(MessageHandler(
Filters.text & ~Filters.command,
submit_cortensor_task,
run_async=True
))

updater.start_polling()
logger.info("Bot is running. Press Ctrl+C to stop.")
updater.idle()

if __name__ == '__main__':
main()