Create an open-source Telegram bot that notifies users of new Haveno offers that meet user-defined criteria, such as currency, payment method, and price.
Assistant
User
can you make the bot using aiogram 3?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating an open-source Telegram bot to notify users of new Haveno offers that meet specific criteria is a great idea! Below is a step-by-step guide to help you build this bot using the haveno-ts library and the Telegram Bot API. This implementation will involve setting up the bot, connecting to the Haveno API, filtering offers based on user-defined criteria, and sending notifications via Telegram.
Step 1: Set Up Your Environment
Create a New Project:
Create a new directory for your bot project and navigate into it.
bash
mkdir haveno-telegram-bot
cd haveno-telegram-bot
Initialize the Project:
Initialize a new Node.js project.
bash
npm init -y
Install Required Packages:
Install the necessary packages, including node-telegram-bot-api for the Telegram bot and haveno-ts for interacting with the Haveno daemon.
bash
npm install node-telegram-bot-api haveno-ts
Create a .env file:
Store your Telegram bot token and Haveno daemon credentials in an .env file for security.
Create bot.js:
Create a file named bot.js in your project directory.
javascript
// bot.js
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const { HavenoClient } = require('haveno-ts');
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
const havenoClient = new HavenoClient(process.env.HAVENO_URL, process.env.HAVENO_PASSWORD);
// Store user criteria
const userCriteria = {};
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Welcome! Use /setcriteria to set your offer criteria.');
});
bot.onText(/\/setcriteria/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Please enter your criteria in the following format: `currency,payment_method,price`');
});
bot.onText(/([a-zA-Z]+),([a-zA-Z]+),(\d+)/, (msg, match) => {
const chatId = msg.chat.id;
const currency = match[1];
const paymentMethod = match[2];
const price = parseFloat(match[3]);
userCriteria[chatId] = { currency, paymentMethod, price };
bot.sendMessage(chatId, `Criteria set: Currency: ${currency}, Payment Method: ${paymentMethod}, Price: ${price}`);
});
function notifyUsers(offer) {
Object.keys(userCriteria).forEach(chatId => {
const criteria = userCriteria[chatId];
if (offer.getCurrency() === criteria.currency &&
offer.getPaymentMethod() === criteria.paymentMethod &&
offer.getPrice() <= criteria.price) {
bot.sendMessage(chatId, `New offer available: ${offer}`);
}
});
}
async function checkForNewOffers() {
try {
const offers = await havenoClient.getOffers(); // Method to fetch offers
offers.forEach(offer => {
notifyUsers(offer);
});
} catch (error) {
console.error('Error fetching offers:', error);
}
}
setInterval(checkForNewOffers, 60000); // Check every minute
Step 3: Run Your Bot
Start the Bot:
Run your bot using Node.js.
bash
node bot.js
Interact with the Bot:
Start a chat with your bot on Telegram.
Set your criteria using the command /setcriteria.
Step 4: Handle Offers
You need to implement the method getOffers() in the Haveno client to fetch current offers. This would typically involve calling the relevant Haveno API endpoint and processing the response.
Additional Considerations
Error Handling:
Implement more robust error handling for API calls and user input.
Persistent Storage:
Consider using a database (like SQLite or MongoDB) to store user criteria rather than keeping it in-memory, especially if you want the bot to retain user settings across restarts.
Deployment:
Once your bot is functioning correctly, consider deploying it on a cloud service (like Heroku, AWS, or DigitalOcean) for continuous operation.
Security:
Ensure that sensitive information (like the API password) is not hard-coded in your codebase.
Improvement:
You can enhance the bot by adding features like listing current offers, allowing users to unsubscribe, or sending notifications for specific types of offers.
Conclusion
By following these steps, you will have a basic Telegram bot that notifies users of new Haveno offers based on their specified criteria. This can be a great tool for traders looking to act quickly on new opportunities!
Certainly! Below is a complete guide to creating a Telegram bot using aiogram version 3. This bot will notify users of new Haveno offers that meet user-defined criteria such as currency, payment method, and price.
Step 1: Set Up Your Environment
Create a New Project:
Create a new directory for your bot project and navigate into it.
bash
mkdir haveno-telegram-bot
cd haveno-telegram-bot
Initialize the Project:
Initialize a new Python project (you can use a virtual environment if desired).
bash
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
Install Required Packages:
Install aiogram for the Telegram bot and haveno-ts for interacting with the Haveno daemon.
bash
pip install aiogram python-dotenv haveno-ts
Create a .env file:
Store your Telegram bot token and Haveno daemon credentials in an .env file.
Create bot.py:
Create a file named bot.py in your project directory.
python
# bot.py
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher import filters
from aiogram.dispatcher import FSMContext
from aiogram.utils import executor
from dotenv import load_dotenv
import os
import asyncio
# Load environment variables
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
HAVENO_URL = os.getenv('HAVENO_URL')
HAVENO_PASSWORD = os.getenv('HAVENO_PASSWORD')
# Set up logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=TELEGRAM_BOT_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
# User state for FSM
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher import State, StatesGroup
class Form(StatesGroup):
waiting_for_criteria = State()
# Store user criteria
user_criteria = {}
# Start command handler
@dp.message_handler(commands=['start'])
async def start_command(message: types.Message):
await message.answer("Welcome! Use /setcriteria to set your offer criteria.")
# Set criteria command handler
@dp.message_handler(commands=['setcriteria'])
async def set_criteria_command(message: types.Message):
await Form.waiting_for_criteria.set()
await message.answer("Please enter your criteria in the following format: `currency,payment_method,price`")
# Handle user input for criteria
@dp.message_handler(state=Form.waiting_for_criteria)
async def process_criteria(message: types.Message, state: FSMContext):
chat_id = message.chat.id
data = message.text.split(',')
if len(data) != 3:
await message.answer("Invalid format. Please use: `currency,payment_method,price`")
return
currency, payment_method, price = data[0], data[1], float(data[2])
user_criteria[chat_id] = {'currency': currency, 'payment_method': payment_method, 'price': price}
await state.finish() # Finish the state
await message.answer(f"Criteria set: Currency: {currency}, Payment Method: {payment_method}, Price: {price}")
# Notify users with new offers
async def notify_users(offer):
for chat_id, criteria in user_criteria.items():
if (offer['currency'] == criteria['currency'] and
offer['payment_method'] == criteria['payment_method'] and
offer['price'] <= criteria['price']):
await bot.send_message(chat_id, f"New offer available: {offer}")
# Function to check for new offers
async def check_for_new_offers():
while True:
try:
# Simulate getting offers from Haveno API
offers = await get_offers() # You need to implement this function
for offer in offers:
await notify_users(offer)
except Exception as e:
logging.error(f"Error fetching offers: {e}")
await asyncio.sleep(60) # Check every minute
# Replace this function with actual Haveno API call
async def get_offers():
# Simulated offers for demonstration
return [
{'currency': 'USD', 'payment_method': 'PayPal', 'price': 100},
{'currency': 'EUR', 'payment_method': 'Bank Transfer', 'price': 90},
]
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(check_for_new_offers()) # Start checking for offers
executor.start_polling(dp, skip_updates=True) # Start the bot
Step 3: Run Your Bot
Start the Bot:
Run your bot using Python.
bash
python bot.py
Interact with the Bot:
Start a chat with your bot on Telegram.
Set your criteria using the command /setcriteria following the specified format.
Step 4: Implement the get_offers() Function
Replace the get_offers() function with actual calls to the Haveno daemon. You can use the haveno-ts library in Python if you have a compatible implementation or use grpc to connect to the Haveno RPC server.
Additional Considerations
Error Handling:
Implement more robust error handling for API calls and user input.
Persistent Storage:
Consider using a database (like SQLite or PostgreSQL) to store user criteria rather than keeping it in-memory, especially if you want the bot to retain user settings across restarts.
Deployment:
Once your bot is functioning correctly, consider deploying it on a cloud service (like Heroku, AWS, or DigitalOcean) for continuous operation.
Security:
Ensure that sensitive information (like the API password) is not hard-coded in your codebase.
Enhancements:
You can enhance the bot by adding features like listing current offers, allowing users to unsubscribe, or sending notifications for specific types of offers.
Conclusion
By following these steps, you will have a Telegram bot that notifies users of new Haveno offers based on their specified criteria using aiogram version 3. This bot can serve as an effective tool for traders looking to stay updated on new opportunities!