import asyncio
import json
import logging
import os
import re
from collections import defaultdict
from datetime import datetime
from typing import Any, Dict
import requests
import websockets
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
JobQueue,
)
Configuration (Ensure environment variables are set)
def escape_markdown(text):
"""Helper function to escape special characters for MarkdownV2."""
escape_chars = r'_*~`>#+-=|{}.!'
return re.sub(f'([{re.escape(escape_chars)}])', r'\\1', str(text))
def format_number(number, decimals=2, suffix=''):
"""
Formats a number into a more readable format with suffixes.
code
Args:
number (float or str): The number to format.
decimals (int): Number of decimal places.
suffix (str): Optional suffix to append.
Returns:
str: Formatted number as a string.
"""
# Remove currency symbols and commas if present
if isinstance(number, str):
number = number.replace('$', '').replace(',', '')
try:
number = float(number)
except ValueError:
return "N/A" # Return "N/A" if conversion fails
if abs(number) >= 1_000_000:
return f"${number / 1_000_000:.{decimals}f}m{suffix}"
elif abs(number) >= 1_000:
return f"${number / 1_000:.{decimals}f}k{suffix}"
else:
return f"${number:.{decimals}f}{suffix}"
Assistant
def parse_formatted_number(s):
"""
Parses a formatted string with 'k' or 'm' suffixes back to a float.
code
Args:
s (str): The formatted string (e.g., '$41k', '$1.2m').
Returns:
float: The numerical value.
"""
s = s.replace('$', '').replace(',', '').strip().lower()
multiplier = 1
if s.endswith('k'):
multiplier = 1_000
s = s[:-1]
elif s.endswith('m'):
multiplier = 1_000_000
s = s[:-1]
try:
return float(s) * multiplier
except ValueError:
logger.error(f"Failed to parse number: {s}")
return 0.0 # or handle as appropriate
def format_crypto_value(value, coin):
"""Formats the crypto value based on its magnitude."""
return format_number(value)
def safe_request(url, json_data, timeout=10):
"""Makes a safe request to the specified URL, handling potential errors."""
try:
response = requests.post(url, json=json_data, timeout=timeout)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"Request failed: {e}")
return None
def fetch_user_state(wallet_address):
"""Fetches the user state from the Hyperliquid API."""
return safe_request("https://api.hyperliquid.xyz/info", {"type": "clearinghouseState", "user": wallet_address})
def fetch_all_mids():
"""Fetches the allMids data from the Hyperliquid API."""
return safe_request("https://api.hyperliquid.xyz/info", {"type": "allMids"})
def get_open_orders_count(wallet_address, return_data=False):
"""Fetches the number of open orders for a given wallet address."""
data = safe_request("https://api.hyperliquid.xyz/info", {"type": "frontendOpenOrders", "user": wallet_address})
return data if return_data else len(data) if data else 0
def get_all_prices(all_mids):
"""Extracts and returns a dictionary of coin prices from the allMids data."""
if all_mids is None:
return {}
return {coin: float(price) for coin, price in all_mids.items()}
def format_user_state(wallet_address, all_mids):
"""Formats the user state into a structured format."""
user_state = fetch_user_state(wallet_address)
if not user_state or not user_state.get("assetPositions"):
return [], {}, 0, 0
def check_position_changes(wallet_address, current_positions):
"""
Checks for any changes in positions (opened or closed) compared to previous positions.
code
Args:
wallet_address (str): The wallet address being tracked.
current_positions (dict): Current positions {coin: position_data}.
Returns:
tuple: (position_opened (bool), position_closed (bool))
"""
position_opened = False
position_closed = False
# Current set of coins
current_coins = set(current_positions.keys())
# Previous set of coins
previous_coins = previous_positions[wallet_address]
if not previous_coins:
# No previous positions, treat all current positions as opened
position_opened = True
logger.info(f"Initial positions detected for coins: {', '.join(current_coins)} in wallet {wallet_address}")
else:
# Detect opened positions
opened = current_coins - previous_coins
if opened:
position_opened = True
logger.info(f"Positions opened for coins: {', '.join(opened)} in wallet {wallet_address}")
# Detect closed positions
closed = previous_coins - current_coins
if closed:
position_closed = True
logger.info(f"Positions closed for coins: {', '.join(closed)} in wallet {wallet_address}")
logger.debug(f"check_position_changes - Wallet: {wallet_address}, Opened: {position_opened}, Closed: {position_closed}")
return position_opened, position_closed
async def update_positions(wallet_address, current_positions, formatted_positions, nickname, previous_positions, previous_pnls):
"""Update positions and send Telegram alerts for any changes detected."""
logger.info(f"Updating positions for {nickname} ({wallet_address})")
message = f"Wallet Positions Update for {html.escape(nickname)}:\n"
send_update = False # Flag to determine whether to send the update
pnl_change_threshold = 500 # Set the PnL change threshold to $500
code
for position in formatted_positions:
coin, position_type, entry_price, mark_price, pnl, size, leverage = position
logger.info(f"Processing position: {coin} {position_type}")
# Retrieve the raw position data
raw_position = current_positions.get(coin, {})
if not raw_position:
logger.warning(f"No raw data found for coin: {coin}")
continue
# Determine if this is the first time checking this position
is_first_check = coin not in previous_pnls[wallet_address]
# Calculate PnL difference
previous_pnl = previous_pnls[wallet_address].get(coin, 0)
pnl_diff = raw_position['unrealized_pnl'] - previous_pnl
# Check if PnL difference exceeds the threshold
if is_first_check or abs(pnl_diff) >= pnl_change_threshold:
send_update = True # Significant change detected
# Format the PnL difference with sign and shorthand notation
if pnl_diff >= 0:
pnl_diff_str = f" (+{format_number(pnl_diff, decimals=0)[1:]})"
else:
pnl_diff_str = f" (-{format_number(abs(pnl_diff), decimals=0)[1:]})"
# Adjust mark price decimal places based on its value
mark_price_value = raw_position['mark_price']
if mark_price_value < 1:
mark_price_formatted = f"{mark_price_value:.4f}"
else:
mark_price_formatted = f"{mark_price_value:.2f}"
# Format entry price with 4 decimal places if needed
entry_price_value = raw_position['entry_price']
entry_price_formatted = f"{entry_price_value:.4f}" if entry_price_value < 1 else f"{entry_price_value:.2f}"
# Format PnL
formatted_pnl = format_number(raw_position['unrealized_pnl'], decimals=0)
# Format size: show as positive for positions
display_size = abs(raw_position['size'])
formatted_size = format_number(display_size, decimals=0)
# Format leverage
formatted_leverage = format_number(raw_position['leverage'], decimals=0)
# Assemble the message line
message += (
f"- {html.escape(coin)} {formatted_size} {html.escape(position_type)}, "
f"Entry: {entry_price_formatted}, "
f"Mark: {mark_price_formatted}, "
f"PnL: {formatted_pnl}{pnl_diff_str}\n"
)
# Update the previous PnL for the next comparison
previous_pnls[wallet_address][coin] = raw_position['unrealized_pnl']
if send_update:
logger.info(f"Sending message to Telegram: {message}")
try:
await application.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message, parse_mode=ParseMode.HTML)
logger.info("Telegram position update sent successfully.")
except Exception as e:
logger.error(f"Failed to send message: {e}")
else:
logger.info("No significant PnL changes detected; no update sent.")
# Check for closed positions and send alerts
for coin in list(previous_positions[wallet_address]):
if coin not in current_positions:
close_message = (
f"<b>ALERT: Position Closed</b>\n"
f"{html.escape(nickname)} | {html.escape(coin)}"
)
try:
await application.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=close_message, parse_mode=ParseMode.HTML)
logger.info(f"Sent position closed alert for {coin}.")
except Exception as e:
logger.error(f"Failed to send position closed alert for {coin}: {e}")
# Update previous_positions to reflect current positions
previous_positions[wallet_address] = set(current_positions.keys())
async def websocket_handler():
uri = HYPERLIQUID_WS_URL
async with websockets.connect(uri) as websocket:
# Subscribe to user events for all tracked wallets
for wallet_address in tracked_wallets:
subscription_message = {
"method": "subscribe",
"subscription": {
"type": "userEvents",
"user": wallet_address
}
}
await websocket.send(json.dumps(subscription_message))
logger.info(f"Subscribed to userEvents for wallet: {wallet_address}")
code
# Start a task to handle subscription updates
asyncio.create_task(subscription_manager(websocket))
# Receive messages
async for message in websocket:
await process_websocket_message(message)
async def subscription_manager(websocket):
while True:
action, wallet_address = await subscription_queue.get()
if action == "subscribe":
subscription_message = {
"method": "subscribe",
"subscription": {
"type": "userEvents",
"user": wallet_address
}
}
await websocket.send(json.dumps(subscription_message))
logger.info(f"Subscribed to userEvents for wallet: {wallet_address}")
elif action == "unsubscribe":
unsubscription_message = {
"method": "unsubscribe",
"subscription": {
"type": "userEvents",
"user": wallet_address
}
}
await websocket.send(json.dumps(unsubscription_message))
logger.info(f"Unsubscribed from userEvents for wallet: {wallet_address}")
# Identify the type of message
channel = ws_msg.get("channel")
if channel == "user":
data = ws_msg.get("data", {})
fills = data.get("fills", [])
# Process each fill
for fill in fills:
await handle_fill_event(fill)
# Handle other message types if necessary
async def handle_fill_event(fill: Dict[str, Any]):
wallet_address = fill.get("user")
if wallet_address not in tracked_wallets:
# Not a tracked wallet
return
code
nickname = tracked_wallets.get(wallet_address, wallet_address)
coin = fill.get("coin")
side = fill.get("side")
px = float(fill.get("px", 0))
sz = float(fill.get("sz", 0))
time_of_trade = datetime.utcfromtimestamp(fill.get("time", 0) / 1000).strftime('%Y-%m-%d %H:%M:%S')
# You may need to adjust the timestamp format based on the API's time field
# Update positions and PnL
# Fetch user state and positions
all_mids = fetch_all_mids()
formatted_positions, raw_data, total_upnl, account_equity = format_user_state(wallet_address, all_mids)
current_positions = raw_data
position_opened, position_closed = check_position_changes(
wallet_address, current_positions
)
await update_positions(
wallet_address,
current_positions,
formatted_positions,
nickname,
previous_positions,
previous_pnls
)
# Construct the message
message = (
f"<b>Trade Executed for {html.escape(nickname)}:</b>\n"
f"Coin: {html.escape(coin)}\n"
f"Side: {'Buy' if side == 'B' else 'Sell'}\n"
f"Price: {px}\n"
f"Size: {sz}\n"
f"Time: {time_of_trade}"
)
# Send the message to Telegram
try:
await application.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message, parse_mode=ParseMode.HTML)
logger.info(f"Sent trade update to Telegram for wallet {wallet_address}.")
except Exception as e:
logger.error(f"Failed to send message: {e}")
Telegram bot command handlers
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a message when the command /start is issued."""
start_message = (
"Bot started. Use these commands:\n"
"/add <wallet_address> [nickname] - Add a wallet to track\n"
"/remove <wallet_address or nickname> - Remove a wallet\n"
"/list - List tracked wallets\n"
"/details <wallet_address or nickname> - Show wallet details"
)
await update.message.reply_text(start_message)
logger.info(f"User {update.effective_user.id} started the bot.")
async def add_wallet(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Adds a wallet address to the tracking list with an optional nickname."""
if len(context.args) == 0:
await update.message.reply_text("Please provide a wallet address to add.")
return
code
wallet_address = context.args[0]
nickname = " ".join(context.args[1:]) if len(context.args) > 1 else wallet_address
tracked_wallets[wallet_address] = nickname
# Add to the subscription queue
await subscription_queue.put(("subscribe", wallet_address))
await update.message.reply_text(f"Added wallet {nickname} ({wallet_address}) to tracking.")
logger.info(f"Added wallet {nickname} ({wallet_address}) to tracking.")
async def remove_wallet(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Removes a wallet address from the tracking list."""
if not context.args:
await update.message.reply_text("Please provide a wallet address or nickname to remove.")
return
code
identifier = context.args[0]
wallet_address = next((addr for addr, name in tracked_wallets.items() if identifier in [addr, name]), None)
if wallet_address:
nickname = tracked_wallets.pop(wallet_address)
# Remove tracking data
previous_pnls.pop(wallet_address, None)
previous_positions.pop(wallet_address, None)
# Add to the subscription queue
await subscription_queue.put(("unsubscribe", wallet_address))
await update.message.reply_text(f"Removed wallet {nickname} ({wallet_address}) from tracking.")
logger.info(f"Removed wallet {nickname} ({wallet_address}) from tracking.")
else:
await update.message.reply_text(f"Wallet {identifier} is not being tracked.")
logger.warning(f"Attempted to remove non-tracked wallet {identifier}.")
async def list_wallets(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Lists all tracked wallet addresses with their nicknames."""
if tracked_wallets:
wallet_list = "\n".join([f"{escape_markdown(name)} ({address})" for address, name in tracked_wallets.items()])
await update.message.reply_text(f"Currently tracking these wallets:\n{wallet_list}", parse_mode=ParseMode.HTML)
logger.info(f"Listed wallets for user {update.effective_user.id}.")
else:
await update.message.reply_text("Not tracking any wallets yet.")
logger.info(f"User {update.effective_user.id} requested wallet list but none are being tracked.")
async def wallet_details(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Shows detailed information about a specific wallet."""
if not context.args:
await update.message.reply_text("Please provide a wallet address or nickname to view details.")
return
code
identifier = context.args[0]
wallet_address = next((address for address, nickname in tracked_wallets.items() if identifier in [address, nickname]), None)
if not wallet_address:
await update.message.reply_text(f"Wallet {identifier} is not being tracked.")
logger.warning(f"User {update.effective_user.id} requested details for non-tracked wallet {identifier}.")
return
try:
user_state = fetch_user_state(wallet_address)
open_orders = get_open_orders_count(wallet_address, return_data=True)
all_mids = fetch_all_mids()
formatted_positions, raw_data, total_upnl, account_equity = format_user_state(wallet_address, all_mids)
wallet_name = tracked_wallets.get(wallet_address, wallet_address)
message = f"<b>Wallet Details: {escape_markdown(wallet_name)}</b>\n"
if not formatted_positions and account_equity == 0 and not open_orders:
message += "Currently inactive"
else:
message += f"- Margin: {escape_markdown(format_number(account_equity))}\n\n"
if formatted_positions:
message += "<b>Positions:</b>\n"
for position in formatted_positions:
coin, position_type, entry_price, mark_price, pnl, size, leverage = position
# Retrieve raw position data
raw_position = raw_data.get(coin, {})
# Determine if this is the first time checking this position
is_first_check = coin not in previous_pnls[wallet_address]
# Calculate PnL difference only if not the first check
if not is_first_check:
previous_pnl = previous_pnls[wallet_address].get(coin, 0)
pnl_diff = raw_position['unrealized_pnl'] - previous_pnl
# Format the PnL difference with sign and shorthand notation
if pnl_diff >= 0:
pnl_diff_str = f" (+{format_number(pnl_diff, decimals=0)[1:]})"
else:
pnl_diff_str = f" (-{format_number(abs(pnl_diff), decimals=0)[1:]})"
else:
pnl_diff_str = "" # No diff on first check
# Update the previous PnL for the next comparison
previous_pnls[wallet_address][coin] = raw_position['unrealized_pnl']
# Adjust mark price decimal places based on its value
mark_price_value = raw_position['mark_price']
if mark_price_value < 1:
mark_price_formatted = f"{mark_price_value:.4f}"
else:
mark_price_formatted = f"{mark_price_value:.2f}"
# Format entry price with 4 decimal places if needed
entry_price_value = raw_position['entry_price']
entry_price_formatted = f"{entry_price_value:.4f}" if entry_price_value < 1 else f"{entry_price_value:.2f}"
# Format PnL
formatted_pnl = format_number(raw_position['unrealized_pnl'], decimals=0)
# Format size: show as positive for positions
display_size = abs(raw_position['size'])
formatted_size = format_number(display_size, decimals=0)
# Format leverage
formatted_leverage = format_number(raw_position['leverage'], decimals=0)
# Assemble the message line
message += (
f"- <b>{escape_markdown(coin)}</b> {formatted_size} {escape_markdown(position_type)}, "
f"Entry: {entry_price_formatted}, "
f"Mark: {mark_price_formatted},\n"
f" Size: {formatted_size}x, "
f"<b>PnL: {formatted_pnl}</b>{pnl_diff_str}\n"
)
else:
message += "<b>Positions:</b> N/A\n"
open_orders_message = (
"\n".join(
[
f"- <b>{escape_markdown(order.get('coin', 'N/A'))}</b>: "
f"Type: {escape_markdown(order.get('type', 'N/A'))}, "
f"Side: {escape_markdown(order.get('side', 'N/A'))}, "
f"Price: {escape_markdown(str(order.get('px', 'N/A')))}, "
f"Quantity: {escape_markdown(str(order.get('qty', 'N/A')))}"
for order in open_orders
]
)
if open_orders
else "N/A"
)
message += f"\n<b>Open Orders:</b> {open_orders_message}\n"
chat_id = update.effective_chat.id if update and update.effective_chat else TELEGRAM_CHAT_ID
await context.bot.send_message(chat_id=chat_id, text=message, parse_mode=ParseMode.HTML)
logger.info(f"Sent wallet details for {wallet_name} to Telegram.")
except Exception as e:
logger.error(f"Error fetching wallet details for {wallet_address}: {e}", exc_info=True)
error_message = f"Failed to fetch wallet details. Error: {str(e)}"
await context.bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=error_message)
logger.info(f"Sent error message to Telegram for wallet {wallet_address}.")
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE):
"""Handle errors caused by updates."""
logger.error(msg="Exception while handling an update:", exc_info=context.error)
# Optionally, notify the admin via Telegram or another method
if TELEGRAM_CHAT_ID:
try:
await context.bot.send_message(
chat_id=TELEGRAM_CHAT_ID,
text=f"An error occurred: {context.error}"
)
except Exception as e:
logger.error(f"Failed to send error message to Telegram: {e}")
async def initialize_application():
"""Initialize and configure the application."""
global application
def main():
"""Main function to run the bot."""
global application
code
try:
# Initialize the application
asyncio.run(initialize_application())
# Run the application
application.run_polling()
except KeyboardInterrupt:
logger.info("Bot stopped by user.")
except Exception as e:
logger.error(f"An unexpected error occurred: {e}", exc_info=True)
finally:
if application:
asyncio.run(application.stop())
logger.info("Script finished.")
if name == "main":
main()
Error:
2024-10-07 13:35:41,793 - asyncio - DEBUG - Using selector: KqueueSelector
2024-10-07 13:35:41,795 - main - INFO - Starting the bot...
2024-10-07 13:35:41,799 - httpx - DEBUG - load_ssl_context verify=True cert=None trust_env=True http2=False
2024-10-07 13:35:41,800 - httpx - DEBUG - load_verify_locations cafile='/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/certifi/cacert.pem'
2024-10-07 13:35:41,804 - httpx - DEBUG - load_ssl_context verify=True cert=None trust_env=True http2=False
2024-10-07 13:35:41,804 - httpx - DEBUG - load_verify_locations cafile='/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/certifi/cacert.pem'
2024-10-07 13:35:41,809 - main - INFO - Added default wallet: kPepe Shorter (0xcd278177b13eb5c269fed43960c4171b66df5b9c)
/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/monitor-purr.py:658: PTBUserWarning: Tasks created via Application.create_task while the application is not running won't be automatically awaited!
application.create_task(websocket_handler())
2024-10-07 13:35:41,822 - telegram.ext.ExtBot - DEBUG - Calling Bot API endpoint getMe with parameters {}
2024-10-07 13:35:41,825 - httpcore.connection - DEBUG - connect_tcp.started host='api.telegram.org' port=443 local_address=None timeout=5.0 socket_options=None
2024-10-07 13:35:41,892 - httpcore.connection - DEBUG - connect_tcp.complete return_value=<httpcore._backends.anyio.AnyIOStream object at 0x10474cbf0>
2024-10-07 13:35:41,892 - httpcore.connection - DEBUG - start_tls.started ssl_context=<ssl.SSLContext object at 0x10460b8d0> server_hostname='api.telegram.org' timeout=5.0
2024-10-07 13:35:41,958 - httpcore.connection - DEBUG - start_tls.complete return_value=<httpcore._backends.anyio.AnyIOStream object at 0x104377e00>
2024-10-07 13:35:41,958 - httpcore.http11 - DEBUG - send_request_headers.started request=<Request [b'POST']>
2024-10-07 13:35:41,959 - httpcore.http11 - DEBUG - send_request_headers.complete
2024-10-07 13:35:41,959 - httpcore.http11 - DEBUG - send_request_body.started request=<Request [b'POST']>
2024-10-07 13:35:41,959 - httpcore.http11 - DEBUG - send_request_body.complete
2024-10-07 13:35:41,959 - httpcore.http11 - DEBUG - receive_response_headers.started request=<Request [b'POST']>
2024-10-07 13:35:42,066 - httpcore.http11 - DEBUG - receive_response_headers.complete return_value=(b'HTTP/1.1', 200, b'OK', [(b'Server', b'nginx/1.18.0'), (b'Date', b'Mon, 07 Oct 2024 10:35:42 GMT'), (b'Content-Type', b'application/json'), (b'Content-Length', b'241'), (b'Connection', b'keep-alive'), (b'Strict-Transport-Security', b'max-age=31536000; includeSubDomains; preload'), (b'Access-Control-Allow-Origin', b'*'), (b'Access-Control-Allow-Methods', b'GET, POST, OPTIONS'), (b'Access-Control-Expose-Headers', b'Content-Length,Content-Type,Date,Server,Connection')])
2024-10-07 13:35:42,067 - httpx - INFO - HTTP Request: POST https://api.telegram.org/bot7110336716:AAGS5B7Uza4dOCCZVTbHJ0eJh1VSo7QiHjk/getMe "HTTP/1.1 200 OK"
2024-10-07 13:35:42,068 - httpcore.http11 - DEBUG - receive_response_body.started request=<Request [b'POST']>
2024-10-07 13:35:42,068 - httpcore.http11 - DEBUG - receive_response_body.complete
2024-10-07 13:35:42,069 - httpcore.http11 - DEBUG - response_closed.started
2024-10-07 13:35:42,069 - httpcore.http11 - DEBUG - response_closed.complete
2024-10-07 13:35:42,069 - telegram.ext.ExtBot - DEBUG - Call to Bot API endpoint getMe finished with return value {'id': 7110336716, 'is_bot': True, 'first_name': 'HL', 'username': 'hlmegabot', 'can_join_groups': True, 'can_read_all_group_messages': False, 'supports_inline_queries': False, 'can_connect_to_business': False, 'has_main_web_app': False}
2024-10-07 13:35:42,069 - telegram.ext.ExtBot - DEBUG - This Bot is already initialized.
2024-10-07 13:35:42,070 - apscheduler.scheduler - INFO - Scheduler started
2024-10-07 13:35:42,070 - telegram.ext.Application - DEBUG - JobQueue started
2024-10-07 13:35:42,070 - telegram.ext.Application - INFO - Application started
2024-10-07 13:35:42,070 - main - INFO - Bot initialized successfully.
2024-10-07 13:35:42,070 - apscheduler.scheduler - DEBUG - Looking for jobs to run
2024-10-07 13:35:42,070 - apscheduler.scheduler - DEBUG - No jobs; waiting until a job is added
2024-10-07 13:35:42,072 - main - ERROR - An unexpected error occurred: There is no current event loop in thread 'MainThread'.
Traceback (most recent call last):
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/monitor-purr.py", line 675, in main
application.run_polling()
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 881, in run_polling
return self.__run(
^^^^^^^^^^^
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 1061, in __run
loop = asyncio.get_event_loop()
^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/events.py", line 702, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.
/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/monitor-purr.py:680: RuntimeWarning: coroutine 'Updater.start_polling' was never awaited
logger.error(f"An unexpected error occurred: {e}", exc_info=True)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-10-07 13:35:42,075 - asyncio - DEBUG - Using selector: KqueueSelector
2024-10-07 13:35:42,075 - telegram.ext.Application - INFO - Application is stopping. This might take a moment.
2024-10-07 13:35:42,075 - telegram.ext.Application - CRITICAL - Fetching updates was aborted due to CancelledError(). Suppressing exception to ensure graceful shutdown.
Traceback (most recent call last):
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 687, in stop
self.__update_fetcher_task.result()
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 1258, in _update_fetcher
await self.__update_fetcher()
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 1237, in __update_fetcher
update = await self.update_queue.get()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/queues.py", line 158, in get
await getter
asyncio.exceptions.CancelledError
2024-10-07 13:35:42,076 - telegram.ext.Application - DEBUG - Application stopped fetching of updates.
2024-10-07 13:35:42,076 - telegram.ext.Application - DEBUG - Waiting for running jobs to finish
Traceback (most recent call last):
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/monitor-purr.py", line 687, in
main()
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/monitor-purr.py", line 683, in main
asyncio.run(application.stop())
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_application.py", line 704, in stop
await self._job_queue.stop(wait=True) # type: ignore[union-attr]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/telegram/ext/_jobqueue.py", line 691, in stop
self.scheduler.shutdown(wait=wait)
File "/Users/mcb/Library/Mobile Documents/comappleCloudDocs/Code/Python/crypto/archive/hl-specific-wallet/env/lib/python3.12/site-packages/apscheduler/schedulers/asyncio.py", line 13, in wrapper
self._eventloop.call_soon_threadsafe(wrapped)
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 840, in call_soon_threadsafe
self._check_closed()
File "/opt/homebrew/Cellar/python@3.12/3.12.5/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 541, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
The error you're encountering stems from the way the asynchronous event loop is managed in your script. Specifically, after you call asyncio.run(initialize_application()), the event loop is closed. Then, when application.run_polling() tries to start, it can't find an active event loop, resulting in the error:
code
RuntimeError: There is no current event loop in thread 'MainThread'.
Additionally, you're seeing a warning about creating tasks before the application is running:
code
PTBUserWarning: Tasks created via `Application.create_task` while the application is not running won't be automatically awaited!
Here's how you can resolve these issues:
Consolidate the Event Loop: Instead of calling asyncio.run() multiple times and mixing synchronous and asynchronous code, you should structure your code to run within a single event loop. This ensures that all asynchronous operations share the same loop, preventing conflicts and errors.
Use application.run_polling() Properly: The run_polling() method is coroutine-aware and should be awaited within an async function. It starts the bot and keeps it running until it's stopped. You shouldn't call application.start() and then application.run_polling(), as run_polling() handles the initialization and starting internally.
Create Background Tasks After the Bot Starts: Use the post_init parameter of Application.run_polling() or schedule tasks within the event loop to ensure that they start after the application is initialized.
Here's the corrected version of your main function and initialization logic:
python
import asyncio
async def main():
global application
logger.info("Starting the bot...")
# Initialize the Application
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
# Add command handlers
application.add_handler(CommandHandler("start", start_command))
application.add_handler(CommandHandler("add", add_wallet))
application.add_handler(CommandHandler("remove", remove_wallet))
application.add_handler(CommandHandler("list", list_wallets))
application.add_handler(CommandHandler("details", wallet_details))
# Add error handler
application.add_error_handler(error_handler)
# Add default wallet
default_wallet = "0xcd278177b13eb5c269fed43960c4171b66df5b9c"
default_nickname = "kPepe Shorter"
tracked_wallets[default_wallet] = default_nickname
logger.info(f"Added default wallet: {default_nickname} ({default_wallet})")
# Define a post_init function to create the websocket_handler task
async def post_init(app: Application):
app.create_task(websocket_handler())
logger.info("WebSocket handler task started.")
# Run the bot with the websocket handler
await application.run_polling(post_init=post_init)
if __name__ == "__main__":
asyncio.run(main())
Explanation:
Single Event Loop: By defining an async def main() function and running it with asyncio.run(main()), you ensure that all asynchronous operations occur within a single event loop.
Using run_polling() Correctly: The await application.run_polling(post_init=post_init) call initializes and starts the bot, then keeps it running until it's stopped (e.g., via a KeyboardInterrupt). It's an asynchronous method, so it should be awaited within an async function.
Starting Background Tasks After Initialization: The post_init callback is called after the application is initialized but before it starts polling for updates. By defining post_init and starting the websocket_handler() task within it, you ensure that the task starts in the correct context.
Removed Redundant Calls: There's no need to call await application.initialize() or await application.start() separately when using run_polling(), as it handles initialization internally.
Additional Notes:
Error Handling: The error handler remains in place to catch any exceptions that occur during execution.
Logging: The logger statements will provide insight into the bot's operation, including when the WebSocket handler starts.
Warnings Resolved: By starting the websocket_handler() after the application is running, you eliminate the warning about creating tasks before the application starts.
By restructuring your code in this way, you ensure that the event loop is managed correctly, preventing the RuntimeError you're encountering. All asynchronous tasks will operate within the same event loop, and the bot will initialize and run as expected.
Updated websocket_handler Function (Optional):
If you need the WebSocket handler to start only after the bot is fully up and running, you might consider moving the task creation into a handler that's called when the bot is ready. However, the post_init approach is generally sufficient.
Final Thoughts:
Managing asynchronous code can be tricky, especially when dealing with event loops and background tasks. Always ensure that your asynchronous functions are called within an active event loop and that tasks are scheduled appropriately. This will help prevent runtime errors and ensure smooth operation of your bot.