Skip to content
Open
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
143 changes: 122 additions & 21 deletions bot/cryptocom-ai-telegram-bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
"""
Telegram Bot Example

This example demonstrates how to use the existing Telegram bot functionality
This example demonstrates how to use the Telegram bot functionality
with the crypto_com_agent_client library. The bot will:

1. Load the TELEGRAM_BOT_TOKEN from .env file
2. Ask user to choose LLM provider (OpenAI or Grok3)
3. Initialize the agent with selected provider and Telegram plugin
3. Initialize the agent with selected provider
4. Start the Telegram bot to handle user messages

Prerequisites:
1. Create a .env file with TELEGRAM_BOT_TOKEN
2. Set up your Telegram bot via @BotFather
3. Install dependencies: python-telegram-bot is already in pyproject.toml
3. Install dependencies: python-telegram-bot==22.3
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not needed intirely, its in the package

4. Set DASHBOARD_API_KEY in .env for blockchain operations
5. For OpenAI: Set OPENAI_API_KEY in .env
6. For Grok3: Set GROK_API_KEY in .env
Expand All @@ -32,18 +32,39 @@
DEBUG_LOGGING=true python bot.py
"""

import logging
import os
import sys
from datetime import datetime

import pytz
from crypto_com_agent_client import Agent, tool, SQLitePlugin
from crypto_com_agent_client import Agent, SQLitePlugin, tool
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

from crypto_com_agent_client.lib.enums.provider_enum import Provider
# Add agent-plugins-py to path for TelegramPlugin
# sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'agent-plugins-py', 'telegram'))
from crypto_com_agent_plugin_telegram import TelegramPlugin
from dotenv import load_dotenv

from cronos_tx_analyzer import CronosTransactionAnalyzer

# Load environment variables from .env file
load_dotenv()

# Custom storage for persistence (optional)
custom_storage = SQLitePlugin(db_path="telegram_agent_state.db")
# Set up logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)


# Initialize the Cronos transaction analyzer with dashboard API key
# This will automatically determine the correct chain and RPC endpoint
tx_analyzer = CronosTransactionAnalyzer(
dashboard_api_key=os.getenv("DASHBOARD_API_KEY")
)

# Global agent instance
agent = None


# Example custom tool that the bot can use
Expand All @@ -62,14 +83,83 @@ def get_time() -> str:
local_time = datetime.now()

message = (
f"🕒 Current time:\n\n"
f"Current time:\n\n"
f"UTC: {utc_time.strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
f"Local: {local_time.strftime('%Y-%m-%d %H:%M:%S')}"
)

return message


@tool
def get_transaction_info(tx_hash: str) -> str:
"""
Get detailed information about a Cronos EVM transaction.

Args:
tx_hash: The transaction hash (0x followed by 64 hex characters)

Returns:
A detailed description of the transaction including type, participants, amounts, and status.
"""
try:
print(f"[get_transaction_info] Retrieving transaction info for: {tx_hash}")
# Validate transaction hash format
if not tx_hash.startswith("0x") or len(tx_hash) != 66:
return f"Invalid transaction hash format. Expected 0x followed by 64 hex characters, got: {tx_hash}"

# Check connection
if not tx_analyzer.is_connected():
return (
"Unable to connect to Cronos EVM RPC. Please check network connection."
)

# Get transaction data
tx_data = tx_analyzer.get_transaction(tx_hash)
if not tx_data:
return f"Transaction not found: {tx_hash}. Please verify the hash is correct and on Cronos mainnet."

# Analyze the transaction
analysis = tx_analyzer.analyze_transaction_flow(tx_data)

# Build response in formatted display style
result = []

result.append(f"Analyzing: {tx_hash}")
result.append("------------------------------------------------------------")

# DESCRIPTION
result.append("Description:")
description = tx_analyzer.generate_transaction_description(tx_hash)
result.append(description)

# TECHNICAL DETAILS
result.append("\nTechnical Details:")
result.append(f"Type: {analysis['type']}")
result.append(f"From: {analysis['from']}")
result.append(f"To: {analysis['to']}")
result.append(f"Status: {analysis['status']}")
result.append(f"Gas Used: {analysis['gas_used']:,}")
if analysis["value_cro"] > 0:
result.append(f"CRO Value: {analysis['value_cro']}")

