compiling after refactoring

This commit is contained in:
Dobromir Popov
2024-10-13 23:42:40 +03:00
parent 2c2c4ee4df
commit 921386e7fb
3 changed files with 89 additions and 199 deletions

View File

@ -13,8 +13,14 @@ import datetime
logger = logging.getLogger(__name__)
SOLANA_ENDPOINTS = ["your_endpoint_1", "your_endpoint_2"] # Add your endpoints here
SUBSCRIBE_INTERVAL = 300 # 5 minutes in seconds
SOLANA_ENDPOINTS = [
"wss://api.mainnet-beta.solana.com",
# "wss://solana-api.projectserum.com",
# "wss://rpc.ankr.com/solana",
# "wss://mainnet.rpcpool.com",
]
PING_INTERVAL = 30
SUBSCRIBE_INTERVAL = 1*60 # Resubscribe every 10 minutes
from config import (
FOLLOWED_WALLET, SOLANA_HTTP_URL
@ -23,9 +29,9 @@ FOLLOWED_WALLET, SOLANA_HTTP_URL
class SolanaAPI:
def __init__(self):
self.websocket: Optional[websockets.WebSocketClientProtocol] = None
self.subscription_id: Optional[int] = None
self.message_queue: asyncio.Queue = asyncio.Queue()
self.websocket = None
self.subscription_id = None
self.message_queue = asyncio.Queue()
async def connect(self):
while True:
@ -38,37 +44,50 @@ class SolanaAPI:
logger.error(f"Failed to connect to {current_url}: {e}")
await asyncio.sleep(5)
async def subscribe(self):
async def ws_jsonrpc(self, method, params=None):
if not isinstance(params, list):
params = [params] if params is not None else []
request = {
"jsonrpc": "2.0",
"id": 1,
"method": "logsSubscribe",
"params": [
{"mentions": [FOLLOWED_WALLET]},
{"commitment": "confirmed"}
]
"method": method,
"params": params
}
await self.websocket.send(json.dumps(request))
response = await self.websocket.recv()
response_data = json.loads(response)
if 'result' in response_data:
self.subscription_id = response_data['result']
logger.info(f"Subscription successful. Subscription id: {self.subscription_id}")
return response_data['result']
elif 'error' in response_data:
logger.error(f"Error in WebSocket RPC call: {response_data['error']}")
return None
else:
logger.warning(f"Unexpected response: {response_data}")
return None
async def subscribe(self):
params = [
{"mentions": [FOLLOWED_WALLET]},
{"commitment": "confirmed"}
]
result = await self.ws_jsonrpc("logsSubscribe", params)
if result is not None:
self.subscription_id = result
logger.info(f"Subscription successful. Subscription id: {self.subscription_id}")
else:
logger.error("Failed to subscribe")
async def unsubscribe(self):
if self.subscription_id:
request = {
"jsonrpc": "2.0",
"id": 1,
"method": "logsUnsubscribe",
"params": [self.subscription_id]
}
await self.websocket.send(json.dumps(request))
logger.info(f"Unsubscribed from subscription id: {self.subscription_id}")
self.subscription_id = None
result = await self.ws_jsonrpc("logsUnsubscribe", [self.subscription_id])
if result:
logger.info(f"Unsubscribed from subscription id: {self.subscription_id}")
self.subscription_id = None
else:
logger.error(f"Failed to unsubscribe from subscription id: {self.subscription_id}")
async def receive_messages(self):
while True:
@ -83,6 +102,16 @@ class SolanaAPI:
break
async def process_messages(self):
while True:
message = await self.message_queue.get()
# Process the message here
# You can add your message processing logic
logger.info(f"Received message: {message}")
async def close(self):
if self.websocket:
await self.websocket.close()
logger.info("WebSocket connection closed")
while True:
message = await self.message_queue.get()
try:

View File

@ -9,19 +9,35 @@ from telegram import Bot
from telegram.constants import ParseMode
from config import TELEGRAM_BOT_TOKEN, DEVELOPER_CHAT_ID, BOT_NAME
# Initialize Telegram Bot
# Create a custom connection pool
conn_pool = aiohttp.TCPConnector(limit=100) # Increase the connection limit
timeout = aiohttp.ClientTimeout(total=30) # Set a longer timeout
class TelegramUtils:
def __init__(self):
self.bot = None
self.conn_pool = None
self.timeout = None
# bot = Bot(TELEGRAM_BOT_TOKEN) # , request=aiohttp.ClientSession(connector=conn_pool, timeout=timeout).request)
bot = Bot(token=TELEGRAM_BOT_TOKEN)
async def initialize(self):
# Create a custom connection pool
self.conn_pool = aiohttp.TCPConnector(limit=100) # Increase the connection limit
self.timeout = aiohttp.ClientTimeout(total=30) # Set a longer timeout
async def send_telegram_message(message):
try:
await bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=f"[{BOT_NAME}] {message}", parse_mode=ParseMode.HTML)
logging.info(f"Telegram message sent: {message}")
except Exception as e:
logging.error(f"Error sending Telegram message: {str(e)}")
# Initialize Telegram Bot
self.bot = Bot(token=TELEGRAM_BOT_TOKEN)
# You can add more Telegram-related functions here if needed
async def send_telegram_message(self, message):
if not self.bot:
await self.initialize()
try:
await self.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=f"[{BOT_NAME}] {message}", parse_mode=ParseMode.HTML)
logging.info(f"Telegram message sent: {message}")
except Exception as e:
logging.error(f"Error sending Telegram message: {str(e)}")
async def close(self):
if self.conn_pool:
await self.conn_pool.close()
# Create a global instance of TelegramUtils
telegram_utils = TelegramUtils()
# You can add more Telegram-related methods to the TelegramUtils class if needed