0% found this document useful (0 votes)
322 views3 pages

Solana v1.r

sols bot txt file

Uploaded by

abailey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
322 views3 pages

Solana v1.r

sols bot txt file

Uploaded by

abailey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import logging

import requests
import asyncio
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# Enable logging sefedrgthyjw3rfegfthegdrfthgyjk,


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

# Replace 'YOUR_TOKEN' with your bot token


TELEGRAM_TOKEN = '8099459744:AAH-SCdMeiwGUefj1HZpm8pX68UuuR10PBQ'
SOLSCAN_API_KEY =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjcmVhdGVkQXQiOjE3MzU2MDc0ODU4OTUsImVtYWlsI
joidy5jbGFya0BzcGFtb2suY29tIiwiYWN0aW9uIjoidG9rZW4tYXBpIiwiYXBpVmVyc2lvbiI6InYyIiwi
aWF0IjoxNzM1NjA3NDg1fQ.m7GwAdHs8ZUQd2NHYkK9MFL8nZ_V7BFBwVChHq87IOI'

CHECK_INTERVAL = 60 # seconds

# Data structure for tracking wallets and seen transactions


tracked_wallets = {} # {user_id: {wallet_address: name}}
seen_signatures = {} # {user_id: {wallet_address: set(signature)}}

# Headers for API requests and more


HEADERS = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"token": SOLSCAN_API_KEY
}

# Validate Solana wallet addresses


def is_valid_wallet(wallet_address):
"""Check if the wallet address is a valid Solana address."""
import re
return bool(re.match(r"^[A-Za-z0-9]{32,44}$", wallet_address))

# Command Handlers
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Send a welcome message with instructions."""
await update.message.reply_text(
"Welcome to the Solana Wallet Tracker Bot! Use the following commands:\n"
"/track <wallet_address> <name> - Start tracking a wallet.\n"
"/list - List all wallets you are tracking.\n"
"/delete <wallet_address> - Stop tracking a specific wallet."
)

async def track_wallet(update: Update, context: ContextTypes.DEFAULT_TYPE):


"""Track a new wallet."""
args = context.args
if len(args) < 2:
await update.message.reply_text("Usage: /track <wallet_address> <name>")
return

user_id = update.message.from_user.id
wallet_address = args[0]
name = " ".join(args[1:])

if not is_valid_wallet(wallet_address):
await update.message.reply_text(f"Invalid wallet address:
{wallet_address}")
return

# Initialize user's wallet tracking data


tracked_wallets.setdefault(user_id, {})
seen_signatures.setdefault(user_id, {})

if wallet_address in tracked_wallets[user_id]:
await update.message.reply_text(f"Wallet '{name}' ({wallet_address}) is
already being tracked.")
return

# Add wallet to tracking list


tracked_wallets[user_id][wallet_address] = name
seen_signatures[user_id][wallet_address] = set() # Initialize seen signatures
await update.message.reply_text(f"Started tracking wallet '{name}'
({wallet_address}).")

# Start monitoring the wallet


asyncio.create_task(monitor_wallet(user_id, wallet_address, name))

async def list_wallets(update: Update, context: ContextTypes.DEFAULT_TYPE):


"""List all tracked wallets."""
user_id = update.message.from_user.id
user_wallets = tracked_wallets.get(user_id, {})

if not user_wallets:
await update.message.reply_text("You are not tracking any wallets.")
return

message = "Here are the wallets you are tracking:\n"


message += "\n".join(f"- {name}: {wallet}" for wallet, name in
user_wallets.items())
await update.message.reply_text(message)

async def delete_wallet(update: Update, context: ContextTypes.DEFAULT_TYPE):


"""Delete a wallet from tracking."""
args = context.args
if not args:
await update.message.reply_text("Usage: /delete <wallet_address>")
return

user_id = update.message.from_user.id
wallet_address = args[0]

if wallet_address in tracked_wallets.get(user_id, {}):


name = tracked_wallets[user_id].pop(wallet_address)
seen_signatures[user_id].pop(wallet_address, None)
await update.message.reply_text(f"Stopped tracking wallet '{name}'
({wallet_address}).")
else:
await update.message.reply_text(f"Wallet address '{wallet_address}' is not
being tracked.")

# Background Monitoring
async def monitor_wallet(user_id: int, wallet_address: str, name: str):
"""Monitor a wallet for new transactions."""
while wallet_address in tracked_wallets.get(user_id, {}):
try:
logger.info(f"Monitoring wallet {name} ({wallet_address}) for user
{user_id}.")
transactions = await get_transactions(wallet_address)

for tx in transactions:
signature = tx['signature']
if signature not in seen_signatures[user_id][wallet_address]:
seen_signatures[user_id][wallet_address].add(signature)
await notify_user(user_id, name, wallet_address, signature)

except Exception as e:
logger.error(f"Error monitoring wallet {wallet_address}: {e}")
await asyncio.sleep(CHECK_INTERVAL)

async def notify_user(user_id: int, name: str, wallet_address: str, signature:


str):
"""Send a notification to the user about a new transaction."""
application = Application.builder().token(TELEGRAM_TOKEN).build()
await application.bot.send_message(
chat_id=user_id,
text=f"New transaction detected for '{name}' ({wallet_address}):
{signature}"
)

# Helper Function
async def get_transactions(wallet_address):
"""Fetch transactions using Solscan API."""
url = f"https://api.solscan.io/account/transaction?address={wallet_address}"

for attempt in range(5): # Retry up to 5 times


try:
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
return response.json().get('data', [])
except requests.exceptions.RequestException as e:
logger.error(f"Error fetching transactions: {e}")
await asyncio.sleep(2 ** attempt) # Exponential backoff
return []

# Main Function
def main():
application = Application.builder().token(TELEGRAM_TOKEN).build()

# Add command handlers


application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("track", track_wallet))
application.add_handler(CommandHandler("list", list_wallets))
application.add_handler(CommandHandler("delete", delete_wallet))

# Run the bot


application.run_polling()

if __name__ == '__main__':
main()

You might also like