# SWAP DETAILS (if applicable)
if analysis["type"] == "token_swap":
from_token = analysis.get("from_token") or analysis.get("input_token")
to_token = analysis.get("to_token") or analysis.get("output_token")
from_amount = analysis.get("from_amount") or analysis.get("input_amount")
to_amount = analysis.get("to_amount") or analysis.get("output_amount")

if from_token and to_token and from_amount and to_amount:
result.append("Swap Details:")
result.append(f" {from_amount} {from_token} → {to_amount} {to_token}")

return "\n".join(result)

except Exception as e:
return f"Error analyzing transaction: {str(e)}"


def get_llm_choice():
"""
Ask user to choose which LLM provider to use.
Expand All @@ -78,7 +168,7 @@ def get_llm_choice():
str: 'openai' or 'grok3'
"""
print("\nChoose your LLM provider:")
print("1. OpenAI (gpt-4o-mini)")
print("1. OpenAI (gpt-5-nano)")
print("2. Grok3")

while True:
Expand Down Expand Up @@ -115,8 +205,7 @@ def get_llm_config(provider_choice):
return None

return {
"provider": "OpenAI",
"model": "gpt-4o-mini",
"provider": Provider.OpenAI,
"provider-api-key": api_key,
"debug-logging": debug_logging,
}
Expand All @@ -136,10 +225,17 @@ def get_llm_config(provider_choice):
}


# Note: The handler functions (start, help_command, handle_message) are now managed
# by the TelegramPlugin and don't need to be defined here anymore.
# The plugin handles all Telegram-specific interactions internally.


def main():
"""
Main function to initialize and start the Telegram bot.
"""
global agent

# Check if TELEGRAM_BOT_TOKEN is set
telegram_token = os.getenv("TELEGRAM_BOT_TOKEN")
if not telegram_token:
Expand All @@ -160,9 +256,12 @@ def main():
if not llm_config:
return

print(f"\nInitializing Telegram Agent with {provider_choice.upper()}...")
print(f"\nInitializing Agent with {provider_choice.upper()}...")

# Create TelegramPlugin instance
telegram_plugin = TelegramPlugin(bot_token=telegram_token)

# Initialize the agent with selected configuration
# Initialize the agent with TelegramPlugin as a plugin instance
agent = Agent.init(
llm_config=llm_config,
blockchain_config={
Expand All @@ -177,27 +276,29 @@ def main():
"verbosity": "medium",
},
"instructions": (
"You are a helpful Crypto.com AI assistant. "
"You can help users with cryptocurrency information, "
"blockchain queries, and general crypto-related questions. "
"You are a blockchain transaction analyst and Crypto.com AI assistant. "
"When asked about a transaction, use the get_transaction_info tool to retrieve detailed information. "
"The tool returns pre-formatted responses with '**Summary:**' and '**Description:**' sections. "
"Present the tool's response EXACTLY as returned, without reformatting or summarizing. "
"Do not modify, truncate, or rephrase the formatted response from get_transaction_info. "
"You can also help users with cryptocurrency information, blockchain queries, and general crypto-related questions. "
"Be friendly and informative in your responses."
),
"tools": [get_time],
"storage": custom_storage,
"telegram": {"bot_token": telegram_token},
"tools": [get_time, get_transaction_info],
# Disabled to avoid SQLite issues
},
plugin_instances=[telegram_plugin], # Pass TelegramPlugin as a plugin instance
)

print("Agent initialized successfully!")
print(f"Using {provider_choice.upper()} provider")
print(f"Bot Token: ***...")
print("Starting Telegram bot...")
print("Your bot is now ready to receive messages!")
print("Press Ctrl+C to stop the bot")

# Run the bot through the plugin
try:
# Start the Telegram bot
agent.start_telegram()
telegram_plugin.run()
except KeyboardInterrupt:
print("\nBot stopped by user")
except Exception as e:
Expand Down
Loading